1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * raid5.c : Multiple Devices driver for Linux
4 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
5 * Copyright (C) 1999, 2000 Ingo Molnar
6 * Copyright (C) 2002, 2003 H. Peter Anvin
8 * RAID-4/5/6 management functions.
9 * Thanks to Penguin Computing for making the RAID-6 development possible
10 * by donating a test server!
16 * The sequencing for updating the bitmap reliably is a little
17 * subtle (and I got it wrong the first time) so it deserves some
20 * We group bitmap updates into batches. Each batch has a number.
21 * We may write out several batches at once, but that isn't very important.
22 * conf->seq_write is the number of the last batch successfully written.
23 * conf->seq_flush is the number of the last batch that was closed to
25 * When we discover that we will need to write to any block in a stripe
26 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
27 * the number of the batch it will be in. This is seq_flush+1.
28 * When we are ready to do a write, if that batch hasn't been written yet,
29 * we plug the array and queue the stripe for later.
30 * When an unplug happens, we increment bm_flush, thus closing the current
32 * When we notice that bm_flush > bm_write, we write out all pending updates
33 * to the bitmap, and advance bm_write to where bm_flush was.
34 * This may occasionally write a bit out twice, but is sure never to
38 #include <linux/blkdev.h>
39 #include <linux/delay.h>
40 #include <linux/kthread.h>
41 #include <linux/raid/pq.h>
42 #include <linux/async_tx.h>
43 #include <linux/module.h>
44 #include <linux/async.h>
45 #include <linux/seq_file.h>
46 #include <linux/cpu.h>
47 #include <linux/slab.h>
48 #include <linux/ratelimit.h>
49 #include <linux/nodemask.h>
51 #include <trace/events/block.h>
52 #include <linux/list_sort.h>
57 #include "md-bitmap.h"
58 #include "raid5-log.h"
60 #define UNSUPPORTED_MDDEV_FLAGS (1L << MD_FAILFAST_SUPPORTED)
62 #define cpu_to_group(cpu) cpu_to_node(cpu)
63 #define ANY_GROUP NUMA_NO_NODE
65 static bool devices_handle_discard_safely = false;
66 module_param(devices_handle_discard_safely, bool, 0644);
67 MODULE_PARM_DESC(devices_handle_discard_safely,
68 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
69 static struct workqueue_struct *raid5_wq;
71 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
73 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
74 return &conf->stripe_hashtbl[hash];
77 static inline int stripe_hash_locks_hash(sector_t sect)
79 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
82 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
84 spin_lock_irq(conf->hash_locks + hash);
85 spin_lock(&conf->device_lock);
88 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
90 spin_unlock(&conf->device_lock);
91 spin_unlock_irq(conf->hash_locks + hash);
94 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
97 spin_lock_irq(conf->hash_locks);
98 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
99 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
100 spin_lock(&conf->device_lock);
103 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
106 spin_unlock(&conf->device_lock);
107 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
108 spin_unlock(conf->hash_locks + i);
109 spin_unlock_irq(conf->hash_locks);
112 /* Find first data disk in a raid6 stripe */
113 static inline int raid6_d0(struct stripe_head *sh)
116 /* ddf always start from first device */
118 /* md starts just after Q block */
119 if (sh->qd_idx == sh->disks - 1)
122 return sh->qd_idx + 1;
124 static inline int raid6_next_disk(int disk, int raid_disks)
127 return (disk < raid_disks) ? disk : 0;
130 /* When walking through the disks in a raid5, starting at raid6_d0,
131 * We need to map each disk to a 'slot', where the data disks are slot
132 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
133 * is raid_disks-1. This help does that mapping.
135 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
136 int *count, int syndrome_disks)
142 if (idx == sh->pd_idx)
143 return syndrome_disks;
144 if (idx == sh->qd_idx)
145 return syndrome_disks + 1;
151 static void print_raid5_conf (struct r5conf *conf);
153 static int stripe_operations_active(struct stripe_head *sh)
155 return sh->check_state || sh->reconstruct_state ||
156 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
157 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
160 static bool stripe_is_lowprio(struct stripe_head *sh)
162 return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
163 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
164 !test_bit(STRIPE_R5C_CACHING, &sh->state);
167 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
169 struct r5conf *conf = sh->raid_conf;
170 struct r5worker_group *group;
172 int i, cpu = sh->cpu;
174 if (!cpu_online(cpu)) {
175 cpu = cpumask_any(cpu_online_mask);
179 if (list_empty(&sh->lru)) {
180 struct r5worker_group *group;
181 group = conf->worker_groups + cpu_to_group(cpu);
182 if (stripe_is_lowprio(sh))
183 list_add_tail(&sh->lru, &group->loprio_list);
185 list_add_tail(&sh->lru, &group->handle_list);
186 group->stripes_cnt++;
190 if (conf->worker_cnt_per_group == 0) {
191 md_wakeup_thread(conf->mddev->thread);
195 group = conf->worker_groups + cpu_to_group(sh->cpu);
197 group->workers[0].working = true;
198 /* at least one worker should run to avoid race */
199 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
201 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
202 /* wakeup more workers */
203 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
204 if (group->workers[i].working == false) {
205 group->workers[i].working = true;
206 queue_work_on(sh->cpu, raid5_wq,
207 &group->workers[i].work);
213 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
214 struct list_head *temp_inactive_list)
217 int injournal = 0; /* number of date pages with R5_InJournal */
219 BUG_ON(!list_empty(&sh->lru));
220 BUG_ON(atomic_read(&conf->active_stripes)==0);
222 if (r5c_is_writeback(conf->log))
223 for (i = sh->disks; i--; )
224 if (test_bit(R5_InJournal, &sh->dev[i].flags))
227 * In the following cases, the stripe cannot be released to cached
228 * lists. Therefore, we make the stripe write out and set
230 * 1. when quiesce in r5c write back;
231 * 2. when resync is requested fot the stripe.
233 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
234 (conf->quiesce && r5c_is_writeback(conf->log) &&
235 !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
236 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
237 r5c_make_stripe_write_out(sh);
238 set_bit(STRIPE_HANDLE, &sh->state);
241 if (test_bit(STRIPE_HANDLE, &sh->state)) {
242 if (test_bit(STRIPE_DELAYED, &sh->state) &&
243 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
244 list_add_tail(&sh->lru, &conf->delayed_list);
245 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
246 sh->bm_seq - conf->seq_write > 0)
247 list_add_tail(&sh->lru, &conf->bitmap_list);
249 clear_bit(STRIPE_DELAYED, &sh->state);
250 clear_bit(STRIPE_BIT_DELAY, &sh->state);
251 if (conf->worker_cnt_per_group == 0) {
252 if (stripe_is_lowprio(sh))
253 list_add_tail(&sh->lru,
256 list_add_tail(&sh->lru,
259 raid5_wakeup_stripe_thread(sh);
263 md_wakeup_thread(conf->mddev->thread);
265 BUG_ON(stripe_operations_active(sh));
266 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
267 if (atomic_dec_return(&conf->preread_active_stripes)
269 md_wakeup_thread(conf->mddev->thread);
270 atomic_dec(&conf->active_stripes);
271 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
272 if (!r5c_is_writeback(conf->log))
273 list_add_tail(&sh->lru, temp_inactive_list);
275 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
277 list_add_tail(&sh->lru, temp_inactive_list);
278 else if (injournal == conf->raid_disks - conf->max_degraded) {
280 if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
281 atomic_inc(&conf->r5c_cached_full_stripes);
282 if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
283 atomic_dec(&conf->r5c_cached_partial_stripes);
284 list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
285 r5c_check_cached_full_stripe(conf);
288 * STRIPE_R5C_PARTIAL_STRIPE is set in
289 * r5c_try_caching_write(). No need to
292 list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
298 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
299 struct list_head *temp_inactive_list)
301 if (atomic_dec_and_test(&sh->count))
302 do_release_stripe(conf, sh, temp_inactive_list);
306 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
308 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
309 * given time. Adding stripes only takes device lock, while deleting stripes
310 * only takes hash lock.
312 static void release_inactive_stripe_list(struct r5conf *conf,
313 struct list_head *temp_inactive_list,
317 bool do_wakeup = false;
320 if (hash == NR_STRIPE_HASH_LOCKS) {
321 size = NR_STRIPE_HASH_LOCKS;
322 hash = NR_STRIPE_HASH_LOCKS - 1;
326 struct list_head *list = &temp_inactive_list[size - 1];
329 * We don't hold any lock here yet, raid5_get_active_stripe() might
330 * remove stripes from the list
332 if (!list_empty_careful(list)) {
333 spin_lock_irqsave(conf->hash_locks + hash, flags);
334 if (list_empty(conf->inactive_list + hash) &&
336 atomic_dec(&conf->empty_inactive_list_nr);
337 list_splice_tail_init(list, conf->inactive_list + hash);
339 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
346 wake_up(&conf->wait_for_stripe);
347 if (atomic_read(&conf->active_stripes) == 0)
348 wake_up(&conf->wait_for_quiescent);
349 if (conf->retry_read_aligned)
350 md_wakeup_thread(conf->mddev->thread);
354 /* should hold conf->device_lock already */
355 static int release_stripe_list(struct r5conf *conf,
356 struct list_head *temp_inactive_list)
358 struct stripe_head *sh, *t;
360 struct llist_node *head;
362 head = llist_del_all(&conf->released_stripes);
363 head = llist_reverse_order(head);
364 llist_for_each_entry_safe(sh, t, head, release_list) {
367 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
369 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
371 * Don't worry the bit is set here, because if the bit is set
372 * again, the count is always > 1. This is true for
373 * STRIPE_ON_UNPLUG_LIST bit too.
375 hash = sh->hash_lock_index;
376 __release_stripe(conf, sh, &temp_inactive_list[hash]);
383 void raid5_release_stripe(struct stripe_head *sh)
385 struct r5conf *conf = sh->raid_conf;
387 struct list_head list;
391 /* Avoid release_list until the last reference.
393 if (atomic_add_unless(&sh->count, -1, 1))
396 if (unlikely(!conf->mddev->thread) ||
397 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
399 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
401 md_wakeup_thread(conf->mddev->thread);
404 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
405 if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
406 INIT_LIST_HEAD(&list);
407 hash = sh->hash_lock_index;
408 do_release_stripe(conf, sh, &list);
409 spin_unlock_irqrestore(&conf->device_lock, flags);
410 release_inactive_stripe_list(conf, &list, hash);
414 static inline void remove_hash(struct stripe_head *sh)
416 pr_debug("remove_hash(), stripe %llu\n",
417 (unsigned long long)sh->sector);
419 hlist_del_init(&sh->hash);
422 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
424 struct hlist_head *hp = stripe_hash(conf, sh->sector);
426 pr_debug("insert_hash(), stripe %llu\n",
427 (unsigned long long)sh->sector);
429 hlist_add_head(&sh->hash, hp);
432 /* find an idle stripe, make sure it is unhashed, and return it. */
433 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
435 struct stripe_head *sh = NULL;
436 struct list_head *first;
438 if (list_empty(conf->inactive_list + hash))
440 first = (conf->inactive_list + hash)->next;
441 sh = list_entry(first, struct stripe_head, lru);
442 list_del_init(first);
444 atomic_inc(&conf->active_stripes);
445 BUG_ON(hash != sh->hash_lock_index);
446 if (list_empty(conf->inactive_list + hash))
447 atomic_inc(&conf->empty_inactive_list_nr);
452 static void shrink_buffers(struct stripe_head *sh)
456 int num = sh->raid_conf->pool_size;
458 for (i = 0; i < num ; i++) {
459 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
463 sh->dev[i].page = NULL;
468 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
471 int num = sh->raid_conf->pool_size;
473 for (i = 0; i < num; i++) {
476 if (!(page = alloc_page(gfp))) {
479 sh->dev[i].page = page;
480 sh->dev[i].orig_page = page;
486 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
487 struct stripe_head *sh);
489 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
491 struct r5conf *conf = sh->raid_conf;
494 BUG_ON(atomic_read(&sh->count) != 0);
495 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
496 BUG_ON(stripe_operations_active(sh));
497 BUG_ON(sh->batch_head);
499 pr_debug("init_stripe called, stripe %llu\n",
500 (unsigned long long)sector);
502 seq = read_seqcount_begin(&conf->gen_lock);
503 sh->generation = conf->generation - previous;
504 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
506 stripe_set_idx(sector, conf, previous, sh);
509 for (i = sh->disks; i--; ) {
510 struct r5dev *dev = &sh->dev[i];
512 if (dev->toread || dev->read || dev->towrite || dev->written ||
513 test_bit(R5_LOCKED, &dev->flags)) {
514 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
515 (unsigned long long)sh->sector, i, dev->toread,
516 dev->read, dev->towrite, dev->written,
517 test_bit(R5_LOCKED, &dev->flags));
521 dev->sector = raid5_compute_blocknr(sh, i, previous);
523 if (read_seqcount_retry(&conf->gen_lock, seq))
525 sh->overwrite_disks = 0;
526 insert_hash(conf, sh);
527 sh->cpu = smp_processor_id();
528 set_bit(STRIPE_BATCH_READY, &sh->state);
531 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
534 struct stripe_head *sh;
536 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
537 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
538 if (sh->sector == sector && sh->generation == generation)
540 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
545 * Need to check if array has failed when deciding whether to:
547 * - remove non-faulty devices
550 * This determination is simple when no reshape is happening.
551 * However if there is a reshape, we need to carefully check
552 * both the before and after sections.
553 * This is because some failed devices may only affect one
554 * of the two sections, and some non-in_sync devices may
555 * be insync in the section most affected by failed devices.
557 int raid5_calc_degraded(struct r5conf *conf)
559 int degraded, degraded2;
564 for (i = 0; i < conf->previous_raid_disks; i++) {
565 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
566 if (rdev && test_bit(Faulty, &rdev->flags))
567 rdev = rcu_dereference(conf->disks[i].replacement);
568 if (!rdev || test_bit(Faulty, &rdev->flags))
570 else if (test_bit(In_sync, &rdev->flags))
573 /* not in-sync or faulty.
574 * If the reshape increases the number of devices,
575 * this is being recovered by the reshape, so
576 * this 'previous' section is not in_sync.
577 * If the number of devices is being reduced however,
578 * the device can only be part of the array if
579 * we are reverting a reshape, so this section will
582 if (conf->raid_disks >= conf->previous_raid_disks)
586 if (conf->raid_disks == conf->previous_raid_disks)
590 for (i = 0; i < conf->raid_disks; i++) {
591 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
592 if (rdev && test_bit(Faulty, &rdev->flags))
593 rdev = rcu_dereference(conf->disks[i].replacement);
594 if (!rdev || test_bit(Faulty, &rdev->flags))
596 else if (test_bit(In_sync, &rdev->flags))
599 /* not in-sync or faulty.
600 * If reshape increases the number of devices, this
601 * section has already been recovered, else it
602 * almost certainly hasn't.
604 if (conf->raid_disks <= conf->previous_raid_disks)
608 if (degraded2 > degraded)
613 static bool has_failed(struct r5conf *conf)
615 int degraded = conf->mddev->degraded;
617 if (test_bit(MD_BROKEN, &conf->mddev->flags))
620 if (conf->mddev->reshape_position != MaxSector)
621 degraded = raid5_calc_degraded(conf);
623 return degraded > conf->max_degraded;
627 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
628 int previous, int noblock, int noquiesce)
630 struct stripe_head *sh;
631 int hash = stripe_hash_locks_hash(sector);
632 int inc_empty_inactive_list_flag;
634 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
636 spin_lock_irq(conf->hash_locks + hash);
639 wait_event_lock_irq(conf->wait_for_quiescent,
640 conf->quiesce == 0 || noquiesce,
641 *(conf->hash_locks + hash));
642 sh = __find_stripe(conf, sector, conf->generation - previous);
644 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
645 sh = get_free_stripe(conf, hash);
646 if (!sh && !test_bit(R5_DID_ALLOC,
648 set_bit(R5_ALLOC_MORE,
651 if (noblock && sh == NULL)
654 r5c_check_stripe_cache_usage(conf);
656 set_bit(R5_INACTIVE_BLOCKED,
658 r5l_wake_reclaim(conf->log, 0);
660 conf->wait_for_stripe,
661 !list_empty(conf->inactive_list + hash) &&
662 (atomic_read(&conf->active_stripes)
663 < (conf->max_nr_stripes * 3 / 4)
664 || !test_bit(R5_INACTIVE_BLOCKED,
665 &conf->cache_state)),
666 *(conf->hash_locks + hash));
667 clear_bit(R5_INACTIVE_BLOCKED,
670 init_stripe(sh, sector, previous);
671 atomic_inc(&sh->count);
673 } else if (!atomic_inc_not_zero(&sh->count)) {
674 spin_lock(&conf->device_lock);
675 if (!atomic_read(&sh->count)) {
676 if (!test_bit(STRIPE_HANDLE, &sh->state))
677 atomic_inc(&conf->active_stripes);
678 BUG_ON(list_empty(&sh->lru) &&
679 !test_bit(STRIPE_EXPANDING, &sh->state));
680 inc_empty_inactive_list_flag = 0;
681 if (!list_empty(conf->inactive_list + hash))
682 inc_empty_inactive_list_flag = 1;
683 list_del_init(&sh->lru);
684 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
685 atomic_inc(&conf->empty_inactive_list_nr);
687 sh->group->stripes_cnt--;
691 atomic_inc(&sh->count);
692 spin_unlock(&conf->device_lock);
694 } while (sh == NULL);
696 spin_unlock_irq(conf->hash_locks + hash);
700 static bool is_full_stripe_write(struct stripe_head *sh)
702 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
703 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
706 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
707 __acquires(&sh1->stripe_lock)
708 __acquires(&sh2->stripe_lock)
711 spin_lock_irq(&sh2->stripe_lock);
712 spin_lock_nested(&sh1->stripe_lock, 1);
714 spin_lock_irq(&sh1->stripe_lock);
715 spin_lock_nested(&sh2->stripe_lock, 1);
719 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
720 __releases(&sh1->stripe_lock)
721 __releases(&sh2->stripe_lock)
723 spin_unlock(&sh1->stripe_lock);
724 spin_unlock_irq(&sh2->stripe_lock);
727 /* Only freshly new full stripe normal write stripe can be added to a batch list */
728 static bool stripe_can_batch(struct stripe_head *sh)
730 struct r5conf *conf = sh->raid_conf;
732 if (raid5_has_log(conf) || raid5_has_ppl(conf))
734 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
735 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
736 is_full_stripe_write(sh);
739 /* we only do back search */
740 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
742 struct stripe_head *head;
743 sector_t head_sector, tmp_sec;
746 int inc_empty_inactive_list_flag;
748 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
749 tmp_sec = sh->sector;
750 if (!sector_div(tmp_sec, conf->chunk_sectors))
752 head_sector = sh->sector - STRIPE_SECTORS;
754 hash = stripe_hash_locks_hash(head_sector);
755 spin_lock_irq(conf->hash_locks + hash);
756 head = __find_stripe(conf, head_sector, conf->generation);
757 if (head && !atomic_inc_not_zero(&head->count)) {
758 spin_lock(&conf->device_lock);
759 if (!atomic_read(&head->count)) {
760 if (!test_bit(STRIPE_HANDLE, &head->state))
761 atomic_inc(&conf->active_stripes);
762 BUG_ON(list_empty(&head->lru) &&
763 !test_bit(STRIPE_EXPANDING, &head->state));
764 inc_empty_inactive_list_flag = 0;
765 if (!list_empty(conf->inactive_list + hash))
766 inc_empty_inactive_list_flag = 1;
767 list_del_init(&head->lru);
768 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
769 atomic_inc(&conf->empty_inactive_list_nr);
771 head->group->stripes_cnt--;
775 atomic_inc(&head->count);
776 spin_unlock(&conf->device_lock);
778 spin_unlock_irq(conf->hash_locks + hash);
782 if (!stripe_can_batch(head))
785 lock_two_stripes(head, sh);
786 /* clear_batch_ready clear the flag */
787 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
794 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
796 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
797 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
800 if (head->batch_head) {
801 spin_lock(&head->batch_head->batch_lock);
802 /* This batch list is already running */
803 if (!stripe_can_batch(head)) {
804 spin_unlock(&head->batch_head->batch_lock);
808 * We must assign batch_head of this stripe within the
809 * batch_lock, otherwise clear_batch_ready of batch head
810 * stripe could clear BATCH_READY bit of this stripe and
811 * this stripe->batch_head doesn't get assigned, which
812 * could confuse clear_batch_ready for this stripe
814 sh->batch_head = head->batch_head;
817 * at this point, head's BATCH_READY could be cleared, but we
818 * can still add the stripe to batch list
820 list_add(&sh->batch_list, &head->batch_list);
821 spin_unlock(&head->batch_head->batch_lock);
823 head->batch_head = head;
824 sh->batch_head = head->batch_head;
825 spin_lock(&head->batch_lock);
826 list_add_tail(&sh->batch_list, &head->batch_list);
827 spin_unlock(&head->batch_lock);
830 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
831 if (atomic_dec_return(&conf->preread_active_stripes)
833 md_wakeup_thread(conf->mddev->thread);
835 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
836 int seq = sh->bm_seq;
837 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
838 sh->batch_head->bm_seq > seq)
839 seq = sh->batch_head->bm_seq;
840 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
841 sh->batch_head->bm_seq = seq;
844 atomic_inc(&sh->count);
846 unlock_two_stripes(head, sh);
848 raid5_release_stripe(head);
851 /* Determine if 'data_offset' or 'new_data_offset' should be used
852 * in this stripe_head.
854 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
856 sector_t progress = conf->reshape_progress;
857 /* Need a memory barrier to make sure we see the value
858 * of conf->generation, or ->data_offset that was set before
859 * reshape_progress was updated.
862 if (progress == MaxSector)
864 if (sh->generation == conf->generation - 1)
866 /* We are in a reshape, and this is a new-generation stripe,
867 * so use new_data_offset.
872 static void dispatch_bio_list(struct bio_list *tmp)
876 while ((bio = bio_list_pop(tmp)))
877 generic_make_request(bio);
880 static int cmp_stripe(void *priv, struct list_head *a, struct list_head *b)
882 const struct r5pending_data *da = list_entry(a,
883 struct r5pending_data, sibling);
884 const struct r5pending_data *db = list_entry(b,
885 struct r5pending_data, sibling);
886 if (da->sector > db->sector)
888 if (da->sector < db->sector)
893 static void dispatch_defer_bios(struct r5conf *conf, int target,
894 struct bio_list *list)
896 struct r5pending_data *data;
897 struct list_head *first, *next = NULL;
900 if (conf->pending_data_cnt == 0)
903 list_sort(NULL, &conf->pending_list, cmp_stripe);
905 first = conf->pending_list.next;
907 /* temporarily move the head */
908 if (conf->next_pending_data)
909 list_move_tail(&conf->pending_list,
910 &conf->next_pending_data->sibling);
912 while (!list_empty(&conf->pending_list)) {
913 data = list_first_entry(&conf->pending_list,
914 struct r5pending_data, sibling);
915 if (&data->sibling == first)
916 first = data->sibling.next;
917 next = data->sibling.next;
919 bio_list_merge(list, &data->bios);
920 list_move(&data->sibling, &conf->free_list);
925 conf->pending_data_cnt -= cnt;
926 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
928 if (next != &conf->pending_list)
929 conf->next_pending_data = list_entry(next,
930 struct r5pending_data, sibling);
932 conf->next_pending_data = NULL;
933 /* list isn't empty */
934 if (first != &conf->pending_list)
935 list_move_tail(&conf->pending_list, first);
938 static void flush_deferred_bios(struct r5conf *conf)
940 struct bio_list tmp = BIO_EMPTY_LIST;
942 if (conf->pending_data_cnt == 0)
945 spin_lock(&conf->pending_bios_lock);
946 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
947 BUG_ON(conf->pending_data_cnt != 0);
948 spin_unlock(&conf->pending_bios_lock);
950 dispatch_bio_list(&tmp);
953 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
954 struct bio_list *bios)
956 struct bio_list tmp = BIO_EMPTY_LIST;
957 struct r5pending_data *ent;
959 spin_lock(&conf->pending_bios_lock);
960 ent = list_first_entry(&conf->free_list, struct r5pending_data,
962 list_move_tail(&ent->sibling, &conf->pending_list);
963 ent->sector = sector;
964 bio_list_init(&ent->bios);
965 bio_list_merge(&ent->bios, bios);
966 conf->pending_data_cnt++;
967 if (conf->pending_data_cnt >= PENDING_IO_MAX)
968 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
970 spin_unlock(&conf->pending_bios_lock);
972 dispatch_bio_list(&tmp);
976 raid5_end_read_request(struct bio *bi);
978 raid5_end_write_request(struct bio *bi);
980 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
982 struct r5conf *conf = sh->raid_conf;
983 int i, disks = sh->disks;
984 struct stripe_head *head_sh = sh;
985 struct bio_list pending_bios = BIO_EMPTY_LIST;
990 if (log_stripe(sh, s) == 0)
993 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
995 for (i = disks; i--; ) {
996 int op, op_flags = 0;
997 int replace_only = 0;
998 struct bio *bi, *rbi;
999 struct md_rdev *rdev, *rrdev = NULL;
1002 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1004 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1006 if (test_bit(R5_Discard, &sh->dev[i].flags))
1007 op = REQ_OP_DISCARD;
1008 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1010 else if (test_and_clear_bit(R5_WantReplace,
1011 &sh->dev[i].flags)) {
1016 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1017 op_flags |= REQ_SYNC;
1020 bi = &sh->dev[i].req;
1021 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1024 rrdev = rcu_dereference(conf->disks[i].replacement);
1025 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1026 rdev = rcu_dereference(conf->disks[i].rdev);
1031 if (op_is_write(op)) {
1035 /* We raced and saw duplicates */
1038 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1043 if (rdev && test_bit(Faulty, &rdev->flags))
1046 atomic_inc(&rdev->nr_pending);
1047 if (rrdev && test_bit(Faulty, &rrdev->flags))
1050 atomic_inc(&rrdev->nr_pending);
1053 /* We have already checked bad blocks for reads. Now
1054 * need to check for writes. We never accept write errors
1055 * on the replacement, so we don't to check rrdev.
1057 while (op_is_write(op) && rdev &&
1058 test_bit(WriteErrorSeen, &rdev->flags)) {
1061 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
1062 &first_bad, &bad_sectors);
1067 set_bit(BlockedBadBlocks, &rdev->flags);
1068 if (!conf->mddev->external &&
1069 conf->mddev->sb_flags) {
1070 /* It is very unlikely, but we might
1071 * still need to write out the
1072 * bad block log - better give it
1074 md_check_recovery(conf->mddev);
1077 * Because md_wait_for_blocked_rdev
1078 * will dec nr_pending, we must
1079 * increment it first.
1081 atomic_inc(&rdev->nr_pending);
1082 md_wait_for_blocked_rdev(rdev, conf->mddev);
1084 /* Acknowledged bad block - skip the write */
1085 rdev_dec_pending(rdev, conf->mddev);
1091 if (s->syncing || s->expanding || s->expanded
1093 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
1095 set_bit(STRIPE_IO_STARTED, &sh->state);
1097 bio_set_dev(bi, rdev->bdev);
1098 bio_set_op_attrs(bi, op, op_flags);
1099 bi->bi_end_io = op_is_write(op)
1100 ? raid5_end_write_request
1101 : raid5_end_read_request;
1102 bi->bi_private = sh;
1104 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1105 __func__, (unsigned long long)sh->sector,
1107 atomic_inc(&sh->count);
1109 atomic_inc(&head_sh->count);
1110 if (use_new_offset(conf, sh))
1111 bi->bi_iter.bi_sector = (sh->sector
1112 + rdev->new_data_offset);
1114 bi->bi_iter.bi_sector = (sh->sector
1115 + rdev->data_offset);
1116 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1117 bi->bi_opf |= REQ_NOMERGE;
1119 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1120 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1122 if (!op_is_write(op) &&
1123 test_bit(R5_InJournal, &sh->dev[i].flags))
1125 * issuing read for a page in journal, this
1126 * must be preparing for prexor in rmw; read
1127 * the data into orig_page
1129 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1131 sh->dev[i].vec.bv_page = sh->dev[i].page;
1133 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1134 bi->bi_io_vec[0].bv_offset = 0;
1135 bi->bi_iter.bi_size = STRIPE_SIZE;
1136 bi->bi_write_hint = sh->dev[i].write_hint;
1138 sh->dev[i].write_hint = RWF_WRITE_LIFE_NOT_SET;
1140 * If this is discard request, set bi_vcnt 0. We don't
1141 * want to confuse SCSI because SCSI will replace payload
1143 if (op == REQ_OP_DISCARD)
1146 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1148 if (conf->mddev->gendisk)
1149 trace_block_bio_remap(bi->bi_disk->queue,
1150 bi, disk_devt(conf->mddev->gendisk),
1152 if (should_defer && op_is_write(op))
1153 bio_list_add(&pending_bios, bi);
1155 generic_make_request(bi);
1158 if (s->syncing || s->expanding || s->expanded
1160 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1162 set_bit(STRIPE_IO_STARTED, &sh->state);
1164 bio_set_dev(rbi, rrdev->bdev);
1165 bio_set_op_attrs(rbi, op, op_flags);
1166 BUG_ON(!op_is_write(op));
1167 rbi->bi_end_io = raid5_end_write_request;
1168 rbi->bi_private = sh;
1170 pr_debug("%s: for %llu schedule op %d on "
1171 "replacement disc %d\n",
1172 __func__, (unsigned long long)sh->sector,
1174 atomic_inc(&sh->count);
1176 atomic_inc(&head_sh->count);
1177 if (use_new_offset(conf, sh))
1178 rbi->bi_iter.bi_sector = (sh->sector
1179 + rrdev->new_data_offset);
1181 rbi->bi_iter.bi_sector = (sh->sector
1182 + rrdev->data_offset);
1183 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1184 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1185 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1187 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1188 rbi->bi_io_vec[0].bv_offset = 0;
1189 rbi->bi_iter.bi_size = STRIPE_SIZE;
1190 rbi->bi_write_hint = sh->dev[i].write_hint;
1191 sh->dev[i].write_hint = RWF_WRITE_LIFE_NOT_SET;
1193 * If this is discard request, set bi_vcnt 0. We don't
1194 * want to confuse SCSI because SCSI will replace payload
1196 if (op == REQ_OP_DISCARD)
1198 if (conf->mddev->gendisk)
1199 trace_block_bio_remap(rbi->bi_disk->queue,
1200 rbi, disk_devt(conf->mddev->gendisk),
1202 if (should_defer && op_is_write(op))
1203 bio_list_add(&pending_bios, rbi);
1205 generic_make_request(rbi);
1207 if (!rdev && !rrdev) {
1208 if (op_is_write(op))
1209 set_bit(STRIPE_DEGRADED, &sh->state);
1210 pr_debug("skip op %d on disc %d for sector %llu\n",
1211 bi->bi_opf, i, (unsigned long long)sh->sector);
1212 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1213 set_bit(STRIPE_HANDLE, &sh->state);
1216 if (!head_sh->batch_head)
1218 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1224 if (should_defer && !bio_list_empty(&pending_bios))
1225 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1228 static struct dma_async_tx_descriptor *
1229 async_copy_data(int frombio, struct bio *bio, struct page **page,
1230 sector_t sector, struct dma_async_tx_descriptor *tx,
1231 struct stripe_head *sh, int no_skipcopy)
1234 struct bvec_iter iter;
1235 struct page *bio_page;
1237 struct async_submit_ctl submit;
1238 enum async_tx_flags flags = 0;
1240 if (bio->bi_iter.bi_sector >= sector)
1241 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1243 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1246 flags |= ASYNC_TX_FENCE;
1247 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1249 bio_for_each_segment(bvl, bio, iter) {
1250 int len = bvl.bv_len;
1254 if (page_offset < 0) {
1255 b_offset = -page_offset;
1256 page_offset += b_offset;
1260 if (len > 0 && page_offset + len > STRIPE_SIZE)
1261 clen = STRIPE_SIZE - page_offset;
1266 b_offset += bvl.bv_offset;
1267 bio_page = bvl.bv_page;
1269 if (sh->raid_conf->skip_copy &&
1270 b_offset == 0 && page_offset == 0 &&
1271 clen == STRIPE_SIZE &&
1275 tx = async_memcpy(*page, bio_page, page_offset,
1276 b_offset, clen, &submit);
1278 tx = async_memcpy(bio_page, *page, b_offset,
1279 page_offset, clen, &submit);
1281 /* chain the operations */
1282 submit.depend_tx = tx;
1284 if (clen < len) /* hit end of page */
1292 static void ops_complete_biofill(void *stripe_head_ref)
1294 struct stripe_head *sh = stripe_head_ref;
1297 pr_debug("%s: stripe %llu\n", __func__,
1298 (unsigned long long)sh->sector);
1300 /* clear completed biofills */
1301 for (i = sh->disks; i--; ) {
1302 struct r5dev *dev = &sh->dev[i];
1304 /* acknowledge completion of a biofill operation */
1305 /* and check if we need to reply to a read request,
1306 * new R5_Wantfill requests are held off until
1307 * !STRIPE_BIOFILL_RUN
1309 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1310 struct bio *rbi, *rbi2;
1315 while (rbi && rbi->bi_iter.bi_sector <
1316 dev->sector + STRIPE_SECTORS) {
1317 rbi2 = r5_next_bio(rbi, dev->sector);
1323 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1325 set_bit(STRIPE_HANDLE, &sh->state);
1326 raid5_release_stripe(sh);
1329 static void ops_run_biofill(struct stripe_head *sh)
1331 struct dma_async_tx_descriptor *tx = NULL;
1332 struct async_submit_ctl submit;
1335 BUG_ON(sh->batch_head);
1336 pr_debug("%s: stripe %llu\n", __func__,
1337 (unsigned long long)sh->sector);
1339 for (i = sh->disks; i--; ) {
1340 struct r5dev *dev = &sh->dev[i];
1341 if (test_bit(R5_Wantfill, &dev->flags)) {
1343 spin_lock_irq(&sh->stripe_lock);
1344 dev->read = rbi = dev->toread;
1346 spin_unlock_irq(&sh->stripe_lock);
1347 while (rbi && rbi->bi_iter.bi_sector <
1348 dev->sector + STRIPE_SECTORS) {
1349 tx = async_copy_data(0, rbi, &dev->page,
1350 dev->sector, tx, sh, 0);
1351 rbi = r5_next_bio(rbi, dev->sector);
1356 atomic_inc(&sh->count);
1357 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1358 async_trigger_callback(&submit);
1361 static void mark_target_uptodate(struct stripe_head *sh, int target)
1368 tgt = &sh->dev[target];
1369 set_bit(R5_UPTODATE, &tgt->flags);
1370 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1371 clear_bit(R5_Wantcompute, &tgt->flags);
1374 static void ops_complete_compute(void *stripe_head_ref)
1376 struct stripe_head *sh = stripe_head_ref;
1378 pr_debug("%s: stripe %llu\n", __func__,
1379 (unsigned long long)sh->sector);
1381 /* mark the computed target(s) as uptodate */
1382 mark_target_uptodate(sh, sh->ops.target);
1383 mark_target_uptodate(sh, sh->ops.target2);
1385 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1386 if (sh->check_state == check_state_compute_run)
1387 sh->check_state = check_state_compute_result;
1388 set_bit(STRIPE_HANDLE, &sh->state);
1389 raid5_release_stripe(sh);
1392 /* return a pointer to the address conversion region of the scribble buffer */
1393 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1395 return percpu->scribble + i * percpu->scribble_obj_size;
1398 /* return a pointer to the address conversion region of the scribble buffer */
1399 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1400 struct raid5_percpu *percpu, int i)
1402 return (void *) (to_addr_page(percpu, i) + sh->disks + 2);
1405 static struct dma_async_tx_descriptor *
1406 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1408 int disks = sh->disks;
1409 struct page **xor_srcs = to_addr_page(percpu, 0);
1410 int target = sh->ops.target;
1411 struct r5dev *tgt = &sh->dev[target];
1412 struct page *xor_dest = tgt->page;
1414 struct dma_async_tx_descriptor *tx;
1415 struct async_submit_ctl submit;
1418 BUG_ON(sh->batch_head);
1420 pr_debug("%s: stripe %llu block: %d\n",
1421 __func__, (unsigned long long)sh->sector, target);
1422 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1424 for (i = disks; i--; )
1426 xor_srcs[count++] = sh->dev[i].page;
1428 atomic_inc(&sh->count);
1430 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1431 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1432 if (unlikely(count == 1))
1433 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1435 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1440 /* set_syndrome_sources - populate source buffers for gen_syndrome
1441 * @srcs - (struct page *) array of size sh->disks
1442 * @sh - stripe_head to parse
1444 * Populates srcs in proper layout order for the stripe and returns the
1445 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1446 * destination buffer is recorded in srcs[count] and the Q destination
1447 * is recorded in srcs[count+1]].
1449 static int set_syndrome_sources(struct page **srcs,
1450 struct stripe_head *sh,
1453 int disks = sh->disks;
1454 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1455 int d0_idx = raid6_d0(sh);
1459 for (i = 0; i < disks; i++)
1465 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1466 struct r5dev *dev = &sh->dev[i];
1468 if (i == sh->qd_idx || i == sh->pd_idx ||
1469 (srctype == SYNDROME_SRC_ALL) ||
1470 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1471 (test_bit(R5_Wantdrain, &dev->flags) ||
1472 test_bit(R5_InJournal, &dev->flags))) ||
1473 (srctype == SYNDROME_SRC_WRITTEN &&
1475 test_bit(R5_InJournal, &dev->flags)))) {
1476 if (test_bit(R5_InJournal, &dev->flags))
1477 srcs[slot] = sh->dev[i].orig_page;
1479 srcs[slot] = sh->dev[i].page;
1481 i = raid6_next_disk(i, disks);
1482 } while (i != d0_idx);
1484 return syndrome_disks;
1487 static struct dma_async_tx_descriptor *
1488 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1490 int disks = sh->disks;
1491 struct page **blocks = to_addr_page(percpu, 0);
1493 int qd_idx = sh->qd_idx;
1494 struct dma_async_tx_descriptor *tx;
1495 struct async_submit_ctl submit;
1501 BUG_ON(sh->batch_head);
1502 if (sh->ops.target < 0)
1503 target = sh->ops.target2;
1504 else if (sh->ops.target2 < 0)
1505 target = sh->ops.target;
1507 /* we should only have one valid target */
1510 pr_debug("%s: stripe %llu block: %d\n",
1511 __func__, (unsigned long long)sh->sector, target);
1513 tgt = &sh->dev[target];
1514 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1517 atomic_inc(&sh->count);
1519 if (target == qd_idx) {
1520 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1521 blocks[count] = NULL; /* regenerating p is not necessary */
1522 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1523 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1524 ops_complete_compute, sh,
1525 to_addr_conv(sh, percpu, 0));
1526 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1528 /* Compute any data- or p-drive using XOR */
1530 for (i = disks; i-- ; ) {
1531 if (i == target || i == qd_idx)
1533 blocks[count++] = sh->dev[i].page;
1536 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1537 NULL, ops_complete_compute, sh,
1538 to_addr_conv(sh, percpu, 0));
1539 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1545 static struct dma_async_tx_descriptor *
1546 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1548 int i, count, disks = sh->disks;
1549 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1550 int d0_idx = raid6_d0(sh);
1551 int faila = -1, failb = -1;
1552 int target = sh->ops.target;
1553 int target2 = sh->ops.target2;
1554 struct r5dev *tgt = &sh->dev[target];
1555 struct r5dev *tgt2 = &sh->dev[target2];
1556 struct dma_async_tx_descriptor *tx;
1557 struct page **blocks = to_addr_page(percpu, 0);
1558 struct async_submit_ctl submit;
1560 BUG_ON(sh->batch_head);
1561 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1562 __func__, (unsigned long long)sh->sector, target, target2);
1563 BUG_ON(target < 0 || target2 < 0);
1564 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1565 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1567 /* we need to open-code set_syndrome_sources to handle the
1568 * slot number conversion for 'faila' and 'failb'
1570 for (i = 0; i < disks ; i++)
1575 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1577 blocks[slot] = sh->dev[i].page;
1583 i = raid6_next_disk(i, disks);
1584 } while (i != d0_idx);
1586 BUG_ON(faila == failb);
1589 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1590 __func__, (unsigned long long)sh->sector, faila, failb);
1592 atomic_inc(&sh->count);
1594 if (failb == syndrome_disks+1) {
1595 /* Q disk is one of the missing disks */
1596 if (faila == syndrome_disks) {
1597 /* Missing P+Q, just recompute */
1598 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1599 ops_complete_compute, sh,
1600 to_addr_conv(sh, percpu, 0));
1601 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1602 STRIPE_SIZE, &submit);
1606 int qd_idx = sh->qd_idx;
1608 /* Missing D+Q: recompute D from P, then recompute Q */
1609 if (target == qd_idx)
1610 data_target = target2;
1612 data_target = target;
1615 for (i = disks; i-- ; ) {
1616 if (i == data_target || i == qd_idx)
1618 blocks[count++] = sh->dev[i].page;
1620 dest = sh->dev[data_target].page;
1621 init_async_submit(&submit,
1622 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1624 to_addr_conv(sh, percpu, 0));
1625 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1628 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1629 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1630 ops_complete_compute, sh,
1631 to_addr_conv(sh, percpu, 0));
1632 return async_gen_syndrome(blocks, 0, count+2,
1633 STRIPE_SIZE, &submit);
1636 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1637 ops_complete_compute, sh,
1638 to_addr_conv(sh, percpu, 0));
1639 if (failb == syndrome_disks) {
1640 /* We're missing D+P. */
1641 return async_raid6_datap_recov(syndrome_disks+2,
1645 /* We're missing D+D. */
1646 return async_raid6_2data_recov(syndrome_disks+2,
1647 STRIPE_SIZE, faila, failb,
1653 static void ops_complete_prexor(void *stripe_head_ref)
1655 struct stripe_head *sh = stripe_head_ref;
1657 pr_debug("%s: stripe %llu\n", __func__,
1658 (unsigned long long)sh->sector);
1660 if (r5c_is_writeback(sh->raid_conf->log))
1662 * raid5-cache write back uses orig_page during prexor.
1663 * After prexor, it is time to free orig_page
1665 r5c_release_extra_page(sh);
1668 static struct dma_async_tx_descriptor *
1669 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1670 struct dma_async_tx_descriptor *tx)
1672 int disks = sh->disks;
1673 struct page **xor_srcs = to_addr_page(percpu, 0);
1674 int count = 0, pd_idx = sh->pd_idx, i;
1675 struct async_submit_ctl submit;
1677 /* existing parity data subtracted */
1678 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1680 BUG_ON(sh->batch_head);
1681 pr_debug("%s: stripe %llu\n", __func__,
1682 (unsigned long long)sh->sector);
1684 for (i = disks; i--; ) {
1685 struct r5dev *dev = &sh->dev[i];
1686 /* Only process blocks that are known to be uptodate */
1687 if (test_bit(R5_InJournal, &dev->flags))
1688 xor_srcs[count++] = dev->orig_page;
1689 else if (test_bit(R5_Wantdrain, &dev->flags))
1690 xor_srcs[count++] = dev->page;
1693 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1694 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1695 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1700 static struct dma_async_tx_descriptor *
1701 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1702 struct dma_async_tx_descriptor *tx)
1704 struct page **blocks = to_addr_page(percpu, 0);
1706 struct async_submit_ctl submit;
1708 pr_debug("%s: stripe %llu\n", __func__,
1709 (unsigned long long)sh->sector);
1711 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1713 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1714 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1715 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1720 static struct dma_async_tx_descriptor *
1721 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1723 struct r5conf *conf = sh->raid_conf;
1724 int disks = sh->disks;
1726 struct stripe_head *head_sh = sh;
1728 pr_debug("%s: stripe %llu\n", __func__,
1729 (unsigned long long)sh->sector);
1731 for (i = disks; i--; ) {
1736 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1742 * clear R5_InJournal, so when rewriting a page in
1743 * journal, it is not skipped by r5l_log_stripe()
1745 clear_bit(R5_InJournal, &dev->flags);
1746 spin_lock_irq(&sh->stripe_lock);
1747 chosen = dev->towrite;
1748 dev->towrite = NULL;
1749 sh->overwrite_disks = 0;
1750 BUG_ON(dev->written);
1751 wbi = dev->written = chosen;
1752 spin_unlock_irq(&sh->stripe_lock);
1753 WARN_ON(dev->page != dev->orig_page);
1755 while (wbi && wbi->bi_iter.bi_sector <
1756 dev->sector + STRIPE_SECTORS) {
1757 if (wbi->bi_opf & REQ_FUA)
1758 set_bit(R5_WantFUA, &dev->flags);
1759 if (wbi->bi_opf & REQ_SYNC)
1760 set_bit(R5_SyncIO, &dev->flags);
1761 if (bio_op(wbi) == REQ_OP_DISCARD)
1762 set_bit(R5_Discard, &dev->flags);
1764 tx = async_copy_data(1, wbi, &dev->page,
1765 dev->sector, tx, sh,
1766 r5c_is_writeback(conf->log));
1767 if (dev->page != dev->orig_page &&
1768 !r5c_is_writeback(conf->log)) {
1769 set_bit(R5_SkipCopy, &dev->flags);
1770 clear_bit(R5_UPTODATE, &dev->flags);
1771 clear_bit(R5_OVERWRITE, &dev->flags);
1774 wbi = r5_next_bio(wbi, dev->sector);
1777 if (head_sh->batch_head) {
1778 sh = list_first_entry(&sh->batch_list,
1791 static void ops_complete_reconstruct(void *stripe_head_ref)
1793 struct stripe_head *sh = stripe_head_ref;
1794 int disks = sh->disks;
1795 int pd_idx = sh->pd_idx;
1796 int qd_idx = sh->qd_idx;
1798 bool fua = false, sync = false, discard = false;
1800 pr_debug("%s: stripe %llu\n", __func__,
1801 (unsigned long long)sh->sector);
1803 for (i = disks; i--; ) {
1804 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1805 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1806 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1809 for (i = disks; i--; ) {
1810 struct r5dev *dev = &sh->dev[i];
1812 if (dev->written || i == pd_idx || i == qd_idx) {
1813 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1814 set_bit(R5_UPTODATE, &dev->flags);
1815 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1816 set_bit(R5_Expanded, &dev->flags);
1819 set_bit(R5_WantFUA, &dev->flags);
1821 set_bit(R5_SyncIO, &dev->flags);
1825 if (sh->reconstruct_state == reconstruct_state_drain_run)
1826 sh->reconstruct_state = reconstruct_state_drain_result;
1827 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1828 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1830 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1831 sh->reconstruct_state = reconstruct_state_result;
1834 set_bit(STRIPE_HANDLE, &sh->state);
1835 raid5_release_stripe(sh);
1839 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1840 struct dma_async_tx_descriptor *tx)
1842 int disks = sh->disks;
1843 struct page **xor_srcs;
1844 struct async_submit_ctl submit;
1845 int count, pd_idx = sh->pd_idx, i;
1846 struct page *xor_dest;
1848 unsigned long flags;
1850 struct stripe_head *head_sh = sh;
1853 pr_debug("%s: stripe %llu\n", __func__,
1854 (unsigned long long)sh->sector);
1856 for (i = 0; i < sh->disks; i++) {
1859 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1862 if (i >= sh->disks) {
1863 atomic_inc(&sh->count);
1864 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1865 ops_complete_reconstruct(sh);
1870 xor_srcs = to_addr_page(percpu, j);
1871 /* check if prexor is active which means only process blocks
1872 * that are part of a read-modify-write (written)
1874 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1876 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1877 for (i = disks; i--; ) {
1878 struct r5dev *dev = &sh->dev[i];
1879 if (head_sh->dev[i].written ||
1880 test_bit(R5_InJournal, &head_sh->dev[i].flags))
1881 xor_srcs[count++] = dev->page;
1884 xor_dest = sh->dev[pd_idx].page;
1885 for (i = disks; i--; ) {
1886 struct r5dev *dev = &sh->dev[i];
1888 xor_srcs[count++] = dev->page;
1892 /* 1/ if we prexor'd then the dest is reused as a source
1893 * 2/ if we did not prexor then we are redoing the parity
1894 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1895 * for the synchronous xor case
1897 last_stripe = !head_sh->batch_head ||
1898 list_first_entry(&sh->batch_list,
1899 struct stripe_head, batch_list) == head_sh;
1901 flags = ASYNC_TX_ACK |
1902 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1904 atomic_inc(&head_sh->count);
1905 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1906 to_addr_conv(sh, percpu, j));
1908 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1909 init_async_submit(&submit, flags, tx, NULL, NULL,
1910 to_addr_conv(sh, percpu, j));
1913 if (unlikely(count == 1))
1914 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1916 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1919 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1926 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1927 struct dma_async_tx_descriptor *tx)
1929 struct async_submit_ctl submit;
1930 struct page **blocks;
1931 int count, i, j = 0;
1932 struct stripe_head *head_sh = sh;
1935 unsigned long txflags;
1937 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1939 for (i = 0; i < sh->disks; i++) {
1940 if (sh->pd_idx == i || sh->qd_idx == i)
1942 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1945 if (i >= sh->disks) {
1946 atomic_inc(&sh->count);
1947 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1948 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1949 ops_complete_reconstruct(sh);
1954 blocks = to_addr_page(percpu, j);
1956 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1957 synflags = SYNDROME_SRC_WRITTEN;
1958 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1960 synflags = SYNDROME_SRC_ALL;
1961 txflags = ASYNC_TX_ACK;
1964 count = set_syndrome_sources(blocks, sh, synflags);
1965 last_stripe = !head_sh->batch_head ||
1966 list_first_entry(&sh->batch_list,
1967 struct stripe_head, batch_list) == head_sh;
1970 atomic_inc(&head_sh->count);
1971 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1972 head_sh, to_addr_conv(sh, percpu, j));
1974 init_async_submit(&submit, 0, tx, NULL, NULL,
1975 to_addr_conv(sh, percpu, j));
1976 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1979 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1985 static void ops_complete_check(void *stripe_head_ref)
1987 struct stripe_head *sh = stripe_head_ref;
1989 pr_debug("%s: stripe %llu\n", __func__,
1990 (unsigned long long)sh->sector);
1992 sh->check_state = check_state_check_result;
1993 set_bit(STRIPE_HANDLE, &sh->state);
1994 raid5_release_stripe(sh);
1997 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1999 int disks = sh->disks;
2000 int pd_idx = sh->pd_idx;
2001 int qd_idx = sh->qd_idx;
2002 struct page *xor_dest;
2003 struct page **xor_srcs = to_addr_page(percpu, 0);
2004 struct dma_async_tx_descriptor *tx;
2005 struct async_submit_ctl submit;
2009 pr_debug("%s: stripe %llu\n", __func__,
2010 (unsigned long long)sh->sector);
2012 BUG_ON(sh->batch_head);
2014 xor_dest = sh->dev[pd_idx].page;
2015 xor_srcs[count++] = xor_dest;
2016 for (i = disks; i--; ) {
2017 if (i == pd_idx || i == qd_idx)
2019 xor_srcs[count++] = sh->dev[i].page;
2022 init_async_submit(&submit, 0, NULL, NULL, NULL,
2023 to_addr_conv(sh, percpu, 0));
2024 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
2025 &sh->ops.zero_sum_result, &submit);
2027 atomic_inc(&sh->count);
2028 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2029 tx = async_trigger_callback(&submit);
2032 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2034 struct page **srcs = to_addr_page(percpu, 0);
2035 struct async_submit_ctl submit;
2038 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2039 (unsigned long long)sh->sector, checkp);
2041 BUG_ON(sh->batch_head);
2042 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
2046 atomic_inc(&sh->count);
2047 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2048 sh, to_addr_conv(sh, percpu, 0));
2049 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
2050 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
2053 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2055 int overlap_clear = 0, i, disks = sh->disks;
2056 struct dma_async_tx_descriptor *tx = NULL;
2057 struct r5conf *conf = sh->raid_conf;
2058 int level = conf->level;
2059 struct raid5_percpu *percpu;
2063 percpu = per_cpu_ptr(conf->percpu, cpu);
2064 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2065 ops_run_biofill(sh);
2069 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2071 tx = ops_run_compute5(sh, percpu);
2073 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2074 tx = ops_run_compute6_1(sh, percpu);
2076 tx = ops_run_compute6_2(sh, percpu);
2078 /* terminate the chain if reconstruct is not set to be run */
2079 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2083 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2085 tx = ops_run_prexor5(sh, percpu, tx);
2087 tx = ops_run_prexor6(sh, percpu, tx);
2090 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2091 tx = ops_run_partial_parity(sh, percpu, tx);
2093 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2094 tx = ops_run_biodrain(sh, tx);
2098 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2100 ops_run_reconstruct5(sh, percpu, tx);
2102 ops_run_reconstruct6(sh, percpu, tx);
2105 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2106 if (sh->check_state == check_state_run)
2107 ops_run_check_p(sh, percpu);
2108 else if (sh->check_state == check_state_run_q)
2109 ops_run_check_pq(sh, percpu, 0);
2110 else if (sh->check_state == check_state_run_pq)
2111 ops_run_check_pq(sh, percpu, 1);
2116 if (overlap_clear && !sh->batch_head)
2117 for (i = disks; i--; ) {
2118 struct r5dev *dev = &sh->dev[i];
2119 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2120 wake_up(&sh->raid_conf->wait_for_overlap);
2125 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2128 __free_page(sh->ppl_page);
2129 kmem_cache_free(sc, sh);
2132 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2133 int disks, struct r5conf *conf)
2135 struct stripe_head *sh;
2138 sh = kmem_cache_zalloc(sc, gfp);
2140 spin_lock_init(&sh->stripe_lock);
2141 spin_lock_init(&sh->batch_lock);
2142 INIT_LIST_HEAD(&sh->batch_list);
2143 INIT_LIST_HEAD(&sh->lru);
2144 INIT_LIST_HEAD(&sh->r5c);
2145 INIT_LIST_HEAD(&sh->log_list);
2146 atomic_set(&sh->count, 1);
2147 sh->raid_conf = conf;
2148 sh->log_start = MaxSector;
2149 for (i = 0; i < disks; i++) {
2150 struct r5dev *dev = &sh->dev[i];
2152 bio_init(&dev->req, &dev->vec, 1);
2153 bio_init(&dev->rreq, &dev->rvec, 1);
2156 if (raid5_has_ppl(conf)) {
2157 sh->ppl_page = alloc_page(gfp);
2158 if (!sh->ppl_page) {
2159 free_stripe(sc, sh);
2166 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2168 struct stripe_head *sh;
2170 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2174 if (grow_buffers(sh, gfp)) {
2176 free_stripe(conf->slab_cache, sh);
2179 sh->hash_lock_index =
2180 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2181 /* we just created an active stripe so... */
2182 atomic_inc(&conf->active_stripes);
2184 raid5_release_stripe(sh);
2185 conf->max_nr_stripes++;
2189 static int grow_stripes(struct r5conf *conf, int num)
2191 struct kmem_cache *sc;
2192 size_t namelen = sizeof(conf->cache_name[0]);
2193 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2195 if (conf->mddev->gendisk)
2196 snprintf(conf->cache_name[0], namelen,
2197 "raid%d-%s", conf->level, mdname(conf->mddev));
2199 snprintf(conf->cache_name[0], namelen,
2200 "raid%d-%p", conf->level, conf->mddev);
2201 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2203 conf->active_name = 0;
2204 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2205 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2209 conf->slab_cache = sc;
2210 conf->pool_size = devs;
2212 if (!grow_one_stripe(conf, GFP_KERNEL))
2219 * scribble_len - return the required size of the scribble region
2220 * @num - total number of disks in the array
2222 * The size must be enough to contain:
2223 * 1/ a struct page pointer for each device in the array +2
2224 * 2/ room to convert each entry in (1) to its corresponding dma
2225 * (dma_map_page()) or page (page_address()) address.
2227 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2228 * calculate over all devices (not just the data blocks), using zeros in place
2229 * of the P and Q blocks.
2231 static int scribble_alloc(struct raid5_percpu *percpu,
2235 sizeof(struct page *) * (num+2) +
2236 sizeof(addr_conv_t) * (num+2);
2240 * If here is in raid array suspend context, it is in memalloc noio
2241 * context as well, there is no potential recursive memory reclaim
2242 * I/Os with the GFP_KERNEL flag.
2244 scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2248 kvfree(percpu->scribble);
2250 percpu->scribble = scribble;
2251 percpu->scribble_obj_size = obj_size;
2255 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2261 * Never shrink. And mddev_suspend() could deadlock if this is called
2262 * from raid5d. In that case, scribble_disks and scribble_sectors
2263 * should equal to new_disks and new_sectors
2265 if (conf->scribble_disks >= new_disks &&
2266 conf->scribble_sectors >= new_sectors)
2268 mddev_suspend(conf->mddev);
2271 for_each_present_cpu(cpu) {
2272 struct raid5_percpu *percpu;
2274 percpu = per_cpu_ptr(conf->percpu, cpu);
2275 err = scribble_alloc(percpu, new_disks,
2276 new_sectors / STRIPE_SECTORS);
2282 mddev_resume(conf->mddev);
2284 conf->scribble_disks = new_disks;
2285 conf->scribble_sectors = new_sectors;
2290 static int resize_stripes(struct r5conf *conf, int newsize)
2292 /* Make all the stripes able to hold 'newsize' devices.
2293 * New slots in each stripe get 'page' set to a new page.
2295 * This happens in stages:
2296 * 1/ create a new kmem_cache and allocate the required number of
2298 * 2/ gather all the old stripe_heads and transfer the pages across
2299 * to the new stripe_heads. This will have the side effect of
2300 * freezing the array as once all stripe_heads have been collected,
2301 * no IO will be possible. Old stripe heads are freed once their
2302 * pages have been transferred over, and the old kmem_cache is
2303 * freed when all stripes are done.
2304 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2305 * we simple return a failure status - no need to clean anything up.
2306 * 4/ allocate new pages for the new slots in the new stripe_heads.
2307 * If this fails, we don't bother trying the shrink the
2308 * stripe_heads down again, we just leave them as they are.
2309 * As each stripe_head is processed the new one is released into
2312 * Once step2 is started, we cannot afford to wait for a write,
2313 * so we use GFP_NOIO allocations.
2315 struct stripe_head *osh, *nsh;
2316 LIST_HEAD(newstripes);
2317 struct disk_info *ndisks;
2319 struct kmem_cache *sc;
2323 md_allow_write(conf->mddev);
2326 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2327 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2332 /* Need to ensure auto-resizing doesn't interfere */
2333 mutex_lock(&conf->cache_size_mutex);
2335 for (i = conf->max_nr_stripes; i; i--) {
2336 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2340 list_add(&nsh->lru, &newstripes);
2343 /* didn't get enough, give up */
2344 while (!list_empty(&newstripes)) {
2345 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2346 list_del(&nsh->lru);
2347 free_stripe(sc, nsh);
2349 kmem_cache_destroy(sc);
2350 mutex_unlock(&conf->cache_size_mutex);
2353 /* Step 2 - Must use GFP_NOIO now.
2354 * OK, we have enough stripes, start collecting inactive
2355 * stripes and copying them over
2359 list_for_each_entry(nsh, &newstripes, lru) {
2360 lock_device_hash_lock(conf, hash);
2361 wait_event_cmd(conf->wait_for_stripe,
2362 !list_empty(conf->inactive_list + hash),
2363 unlock_device_hash_lock(conf, hash),
2364 lock_device_hash_lock(conf, hash));
2365 osh = get_free_stripe(conf, hash);
2366 unlock_device_hash_lock(conf, hash);
2368 for(i=0; i<conf->pool_size; i++) {
2369 nsh->dev[i].page = osh->dev[i].page;
2370 nsh->dev[i].orig_page = osh->dev[i].page;
2372 nsh->hash_lock_index = hash;
2373 free_stripe(conf->slab_cache, osh);
2375 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2376 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2381 kmem_cache_destroy(conf->slab_cache);
2384 * At this point, we are holding all the stripes so the array
2385 * is completely stalled, so now is a good time to resize
2386 * conf->disks and the scribble region
2388 ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2390 for (i = 0; i < conf->pool_size; i++)
2391 ndisks[i] = conf->disks[i];
2393 for (i = conf->pool_size; i < newsize; i++) {
2394 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2395 if (!ndisks[i].extra_page)
2400 for (i = conf->pool_size; i < newsize; i++)
2401 if (ndisks[i].extra_page)
2402 put_page(ndisks[i].extra_page);
2406 conf->disks = ndisks;
2411 conf->slab_cache = sc;
2412 conf->active_name = 1-conf->active_name;
2414 /* Step 4, return new stripes to service */
2415 while(!list_empty(&newstripes)) {
2416 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2417 list_del_init(&nsh->lru);
2419 for (i=conf->raid_disks; i < newsize; i++)
2420 if (nsh->dev[i].page == NULL) {
2421 struct page *p = alloc_page(GFP_NOIO);
2422 nsh->dev[i].page = p;
2423 nsh->dev[i].orig_page = p;
2427 raid5_release_stripe(nsh);
2429 /* critical section pass, GFP_NOIO no longer needed */
2432 conf->pool_size = newsize;
2433 mutex_unlock(&conf->cache_size_mutex);
2438 static int drop_one_stripe(struct r5conf *conf)
2440 struct stripe_head *sh;
2441 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2443 spin_lock_irq(conf->hash_locks + hash);
2444 sh = get_free_stripe(conf, hash);
2445 spin_unlock_irq(conf->hash_locks + hash);
2448 BUG_ON(atomic_read(&sh->count));
2450 free_stripe(conf->slab_cache, sh);
2451 atomic_dec(&conf->active_stripes);
2452 conf->max_nr_stripes--;
2456 static void shrink_stripes(struct r5conf *conf)
2458 while (conf->max_nr_stripes &&
2459 drop_one_stripe(conf))
2462 kmem_cache_destroy(conf->slab_cache);
2463 conf->slab_cache = NULL;
2466 static void raid5_end_read_request(struct bio * bi)
2468 struct stripe_head *sh = bi->bi_private;
2469 struct r5conf *conf = sh->raid_conf;
2470 int disks = sh->disks, i;
2471 char b[BDEVNAME_SIZE];
2472 struct md_rdev *rdev = NULL;
2475 for (i=0 ; i<disks; i++)
2476 if (bi == &sh->dev[i].req)
2479 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2480 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2487 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2488 /* If replacement finished while this request was outstanding,
2489 * 'replacement' might be NULL already.
2490 * In that case it moved down to 'rdev'.
2491 * rdev is not removed until all requests are finished.
2493 rdev = conf->disks[i].replacement;
2495 rdev = conf->disks[i].rdev;
2497 if (use_new_offset(conf, sh))
2498 s = sh->sector + rdev->new_data_offset;
2500 s = sh->sector + rdev->data_offset;
2501 if (!bi->bi_status) {
2502 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2503 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2504 /* Note that this cannot happen on a
2505 * replacement device. We just fail those on
2508 pr_info_ratelimited(
2509 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2510 mdname(conf->mddev), STRIPE_SECTORS,
2511 (unsigned long long)s,
2512 bdevname(rdev->bdev, b));
2513 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2514 clear_bit(R5_ReadError, &sh->dev[i].flags);
2515 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2516 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2517 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2519 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2521 * end read for a page in journal, this
2522 * must be preparing for prexor in rmw
2524 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2526 if (atomic_read(&rdev->read_errors))
2527 atomic_set(&rdev->read_errors, 0);
2529 const char *bdn = bdevname(rdev->bdev, b);
2533 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2534 if (!(bi->bi_status == BLK_STS_PROTECTION))
2535 atomic_inc(&rdev->read_errors);
2536 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2537 pr_warn_ratelimited(
2538 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2539 mdname(conf->mddev),
2540 (unsigned long long)s,
2542 else if (conf->mddev->degraded >= conf->max_degraded) {
2544 pr_warn_ratelimited(
2545 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2546 mdname(conf->mddev),
2547 (unsigned long long)s,
2549 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2552 pr_warn_ratelimited(
2553 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2554 mdname(conf->mddev),
2555 (unsigned long long)s,
2557 } else if (atomic_read(&rdev->read_errors)
2558 > conf->max_nr_stripes) {
2559 if (!test_bit(Faulty, &rdev->flags)) {
2560 pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2561 mdname(conf->mddev),
2562 atomic_read(&rdev->read_errors),
2563 conf->max_nr_stripes);
2564 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2565 mdname(conf->mddev), bdn);
2569 if (set_bad && test_bit(In_sync, &rdev->flags)
2570 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2573 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2574 set_bit(R5_ReadError, &sh->dev[i].flags);
2575 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2576 set_bit(R5_ReadError, &sh->dev[i].flags);
2577 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2579 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2581 clear_bit(R5_ReadError, &sh->dev[i].flags);
2582 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2584 && test_bit(In_sync, &rdev->flags)
2585 && rdev_set_badblocks(
2586 rdev, sh->sector, STRIPE_SECTORS, 0)))
2587 md_error(conf->mddev, rdev);
2590 rdev_dec_pending(rdev, conf->mddev);
2592 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2593 set_bit(STRIPE_HANDLE, &sh->state);
2594 raid5_release_stripe(sh);
2597 static void raid5_end_write_request(struct bio *bi)
2599 struct stripe_head *sh = bi->bi_private;
2600 struct r5conf *conf = sh->raid_conf;
2601 int disks = sh->disks, i;
2602 struct md_rdev *uninitialized_var(rdev);
2605 int replacement = 0;
2607 for (i = 0 ; i < disks; i++) {
2608 if (bi == &sh->dev[i].req) {
2609 rdev = conf->disks[i].rdev;
2612 if (bi == &sh->dev[i].rreq) {
2613 rdev = conf->disks[i].replacement;
2617 /* rdev was removed and 'replacement'
2618 * replaced it. rdev is not removed
2619 * until all requests are finished.
2621 rdev = conf->disks[i].rdev;
2625 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2626 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2636 md_error(conf->mddev, rdev);
2637 else if (is_badblock(rdev, sh->sector,
2639 &first_bad, &bad_sectors))
2640 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2642 if (bi->bi_status) {
2643 set_bit(STRIPE_DEGRADED, &sh->state);
2644 set_bit(WriteErrorSeen, &rdev->flags);
2645 set_bit(R5_WriteError, &sh->dev[i].flags);
2646 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2647 set_bit(MD_RECOVERY_NEEDED,
2648 &rdev->mddev->recovery);
2649 } else if (is_badblock(rdev, sh->sector,
2651 &first_bad, &bad_sectors)) {
2652 set_bit(R5_MadeGood, &sh->dev[i].flags);
2653 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2654 /* That was a successful write so make
2655 * sure it looks like we already did
2658 set_bit(R5_ReWrite, &sh->dev[i].flags);
2661 rdev_dec_pending(rdev, conf->mddev);
2663 if (sh->batch_head && bi->bi_status && !replacement)
2664 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2667 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2668 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2669 set_bit(STRIPE_HANDLE, &sh->state);
2671 if (sh->batch_head && sh != sh->batch_head)
2672 raid5_release_stripe(sh->batch_head);
2673 raid5_release_stripe(sh);
2676 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2678 char b[BDEVNAME_SIZE];
2679 struct r5conf *conf = mddev->private;
2680 unsigned long flags;
2681 pr_debug("raid456: error called\n");
2683 pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n",
2684 mdname(mddev), bdevname(rdev->bdev, b));
2686 spin_lock_irqsave(&conf->device_lock, flags);
2687 set_bit(Faulty, &rdev->flags);
2688 clear_bit(In_sync, &rdev->flags);
2689 mddev->degraded = raid5_calc_degraded(conf);
2691 if (has_failed(conf)) {
2692 set_bit(MD_BROKEN, &conf->mddev->flags);
2693 conf->recovery_disabled = mddev->recovery_disabled;
2695 pr_crit("md/raid:%s: Cannot continue operation (%d/%d failed).\n",
2696 mdname(mddev), mddev->degraded, conf->raid_disks);
2698 pr_crit("md/raid:%s: Operation continuing on %d devices.\n",
2699 mdname(mddev), conf->raid_disks - mddev->degraded);
2702 spin_unlock_irqrestore(&conf->device_lock, flags);
2703 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2705 set_bit(Blocked, &rdev->flags);
2706 set_mask_bits(&mddev->sb_flags, 0,
2707 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2708 r5c_update_on_rdev_error(mddev, rdev);
2712 * Input: a 'big' sector number,
2713 * Output: index of the data and parity disk, and the sector # in them.
2715 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2716 int previous, int *dd_idx,
2717 struct stripe_head *sh)
2719 sector_t stripe, stripe2;
2720 sector_t chunk_number;
2721 unsigned int chunk_offset;
2724 sector_t new_sector;
2725 int algorithm = previous ? conf->prev_algo
2727 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2728 : conf->chunk_sectors;
2729 int raid_disks = previous ? conf->previous_raid_disks
2731 int data_disks = raid_disks - conf->max_degraded;
2733 /* First compute the information on this sector */
2736 * Compute the chunk number and the sector offset inside the chunk
2738 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2739 chunk_number = r_sector;
2742 * Compute the stripe number
2744 stripe = chunk_number;
2745 *dd_idx = sector_div(stripe, data_disks);
2748 * Select the parity disk based on the user selected algorithm.
2750 pd_idx = qd_idx = -1;
2751 switch(conf->level) {
2753 pd_idx = data_disks;
2756 switch (algorithm) {
2757 case ALGORITHM_LEFT_ASYMMETRIC:
2758 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2759 if (*dd_idx >= pd_idx)
2762 case ALGORITHM_RIGHT_ASYMMETRIC:
2763 pd_idx = sector_div(stripe2, raid_disks);
2764 if (*dd_idx >= pd_idx)
2767 case ALGORITHM_LEFT_SYMMETRIC:
2768 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2769 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2771 case ALGORITHM_RIGHT_SYMMETRIC:
2772 pd_idx = sector_div(stripe2, raid_disks);
2773 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2775 case ALGORITHM_PARITY_0:
2779 case ALGORITHM_PARITY_N:
2780 pd_idx = data_disks;
2788 switch (algorithm) {
2789 case ALGORITHM_LEFT_ASYMMETRIC:
2790 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2791 qd_idx = pd_idx + 1;
2792 if (pd_idx == raid_disks-1) {
2793 (*dd_idx)++; /* Q D D D P */
2795 } else if (*dd_idx >= pd_idx)
2796 (*dd_idx) += 2; /* D D P Q D */
2798 case ALGORITHM_RIGHT_ASYMMETRIC:
2799 pd_idx = sector_div(stripe2, raid_disks);
2800 qd_idx = pd_idx + 1;
2801 if (pd_idx == raid_disks-1) {
2802 (*dd_idx)++; /* Q D D D P */
2804 } else if (*dd_idx >= pd_idx)
2805 (*dd_idx) += 2; /* D D P Q D */
2807 case ALGORITHM_LEFT_SYMMETRIC:
2808 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2809 qd_idx = (pd_idx + 1) % raid_disks;
2810 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2812 case ALGORITHM_RIGHT_SYMMETRIC:
2813 pd_idx = sector_div(stripe2, raid_disks);
2814 qd_idx = (pd_idx + 1) % raid_disks;
2815 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2818 case ALGORITHM_PARITY_0:
2823 case ALGORITHM_PARITY_N:
2824 pd_idx = data_disks;
2825 qd_idx = data_disks + 1;
2828 case ALGORITHM_ROTATING_ZERO_RESTART:
2829 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2830 * of blocks for computing Q is different.
2832 pd_idx = sector_div(stripe2, raid_disks);
2833 qd_idx = pd_idx + 1;
2834 if (pd_idx == raid_disks-1) {
2835 (*dd_idx)++; /* Q D D D P */
2837 } else if (*dd_idx >= pd_idx)
2838 (*dd_idx) += 2; /* D D P Q D */
2842 case ALGORITHM_ROTATING_N_RESTART:
2843 /* Same a left_asymmetric, by first stripe is
2844 * D D D P Q rather than
2848 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2849 qd_idx = pd_idx + 1;
2850 if (pd_idx == raid_disks-1) {
2851 (*dd_idx)++; /* Q D D D P */
2853 } else if (*dd_idx >= pd_idx)
2854 (*dd_idx) += 2; /* D D P Q D */
2858 case ALGORITHM_ROTATING_N_CONTINUE:
2859 /* Same as left_symmetric but Q is before P */
2860 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2861 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2862 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2866 case ALGORITHM_LEFT_ASYMMETRIC_6:
2867 /* RAID5 left_asymmetric, with Q on last device */
2868 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2869 if (*dd_idx >= pd_idx)
2871 qd_idx = raid_disks - 1;
2874 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2875 pd_idx = sector_div(stripe2, raid_disks-1);
2876 if (*dd_idx >= pd_idx)
2878 qd_idx = raid_disks - 1;
2881 case ALGORITHM_LEFT_SYMMETRIC_6:
2882 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2883 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2884 qd_idx = raid_disks - 1;
2887 case ALGORITHM_RIGHT_SYMMETRIC_6:
2888 pd_idx = sector_div(stripe2, raid_disks-1);
2889 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2890 qd_idx = raid_disks - 1;
2893 case ALGORITHM_PARITY_0_6:
2896 qd_idx = raid_disks - 1;
2906 sh->pd_idx = pd_idx;
2907 sh->qd_idx = qd_idx;
2908 sh->ddf_layout = ddf_layout;
2911 * Finally, compute the new sector number
2913 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2917 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2919 struct r5conf *conf = sh->raid_conf;
2920 int raid_disks = sh->disks;
2921 int data_disks = raid_disks - conf->max_degraded;
2922 sector_t new_sector = sh->sector, check;
2923 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2924 : conf->chunk_sectors;
2925 int algorithm = previous ? conf->prev_algo
2929 sector_t chunk_number;
2930 int dummy1, dd_idx = i;
2932 struct stripe_head sh2;
2934 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2935 stripe = new_sector;
2937 if (i == sh->pd_idx)
2939 switch(conf->level) {
2942 switch (algorithm) {
2943 case ALGORITHM_LEFT_ASYMMETRIC:
2944 case ALGORITHM_RIGHT_ASYMMETRIC:
2948 case ALGORITHM_LEFT_SYMMETRIC:
2949 case ALGORITHM_RIGHT_SYMMETRIC:
2952 i -= (sh->pd_idx + 1);
2954 case ALGORITHM_PARITY_0:
2957 case ALGORITHM_PARITY_N:
2964 if (i == sh->qd_idx)
2965 return 0; /* It is the Q disk */
2966 switch (algorithm) {
2967 case ALGORITHM_LEFT_ASYMMETRIC:
2968 case ALGORITHM_RIGHT_ASYMMETRIC:
2969 case ALGORITHM_ROTATING_ZERO_RESTART:
2970 case ALGORITHM_ROTATING_N_RESTART:
2971 if (sh->pd_idx == raid_disks-1)
2972 i--; /* Q D D D P */
2973 else if (i > sh->pd_idx)
2974 i -= 2; /* D D P Q D */
2976 case ALGORITHM_LEFT_SYMMETRIC:
2977 case ALGORITHM_RIGHT_SYMMETRIC:
2978 if (sh->pd_idx == raid_disks-1)
2979 i--; /* Q D D D P */
2984 i -= (sh->pd_idx + 2);
2987 case ALGORITHM_PARITY_0:
2990 case ALGORITHM_PARITY_N:
2992 case ALGORITHM_ROTATING_N_CONTINUE:
2993 /* Like left_symmetric, but P is before Q */
2994 if (sh->pd_idx == 0)
2995 i--; /* P D D D Q */
3000 i -= (sh->pd_idx + 1);
3003 case ALGORITHM_LEFT_ASYMMETRIC_6:
3004 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3008 case ALGORITHM_LEFT_SYMMETRIC_6:
3009 case ALGORITHM_RIGHT_SYMMETRIC_6:
3011 i += data_disks + 1;
3012 i -= (sh->pd_idx + 1);
3014 case ALGORITHM_PARITY_0_6:
3023 chunk_number = stripe * data_disks + i;
3024 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3026 check = raid5_compute_sector(conf, r_sector,
3027 previous, &dummy1, &sh2);
3028 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3029 || sh2.qd_idx != sh->qd_idx) {
3030 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3031 mdname(conf->mddev));
3038 * There are cases where we want handle_stripe_dirtying() and
3039 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3041 * This function checks whether we want to delay the towrite. Specifically,
3042 * we delay the towrite when:
3044 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3045 * stripe has data in journal (for other devices).
3047 * In this case, when reading data for the non-overwrite dev, it is
3048 * necessary to handle complex rmw of write back cache (prexor with
3049 * orig_page, and xor with page). To keep read path simple, we would
3050 * like to flush data in journal to RAID disks first, so complex rmw
3051 * is handled in the write patch (handle_stripe_dirtying).
3053 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3055 * It is important to be able to flush all stripes in raid5-cache.
3056 * Therefore, we need reserve some space on the journal device for
3057 * these flushes. If flush operation includes pending writes to the
3058 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3059 * for the flush out. If we exclude these pending writes from flush
3060 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3061 * Therefore, excluding pending writes in these cases enables more
3062 * efficient use of the journal device.
3064 * Note: To make sure the stripe makes progress, we only delay
3065 * towrite for stripes with data already in journal (injournal > 0).
3066 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3067 * no_space_stripes list.
3069 * 3. during journal failure
3070 * In journal failure, we try to flush all cached data to raid disks
3071 * based on data in stripe cache. The array is read-only to upper
3072 * layers, so we would skip all pending writes.
3075 static inline bool delay_towrite(struct r5conf *conf,
3077 struct stripe_head_state *s)
3080 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3081 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3084 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3088 if (s->log_failed && s->injournal)
3094 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3095 int rcw, int expand)
3097 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3098 struct r5conf *conf = sh->raid_conf;
3099 int level = conf->level;
3103 * In some cases, handle_stripe_dirtying initially decided to
3104 * run rmw and allocates extra page for prexor. However, rcw is
3105 * cheaper later on. We need to free the extra page now,
3106 * because we won't be able to do that in ops_complete_prexor().
3108 r5c_release_extra_page(sh);
3110 for (i = disks; i--; ) {
3111 struct r5dev *dev = &sh->dev[i];
3113 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3114 set_bit(R5_LOCKED, &dev->flags);
3115 set_bit(R5_Wantdrain, &dev->flags);
3117 clear_bit(R5_UPTODATE, &dev->flags);
3119 } else if (test_bit(R5_InJournal, &dev->flags)) {
3120 set_bit(R5_LOCKED, &dev->flags);
3124 /* if we are not expanding this is a proper write request, and
3125 * there will be bios with new data to be drained into the
3130 /* False alarm, nothing to do */
3132 sh->reconstruct_state = reconstruct_state_drain_run;
3133 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3135 sh->reconstruct_state = reconstruct_state_run;
3137 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3139 if (s->locked + conf->max_degraded == disks)
3140 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3141 atomic_inc(&conf->pending_full_writes);
3143 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3144 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3145 BUG_ON(level == 6 &&
3146 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3147 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3149 for (i = disks; i--; ) {
3150 struct r5dev *dev = &sh->dev[i];
3151 if (i == pd_idx || i == qd_idx)
3155 (test_bit(R5_UPTODATE, &dev->flags) ||
3156 test_bit(R5_Wantcompute, &dev->flags))) {
3157 set_bit(R5_Wantdrain, &dev->flags);
3158 set_bit(R5_LOCKED, &dev->flags);
3159 clear_bit(R5_UPTODATE, &dev->flags);
3161 } else if (test_bit(R5_InJournal, &dev->flags)) {
3162 set_bit(R5_LOCKED, &dev->flags);
3167 /* False alarm - nothing to do */
3169 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3170 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3171 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3172 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3175 /* keep the parity disk(s) locked while asynchronous operations
3178 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3179 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3183 int qd_idx = sh->qd_idx;
3184 struct r5dev *dev = &sh->dev[qd_idx];
3186 set_bit(R5_LOCKED, &dev->flags);
3187 clear_bit(R5_UPTODATE, &dev->flags);
3191 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3192 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3193 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3194 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3195 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3197 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3198 __func__, (unsigned long long)sh->sector,
3199 s->locked, s->ops_request);
3203 * Each stripe/dev can have one or more bion attached.
3204 * toread/towrite point to the first in a chain.
3205 * The bi_next chain must be in order.
3207 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3208 int forwrite, int previous)
3211 struct r5conf *conf = sh->raid_conf;
3214 pr_debug("adding bi b#%llu to stripe s#%llu\n",
3215 (unsigned long long)bi->bi_iter.bi_sector,
3216 (unsigned long long)sh->sector);
3218 spin_lock_irq(&sh->stripe_lock);
3219 sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3220 /* Don't allow new IO added to stripes in batch list */
3224 bip = &sh->dev[dd_idx].towrite;
3228 bip = &sh->dev[dd_idx].toread;
3229 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3230 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3232 bip = & (*bip)->bi_next;
3234 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3237 if (forwrite && raid5_has_ppl(conf)) {
3239 * With PPL only writes to consecutive data chunks within a
3240 * stripe are allowed because for a single stripe_head we can
3241 * only have one PPL entry at a time, which describes one data
3242 * range. Not really an overlap, but wait_for_overlap can be
3243 * used to handle this.
3251 for (i = 0; i < sh->disks; i++) {
3252 if (i != sh->pd_idx &&
3253 (i == dd_idx || sh->dev[i].towrite)) {
3254 sector = sh->dev[i].sector;
3255 if (count == 0 || sector < first)
3263 if (first + conf->chunk_sectors * (count - 1) != last)
3267 if (!forwrite || previous)
3268 clear_bit(STRIPE_BATCH_READY, &sh->state);
3270 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3274 bio_inc_remaining(bi);
3275 md_write_inc(conf->mddev, bi);
3278 /* check if page is covered */
3279 sector_t sector = sh->dev[dd_idx].sector;
3280 for (bi=sh->dev[dd_idx].towrite;
3281 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3282 bi && bi->bi_iter.bi_sector <= sector;
3283 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3284 if (bio_end_sector(bi) >= sector)
3285 sector = bio_end_sector(bi);
3287 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3288 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3289 sh->overwrite_disks++;
3292 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3293 (unsigned long long)(*bip)->bi_iter.bi_sector,
3294 (unsigned long long)sh->sector, dd_idx);
3296 if (conf->mddev->bitmap && firstwrite) {
3297 /* Cannot hold spinlock over bitmap_startwrite,
3298 * but must ensure this isn't added to a batch until
3299 * we have added to the bitmap and set bm_seq.
3300 * So set STRIPE_BITMAP_PENDING to prevent
3302 * If multiple add_stripe_bio() calls race here they
3303 * much all set STRIPE_BITMAP_PENDING. So only the first one
3304 * to complete "bitmap_startwrite" gets to set
3305 * STRIPE_BIT_DELAY. This is important as once a stripe
3306 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3309 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3310 spin_unlock_irq(&sh->stripe_lock);
3311 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3313 spin_lock_irq(&sh->stripe_lock);
3314 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3315 if (!sh->batch_head) {
3316 sh->bm_seq = conf->seq_flush+1;
3317 set_bit(STRIPE_BIT_DELAY, &sh->state);
3320 spin_unlock_irq(&sh->stripe_lock);
3322 if (stripe_can_batch(sh))
3323 stripe_add_to_batch_list(conf, sh);
3327 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3328 spin_unlock_irq(&sh->stripe_lock);
3332 static void end_reshape(struct r5conf *conf);
3334 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3335 struct stripe_head *sh)
3337 int sectors_per_chunk =
3338 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3340 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3341 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3343 raid5_compute_sector(conf,
3344 stripe * (disks - conf->max_degraded)
3345 *sectors_per_chunk + chunk_offset,
3351 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3352 struct stripe_head_state *s, int disks)
3355 BUG_ON(sh->batch_head);
3356 for (i = disks; i--; ) {
3360 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3361 struct md_rdev *rdev;
3363 rdev = rcu_dereference(conf->disks[i].rdev);
3364 if (rdev && test_bit(In_sync, &rdev->flags) &&
3365 !test_bit(Faulty, &rdev->flags))
3366 atomic_inc(&rdev->nr_pending);
3371 if (!rdev_set_badblocks(
3375 md_error(conf->mddev, rdev);
3376 rdev_dec_pending(rdev, conf->mddev);
3379 spin_lock_irq(&sh->stripe_lock);
3380 /* fail all writes first */
3381 bi = sh->dev[i].towrite;
3382 sh->dev[i].towrite = NULL;
3383 sh->overwrite_disks = 0;
3384 spin_unlock_irq(&sh->stripe_lock);
3388 log_stripe_write_finished(sh);
3390 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3391 wake_up(&conf->wait_for_overlap);
3393 while (bi && bi->bi_iter.bi_sector <
3394 sh->dev[i].sector + STRIPE_SECTORS) {
3395 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3397 md_write_end(conf->mddev);
3402 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3403 STRIPE_SECTORS, 0, 0);
3405 /* and fail all 'written' */
3406 bi = sh->dev[i].written;
3407 sh->dev[i].written = NULL;
3408 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3409 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3410 sh->dev[i].page = sh->dev[i].orig_page;
3413 if (bi) bitmap_end = 1;
3414 while (bi && bi->bi_iter.bi_sector <
3415 sh->dev[i].sector + STRIPE_SECTORS) {
3416 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3418 md_write_end(conf->mddev);
3423 /* fail any reads if this device is non-operational and
3424 * the data has not reached the cache yet.
3426 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3427 s->failed > conf->max_degraded &&
3428 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3429 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3430 spin_lock_irq(&sh->stripe_lock);
3431 bi = sh->dev[i].toread;
3432 sh->dev[i].toread = NULL;
3433 spin_unlock_irq(&sh->stripe_lock);
3434 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3435 wake_up(&conf->wait_for_overlap);
3438 while (bi && bi->bi_iter.bi_sector <
3439 sh->dev[i].sector + STRIPE_SECTORS) {
3440 struct bio *nextbi =
3441 r5_next_bio(bi, sh->dev[i].sector);
3448 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3449 STRIPE_SECTORS, 0, 0);
3450 /* If we were in the middle of a write the parity block might
3451 * still be locked - so just clear all R5_LOCKED flags
3453 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3458 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3459 if (atomic_dec_and_test(&conf->pending_full_writes))
3460 md_wakeup_thread(conf->mddev->thread);
3464 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3465 struct stripe_head_state *s)
3470 BUG_ON(sh->batch_head);
3471 clear_bit(STRIPE_SYNCING, &sh->state);
3472 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3473 wake_up(&conf->wait_for_overlap);
3476 /* There is nothing more to do for sync/check/repair.
3477 * Don't even need to abort as that is handled elsewhere
3478 * if needed, and not always wanted e.g. if there is a known
3480 * For recover/replace we need to record a bad block on all
3481 * non-sync devices, or abort the recovery
3483 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3484 /* During recovery devices cannot be removed, so
3485 * locking and refcounting of rdevs is not needed
3488 for (i = 0; i < conf->raid_disks; i++) {
3489 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3491 && !test_bit(Faulty, &rdev->flags)
3492 && !test_bit(In_sync, &rdev->flags)
3493 && !rdev_set_badblocks(rdev, sh->sector,
3496 rdev = rcu_dereference(conf->disks[i].replacement);
3498 && !test_bit(Faulty, &rdev->flags)
3499 && !test_bit(In_sync, &rdev->flags)
3500 && !rdev_set_badblocks(rdev, sh->sector,
3506 conf->recovery_disabled =
3507 conf->mddev->recovery_disabled;
3509 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3512 static int want_replace(struct stripe_head *sh, int disk_idx)
3514 struct md_rdev *rdev;
3518 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3520 && !test_bit(Faulty, &rdev->flags)
3521 && !test_bit(In_sync, &rdev->flags)
3522 && (rdev->recovery_offset <= sh->sector
3523 || rdev->mddev->recovery_cp <= sh->sector))
3529 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3530 int disk_idx, int disks)
3532 struct r5dev *dev = &sh->dev[disk_idx];
3533 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3534 &sh->dev[s->failed_num[1]] };
3538 if (test_bit(R5_LOCKED, &dev->flags) ||
3539 test_bit(R5_UPTODATE, &dev->flags))
3540 /* No point reading this as we already have it or have
3541 * decided to get it.
3546 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3547 /* We need this block to directly satisfy a request */
3550 if (s->syncing || s->expanding ||
3551 (s->replacing && want_replace(sh, disk_idx)))
3552 /* When syncing, or expanding we read everything.
3553 * When replacing, we need the replaced block.
3557 if ((s->failed >= 1 && fdev[0]->toread) ||
3558 (s->failed >= 2 && fdev[1]->toread))
3559 /* If we want to read from a failed device, then
3560 * we need to actually read every other device.
3564 /* Sometimes neither read-modify-write nor reconstruct-write
3565 * cycles can work. In those cases we read every block we
3566 * can. Then the parity-update is certain to have enough to
3568 * This can only be a problem when we need to write something,
3569 * and some device has failed. If either of those tests
3570 * fail we need look no further.
3572 if (!s->failed || !s->to_write)
3575 if (test_bit(R5_Insync, &dev->flags) &&
3576 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3577 /* Pre-reads at not permitted until after short delay
3578 * to gather multiple requests. However if this
3579 * device is no Insync, the block could only be computed
3580 * and there is no need to delay that.
3584 for (i = 0; i < s->failed && i < 2; i++) {
3585 if (fdev[i]->towrite &&
3586 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3587 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3588 /* If we have a partial write to a failed
3589 * device, then we will need to reconstruct
3590 * the content of that device, so all other
3591 * devices must be read.
3596 /* If we are forced to do a reconstruct-write, either because
3597 * the current RAID6 implementation only supports that, or
3598 * because parity cannot be trusted and we are currently
3599 * recovering it, there is extra need to be careful.
3600 * If one of the devices that we would need to read, because
3601 * it is not being overwritten (and maybe not written at all)
3602 * is missing/faulty, then we need to read everything we can.
3604 if (sh->raid_conf->level != 6 &&
3605 sh->raid_conf->rmw_level != PARITY_DISABLE_RMW &&
3606 sh->sector < sh->raid_conf->mddev->recovery_cp)
3607 /* reconstruct-write isn't being forced */
3609 for (i = 0; i < s->failed && i < 2; i++) {
3610 if (s->failed_num[i] != sh->pd_idx &&
3611 s->failed_num[i] != sh->qd_idx &&
3612 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3613 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3620 /* fetch_block - checks the given member device to see if its data needs
3621 * to be read or computed to satisfy a request.
3623 * Returns 1 when no more member devices need to be checked, otherwise returns
3624 * 0 to tell the loop in handle_stripe_fill to continue
3626 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3627 int disk_idx, int disks)
3629 struct r5dev *dev = &sh->dev[disk_idx];
3631 /* is the data in this block needed, and can we get it? */
3632 if (need_this_block(sh, s, disk_idx, disks)) {
3633 /* we would like to get this block, possibly by computing it,
3634 * otherwise read it if the backing disk is insync
3636 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3637 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3638 BUG_ON(sh->batch_head);
3641 * In the raid6 case if the only non-uptodate disk is P
3642 * then we already trusted P to compute the other failed
3643 * drives. It is safe to compute rather than re-read P.
3644 * In other cases we only compute blocks from failed
3645 * devices, otherwise check/repair might fail to detect
3646 * a real inconsistency.
3649 if ((s->uptodate == disks - 1) &&
3650 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3651 (s->failed && (disk_idx == s->failed_num[0] ||
3652 disk_idx == s->failed_num[1])))) {
3653 /* have disk failed, and we're requested to fetch it;
3656 pr_debug("Computing stripe %llu block %d\n",
3657 (unsigned long long)sh->sector, disk_idx);
3658 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3659 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3660 set_bit(R5_Wantcompute, &dev->flags);
3661 sh->ops.target = disk_idx;
3662 sh->ops.target2 = -1; /* no 2nd target */
3664 /* Careful: from this point on 'uptodate' is in the eye
3665 * of raid_run_ops which services 'compute' operations
3666 * before writes. R5_Wantcompute flags a block that will
3667 * be R5_UPTODATE by the time it is needed for a
3668 * subsequent operation.
3672 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3673 /* Computing 2-failure is *very* expensive; only
3674 * do it if failed >= 2
3677 for (other = disks; other--; ) {
3678 if (other == disk_idx)
3680 if (!test_bit(R5_UPTODATE,
3681 &sh->dev[other].flags))
3685 pr_debug("Computing stripe %llu blocks %d,%d\n",
3686 (unsigned long long)sh->sector,
3688 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3689 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3690 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3691 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3692 sh->ops.target = disk_idx;
3693 sh->ops.target2 = other;
3697 } else if (test_bit(R5_Insync, &dev->flags)) {
3698 set_bit(R5_LOCKED, &dev->flags);
3699 set_bit(R5_Wantread, &dev->flags);
3701 pr_debug("Reading block %d (sync=%d)\n",
3702 disk_idx, s->syncing);
3710 * handle_stripe_fill - read or compute data to satisfy pending requests.
3712 static void handle_stripe_fill(struct stripe_head *sh,
3713 struct stripe_head_state *s,
3718 /* look for blocks to read/compute, skip this if a compute
3719 * is already in flight, or if the stripe contents are in the
3720 * midst of changing due to a write
3722 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3723 !sh->reconstruct_state) {
3726 * For degraded stripe with data in journal, do not handle
3727 * read requests yet, instead, flush the stripe to raid
3728 * disks first, this avoids handling complex rmw of write
3729 * back cache (prexor with orig_page, and then xor with
3730 * page) in the read path
3732 if (s->to_read && s->injournal && s->failed) {
3733 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3734 r5c_make_stripe_write_out(sh);
3738 for (i = disks; i--; )
3739 if (fetch_block(sh, s, i, disks))
3743 set_bit(STRIPE_HANDLE, &sh->state);
3746 static void break_stripe_batch_list(struct stripe_head *head_sh,
3747 unsigned long handle_flags);
3748 /* handle_stripe_clean_event
3749 * any written block on an uptodate or failed drive can be returned.
3750 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3751 * never LOCKED, so we don't need to test 'failed' directly.
3753 static void handle_stripe_clean_event(struct r5conf *conf,
3754 struct stripe_head *sh, int disks)
3758 int discard_pending = 0;
3759 struct stripe_head *head_sh = sh;
3760 bool do_endio = false;
3762 for (i = disks; i--; )
3763 if (sh->dev[i].written) {
3765 if (!test_bit(R5_LOCKED, &dev->flags) &&
3766 (test_bit(R5_UPTODATE, &dev->flags) ||
3767 test_bit(R5_Discard, &dev->flags) ||
3768 test_bit(R5_SkipCopy, &dev->flags))) {
3769 /* We can return any write requests */
3770 struct bio *wbi, *wbi2;
3771 pr_debug("Return write for disc %d\n", i);
3772 if (test_and_clear_bit(R5_Discard, &dev->flags))
3773 clear_bit(R5_UPTODATE, &dev->flags);
3774 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3775 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3780 dev->page = dev->orig_page;
3782 dev->written = NULL;
3783 while (wbi && wbi->bi_iter.bi_sector <
3784 dev->sector + STRIPE_SECTORS) {
3785 wbi2 = r5_next_bio(wbi, dev->sector);
3786 md_write_end(conf->mddev);
3790 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3792 !test_bit(STRIPE_DEGRADED, &sh->state),
3794 if (head_sh->batch_head) {
3795 sh = list_first_entry(&sh->batch_list,
3798 if (sh != head_sh) {
3805 } else if (test_bit(R5_Discard, &dev->flags))
3806 discard_pending = 1;
3809 log_stripe_write_finished(sh);
3811 if (!discard_pending &&
3812 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3814 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3815 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3816 if (sh->qd_idx >= 0) {
3817 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3818 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3820 /* now that discard is done we can proceed with any sync */
3821 clear_bit(STRIPE_DISCARD, &sh->state);
3823 * SCSI discard will change some bio fields and the stripe has
3824 * no updated data, so remove it from hash list and the stripe
3825 * will be reinitialized
3828 hash = sh->hash_lock_index;
3829 spin_lock_irq(conf->hash_locks + hash);
3831 spin_unlock_irq(conf->hash_locks + hash);
3832 if (head_sh->batch_head) {
3833 sh = list_first_entry(&sh->batch_list,
3834 struct stripe_head, batch_list);
3840 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3841 set_bit(STRIPE_HANDLE, &sh->state);
3845 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3846 if (atomic_dec_and_test(&conf->pending_full_writes))
3847 md_wakeup_thread(conf->mddev->thread);
3849 if (head_sh->batch_head && do_endio)
3850 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3854 * For RMW in write back cache, we need extra page in prexor to store the
3855 * old data. This page is stored in dev->orig_page.
3857 * This function checks whether we have data for prexor. The exact logic
3859 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
3861 static inline bool uptodate_for_rmw(struct r5dev *dev)
3863 return (test_bit(R5_UPTODATE, &dev->flags)) &&
3864 (!test_bit(R5_InJournal, &dev->flags) ||
3865 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
3868 static int handle_stripe_dirtying(struct r5conf *conf,
3869 struct stripe_head *sh,
3870 struct stripe_head_state *s,
3873 int rmw = 0, rcw = 0, i;
3874 sector_t recovery_cp = conf->mddev->recovery_cp;
3876 /* Check whether resync is now happening or should start.
3877 * If yes, then the array is dirty (after unclean shutdown or
3878 * initial creation), so parity in some stripes might be inconsistent.
3879 * In this case, we need to always do reconstruct-write, to ensure
3880 * that in case of drive failure or read-error correction, we
3881 * generate correct data from the parity.
3883 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3884 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3886 /* Calculate the real rcw later - for now make it
3887 * look like rcw is cheaper
3890 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3891 conf->rmw_level, (unsigned long long)recovery_cp,
3892 (unsigned long long)sh->sector);
3893 } else for (i = disks; i--; ) {
3894 /* would I have to read this buffer for read_modify_write */
3895 struct r5dev *dev = &sh->dev[i];
3896 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3897 i == sh->pd_idx || i == sh->qd_idx ||
3898 test_bit(R5_InJournal, &dev->flags)) &&
3899 !test_bit(R5_LOCKED, &dev->flags) &&
3900 !(uptodate_for_rmw(dev) ||
3901 test_bit(R5_Wantcompute, &dev->flags))) {
3902 if (test_bit(R5_Insync, &dev->flags))
3905 rmw += 2*disks; /* cannot read it */
3907 /* Would I have to read this buffer for reconstruct_write */
3908 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3909 i != sh->pd_idx && i != sh->qd_idx &&
3910 !test_bit(R5_LOCKED, &dev->flags) &&
3911 !(test_bit(R5_UPTODATE, &dev->flags) ||
3912 test_bit(R5_Wantcompute, &dev->flags))) {
3913 if (test_bit(R5_Insync, &dev->flags))
3920 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
3921 (unsigned long long)sh->sector, sh->state, rmw, rcw);
3922 set_bit(STRIPE_HANDLE, &sh->state);
3923 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
3924 /* prefer read-modify-write, but need to get some data */
3925 if (conf->mddev->queue)
3926 blk_add_trace_msg(conf->mddev->queue,
3927 "raid5 rmw %llu %d",
3928 (unsigned long long)sh->sector, rmw);
3929 for (i = disks; i--; ) {
3930 struct r5dev *dev = &sh->dev[i];
3931 if (test_bit(R5_InJournal, &dev->flags) &&
3932 dev->page == dev->orig_page &&
3933 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
3934 /* alloc page for prexor */
3935 struct page *p = alloc_page(GFP_NOIO);
3943 * alloc_page() failed, try use
3944 * disk_info->extra_page
3946 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
3947 &conf->cache_state)) {
3948 r5c_use_extra_page(sh);
3952 /* extra_page in use, add to delayed_list */
3953 set_bit(STRIPE_DELAYED, &sh->state);
3954 s->waiting_extra_page = 1;
3959 for (i = disks; i--; ) {
3960 struct r5dev *dev = &sh->dev[i];
3961 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3962 i == sh->pd_idx || i == sh->qd_idx ||
3963 test_bit(R5_InJournal, &dev->flags)) &&
3964 !test_bit(R5_LOCKED, &dev->flags) &&
3965 !(uptodate_for_rmw(dev) ||
3966 test_bit(R5_Wantcompute, &dev->flags)) &&
3967 test_bit(R5_Insync, &dev->flags)) {
3968 if (test_bit(STRIPE_PREREAD_ACTIVE,
3970 pr_debug("Read_old block %d for r-m-w\n",
3972 set_bit(R5_LOCKED, &dev->flags);
3973 set_bit(R5_Wantread, &dev->flags);
3976 set_bit(STRIPE_DELAYED, &sh->state);
3977 set_bit(STRIPE_HANDLE, &sh->state);
3982 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
3983 /* want reconstruct write, but need to get some data */
3986 for (i = disks; i--; ) {
3987 struct r5dev *dev = &sh->dev[i];
3988 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3989 i != sh->pd_idx && i != sh->qd_idx &&
3990 !test_bit(R5_LOCKED, &dev->flags) &&
3991 !(test_bit(R5_UPTODATE, &dev->flags) ||
3992 test_bit(R5_Wantcompute, &dev->flags))) {
3994 if (test_bit(R5_Insync, &dev->flags) &&
3995 test_bit(STRIPE_PREREAD_ACTIVE,
3997 pr_debug("Read_old block "
3998 "%d for Reconstruct\n", i);
3999 set_bit(R5_LOCKED, &dev->flags);
4000 set_bit(R5_Wantread, &dev->flags);
4004 set_bit(STRIPE_DELAYED, &sh->state);
4005 set_bit(STRIPE_HANDLE, &sh->state);
4009 if (rcw && conf->mddev->queue)
4010 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4011 (unsigned long long)sh->sector,
4012 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4015 if (rcw > disks && rmw > disks &&
4016 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4017 set_bit(STRIPE_DELAYED, &sh->state);
4019 /* now if nothing is locked, and if we have enough data,
4020 * we can start a write request
4022 /* since handle_stripe can be called at any time we need to handle the
4023 * case where a compute block operation has been submitted and then a
4024 * subsequent call wants to start a write request. raid_run_ops only
4025 * handles the case where compute block and reconstruct are requested
4026 * simultaneously. If this is not the case then new writes need to be
4027 * held off until the compute completes.
4029 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4030 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4031 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4032 schedule_reconstruction(sh, s, rcw == 0, 0);
4036 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4037 struct stripe_head_state *s, int disks)
4039 struct r5dev *dev = NULL;
4041 BUG_ON(sh->batch_head);
4042 set_bit(STRIPE_HANDLE, &sh->state);
4044 switch (sh->check_state) {
4045 case check_state_idle:
4046 /* start a new check operation if there are no failures */
4047 if (s->failed == 0) {
4048 BUG_ON(s->uptodate != disks);
4049 sh->check_state = check_state_run;
4050 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4051 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4055 dev = &sh->dev[s->failed_num[0]];
4057 case check_state_compute_result:
4058 sh->check_state = check_state_idle;
4060 dev = &sh->dev[sh->pd_idx];
4062 /* check that a write has not made the stripe insync */
4063 if (test_bit(STRIPE_INSYNC, &sh->state))
4066 /* either failed parity check, or recovery is happening */
4067 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4068 BUG_ON(s->uptodate != disks);
4070 set_bit(R5_LOCKED, &dev->flags);
4072 set_bit(R5_Wantwrite, &dev->flags);
4074 clear_bit(STRIPE_DEGRADED, &sh->state);
4075 set_bit(STRIPE_INSYNC, &sh->state);
4077 case check_state_run:
4078 break; /* we will be called again upon completion */
4079 case check_state_check_result:
4080 sh->check_state = check_state_idle;
4082 /* if a failure occurred during the check operation, leave
4083 * STRIPE_INSYNC not set and let the stripe be handled again
4088 /* handle a successful check operation, if parity is correct
4089 * we are done. Otherwise update the mismatch count and repair
4090 * parity if !MD_RECOVERY_CHECK
4092 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4093 /* parity is correct (on disc,
4094 * not in buffer any more)
4096 set_bit(STRIPE_INSYNC, &sh->state);
4098 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4099 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4100 /* don't try to repair!! */
4101 set_bit(STRIPE_INSYNC, &sh->state);
4102 pr_warn_ratelimited("%s: mismatch sector in range "
4103 "%llu-%llu\n", mdname(conf->mddev),
4104 (unsigned long long) sh->sector,
4105 (unsigned long long) sh->sector +
4108 sh->check_state = check_state_compute_run;
4109 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4110 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4111 set_bit(R5_Wantcompute,
4112 &sh->dev[sh->pd_idx].flags);
4113 sh->ops.target = sh->pd_idx;
4114 sh->ops.target2 = -1;
4119 case check_state_compute_run:
4122 pr_err("%s: unknown check_state: %d sector: %llu\n",
4123 __func__, sh->check_state,
4124 (unsigned long long) sh->sector);
4129 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4130 struct stripe_head_state *s,
4133 int pd_idx = sh->pd_idx;
4134 int qd_idx = sh->qd_idx;
4137 BUG_ON(sh->batch_head);
4138 set_bit(STRIPE_HANDLE, &sh->state);
4140 BUG_ON(s->failed > 2);
4142 /* Want to check and possibly repair P and Q.
4143 * However there could be one 'failed' device, in which
4144 * case we can only check one of them, possibly using the
4145 * other to generate missing data
4148 switch (sh->check_state) {
4149 case check_state_idle:
4150 /* start a new check operation if there are < 2 failures */
4151 if (s->failed == s->q_failed) {
4152 /* The only possible failed device holds Q, so it
4153 * makes sense to check P (If anything else were failed,
4154 * we would have used P to recreate it).
4156 sh->check_state = check_state_run;
4158 if (!s->q_failed && s->failed < 2) {
4159 /* Q is not failed, and we didn't use it to generate
4160 * anything, so it makes sense to check it
4162 if (sh->check_state == check_state_run)
4163 sh->check_state = check_state_run_pq;
4165 sh->check_state = check_state_run_q;
4168 /* discard potentially stale zero_sum_result */
4169 sh->ops.zero_sum_result = 0;
4171 if (sh->check_state == check_state_run) {
4172 /* async_xor_zero_sum destroys the contents of P */
4173 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4176 if (sh->check_state >= check_state_run &&
4177 sh->check_state <= check_state_run_pq) {
4178 /* async_syndrome_zero_sum preserves P and Q, so
4179 * no need to mark them !uptodate here
4181 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4185 /* we have 2-disk failure */
4186 BUG_ON(s->failed != 2);
4188 case check_state_compute_result:
4189 sh->check_state = check_state_idle;
4191 /* check that a write has not made the stripe insync */
4192 if (test_bit(STRIPE_INSYNC, &sh->state))
4195 /* now write out any block on a failed drive,
4196 * or P or Q if they were recomputed
4199 if (s->failed == 2) {
4200 dev = &sh->dev[s->failed_num[1]];
4202 set_bit(R5_LOCKED, &dev->flags);
4203 set_bit(R5_Wantwrite, &dev->flags);
4205 if (s->failed >= 1) {
4206 dev = &sh->dev[s->failed_num[0]];
4208 set_bit(R5_LOCKED, &dev->flags);
4209 set_bit(R5_Wantwrite, &dev->flags);
4211 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4212 dev = &sh->dev[pd_idx];
4214 set_bit(R5_LOCKED, &dev->flags);
4215 set_bit(R5_Wantwrite, &dev->flags);
4217 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4218 dev = &sh->dev[qd_idx];
4220 set_bit(R5_LOCKED, &dev->flags);
4221 set_bit(R5_Wantwrite, &dev->flags);
4223 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4224 "%s: disk%td not up to date\n",
4225 mdname(conf->mddev),
4226 dev - (struct r5dev *) &sh->dev)) {
4227 clear_bit(R5_LOCKED, &dev->flags);
4228 clear_bit(R5_Wantwrite, &dev->flags);
4231 clear_bit(STRIPE_DEGRADED, &sh->state);
4233 set_bit(STRIPE_INSYNC, &sh->state);
4235 case check_state_run:
4236 case check_state_run_q:
4237 case check_state_run_pq:
4238 break; /* we will be called again upon completion */
4239 case check_state_check_result:
4240 sh->check_state = check_state_idle;
4242 /* handle a successful check operation, if parity is correct
4243 * we are done. Otherwise update the mismatch count and repair
4244 * parity if !MD_RECOVERY_CHECK
4246 if (sh->ops.zero_sum_result == 0) {
4247 /* both parities are correct */
4249 set_bit(STRIPE_INSYNC, &sh->state);
4251 /* in contrast to the raid5 case we can validate
4252 * parity, but still have a failure to write
4255 sh->check_state = check_state_compute_result;
4256 /* Returning at this point means that we may go
4257 * off and bring p and/or q uptodate again so
4258 * we make sure to check zero_sum_result again
4259 * to verify if p or q need writeback
4263 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4264 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4265 /* don't try to repair!! */
4266 set_bit(STRIPE_INSYNC, &sh->state);
4267 pr_warn_ratelimited("%s: mismatch sector in range "
4268 "%llu-%llu\n", mdname(conf->mddev),
4269 (unsigned long long) sh->sector,
4270 (unsigned long long) sh->sector +
4273 int *target = &sh->ops.target;
4275 sh->ops.target = -1;
4276 sh->ops.target2 = -1;
4277 sh->check_state = check_state_compute_run;
4278 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4279 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4280 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4281 set_bit(R5_Wantcompute,
4282 &sh->dev[pd_idx].flags);
4284 target = &sh->ops.target2;
4287 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4288 set_bit(R5_Wantcompute,
4289 &sh->dev[qd_idx].flags);
4296 case check_state_compute_run:
4299 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4300 __func__, sh->check_state,
4301 (unsigned long long) sh->sector);
4306 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4310 /* We have read all the blocks in this stripe and now we need to
4311 * copy some of them into a target stripe for expand.
4313 struct dma_async_tx_descriptor *tx = NULL;
4314 BUG_ON(sh->batch_head);
4315 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4316 for (i = 0; i < sh->disks; i++)
4317 if (i != sh->pd_idx && i != sh->qd_idx) {
4319 struct stripe_head *sh2;
4320 struct async_submit_ctl submit;
4322 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4323 sector_t s = raid5_compute_sector(conf, bn, 0,
4325 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4327 /* so far only the early blocks of this stripe
4328 * have been requested. When later blocks
4329 * get requested, we will try again
4332 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4333 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4334 /* must have already done this block */
4335 raid5_release_stripe(sh2);
4339 /* place all the copies on one channel */
4340 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4341 tx = async_memcpy(sh2->dev[dd_idx].page,
4342 sh->dev[i].page, 0, 0, STRIPE_SIZE,
4345 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4346 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4347 for (j = 0; j < conf->raid_disks; j++)
4348 if (j != sh2->pd_idx &&
4350 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4352 if (j == conf->raid_disks) {
4353 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4354 set_bit(STRIPE_HANDLE, &sh2->state);
4356 raid5_release_stripe(sh2);
4359 /* done submitting copies, wait for them to complete */
4360 async_tx_quiesce(&tx);
4364 * handle_stripe - do things to a stripe.
4366 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4367 * state of various bits to see what needs to be done.
4369 * return some read requests which now have data
4370 * return some write requests which are safely on storage
4371 * schedule a read on some buffers
4372 * schedule a write of some buffers
4373 * return confirmation of parity correctness
4377 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4379 struct r5conf *conf = sh->raid_conf;
4380 int disks = sh->disks;
4383 int do_recovery = 0;
4385 memset(s, 0, sizeof(*s));
4387 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4388 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4389 s->failed_num[0] = -1;
4390 s->failed_num[1] = -1;
4391 s->log_failed = r5l_log_disk_error(conf);
4393 /* Now to look around and see what can be done */
4395 for (i=disks; i--; ) {
4396 struct md_rdev *rdev;
4403 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4405 dev->toread, dev->towrite, dev->written);
4406 /* maybe we can reply to a read
4408 * new wantfill requests are only permitted while
4409 * ops_complete_biofill is guaranteed to be inactive
4411 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4412 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4413 set_bit(R5_Wantfill, &dev->flags);
4415 /* now count some things */
4416 if (test_bit(R5_LOCKED, &dev->flags))
4418 if (test_bit(R5_UPTODATE, &dev->flags))
4420 if (test_bit(R5_Wantcompute, &dev->flags)) {
4422 BUG_ON(s->compute > 2);
4425 if (test_bit(R5_Wantfill, &dev->flags))
4427 else if (dev->toread)
4431 if (!test_bit(R5_OVERWRITE, &dev->flags))
4436 /* Prefer to use the replacement for reads, but only
4437 * if it is recovered enough and has no bad blocks.
4439 rdev = rcu_dereference(conf->disks[i].replacement);
4440 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4441 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4442 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4443 &first_bad, &bad_sectors))
4444 set_bit(R5_ReadRepl, &dev->flags);
4446 if (rdev && !test_bit(Faulty, &rdev->flags))
4447 set_bit(R5_NeedReplace, &dev->flags);
4449 clear_bit(R5_NeedReplace, &dev->flags);
4450 rdev = rcu_dereference(conf->disks[i].rdev);
4451 clear_bit(R5_ReadRepl, &dev->flags);
4453 if (rdev && test_bit(Faulty, &rdev->flags))
4456 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4457 &first_bad, &bad_sectors);
4458 if (s->blocked_rdev == NULL
4459 && (test_bit(Blocked, &rdev->flags)
4462 set_bit(BlockedBadBlocks,
4464 s->blocked_rdev = rdev;
4465 atomic_inc(&rdev->nr_pending);
4468 clear_bit(R5_Insync, &dev->flags);
4472 /* also not in-sync */
4473 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4474 test_bit(R5_UPTODATE, &dev->flags)) {
4475 /* treat as in-sync, but with a read error
4476 * which we can now try to correct
4478 set_bit(R5_Insync, &dev->flags);
4479 set_bit(R5_ReadError, &dev->flags);
4481 } else if (test_bit(In_sync, &rdev->flags))
4482 set_bit(R5_Insync, &dev->flags);
4483 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4484 /* in sync if before recovery_offset */
4485 set_bit(R5_Insync, &dev->flags);
4486 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4487 test_bit(R5_Expanded, &dev->flags))
4488 /* If we've reshaped into here, we assume it is Insync.
4489 * We will shortly update recovery_offset to make
4492 set_bit(R5_Insync, &dev->flags);
4494 if (test_bit(R5_WriteError, &dev->flags)) {
4495 /* This flag does not apply to '.replacement'
4496 * only to .rdev, so make sure to check that*/
4497 struct md_rdev *rdev2 = rcu_dereference(
4498 conf->disks[i].rdev);
4500 clear_bit(R5_Insync, &dev->flags);
4501 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4502 s->handle_bad_blocks = 1;
4503 atomic_inc(&rdev2->nr_pending);
4505 clear_bit(R5_WriteError, &dev->flags);
4507 if (test_bit(R5_MadeGood, &dev->flags)) {
4508 /* This flag does not apply to '.replacement'
4509 * only to .rdev, so make sure to check that*/
4510 struct md_rdev *rdev2 = rcu_dereference(
4511 conf->disks[i].rdev);
4512 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4513 s->handle_bad_blocks = 1;
4514 atomic_inc(&rdev2->nr_pending);
4516 clear_bit(R5_MadeGood, &dev->flags);
4518 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4519 struct md_rdev *rdev2 = rcu_dereference(
4520 conf->disks[i].replacement);
4521 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4522 s->handle_bad_blocks = 1;
4523 atomic_inc(&rdev2->nr_pending);
4525 clear_bit(R5_MadeGoodRepl, &dev->flags);
4527 if (!test_bit(R5_Insync, &dev->flags)) {
4528 /* The ReadError flag will just be confusing now */
4529 clear_bit(R5_ReadError, &dev->flags);
4530 clear_bit(R5_ReWrite, &dev->flags);
4532 if (test_bit(R5_ReadError, &dev->flags))
4533 clear_bit(R5_Insync, &dev->flags);
4534 if (!test_bit(R5_Insync, &dev->flags)) {
4536 s->failed_num[s->failed] = i;
4538 if (rdev && !test_bit(Faulty, &rdev->flags))
4541 rdev = rcu_dereference(
4542 conf->disks[i].replacement);
4543 if (rdev && !test_bit(Faulty, &rdev->flags))
4548 if (test_bit(R5_InJournal, &dev->flags))
4550 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4553 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4554 /* If there is a failed device being replaced,
4555 * we must be recovering.
4556 * else if we are after recovery_cp, we must be syncing
4557 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4558 * else we can only be replacing
4559 * sync and recovery both need to read all devices, and so
4560 * use the same flag.
4563 sh->sector >= conf->mddev->recovery_cp ||
4564 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4572 static int clear_batch_ready(struct stripe_head *sh)
4574 /* Return '1' if this is a member of batch, or
4575 * '0' if it is a lone stripe or a head which can now be
4578 struct stripe_head *tmp;
4579 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4580 return (sh->batch_head && sh->batch_head != sh);
4581 spin_lock(&sh->stripe_lock);
4582 if (!sh->batch_head) {
4583 spin_unlock(&sh->stripe_lock);
4588 * this stripe could be added to a batch list before we check
4589 * BATCH_READY, skips it
4591 if (sh->batch_head != sh) {
4592 spin_unlock(&sh->stripe_lock);
4595 spin_lock(&sh->batch_lock);
4596 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4597 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4598 spin_unlock(&sh->batch_lock);
4599 spin_unlock(&sh->stripe_lock);
4602 * BATCH_READY is cleared, no new stripes can be added.
4603 * batch_list can be accessed without lock
4608 static void break_stripe_batch_list(struct stripe_head *head_sh,
4609 unsigned long handle_flags)
4611 struct stripe_head *sh, *next;
4615 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4617 list_del_init(&sh->batch_list);
4619 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4620 (1 << STRIPE_SYNCING) |
4621 (1 << STRIPE_REPLACED) |
4622 (1 << STRIPE_DELAYED) |
4623 (1 << STRIPE_BIT_DELAY) |
4624 (1 << STRIPE_FULL_WRITE) |
4625 (1 << STRIPE_BIOFILL_RUN) |
4626 (1 << STRIPE_COMPUTE_RUN) |
4627 (1 << STRIPE_DISCARD) |
4628 (1 << STRIPE_BATCH_READY) |
4629 (1 << STRIPE_BATCH_ERR) |
4630 (1 << STRIPE_BITMAP_PENDING)),
4631 "stripe state: %lx\n", sh->state);
4632 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4633 (1 << STRIPE_REPLACED)),
4634 "head stripe state: %lx\n", head_sh->state);
4636 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4637 (1 << STRIPE_PREREAD_ACTIVE) |
4638 (1 << STRIPE_DEGRADED) |
4639 (1 << STRIPE_ON_UNPLUG_LIST)),
4640 head_sh->state & (1 << STRIPE_INSYNC));
4642 sh->check_state = head_sh->check_state;
4643 sh->reconstruct_state = head_sh->reconstruct_state;
4644 spin_lock_irq(&sh->stripe_lock);
4645 sh->batch_head = NULL;
4646 spin_unlock_irq(&sh->stripe_lock);
4647 for (i = 0; i < sh->disks; i++) {
4648 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4650 sh->dev[i].flags = head_sh->dev[i].flags &
4651 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4653 if (handle_flags == 0 ||
4654 sh->state & handle_flags)
4655 set_bit(STRIPE_HANDLE, &sh->state);
4656 raid5_release_stripe(sh);
4658 spin_lock_irq(&head_sh->stripe_lock);
4659 head_sh->batch_head = NULL;
4660 spin_unlock_irq(&head_sh->stripe_lock);
4661 for (i = 0; i < head_sh->disks; i++)
4662 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4664 if (head_sh->state & handle_flags)
4665 set_bit(STRIPE_HANDLE, &head_sh->state);
4668 wake_up(&head_sh->raid_conf->wait_for_overlap);
4671 static void handle_stripe(struct stripe_head *sh)
4673 struct stripe_head_state s;
4674 struct r5conf *conf = sh->raid_conf;
4677 int disks = sh->disks;
4678 struct r5dev *pdev, *qdev;
4680 clear_bit(STRIPE_HANDLE, &sh->state);
4681 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4682 /* already being handled, ensure it gets handled
4683 * again when current action finishes */
4684 set_bit(STRIPE_HANDLE, &sh->state);
4688 if (clear_batch_ready(sh) ) {
4689 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4693 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4694 break_stripe_batch_list(sh, 0);
4696 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4697 spin_lock(&sh->stripe_lock);
4699 * Cannot process 'sync' concurrently with 'discard'.
4700 * Flush data in r5cache before 'sync'.
4702 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4703 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4704 !test_bit(STRIPE_DISCARD, &sh->state) &&
4705 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4706 set_bit(STRIPE_SYNCING, &sh->state);
4707 clear_bit(STRIPE_INSYNC, &sh->state);
4708 clear_bit(STRIPE_REPLACED, &sh->state);
4710 spin_unlock(&sh->stripe_lock);
4712 clear_bit(STRIPE_DELAYED, &sh->state);
4714 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4715 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4716 (unsigned long long)sh->sector, sh->state,
4717 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4718 sh->check_state, sh->reconstruct_state);
4720 analyse_stripe(sh, &s);
4722 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4725 if (s.handle_bad_blocks ||
4726 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4727 set_bit(STRIPE_HANDLE, &sh->state);
4731 if (unlikely(s.blocked_rdev)) {
4732 if (s.syncing || s.expanding || s.expanded ||
4733 s.replacing || s.to_write || s.written) {
4734 set_bit(STRIPE_HANDLE, &sh->state);
4737 /* There is nothing for the blocked_rdev to block */
4738 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4739 s.blocked_rdev = NULL;
4742 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4743 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4744 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4747 pr_debug("locked=%d uptodate=%d to_read=%d"
4748 " to_write=%d failed=%d failed_num=%d,%d\n",
4749 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4750 s.failed_num[0], s.failed_num[1]);
4752 * check if the array has lost more than max_degraded devices and,
4753 * if so, some requests might need to be failed.
4755 * When journal device failed (log_failed), we will only process
4756 * the stripe if there is data need write to raid disks
4758 if (s.failed > conf->max_degraded ||
4759 (s.log_failed && s.injournal == 0)) {
4760 sh->check_state = 0;
4761 sh->reconstruct_state = 0;
4762 break_stripe_batch_list(sh, 0);
4763 if (s.to_read+s.to_write+s.written)
4764 handle_failed_stripe(conf, sh, &s, disks);
4765 if (s.syncing + s.replacing)
4766 handle_failed_sync(conf, sh, &s);
4769 /* Now we check to see if any write operations have recently
4773 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4775 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4776 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4777 sh->reconstruct_state = reconstruct_state_idle;
4779 /* All the 'written' buffers and the parity block are ready to
4780 * be written back to disk
4782 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4783 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4784 BUG_ON(sh->qd_idx >= 0 &&
4785 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4786 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4787 for (i = disks; i--; ) {
4788 struct r5dev *dev = &sh->dev[i];
4789 if (test_bit(R5_LOCKED, &dev->flags) &&
4790 (i == sh->pd_idx || i == sh->qd_idx ||
4791 dev->written || test_bit(R5_InJournal,
4793 pr_debug("Writing block %d\n", i);
4794 set_bit(R5_Wantwrite, &dev->flags);
4799 if (!test_bit(R5_Insync, &dev->flags) ||
4800 ((i == sh->pd_idx || i == sh->qd_idx) &&
4802 set_bit(STRIPE_INSYNC, &sh->state);
4805 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4806 s.dec_preread_active = 1;
4810 * might be able to return some write requests if the parity blocks
4811 * are safe, or on a failed drive
4813 pdev = &sh->dev[sh->pd_idx];
4814 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4815 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4816 qdev = &sh->dev[sh->qd_idx];
4817 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4818 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4822 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4823 && !test_bit(R5_LOCKED, &pdev->flags)
4824 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4825 test_bit(R5_Discard, &pdev->flags))))) &&
4826 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4827 && !test_bit(R5_LOCKED, &qdev->flags)
4828 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4829 test_bit(R5_Discard, &qdev->flags))))))
4830 handle_stripe_clean_event(conf, sh, disks);
4833 r5c_handle_cached_data_endio(conf, sh, disks);
4834 log_stripe_write_finished(sh);
4836 /* Now we might consider reading some blocks, either to check/generate
4837 * parity, or to satisfy requests
4838 * or to load a block that is being partially written.
4840 if (s.to_read || s.non_overwrite
4841 || (s.to_write && s.failed)
4842 || (s.syncing && (s.uptodate + s.compute < disks))
4845 handle_stripe_fill(sh, &s, disks);
4848 * When the stripe finishes full journal write cycle (write to journal
4849 * and raid disk), this is the clean up procedure so it is ready for
4852 r5c_finish_stripe_write_out(conf, sh, &s);
4855 * Now to consider new write requests, cache write back and what else,
4856 * if anything should be read. We do not handle new writes when:
4857 * 1/ A 'write' operation (copy+xor) is already in flight.
4858 * 2/ A 'check' operation is in flight, as it may clobber the parity
4860 * 3/ A r5c cache log write is in flight.
4863 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
4864 if (!r5c_is_writeback(conf->log)) {
4866 handle_stripe_dirtying(conf, sh, &s, disks);
4867 } else { /* write back cache */
4870 /* First, try handle writes in caching phase */
4872 ret = r5c_try_caching_write(conf, sh, &s,
4875 * If caching phase failed: ret == -EAGAIN
4877 * stripe under reclaim: !caching && injournal
4879 * fall back to handle_stripe_dirtying()
4881 if (ret == -EAGAIN ||
4882 /* stripe under reclaim: !caching && injournal */
4883 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
4885 ret = handle_stripe_dirtying(conf, sh, &s,
4893 /* maybe we need to check and possibly fix the parity for this stripe
4894 * Any reads will already have been scheduled, so we just see if enough
4895 * data is available. The parity check is held off while parity
4896 * dependent operations are in flight.
4898 if (sh->check_state ||
4899 (s.syncing && s.locked == 0 &&
4900 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4901 !test_bit(STRIPE_INSYNC, &sh->state))) {
4902 if (conf->level == 6)
4903 handle_parity_checks6(conf, sh, &s, disks);
4905 handle_parity_checks5(conf, sh, &s, disks);
4908 if ((s.replacing || s.syncing) && s.locked == 0
4909 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4910 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4911 /* Write out to replacement devices where possible */
4912 for (i = 0; i < conf->raid_disks; i++)
4913 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4914 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4915 set_bit(R5_WantReplace, &sh->dev[i].flags);
4916 set_bit(R5_LOCKED, &sh->dev[i].flags);
4920 set_bit(STRIPE_INSYNC, &sh->state);
4921 set_bit(STRIPE_REPLACED, &sh->state);
4923 if ((s.syncing || s.replacing) && s.locked == 0 &&
4924 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4925 test_bit(STRIPE_INSYNC, &sh->state)) {
4926 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4927 clear_bit(STRIPE_SYNCING, &sh->state);
4928 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4929 wake_up(&conf->wait_for_overlap);
4932 /* If the failed drives are just a ReadError, then we might need
4933 * to progress the repair/check process
4935 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4936 for (i = 0; i < s.failed; i++) {
4937 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4938 if (test_bit(R5_ReadError, &dev->flags)
4939 && !test_bit(R5_LOCKED, &dev->flags)
4940 && test_bit(R5_UPTODATE, &dev->flags)
4942 if (!test_bit(R5_ReWrite, &dev->flags)) {
4943 set_bit(R5_Wantwrite, &dev->flags);
4944 set_bit(R5_ReWrite, &dev->flags);
4945 set_bit(R5_LOCKED, &dev->flags);
4948 /* let's read it back */
4949 set_bit(R5_Wantread, &dev->flags);
4950 set_bit(R5_LOCKED, &dev->flags);
4956 /* Finish reconstruct operations initiated by the expansion process */
4957 if (sh->reconstruct_state == reconstruct_state_result) {
4958 struct stripe_head *sh_src
4959 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4960 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4961 /* sh cannot be written until sh_src has been read.
4962 * so arrange for sh to be delayed a little
4964 set_bit(STRIPE_DELAYED, &sh->state);
4965 set_bit(STRIPE_HANDLE, &sh->state);
4966 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4968 atomic_inc(&conf->preread_active_stripes);
4969 raid5_release_stripe(sh_src);
4973 raid5_release_stripe(sh_src);
4975 sh->reconstruct_state = reconstruct_state_idle;
4976 clear_bit(STRIPE_EXPANDING, &sh->state);
4977 for (i = conf->raid_disks; i--; ) {
4978 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4979 set_bit(R5_LOCKED, &sh->dev[i].flags);
4984 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4985 !sh->reconstruct_state) {
4986 /* Need to write out all blocks after computing parity */
4987 sh->disks = conf->raid_disks;
4988 stripe_set_idx(sh->sector, conf, 0, sh);
4989 schedule_reconstruction(sh, &s, 1, 1);
4990 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4991 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4992 atomic_dec(&conf->reshape_stripes);
4993 wake_up(&conf->wait_for_overlap);
4994 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4997 if (s.expanding && s.locked == 0 &&
4998 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4999 handle_stripe_expansion(conf, sh);
5002 /* wait for this device to become unblocked */
5003 if (unlikely(s.blocked_rdev)) {
5004 if (conf->mddev->external)
5005 md_wait_for_blocked_rdev(s.blocked_rdev,
5008 /* Internal metadata will immediately
5009 * be written by raid5d, so we don't
5010 * need to wait here.
5012 rdev_dec_pending(s.blocked_rdev,
5016 if (s.handle_bad_blocks)
5017 for (i = disks; i--; ) {
5018 struct md_rdev *rdev;
5019 struct r5dev *dev = &sh->dev[i];
5020 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5021 /* We own a safe reference to the rdev */
5022 rdev = conf->disks[i].rdev;
5023 if (!rdev_set_badblocks(rdev, sh->sector,
5025 md_error(conf->mddev, rdev);
5026 rdev_dec_pending(rdev, conf->mddev);
5028 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5029 rdev = conf->disks[i].rdev;
5030 rdev_clear_badblocks(rdev, sh->sector,
5032 rdev_dec_pending(rdev, conf->mddev);
5034 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5035 rdev = conf->disks[i].replacement;
5037 /* rdev have been moved down */
5038 rdev = conf->disks[i].rdev;
5039 rdev_clear_badblocks(rdev, sh->sector,
5041 rdev_dec_pending(rdev, conf->mddev);
5046 raid_run_ops(sh, s.ops_request);
5050 if (s.dec_preread_active) {
5051 /* We delay this until after ops_run_io so that if make_request
5052 * is waiting on a flush, it won't continue until the writes
5053 * have actually been submitted.
5055 atomic_dec(&conf->preread_active_stripes);
5056 if (atomic_read(&conf->preread_active_stripes) <
5058 md_wakeup_thread(conf->mddev->thread);
5061 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5064 static void raid5_activate_delayed(struct r5conf *conf)
5066 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5067 while (!list_empty(&conf->delayed_list)) {
5068 struct list_head *l = conf->delayed_list.next;
5069 struct stripe_head *sh;
5070 sh = list_entry(l, struct stripe_head, lru);
5072 clear_bit(STRIPE_DELAYED, &sh->state);
5073 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5074 atomic_inc(&conf->preread_active_stripes);
5075 list_add_tail(&sh->lru, &conf->hold_list);
5076 raid5_wakeup_stripe_thread(sh);
5081 static void activate_bit_delay(struct r5conf *conf,
5082 struct list_head *temp_inactive_list)
5084 /* device_lock is held */
5085 struct list_head head;
5086 list_add(&head, &conf->bitmap_list);
5087 list_del_init(&conf->bitmap_list);
5088 while (!list_empty(&head)) {
5089 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5091 list_del_init(&sh->lru);
5092 atomic_inc(&sh->count);
5093 hash = sh->hash_lock_index;
5094 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5098 static int raid5_congested(struct mddev *mddev, int bits)
5100 struct r5conf *conf = mddev->private;
5102 /* No difference between reads and writes. Just check
5103 * how busy the stripe_cache is
5106 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
5109 /* Also checks whether there is pressure on r5cache log space */
5110 if (test_bit(R5C_LOG_TIGHT, &conf->cache_state))
5114 if (atomic_read(&conf->empty_inactive_list_nr))
5120 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5122 struct r5conf *conf = mddev->private;
5123 sector_t sector = bio->bi_iter.bi_sector;
5124 unsigned int chunk_sectors;
5125 unsigned int bio_sectors = bio_sectors(bio);
5127 WARN_ON_ONCE(bio->bi_partno);
5129 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5130 return chunk_sectors >=
5131 ((sector & (chunk_sectors - 1)) + bio_sectors);
5135 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5136 * later sampled by raid5d.
5138 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5140 unsigned long flags;
5142 spin_lock_irqsave(&conf->device_lock, flags);
5144 bi->bi_next = conf->retry_read_aligned_list;
5145 conf->retry_read_aligned_list = bi;
5147 spin_unlock_irqrestore(&conf->device_lock, flags);
5148 md_wakeup_thread(conf->mddev->thread);
5151 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5152 unsigned int *offset)
5156 bi = conf->retry_read_aligned;
5158 *offset = conf->retry_read_offset;
5159 conf->retry_read_aligned = NULL;
5162 bi = conf->retry_read_aligned_list;
5164 conf->retry_read_aligned_list = bi->bi_next;
5173 * The "raid5_align_endio" should check if the read succeeded and if it
5174 * did, call bio_endio on the original bio (having bio_put the new bio
5176 * If the read failed..
5178 static void raid5_align_endio(struct bio *bi)
5180 struct bio* raid_bi = bi->bi_private;
5181 struct mddev *mddev;
5182 struct r5conf *conf;
5183 struct md_rdev *rdev;
5184 blk_status_t error = bi->bi_status;
5188 rdev = (void*)raid_bi->bi_next;
5189 raid_bi->bi_next = NULL;
5190 mddev = rdev->mddev;
5191 conf = mddev->private;
5193 rdev_dec_pending(rdev, conf->mddev);
5197 if (atomic_dec_and_test(&conf->active_aligned_reads))
5198 wake_up(&conf->wait_for_quiescent);
5202 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5204 add_bio_to_retry(raid_bi, conf);
5207 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5209 struct r5conf *conf = mddev->private;
5211 struct bio* align_bi;
5212 struct md_rdev *rdev;
5213 sector_t end_sector;
5215 if (!in_chunk_boundary(mddev, raid_bio)) {
5216 pr_debug("%s: non aligned\n", __func__);
5220 * use bio_clone_fast to make a copy of the bio
5222 align_bi = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5226 * set bi_end_io to a new function, and set bi_private to the
5229 align_bi->bi_end_io = raid5_align_endio;
5230 align_bi->bi_private = raid_bio;
5234 align_bi->bi_iter.bi_sector =
5235 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5238 end_sector = bio_end_sector(align_bi);
5240 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5241 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5242 rdev->recovery_offset < end_sector) {
5243 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5245 (test_bit(Faulty, &rdev->flags) ||
5246 !(test_bit(In_sync, &rdev->flags) ||
5247 rdev->recovery_offset >= end_sector)))
5251 if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5261 atomic_inc(&rdev->nr_pending);
5263 raid_bio->bi_next = (void*)rdev;
5264 bio_set_dev(align_bi, rdev->bdev);
5266 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5267 bio_sectors(align_bi),
5268 &first_bad, &bad_sectors)) {
5270 rdev_dec_pending(rdev, mddev);
5274 /* No reshape active, so we can trust rdev->data_offset */
5275 align_bi->bi_iter.bi_sector += rdev->data_offset;
5277 spin_lock_irq(&conf->device_lock);
5278 wait_event_lock_irq(conf->wait_for_quiescent,
5281 atomic_inc(&conf->active_aligned_reads);
5282 spin_unlock_irq(&conf->device_lock);
5285 trace_block_bio_remap(align_bi->bi_disk->queue,
5286 align_bi, disk_devt(mddev->gendisk),
5287 raid_bio->bi_iter.bi_sector);
5288 generic_make_request(align_bi);
5297 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5300 sector_t sector = raid_bio->bi_iter.bi_sector;
5301 unsigned chunk_sects = mddev->chunk_sectors;
5302 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5304 if (sectors < bio_sectors(raid_bio)) {
5305 struct r5conf *conf = mddev->private;
5306 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5307 bio_chain(split, raid_bio);
5308 generic_make_request(raid_bio);
5312 if (!raid5_read_one_chunk(mddev, raid_bio))
5318 /* __get_priority_stripe - get the next stripe to process
5320 * Full stripe writes are allowed to pass preread active stripes up until
5321 * the bypass_threshold is exceeded. In general the bypass_count
5322 * increments when the handle_list is handled before the hold_list; however, it
5323 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5324 * stripe with in flight i/o. The bypass_count will be reset when the
5325 * head of the hold_list has changed, i.e. the head was promoted to the
5328 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5330 struct stripe_head *sh, *tmp;
5331 struct list_head *handle_list = NULL;
5332 struct r5worker_group *wg;
5333 bool second_try = !r5c_is_writeback(conf->log) &&
5334 !r5l_log_disk_error(conf);
5335 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5336 r5l_log_disk_error(conf);
5341 if (conf->worker_cnt_per_group == 0) {
5342 handle_list = try_loprio ? &conf->loprio_list :
5344 } else if (group != ANY_GROUP) {
5345 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5346 &conf->worker_groups[group].handle_list;
5347 wg = &conf->worker_groups[group];
5350 for (i = 0; i < conf->group_cnt; i++) {
5351 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5352 &conf->worker_groups[i].handle_list;
5353 wg = &conf->worker_groups[i];
5354 if (!list_empty(handle_list))
5359 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5361 list_empty(handle_list) ? "empty" : "busy",
5362 list_empty(&conf->hold_list) ? "empty" : "busy",
5363 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5365 if (!list_empty(handle_list)) {
5366 sh = list_entry(handle_list->next, typeof(*sh), lru);
5368 if (list_empty(&conf->hold_list))
5369 conf->bypass_count = 0;
5370 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5371 if (conf->hold_list.next == conf->last_hold)
5372 conf->bypass_count++;
5374 conf->last_hold = conf->hold_list.next;
5375 conf->bypass_count -= conf->bypass_threshold;
5376 if (conf->bypass_count < 0)
5377 conf->bypass_count = 0;
5380 } else if (!list_empty(&conf->hold_list) &&
5381 ((conf->bypass_threshold &&
5382 conf->bypass_count > conf->bypass_threshold) ||
5383 atomic_read(&conf->pending_full_writes) == 0)) {
5385 list_for_each_entry(tmp, &conf->hold_list, lru) {
5386 if (conf->worker_cnt_per_group == 0 ||
5387 group == ANY_GROUP ||
5388 !cpu_online(tmp->cpu) ||
5389 cpu_to_group(tmp->cpu) == group) {
5396 conf->bypass_count -= conf->bypass_threshold;
5397 if (conf->bypass_count < 0)
5398 conf->bypass_count = 0;
5407 try_loprio = !try_loprio;
5415 list_del_init(&sh->lru);
5416 BUG_ON(atomic_inc_return(&sh->count) != 1);
5420 struct raid5_plug_cb {
5421 struct blk_plug_cb cb;
5422 struct list_head list;
5423 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5426 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5428 struct raid5_plug_cb *cb = container_of(
5429 blk_cb, struct raid5_plug_cb, cb);
5430 struct stripe_head *sh;
5431 struct mddev *mddev = cb->cb.data;
5432 struct r5conf *conf = mddev->private;
5436 if (cb->list.next && !list_empty(&cb->list)) {
5437 spin_lock_irq(&conf->device_lock);
5438 while (!list_empty(&cb->list)) {
5439 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5440 list_del_init(&sh->lru);
5442 * avoid race release_stripe_plug() sees
5443 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5444 * is still in our list
5446 smp_mb__before_atomic();
5447 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5449 * STRIPE_ON_RELEASE_LIST could be set here. In that
5450 * case, the count is always > 1 here
5452 hash = sh->hash_lock_index;
5453 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5456 spin_unlock_irq(&conf->device_lock);
5458 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5459 NR_STRIPE_HASH_LOCKS);
5461 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5465 static void release_stripe_plug(struct mddev *mddev,
5466 struct stripe_head *sh)
5468 struct blk_plug_cb *blk_cb = blk_check_plugged(
5469 raid5_unplug, mddev,
5470 sizeof(struct raid5_plug_cb));
5471 struct raid5_plug_cb *cb;
5474 raid5_release_stripe(sh);
5478 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5480 if (cb->list.next == NULL) {
5482 INIT_LIST_HEAD(&cb->list);
5483 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5484 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5487 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5488 list_add_tail(&sh->lru, &cb->list);
5490 raid5_release_stripe(sh);
5493 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5495 struct r5conf *conf = mddev->private;
5496 sector_t logical_sector, last_sector;
5497 struct stripe_head *sh;
5500 if (mddev->reshape_position != MaxSector)
5501 /* Skip discard while reshape is happening */
5504 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5505 last_sector = bio_end_sector(bi);
5509 stripe_sectors = conf->chunk_sectors *
5510 (conf->raid_disks - conf->max_degraded);
5511 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5513 sector_div(last_sector, stripe_sectors);
5515 logical_sector *= conf->chunk_sectors;
5516 last_sector *= conf->chunk_sectors;
5518 for (; logical_sector < last_sector;
5519 logical_sector += STRIPE_SECTORS) {
5523 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5524 prepare_to_wait(&conf->wait_for_overlap, &w,
5525 TASK_UNINTERRUPTIBLE);
5526 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5527 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5528 raid5_release_stripe(sh);
5532 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5533 spin_lock_irq(&sh->stripe_lock);
5534 for (d = 0; d < conf->raid_disks; d++) {
5535 if (d == sh->pd_idx || d == sh->qd_idx)
5537 if (sh->dev[d].towrite || sh->dev[d].toread) {
5538 set_bit(R5_Overlap, &sh->dev[d].flags);
5539 spin_unlock_irq(&sh->stripe_lock);
5540 raid5_release_stripe(sh);
5545 set_bit(STRIPE_DISCARD, &sh->state);
5546 finish_wait(&conf->wait_for_overlap, &w);
5547 sh->overwrite_disks = 0;
5548 for (d = 0; d < conf->raid_disks; d++) {
5549 if (d == sh->pd_idx || d == sh->qd_idx)
5551 sh->dev[d].towrite = bi;
5552 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5553 bio_inc_remaining(bi);
5554 md_write_inc(mddev, bi);
5555 sh->overwrite_disks++;
5557 spin_unlock_irq(&sh->stripe_lock);
5558 if (conf->mddev->bitmap) {
5560 d < conf->raid_disks - conf->max_degraded;
5562 md_bitmap_startwrite(mddev->bitmap,
5566 sh->bm_seq = conf->seq_flush + 1;
5567 set_bit(STRIPE_BIT_DELAY, &sh->state);
5570 set_bit(STRIPE_HANDLE, &sh->state);
5571 clear_bit(STRIPE_DELAYED, &sh->state);
5572 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5573 atomic_inc(&conf->preread_active_stripes);
5574 release_stripe_plug(mddev, sh);
5580 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5582 struct r5conf *conf = mddev->private;
5584 sector_t new_sector;
5585 sector_t logical_sector, last_sector;
5586 struct stripe_head *sh;
5587 const int rw = bio_data_dir(bi);
5590 bool do_flush = false;
5592 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5593 int ret = log_handle_flush_request(conf, bi);
5597 if (ret == -ENODEV) {
5598 if (md_flush_request(mddev, bi))
5601 /* ret == -EAGAIN, fallback */
5603 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5604 * we need to flush journal device
5606 do_flush = bi->bi_opf & REQ_PREFLUSH;
5609 if (!md_write_start(mddev, bi))
5612 * If array is degraded, better not do chunk aligned read because
5613 * later we might have to read it again in order to reconstruct
5614 * data on failed drives.
5616 if (rw == READ && mddev->degraded == 0 &&
5617 mddev->reshape_position == MaxSector) {
5618 bi = chunk_aligned_read(mddev, bi);
5623 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5624 make_discard_request(mddev, bi);
5625 md_write_end(mddev);
5629 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5630 last_sector = bio_end_sector(bi);
5633 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5634 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5640 seq = read_seqcount_begin(&conf->gen_lock);
5643 prepare_to_wait(&conf->wait_for_overlap, &w,
5644 TASK_UNINTERRUPTIBLE);
5645 if (unlikely(conf->reshape_progress != MaxSector)) {
5646 /* spinlock is needed as reshape_progress may be
5647 * 64bit on a 32bit platform, and so it might be
5648 * possible to see a half-updated value
5649 * Of course reshape_progress could change after
5650 * the lock is dropped, so once we get a reference
5651 * to the stripe that we think it is, we will have
5654 spin_lock_irq(&conf->device_lock);
5655 if (mddev->reshape_backwards
5656 ? logical_sector < conf->reshape_progress
5657 : logical_sector >= conf->reshape_progress) {
5660 if (mddev->reshape_backwards
5661 ? logical_sector < conf->reshape_safe
5662 : logical_sector >= conf->reshape_safe) {
5663 spin_unlock_irq(&conf->device_lock);
5669 spin_unlock_irq(&conf->device_lock);
5672 new_sector = raid5_compute_sector(conf, logical_sector,
5675 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5676 (unsigned long long)new_sector,
5677 (unsigned long long)logical_sector);
5679 sh = raid5_get_active_stripe(conf, new_sector, previous,
5680 (bi->bi_opf & REQ_RAHEAD), 0);
5682 if (unlikely(previous)) {
5683 /* expansion might have moved on while waiting for a
5684 * stripe, so we must do the range check again.
5685 * Expansion could still move past after this
5686 * test, but as we are holding a reference to
5687 * 'sh', we know that if that happens,
5688 * STRIPE_EXPANDING will get set and the expansion
5689 * won't proceed until we finish with the stripe.
5692 spin_lock_irq(&conf->device_lock);
5693 if (mddev->reshape_backwards
5694 ? logical_sector >= conf->reshape_progress
5695 : logical_sector < conf->reshape_progress)
5696 /* mismatch, need to try again */
5698 spin_unlock_irq(&conf->device_lock);
5700 raid5_release_stripe(sh);
5706 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5707 /* Might have got the wrong stripe_head
5710 raid5_release_stripe(sh);
5714 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5715 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5716 /* Stripe is busy expanding or
5717 * add failed due to overlap. Flush everything
5720 md_wakeup_thread(mddev->thread);
5721 raid5_release_stripe(sh);
5727 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5728 /* we only need flush for one stripe */
5732 if (!sh->batch_head || sh == sh->batch_head)
5733 set_bit(STRIPE_HANDLE, &sh->state);
5734 clear_bit(STRIPE_DELAYED, &sh->state);
5735 if ((!sh->batch_head || sh == sh->batch_head) &&
5736 (bi->bi_opf & REQ_SYNC) &&
5737 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5738 atomic_inc(&conf->preread_active_stripes);
5739 release_stripe_plug(mddev, sh);
5741 /* cannot get stripe for read-ahead, just give-up */
5742 bi->bi_status = BLK_STS_IOERR;
5746 finish_wait(&conf->wait_for_overlap, &w);
5749 md_write_end(mddev);
5754 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5756 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5758 /* reshaping is quite different to recovery/resync so it is
5759 * handled quite separately ... here.
5761 * On each call to sync_request, we gather one chunk worth of
5762 * destination stripes and flag them as expanding.
5763 * Then we find all the source stripes and request reads.
5764 * As the reads complete, handle_stripe will copy the data
5765 * into the destination stripe and release that stripe.
5767 struct r5conf *conf = mddev->private;
5768 struct stripe_head *sh;
5769 struct md_rdev *rdev;
5770 sector_t first_sector, last_sector;
5771 int raid_disks = conf->previous_raid_disks;
5772 int data_disks = raid_disks - conf->max_degraded;
5773 int new_data_disks = conf->raid_disks - conf->max_degraded;
5776 sector_t writepos, readpos, safepos;
5777 sector_t stripe_addr;
5778 int reshape_sectors;
5779 struct list_head stripes;
5782 if (sector_nr == 0) {
5783 /* If restarting in the middle, skip the initial sectors */
5784 if (mddev->reshape_backwards &&
5785 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5786 sector_nr = raid5_size(mddev, 0, 0)
5787 - conf->reshape_progress;
5788 } else if (mddev->reshape_backwards &&
5789 conf->reshape_progress == MaxSector) {
5790 /* shouldn't happen, but just in case, finish up.*/
5791 sector_nr = MaxSector;
5792 } else if (!mddev->reshape_backwards &&
5793 conf->reshape_progress > 0)
5794 sector_nr = conf->reshape_progress;
5795 sector_div(sector_nr, new_data_disks);
5797 mddev->curr_resync_completed = sector_nr;
5798 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5805 /* We need to process a full chunk at a time.
5806 * If old and new chunk sizes differ, we need to process the
5810 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5812 /* We update the metadata at least every 10 seconds, or when
5813 * the data about to be copied would over-write the source of
5814 * the data at the front of the range. i.e. one new_stripe
5815 * along from reshape_progress new_maps to after where
5816 * reshape_safe old_maps to
5818 writepos = conf->reshape_progress;
5819 sector_div(writepos, new_data_disks);
5820 readpos = conf->reshape_progress;
5821 sector_div(readpos, data_disks);
5822 safepos = conf->reshape_safe;
5823 sector_div(safepos, data_disks);
5824 if (mddev->reshape_backwards) {
5825 BUG_ON(writepos < reshape_sectors);
5826 writepos -= reshape_sectors;
5827 readpos += reshape_sectors;
5828 safepos += reshape_sectors;
5830 writepos += reshape_sectors;
5831 /* readpos and safepos are worst-case calculations.
5832 * A negative number is overly pessimistic, and causes
5833 * obvious problems for unsigned storage. So clip to 0.
5835 readpos -= min_t(sector_t, reshape_sectors, readpos);
5836 safepos -= min_t(sector_t, reshape_sectors, safepos);
5839 /* Having calculated the 'writepos' possibly use it
5840 * to set 'stripe_addr' which is where we will write to.
5842 if (mddev->reshape_backwards) {
5843 BUG_ON(conf->reshape_progress == 0);
5844 stripe_addr = writepos;
5845 BUG_ON((mddev->dev_sectors &
5846 ~((sector_t)reshape_sectors - 1))
5847 - reshape_sectors - stripe_addr
5850 BUG_ON(writepos != sector_nr + reshape_sectors);
5851 stripe_addr = sector_nr;
5854 /* 'writepos' is the most advanced device address we might write.
5855 * 'readpos' is the least advanced device address we might read.
5856 * 'safepos' is the least address recorded in the metadata as having
5858 * If there is a min_offset_diff, these are adjusted either by
5859 * increasing the safepos/readpos if diff is negative, or
5860 * increasing writepos if diff is positive.
5861 * If 'readpos' is then behind 'writepos', there is no way that we can
5862 * ensure safety in the face of a crash - that must be done by userspace
5863 * making a backup of the data. So in that case there is no particular
5864 * rush to update metadata.
5865 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5866 * update the metadata to advance 'safepos' to match 'readpos' so that
5867 * we can be safe in the event of a crash.
5868 * So we insist on updating metadata if safepos is behind writepos and
5869 * readpos is beyond writepos.
5870 * In any case, update the metadata every 10 seconds.
5871 * Maybe that number should be configurable, but I'm not sure it is
5872 * worth it.... maybe it could be a multiple of safemode_delay???
5874 if (conf->min_offset_diff < 0) {
5875 safepos += -conf->min_offset_diff;
5876 readpos += -conf->min_offset_diff;
5878 writepos += conf->min_offset_diff;
5880 if ((mddev->reshape_backwards
5881 ? (safepos > writepos && readpos < writepos)
5882 : (safepos < writepos && readpos > writepos)) ||
5883 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5884 /* Cannot proceed until we've updated the superblock... */
5885 wait_event(conf->wait_for_overlap,
5886 atomic_read(&conf->reshape_stripes)==0
5887 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5888 if (atomic_read(&conf->reshape_stripes) != 0)
5890 mddev->reshape_position = conf->reshape_progress;
5891 mddev->curr_resync_completed = sector_nr;
5892 if (!mddev->reshape_backwards)
5893 /* Can update recovery_offset */
5894 rdev_for_each(rdev, mddev)
5895 if (rdev->raid_disk >= 0 &&
5896 !test_bit(Journal, &rdev->flags) &&
5897 !test_bit(In_sync, &rdev->flags) &&
5898 rdev->recovery_offset < sector_nr)
5899 rdev->recovery_offset = sector_nr;
5901 conf->reshape_checkpoint = jiffies;
5902 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5903 md_wakeup_thread(mddev->thread);
5904 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
5905 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5906 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5908 spin_lock_irq(&conf->device_lock);
5909 conf->reshape_safe = mddev->reshape_position;
5910 spin_unlock_irq(&conf->device_lock);
5911 wake_up(&conf->wait_for_overlap);
5912 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5915 INIT_LIST_HEAD(&stripes);
5916 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5918 int skipped_disk = 0;
5919 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5920 set_bit(STRIPE_EXPANDING, &sh->state);
5921 atomic_inc(&conf->reshape_stripes);
5922 /* If any of this stripe is beyond the end of the old
5923 * array, then we need to zero those blocks
5925 for (j=sh->disks; j--;) {
5927 if (j == sh->pd_idx)
5929 if (conf->level == 6 &&
5932 s = raid5_compute_blocknr(sh, j, 0);
5933 if (s < raid5_size(mddev, 0, 0)) {
5937 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5938 set_bit(R5_Expanded, &sh->dev[j].flags);
5939 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5941 if (!skipped_disk) {
5942 set_bit(STRIPE_EXPAND_READY, &sh->state);
5943 set_bit(STRIPE_HANDLE, &sh->state);
5945 list_add(&sh->lru, &stripes);
5947 spin_lock_irq(&conf->device_lock);
5948 if (mddev->reshape_backwards)
5949 conf->reshape_progress -= reshape_sectors * new_data_disks;
5951 conf->reshape_progress += reshape_sectors * new_data_disks;
5952 spin_unlock_irq(&conf->device_lock);
5953 /* Ok, those stripe are ready. We can start scheduling
5954 * reads on the source stripes.
5955 * The source stripes are determined by mapping the first and last
5956 * block on the destination stripes.
5959 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5962 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5963 * new_data_disks - 1),
5965 if (last_sector >= mddev->dev_sectors)
5966 last_sector = mddev->dev_sectors - 1;
5967 while (first_sector <= last_sector) {
5968 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5969 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5970 set_bit(STRIPE_HANDLE, &sh->state);
5971 raid5_release_stripe(sh);
5972 first_sector += STRIPE_SECTORS;
5974 /* Now that the sources are clearly marked, we can release
5975 * the destination stripes
5977 while (!list_empty(&stripes)) {
5978 sh = list_entry(stripes.next, struct stripe_head, lru);
5979 list_del_init(&sh->lru);
5980 raid5_release_stripe(sh);
5982 /* If this takes us to the resync_max point where we have to pause,
5983 * then we need to write out the superblock.
5985 sector_nr += reshape_sectors;
5986 retn = reshape_sectors;
5988 if (mddev->curr_resync_completed > mddev->resync_max ||
5989 (sector_nr - mddev->curr_resync_completed) * 2
5990 >= mddev->resync_max - mddev->curr_resync_completed) {
5991 /* Cannot proceed until we've updated the superblock... */
5992 wait_event(conf->wait_for_overlap,
5993 atomic_read(&conf->reshape_stripes) == 0
5994 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5995 if (atomic_read(&conf->reshape_stripes) != 0)
5997 mddev->reshape_position = conf->reshape_progress;
5998 mddev->curr_resync_completed = sector_nr;
5999 if (!mddev->reshape_backwards)
6000 /* Can update recovery_offset */
6001 rdev_for_each(rdev, mddev)
6002 if (rdev->raid_disk >= 0 &&
6003 !test_bit(Journal, &rdev->flags) &&
6004 !test_bit(In_sync, &rdev->flags) &&
6005 rdev->recovery_offset < sector_nr)
6006 rdev->recovery_offset = sector_nr;
6007 conf->reshape_checkpoint = jiffies;
6008 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6009 md_wakeup_thread(mddev->thread);
6010 wait_event(mddev->sb_wait,
6011 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6012 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6013 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6015 spin_lock_irq(&conf->device_lock);
6016 conf->reshape_safe = mddev->reshape_position;
6017 spin_unlock_irq(&conf->device_lock);
6018 wake_up(&conf->wait_for_overlap);
6019 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
6025 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6028 struct r5conf *conf = mddev->private;
6029 struct stripe_head *sh;
6030 sector_t max_sector = mddev->dev_sectors;
6031 sector_t sync_blocks;
6032 int still_degraded = 0;
6035 if (sector_nr >= max_sector) {
6036 /* just being told to finish up .. nothing much to do */
6038 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6043 if (mddev->curr_resync < max_sector) /* aborted */
6044 md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6046 else /* completed sync */
6048 md_bitmap_close_sync(mddev->bitmap);
6053 /* Allow raid5_quiesce to complete */
6054 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6056 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6057 return reshape_request(mddev, sector_nr, skipped);
6059 /* No need to check resync_max as we never do more than one
6060 * stripe, and as resync_max will always be on a chunk boundary,
6061 * if the check in md_do_sync didn't fire, there is no chance
6062 * of overstepping resync_max here
6065 /* if there is too many failed drives and we are trying
6066 * to resync, then assert that we are finished, because there is
6067 * nothing we can do.
6069 if (mddev->degraded >= conf->max_degraded &&
6070 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6071 sector_t rv = mddev->dev_sectors - sector_nr;
6075 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6077 !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6078 sync_blocks >= STRIPE_SECTORS) {
6079 /* we can skip this block, and probably more */
6080 sync_blocks /= STRIPE_SECTORS;
6082 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
6085 md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6087 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6089 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6090 /* make sure we don't swamp the stripe cache if someone else
6091 * is trying to get access
6093 schedule_timeout_uninterruptible(1);
6095 /* Need to check if array will still be degraded after recovery/resync
6096 * Note in case of > 1 drive failures it's possible we're rebuilding
6097 * one drive while leaving another faulty drive in array.
6100 for (i = 0; i < conf->raid_disks; i++) {
6101 struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6103 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6108 md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6110 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6111 set_bit(STRIPE_HANDLE, &sh->state);
6113 raid5_release_stripe(sh);
6115 return STRIPE_SECTORS;
6118 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6119 unsigned int offset)
6121 /* We may not be able to submit a whole bio at once as there
6122 * may not be enough stripe_heads available.
6123 * We cannot pre-allocate enough stripe_heads as we may need
6124 * more than exist in the cache (if we allow ever large chunks).
6125 * So we do one stripe head at a time and record in
6126 * ->bi_hw_segments how many have been done.
6128 * We *know* that this entire raid_bio is in one chunk, so
6129 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6131 struct stripe_head *sh;
6133 sector_t sector, logical_sector, last_sector;
6137 logical_sector = raid_bio->bi_iter.bi_sector &
6138 ~((sector_t)STRIPE_SECTORS-1);
6139 sector = raid5_compute_sector(conf, logical_sector,
6141 last_sector = bio_end_sector(raid_bio);
6143 for (; logical_sector < last_sector;
6144 logical_sector += STRIPE_SECTORS,
6145 sector += STRIPE_SECTORS,
6149 /* already done this stripe */
6152 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6155 /* failed to get a stripe - must wait */
6156 conf->retry_read_aligned = raid_bio;
6157 conf->retry_read_offset = scnt;
6161 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6162 raid5_release_stripe(sh);
6163 conf->retry_read_aligned = raid_bio;
6164 conf->retry_read_offset = scnt;
6168 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6170 raid5_release_stripe(sh);
6174 bio_endio(raid_bio);
6176 if (atomic_dec_and_test(&conf->active_aligned_reads))
6177 wake_up(&conf->wait_for_quiescent);
6181 static int handle_active_stripes(struct r5conf *conf, int group,
6182 struct r5worker *worker,
6183 struct list_head *temp_inactive_list)
6184 __releases(&conf->device_lock)
6185 __acquires(&conf->device_lock)
6187 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6188 int i, batch_size = 0, hash;
6189 bool release_inactive = false;
6191 while (batch_size < MAX_STRIPE_BATCH &&
6192 (sh = __get_priority_stripe(conf, group)) != NULL)
6193 batch[batch_size++] = sh;
6195 if (batch_size == 0) {
6196 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6197 if (!list_empty(temp_inactive_list + i))
6199 if (i == NR_STRIPE_HASH_LOCKS) {
6200 spin_unlock_irq(&conf->device_lock);
6201 log_flush_stripe_to_raid(conf);
6202 spin_lock_irq(&conf->device_lock);
6205 release_inactive = true;
6207 spin_unlock_irq(&conf->device_lock);
6209 release_inactive_stripe_list(conf, temp_inactive_list,
6210 NR_STRIPE_HASH_LOCKS);
6212 r5l_flush_stripe_to_raid(conf->log);
6213 if (release_inactive) {
6214 spin_lock_irq(&conf->device_lock);
6218 for (i = 0; i < batch_size; i++)
6219 handle_stripe(batch[i]);
6220 log_write_stripe_run(conf);
6224 spin_lock_irq(&conf->device_lock);
6225 for (i = 0; i < batch_size; i++) {
6226 hash = batch[i]->hash_lock_index;
6227 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6232 static void raid5_do_work(struct work_struct *work)
6234 struct r5worker *worker = container_of(work, struct r5worker, work);
6235 struct r5worker_group *group = worker->group;
6236 struct r5conf *conf = group->conf;
6237 struct mddev *mddev = conf->mddev;
6238 int group_id = group - conf->worker_groups;
6240 struct blk_plug plug;
6242 pr_debug("+++ raid5worker active\n");
6244 blk_start_plug(&plug);
6246 spin_lock_irq(&conf->device_lock);
6248 int batch_size, released;
6250 released = release_stripe_list(conf, worker->temp_inactive_list);
6252 batch_size = handle_active_stripes(conf, group_id, worker,
6253 worker->temp_inactive_list);
6254 worker->working = false;
6255 if (!batch_size && !released)
6257 handled += batch_size;
6258 wait_event_lock_irq(mddev->sb_wait,
6259 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6262 pr_debug("%d stripes handled\n", handled);
6264 spin_unlock_irq(&conf->device_lock);
6266 flush_deferred_bios(conf);
6268 r5l_flush_stripe_to_raid(conf->log);
6270 async_tx_issue_pending_all();
6271 blk_finish_plug(&plug);
6273 pr_debug("--- raid5worker inactive\n");
6277 * This is our raid5 kernel thread.
6279 * We scan the hash table for stripes which can be handled now.
6280 * During the scan, completed stripes are saved for us by the interrupt
6281 * handler, so that they will not have to wait for our next wakeup.
6283 static void raid5d(struct md_thread *thread)
6285 struct mddev *mddev = thread->mddev;
6286 struct r5conf *conf = mddev->private;
6288 struct blk_plug plug;
6290 pr_debug("+++ raid5d active\n");
6292 md_check_recovery(mddev);
6294 blk_start_plug(&plug);
6296 spin_lock_irq(&conf->device_lock);
6299 int batch_size, released;
6300 unsigned int offset;
6302 released = release_stripe_list(conf, conf->temp_inactive_list);
6304 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6307 !list_empty(&conf->bitmap_list)) {
6308 /* Now is a good time to flush some bitmap updates */
6310 spin_unlock_irq(&conf->device_lock);
6311 md_bitmap_unplug(mddev->bitmap);
6312 spin_lock_irq(&conf->device_lock);
6313 conf->seq_write = conf->seq_flush;
6314 activate_bit_delay(conf, conf->temp_inactive_list);
6316 raid5_activate_delayed(conf);
6318 while ((bio = remove_bio_from_retry(conf, &offset))) {
6320 spin_unlock_irq(&conf->device_lock);
6321 ok = retry_aligned_read(conf, bio, offset);
6322 spin_lock_irq(&conf->device_lock);
6328 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6329 conf->temp_inactive_list);
6330 if (!batch_size && !released)
6332 handled += batch_size;
6334 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6335 spin_unlock_irq(&conf->device_lock);
6336 md_check_recovery(mddev);
6337 spin_lock_irq(&conf->device_lock);
6340 * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6341 * seeing md_check_recovery() is needed to clear
6342 * the flag when using mdmon.
6347 wait_event_lock_irq(mddev->sb_wait,
6348 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6351 pr_debug("%d stripes handled\n", handled);
6353 spin_unlock_irq(&conf->device_lock);
6354 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6355 mutex_trylock(&conf->cache_size_mutex)) {
6356 grow_one_stripe(conf, __GFP_NOWARN);
6357 /* Set flag even if allocation failed. This helps
6358 * slow down allocation requests when mem is short
6360 set_bit(R5_DID_ALLOC, &conf->cache_state);
6361 mutex_unlock(&conf->cache_size_mutex);
6364 flush_deferred_bios(conf);
6366 r5l_flush_stripe_to_raid(conf->log);
6368 async_tx_issue_pending_all();
6369 blk_finish_plug(&plug);
6371 pr_debug("--- raid5d inactive\n");
6375 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6377 struct r5conf *conf;
6379 spin_lock(&mddev->lock);
6380 conf = mddev->private;
6382 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6383 spin_unlock(&mddev->lock);
6388 raid5_set_cache_size(struct mddev *mddev, int size)
6391 struct r5conf *conf = mddev->private;
6393 if (size <= 16 || size > 32768)
6396 conf->min_nr_stripes = size;
6397 mutex_lock(&conf->cache_size_mutex);
6398 while (size < conf->max_nr_stripes &&
6399 drop_one_stripe(conf))
6401 mutex_unlock(&conf->cache_size_mutex);
6403 md_allow_write(mddev);
6405 mutex_lock(&conf->cache_size_mutex);
6406 while (size > conf->max_nr_stripes)
6407 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6408 conf->min_nr_stripes = conf->max_nr_stripes;
6412 mutex_unlock(&conf->cache_size_mutex);
6416 EXPORT_SYMBOL(raid5_set_cache_size);
6419 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6421 struct r5conf *conf;
6425 if (len >= PAGE_SIZE)
6427 if (kstrtoul(page, 10, &new))
6429 err = mddev_lock(mddev);
6432 conf = mddev->private;
6436 err = raid5_set_cache_size(mddev, new);
6437 mddev_unlock(mddev);
6442 static struct md_sysfs_entry
6443 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6444 raid5_show_stripe_cache_size,
6445 raid5_store_stripe_cache_size);
6448 raid5_show_rmw_level(struct mddev *mddev, char *page)
6450 struct r5conf *conf = mddev->private;
6452 return sprintf(page, "%d\n", conf->rmw_level);
6458 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6460 struct r5conf *conf = mddev->private;
6466 if (len >= PAGE_SIZE)
6469 if (kstrtoul(page, 10, &new))
6472 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6475 if (new != PARITY_DISABLE_RMW &&
6476 new != PARITY_ENABLE_RMW &&
6477 new != PARITY_PREFER_RMW)
6480 conf->rmw_level = new;
6484 static struct md_sysfs_entry
6485 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6486 raid5_show_rmw_level,
6487 raid5_store_rmw_level);
6491 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6493 struct r5conf *conf;
6495 spin_lock(&mddev->lock);
6496 conf = mddev->private;
6498 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6499 spin_unlock(&mddev->lock);
6504 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6506 struct r5conf *conf;
6510 if (len >= PAGE_SIZE)
6512 if (kstrtoul(page, 10, &new))
6515 err = mddev_lock(mddev);
6518 conf = mddev->private;
6521 else if (new > conf->min_nr_stripes)
6524 conf->bypass_threshold = new;
6525 mddev_unlock(mddev);
6529 static struct md_sysfs_entry
6530 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6532 raid5_show_preread_threshold,
6533 raid5_store_preread_threshold);
6536 raid5_show_skip_copy(struct mddev *mddev, char *page)
6538 struct r5conf *conf;
6540 spin_lock(&mddev->lock);
6541 conf = mddev->private;
6543 ret = sprintf(page, "%d\n", conf->skip_copy);
6544 spin_unlock(&mddev->lock);
6549 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6551 struct r5conf *conf;
6555 if (len >= PAGE_SIZE)
6557 if (kstrtoul(page, 10, &new))
6561 err = mddev_lock(mddev);
6564 conf = mddev->private;
6567 else if (new != conf->skip_copy) {
6568 mddev_suspend(mddev);
6569 conf->skip_copy = new;
6571 mddev->queue->backing_dev_info->capabilities |=
6572 BDI_CAP_STABLE_WRITES;
6574 mddev->queue->backing_dev_info->capabilities &=
6575 ~BDI_CAP_STABLE_WRITES;
6576 mddev_resume(mddev);
6578 mddev_unlock(mddev);
6582 static struct md_sysfs_entry
6583 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6584 raid5_show_skip_copy,
6585 raid5_store_skip_copy);
6588 stripe_cache_active_show(struct mddev *mddev, char *page)
6590 struct r5conf *conf = mddev->private;
6592 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6597 static struct md_sysfs_entry
6598 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6601 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6603 struct r5conf *conf;
6605 spin_lock(&mddev->lock);
6606 conf = mddev->private;
6608 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6609 spin_unlock(&mddev->lock);
6613 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6615 int *worker_cnt_per_group,
6616 struct r5worker_group **worker_groups);
6618 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6620 struct r5conf *conf;
6623 struct r5worker_group *new_groups, *old_groups;
6624 int group_cnt, worker_cnt_per_group;
6626 if (len >= PAGE_SIZE)
6628 if (kstrtouint(page, 10, &new))
6630 /* 8192 should be big enough */
6634 err = mddev_lock(mddev);
6637 conf = mddev->private;
6640 else if (new != conf->worker_cnt_per_group) {
6641 mddev_suspend(mddev);
6643 old_groups = conf->worker_groups;
6645 flush_workqueue(raid5_wq);
6647 err = alloc_thread_groups(conf, new,
6648 &group_cnt, &worker_cnt_per_group,
6651 spin_lock_irq(&conf->device_lock);
6652 conf->group_cnt = group_cnt;
6653 conf->worker_cnt_per_group = worker_cnt_per_group;
6654 conf->worker_groups = new_groups;
6655 spin_unlock_irq(&conf->device_lock);
6658 kfree(old_groups[0].workers);
6661 mddev_resume(mddev);
6663 mddev_unlock(mddev);
6668 static struct md_sysfs_entry
6669 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6670 raid5_show_group_thread_cnt,
6671 raid5_store_group_thread_cnt);
6673 static struct attribute *raid5_attrs[] = {
6674 &raid5_stripecache_size.attr,
6675 &raid5_stripecache_active.attr,
6676 &raid5_preread_bypass_threshold.attr,
6677 &raid5_group_thread_cnt.attr,
6678 &raid5_skip_copy.attr,
6679 &raid5_rmw_level.attr,
6680 &r5c_journal_mode.attr,
6681 &ppl_write_hint.attr,
6684 static struct attribute_group raid5_attrs_group = {
6686 .attrs = raid5_attrs,
6689 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6691 int *worker_cnt_per_group,
6692 struct r5worker_group **worker_groups)
6696 struct r5worker *workers;
6698 *worker_cnt_per_group = cnt;
6701 *worker_groups = NULL;
6704 *group_cnt = num_possible_nodes();
6705 size = sizeof(struct r5worker) * cnt;
6706 workers = kcalloc(size, *group_cnt, GFP_NOIO);
6707 *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6709 if (!*worker_groups || !workers) {
6711 kfree(*worker_groups);
6715 for (i = 0; i < *group_cnt; i++) {
6716 struct r5worker_group *group;
6718 group = &(*worker_groups)[i];
6719 INIT_LIST_HEAD(&group->handle_list);
6720 INIT_LIST_HEAD(&group->loprio_list);
6722 group->workers = workers + i * cnt;
6724 for (j = 0; j < cnt; j++) {
6725 struct r5worker *worker = group->workers + j;
6726 worker->group = group;
6727 INIT_WORK(&worker->work, raid5_do_work);
6729 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6730 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6737 static void free_thread_groups(struct r5conf *conf)
6739 if (conf->worker_groups)
6740 kfree(conf->worker_groups[0].workers);
6741 kfree(conf->worker_groups);
6742 conf->worker_groups = NULL;
6746 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6748 struct r5conf *conf = mddev->private;
6751 sectors = mddev->dev_sectors;
6753 /* size is defined by the smallest of previous and new size */
6754 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6756 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6757 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6758 return sectors * (raid_disks - conf->max_degraded);
6761 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6763 safe_put_page(percpu->spare_page);
6764 percpu->spare_page = NULL;
6765 kvfree(percpu->scribble);
6766 percpu->scribble = NULL;
6769 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6771 if (conf->level == 6 && !percpu->spare_page) {
6772 percpu->spare_page = alloc_page(GFP_KERNEL);
6773 if (!percpu->spare_page)
6777 if (scribble_alloc(percpu,
6778 max(conf->raid_disks,
6779 conf->previous_raid_disks),
6780 max(conf->chunk_sectors,
6781 conf->prev_chunk_sectors)
6782 / STRIPE_SECTORS)) {
6783 free_scratch_buffer(conf, percpu);
6790 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
6792 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6794 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6798 static void raid5_free_percpu(struct r5conf *conf)
6803 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6804 free_percpu(conf->percpu);
6807 static void free_conf(struct r5conf *conf)
6813 unregister_shrinker(&conf->shrinker);
6814 free_thread_groups(conf);
6815 shrink_stripes(conf);
6816 raid5_free_percpu(conf);
6817 for (i = 0; i < conf->pool_size; i++)
6818 if (conf->disks[i].extra_page)
6819 put_page(conf->disks[i].extra_page);
6821 bioset_exit(&conf->bio_split);
6822 kfree(conf->stripe_hashtbl);
6823 kfree(conf->pending_data);
6827 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
6829 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6830 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6832 if (alloc_scratch_buffer(conf, percpu)) {
6833 pr_warn("%s: failed memory allocation for cpu%u\n",
6840 static int raid5_alloc_percpu(struct r5conf *conf)
6844 conf->percpu = alloc_percpu(struct raid5_percpu);
6848 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6850 conf->scribble_disks = max(conf->raid_disks,
6851 conf->previous_raid_disks);
6852 conf->scribble_sectors = max(conf->chunk_sectors,
6853 conf->prev_chunk_sectors);
6858 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6859 struct shrink_control *sc)
6861 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6862 unsigned long ret = SHRINK_STOP;
6864 if (mutex_trylock(&conf->cache_size_mutex)) {
6866 while (ret < sc->nr_to_scan &&
6867 conf->max_nr_stripes > conf->min_nr_stripes) {
6868 if (drop_one_stripe(conf) == 0) {
6874 mutex_unlock(&conf->cache_size_mutex);
6879 static unsigned long raid5_cache_count(struct shrinker *shrink,
6880 struct shrink_control *sc)
6882 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6884 if (conf->max_nr_stripes < conf->min_nr_stripes)
6885 /* unlikely, but not impossible */
6887 return conf->max_nr_stripes - conf->min_nr_stripes;
6890 static struct r5conf *setup_conf(struct mddev *mddev)
6892 struct r5conf *conf;
6893 int raid_disk, memory, max_disks;
6894 struct md_rdev *rdev;
6895 struct disk_info *disk;
6898 int group_cnt, worker_cnt_per_group;
6899 struct r5worker_group *new_group;
6902 if (mddev->new_level != 5
6903 && mddev->new_level != 4
6904 && mddev->new_level != 6) {
6905 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6906 mdname(mddev), mddev->new_level);
6907 return ERR_PTR(-EIO);
6909 if ((mddev->new_level == 5
6910 && !algorithm_valid_raid5(mddev->new_layout)) ||
6911 (mddev->new_level == 6
6912 && !algorithm_valid_raid6(mddev->new_layout))) {
6913 pr_warn("md/raid:%s: layout %d not supported\n",
6914 mdname(mddev), mddev->new_layout);
6915 return ERR_PTR(-EIO);
6917 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6918 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6919 mdname(mddev), mddev->raid_disks);
6920 return ERR_PTR(-EINVAL);
6923 if (!mddev->new_chunk_sectors ||
6924 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6925 !is_power_of_2(mddev->new_chunk_sectors)) {
6926 pr_warn("md/raid:%s: invalid chunk size %d\n",
6927 mdname(mddev), mddev->new_chunk_sectors << 9);
6928 return ERR_PTR(-EINVAL);
6931 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6934 INIT_LIST_HEAD(&conf->free_list);
6935 INIT_LIST_HEAD(&conf->pending_list);
6936 conf->pending_data = kcalloc(PENDING_IO_MAX,
6937 sizeof(struct r5pending_data),
6939 if (!conf->pending_data)
6941 for (i = 0; i < PENDING_IO_MAX; i++)
6942 list_add(&conf->pending_data[i].sibling, &conf->free_list);
6943 /* Don't enable multi-threading by default*/
6944 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6946 conf->group_cnt = group_cnt;
6947 conf->worker_cnt_per_group = worker_cnt_per_group;
6948 conf->worker_groups = new_group;
6951 spin_lock_init(&conf->device_lock);
6952 seqcount_init(&conf->gen_lock);
6953 mutex_init(&conf->cache_size_mutex);
6954 init_waitqueue_head(&conf->wait_for_quiescent);
6955 init_waitqueue_head(&conf->wait_for_stripe);
6956 init_waitqueue_head(&conf->wait_for_overlap);
6957 INIT_LIST_HEAD(&conf->handle_list);
6958 INIT_LIST_HEAD(&conf->loprio_list);
6959 INIT_LIST_HEAD(&conf->hold_list);
6960 INIT_LIST_HEAD(&conf->delayed_list);
6961 INIT_LIST_HEAD(&conf->bitmap_list);
6962 init_llist_head(&conf->released_stripes);
6963 atomic_set(&conf->active_stripes, 0);
6964 atomic_set(&conf->preread_active_stripes, 0);
6965 atomic_set(&conf->active_aligned_reads, 0);
6966 spin_lock_init(&conf->pending_bios_lock);
6967 conf->batch_bio_dispatch = true;
6968 rdev_for_each(rdev, mddev) {
6969 if (test_bit(Journal, &rdev->flags))
6971 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
6972 conf->batch_bio_dispatch = false;
6977 conf->bypass_threshold = BYPASS_THRESHOLD;
6978 conf->recovery_disabled = mddev->recovery_disabled - 1;
6980 conf->raid_disks = mddev->raid_disks;
6981 if (mddev->reshape_position == MaxSector)
6982 conf->previous_raid_disks = mddev->raid_disks;
6984 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6985 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6987 conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
6993 for (i = 0; i < max_disks; i++) {
6994 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
6995 if (!conf->disks[i].extra_page)
6999 ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7002 conf->mddev = mddev;
7004 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7007 /* We init hash_locks[0] separately to that it can be used
7008 * as the reference lock in the spin_lock_nest_lock() call
7009 * in lock_all_device_hash_locks_irq in order to convince
7010 * lockdep that we know what we are doing.
7012 spin_lock_init(conf->hash_locks);
7013 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7014 spin_lock_init(conf->hash_locks + i);
7016 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7017 INIT_LIST_HEAD(conf->inactive_list + i);
7019 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7020 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7022 atomic_set(&conf->r5c_cached_full_stripes, 0);
7023 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7024 atomic_set(&conf->r5c_cached_partial_stripes, 0);
7025 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7026 atomic_set(&conf->r5c_flushing_full_stripes, 0);
7027 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7029 conf->level = mddev->new_level;
7030 conf->chunk_sectors = mddev->new_chunk_sectors;
7031 if (raid5_alloc_percpu(conf) != 0)
7034 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7036 rdev_for_each(rdev, mddev) {
7037 raid_disk = rdev->raid_disk;
7038 if (raid_disk >= max_disks
7039 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7041 disk = conf->disks + raid_disk;
7043 if (test_bit(Replacement, &rdev->flags)) {
7044 if (disk->replacement)
7046 disk->replacement = rdev;
7053 if (test_bit(In_sync, &rdev->flags)) {
7054 char b[BDEVNAME_SIZE];
7055 pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7056 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7057 } else if (rdev->saved_raid_disk != raid_disk)
7058 /* Cannot rely on bitmap to complete recovery */
7062 conf->level = mddev->new_level;
7063 if (conf->level == 6) {
7064 conf->max_degraded = 2;
7065 if (raid6_call.xor_syndrome)
7066 conf->rmw_level = PARITY_ENABLE_RMW;
7068 conf->rmw_level = PARITY_DISABLE_RMW;
7070 conf->max_degraded = 1;
7071 conf->rmw_level = PARITY_ENABLE_RMW;
7073 conf->algorithm = mddev->new_layout;
7074 conf->reshape_progress = mddev->reshape_position;
7075 if (conf->reshape_progress != MaxSector) {
7076 conf->prev_chunk_sectors = mddev->chunk_sectors;
7077 conf->prev_algo = mddev->layout;
7079 conf->prev_chunk_sectors = conf->chunk_sectors;
7080 conf->prev_algo = conf->algorithm;
7083 conf->min_nr_stripes = NR_STRIPES;
7084 if (mddev->reshape_position != MaxSector) {
7085 int stripes = max_t(int,
7086 ((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4,
7087 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4);
7088 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7089 if (conf->min_nr_stripes != NR_STRIPES)
7090 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7091 mdname(mddev), conf->min_nr_stripes);
7093 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7094 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7095 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7096 if (grow_stripes(conf, conf->min_nr_stripes)) {
7097 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7098 mdname(mddev), memory);
7101 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7103 * Losing a stripe head costs more than the time to refill it,
7104 * it reduces the queue depth and so can hurt throughput.
7105 * So set it rather large, scaled by number of devices.
7107 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7108 conf->shrinker.scan_objects = raid5_cache_scan;
7109 conf->shrinker.count_objects = raid5_cache_count;
7110 conf->shrinker.batch = 128;
7111 conf->shrinker.flags = 0;
7112 if (register_shrinker(&conf->shrinker)) {
7113 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7118 sprintf(pers_name, "raid%d", mddev->new_level);
7119 conf->thread = md_register_thread(raid5d, mddev, pers_name);
7120 if (!conf->thread) {
7121 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7131 return ERR_PTR(-EIO);
7133 return ERR_PTR(-ENOMEM);
7136 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7139 case ALGORITHM_PARITY_0:
7140 if (raid_disk < max_degraded)
7143 case ALGORITHM_PARITY_N:
7144 if (raid_disk >= raid_disks - max_degraded)
7147 case ALGORITHM_PARITY_0_6:
7148 if (raid_disk == 0 ||
7149 raid_disk == raid_disks - 1)
7152 case ALGORITHM_LEFT_ASYMMETRIC_6:
7153 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7154 case ALGORITHM_LEFT_SYMMETRIC_6:
7155 case ALGORITHM_RIGHT_SYMMETRIC_6:
7156 if (raid_disk == raid_disks - 1)
7162 static int raid5_run(struct mddev *mddev)
7164 struct r5conf *conf;
7165 int working_disks = 0;
7166 int dirty_parity_disks = 0;
7167 struct md_rdev *rdev;
7168 struct md_rdev *journal_dev = NULL;
7169 sector_t reshape_offset = 0;
7171 long long min_offset_diff = 0;
7174 if (mddev_init_writes_pending(mddev) < 0)
7177 if (mddev->recovery_cp != MaxSector)
7178 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7181 rdev_for_each(rdev, mddev) {
7184 if (test_bit(Journal, &rdev->flags)) {
7188 if (rdev->raid_disk < 0)
7190 diff = (rdev->new_data_offset - rdev->data_offset);
7192 min_offset_diff = diff;
7194 } else if (mddev->reshape_backwards &&
7195 diff < min_offset_diff)
7196 min_offset_diff = diff;
7197 else if (!mddev->reshape_backwards &&
7198 diff > min_offset_diff)
7199 min_offset_diff = diff;
7202 if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7203 (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7204 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7209 if (mddev->reshape_position != MaxSector) {
7210 /* Check that we can continue the reshape.
7211 * Difficulties arise if the stripe we would write to
7212 * next is at or after the stripe we would read from next.
7213 * For a reshape that changes the number of devices, this
7214 * is only possible for a very short time, and mdadm makes
7215 * sure that time appears to have past before assembling
7216 * the array. So we fail if that time hasn't passed.
7217 * For a reshape that keeps the number of devices the same
7218 * mdadm must be monitoring the reshape can keeping the
7219 * critical areas read-only and backed up. It will start
7220 * the array in read-only mode, so we check for that.
7222 sector_t here_new, here_old;
7224 int max_degraded = (mddev->level == 6 ? 2 : 1);
7229 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7234 if (mddev->new_level != mddev->level) {
7235 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7239 old_disks = mddev->raid_disks - mddev->delta_disks;
7240 /* reshape_position must be on a new-stripe boundary, and one
7241 * further up in new geometry must map after here in old
7243 * If the chunk sizes are different, then as we perform reshape
7244 * in units of the largest of the two, reshape_position needs
7245 * be a multiple of the largest chunk size times new data disks.
7247 here_new = mddev->reshape_position;
7248 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7249 new_data_disks = mddev->raid_disks - max_degraded;
7250 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7251 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7255 reshape_offset = here_new * chunk_sectors;
7256 /* here_new is the stripe we will write to */
7257 here_old = mddev->reshape_position;
7258 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7259 /* here_old is the first stripe that we might need to read
7261 if (mddev->delta_disks == 0) {
7262 /* We cannot be sure it is safe to start an in-place
7263 * reshape. It is only safe if user-space is monitoring
7264 * and taking constant backups.
7265 * mdadm always starts a situation like this in
7266 * readonly mode so it can take control before
7267 * allowing any writes. So just check for that.
7269 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7270 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7271 /* not really in-place - so OK */;
7272 else if (mddev->ro == 0) {
7273 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7277 } else if (mddev->reshape_backwards
7278 ? (here_new * chunk_sectors + min_offset_diff <=
7279 here_old * chunk_sectors)
7280 : (here_new * chunk_sectors >=
7281 here_old * chunk_sectors + (-min_offset_diff))) {
7282 /* Reading from the same stripe as writing to - bad */
7283 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7287 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7288 /* OK, we should be able to continue; */
7290 BUG_ON(mddev->level != mddev->new_level);
7291 BUG_ON(mddev->layout != mddev->new_layout);
7292 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7293 BUG_ON(mddev->delta_disks != 0);
7296 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7297 test_bit(MD_HAS_PPL, &mddev->flags)) {
7298 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7300 clear_bit(MD_HAS_PPL, &mddev->flags);
7301 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7304 if (mddev->private == NULL)
7305 conf = setup_conf(mddev);
7307 conf = mddev->private;
7310 return PTR_ERR(conf);
7312 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7314 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7317 set_disk_ro(mddev->gendisk, 1);
7318 } else if (mddev->recovery_cp == MaxSector)
7319 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7322 conf->min_offset_diff = min_offset_diff;
7323 mddev->thread = conf->thread;
7324 conf->thread = NULL;
7325 mddev->private = conf;
7327 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7329 rdev = conf->disks[i].rdev;
7330 if (!rdev && conf->disks[i].replacement) {
7331 /* The replacement is all we have yet */
7332 rdev = conf->disks[i].replacement;
7333 conf->disks[i].replacement = NULL;
7334 clear_bit(Replacement, &rdev->flags);
7335 conf->disks[i].rdev = rdev;
7339 if (conf->disks[i].replacement &&
7340 conf->reshape_progress != MaxSector) {
7341 /* replacements and reshape simply do not mix. */
7342 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7345 if (test_bit(In_sync, &rdev->flags)) {
7349 /* This disc is not fully in-sync. However if it
7350 * just stored parity (beyond the recovery_offset),
7351 * when we don't need to be concerned about the
7352 * array being dirty.
7353 * When reshape goes 'backwards', we never have
7354 * partially completed devices, so we only need
7355 * to worry about reshape going forwards.
7357 /* Hack because v0.91 doesn't store recovery_offset properly. */
7358 if (mddev->major_version == 0 &&
7359 mddev->minor_version > 90)
7360 rdev->recovery_offset = reshape_offset;
7362 if (rdev->recovery_offset < reshape_offset) {
7363 /* We need to check old and new layout */
7364 if (!only_parity(rdev->raid_disk,
7367 conf->max_degraded))
7370 if (!only_parity(rdev->raid_disk,
7372 conf->previous_raid_disks,
7373 conf->max_degraded))
7375 dirty_parity_disks++;
7379 * 0 for a fully functional array, 1 or 2 for a degraded array.
7381 mddev->degraded = raid5_calc_degraded(conf);
7383 if (has_failed(conf)) {
7384 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7385 mdname(mddev), mddev->degraded, conf->raid_disks);
7389 /* device size must be a multiple of chunk size */
7390 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7391 mddev->resync_max_sectors = mddev->dev_sectors;
7393 if (mddev->degraded > dirty_parity_disks &&
7394 mddev->recovery_cp != MaxSector) {
7395 if (test_bit(MD_HAS_PPL, &mddev->flags))
7396 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7398 else if (mddev->ok_start_degraded)
7399 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7402 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7408 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7409 mdname(mddev), conf->level,
7410 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7413 print_raid5_conf(conf);
7415 if (conf->reshape_progress != MaxSector) {
7416 conf->reshape_safe = conf->reshape_progress;
7417 atomic_set(&conf->reshape_stripes, 0);
7418 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7419 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7420 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7421 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7422 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7424 if (!mddev->sync_thread)
7428 /* Ok, everything is just fine now */
7429 if (mddev->to_remove == &raid5_attrs_group)
7430 mddev->to_remove = NULL;
7431 else if (mddev->kobj.sd &&
7432 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7433 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7435 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7439 /* read-ahead size must cover two whole stripes, which
7440 * is 2 * (datadisks) * chunksize where 'n' is the
7441 * number of raid devices
7443 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7444 int stripe = data_disks *
7445 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7446 if (mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
7447 mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
7449 chunk_size = mddev->chunk_sectors << 9;
7450 blk_queue_io_min(mddev->queue, chunk_size);
7451 blk_queue_io_opt(mddev->queue, chunk_size *
7452 (conf->raid_disks - conf->max_degraded));
7453 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7455 * We can only discard a whole stripe. It doesn't make sense to
7456 * discard data disk but write parity disk
7458 stripe = stripe * PAGE_SIZE;
7459 /* Round up to power of 2, as discard handling
7460 * currently assumes that */
7461 while ((stripe-1) & stripe)
7462 stripe = (stripe | (stripe-1)) + 1;
7463 mddev->queue->limits.discard_alignment = stripe;
7464 mddev->queue->limits.discard_granularity = stripe;
7466 blk_queue_max_write_same_sectors(mddev->queue, 0);
7467 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7469 rdev_for_each(rdev, mddev) {
7470 disk_stack_limits(mddev->gendisk, rdev->bdev,
7471 rdev->data_offset << 9);
7472 disk_stack_limits(mddev->gendisk, rdev->bdev,
7473 rdev->new_data_offset << 9);
7477 * zeroing is required, otherwise data
7478 * could be lost. Consider a scenario: discard a stripe
7479 * (the stripe could be inconsistent if
7480 * discard_zeroes_data is 0); write one disk of the
7481 * stripe (the stripe could be inconsistent again
7482 * depending on which disks are used to calculate
7483 * parity); the disk is broken; The stripe data of this
7486 * We only allow DISCARD if the sysadmin has confirmed that
7487 * only safe devices are in use by setting a module parameter.
7488 * A better idea might be to turn DISCARD into WRITE_ZEROES
7489 * requests, as that is required to be safe.
7491 if (devices_handle_discard_safely &&
7492 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7493 mddev->queue->limits.discard_granularity >= stripe)
7494 blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7497 blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7500 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7503 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7508 md_unregister_thread(&mddev->thread);
7509 print_raid5_conf(conf);
7511 mddev->private = NULL;
7512 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7516 static void raid5_free(struct mddev *mddev, void *priv)
7518 struct r5conf *conf = priv;
7521 mddev->to_remove = &raid5_attrs_group;
7524 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7526 struct r5conf *conf = mddev->private;
7529 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7530 conf->chunk_sectors / 2, mddev->layout);
7531 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7533 for (i = 0; i < conf->raid_disks; i++) {
7534 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7535 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7538 seq_printf (seq, "]");
7541 static void print_raid5_conf (struct r5conf *conf)
7544 struct disk_info *tmp;
7546 pr_debug("RAID conf printout:\n");
7548 pr_debug("(conf==NULL)\n");
7551 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7553 conf->raid_disks - conf->mddev->degraded);
7555 for (i = 0; i < conf->raid_disks; i++) {
7556 char b[BDEVNAME_SIZE];
7557 tmp = conf->disks + i;
7559 pr_debug(" disk %d, o:%d, dev:%s\n",
7560 i, !test_bit(Faulty, &tmp->rdev->flags),
7561 bdevname(tmp->rdev->bdev, b));
7565 static int raid5_spare_active(struct mddev *mddev)
7568 struct r5conf *conf = mddev->private;
7569 struct disk_info *tmp;
7571 unsigned long flags;
7573 for (i = 0; i < conf->raid_disks; i++) {
7574 tmp = conf->disks + i;
7575 if (tmp->replacement
7576 && tmp->replacement->recovery_offset == MaxSector
7577 && !test_bit(Faulty, &tmp->replacement->flags)
7578 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7579 /* Replacement has just become active. */
7581 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7584 /* Replaced device not technically faulty,
7585 * but we need to be sure it gets removed
7586 * and never re-added.
7588 set_bit(Faulty, &tmp->rdev->flags);
7589 sysfs_notify_dirent_safe(
7590 tmp->rdev->sysfs_state);
7592 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7593 } else if (tmp->rdev
7594 && tmp->rdev->recovery_offset == MaxSector
7595 && !test_bit(Faulty, &tmp->rdev->flags)
7596 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7598 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7601 spin_lock_irqsave(&conf->device_lock, flags);
7602 mddev->degraded = raid5_calc_degraded(conf);
7603 spin_unlock_irqrestore(&conf->device_lock, flags);
7604 print_raid5_conf(conf);
7608 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7610 struct r5conf *conf = mddev->private;
7612 int number = rdev->raid_disk;
7613 struct md_rdev **rdevp;
7614 struct disk_info *p = conf->disks + number;
7616 print_raid5_conf(conf);
7617 if (test_bit(Journal, &rdev->flags) && conf->log) {
7619 * we can't wait pending write here, as this is called in
7620 * raid5d, wait will deadlock.
7621 * neilb: there is no locking about new writes here,
7622 * so this cannot be safe.
7624 if (atomic_read(&conf->active_stripes) ||
7625 atomic_read(&conf->r5c_cached_full_stripes) ||
7626 atomic_read(&conf->r5c_cached_partial_stripes)) {
7632 if (rdev == p->rdev)
7634 else if (rdev == p->replacement)
7635 rdevp = &p->replacement;
7639 if (number >= conf->raid_disks &&
7640 conf->reshape_progress == MaxSector)
7641 clear_bit(In_sync, &rdev->flags);
7643 if (test_bit(In_sync, &rdev->flags) ||
7644 atomic_read(&rdev->nr_pending)) {
7648 /* Only remove non-faulty devices if recovery
7651 if (!test_bit(Faulty, &rdev->flags) &&
7652 mddev->recovery_disabled != conf->recovery_disabled &&
7653 !has_failed(conf) &&
7654 (!p->replacement || p->replacement == rdev) &&
7655 number < conf->raid_disks) {
7660 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7662 if (atomic_read(&rdev->nr_pending)) {
7663 /* lost the race, try later */
7669 err = log_modify(conf, rdev, false);
7673 if (p->replacement) {
7674 /* We must have just cleared 'rdev' */
7675 p->rdev = p->replacement;
7676 clear_bit(Replacement, &p->replacement->flags);
7677 smp_mb(); /* Make sure other CPUs may see both as identical
7678 * but will never see neither - if they are careful
7680 p->replacement = NULL;
7683 err = log_modify(conf, p->rdev, true);
7686 clear_bit(WantReplacement, &rdev->flags);
7689 print_raid5_conf(conf);
7693 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7695 struct r5conf *conf = mddev->private;
7696 int ret, err = -EEXIST;
7698 struct disk_info *p;
7700 int last = conf->raid_disks - 1;
7702 if (test_bit(Journal, &rdev->flags)) {
7706 rdev->raid_disk = 0;
7708 * The array is in readonly mode if journal is missing, so no
7709 * write requests running. We should be safe
7711 ret = log_init(conf, rdev, false);
7715 ret = r5l_start(conf->log);
7721 if (mddev->recovery_disabled == conf->recovery_disabled)
7724 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7725 /* no point adding a device */
7728 if (rdev->raid_disk >= 0)
7729 first = last = rdev->raid_disk;
7732 * find the disk ... but prefer rdev->saved_raid_disk
7735 if (rdev->saved_raid_disk >= 0 &&
7736 rdev->saved_raid_disk >= first &&
7737 rdev->saved_raid_disk <= last &&
7738 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7739 first = rdev->saved_raid_disk;
7741 for (disk = first; disk <= last; disk++) {
7742 p = conf->disks + disk;
7743 if (p->rdev == NULL) {
7744 clear_bit(In_sync, &rdev->flags);
7745 rdev->raid_disk = disk;
7746 if (rdev->saved_raid_disk != disk)
7748 rcu_assign_pointer(p->rdev, rdev);
7750 err = log_modify(conf, rdev, true);
7755 for (disk = first; disk <= last; disk++) {
7756 p = conf->disks + disk;
7757 if (test_bit(WantReplacement, &p->rdev->flags) &&
7758 p->replacement == NULL) {
7759 clear_bit(In_sync, &rdev->flags);
7760 set_bit(Replacement, &rdev->flags);
7761 rdev->raid_disk = disk;
7764 rcu_assign_pointer(p->replacement, rdev);
7769 print_raid5_conf(conf);
7773 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7775 /* no resync is happening, and there is enough space
7776 * on all devices, so we can resize.
7777 * We need to make sure resync covers any new space.
7778 * If the array is shrinking we should possibly wait until
7779 * any io in the removed space completes, but it hardly seems
7783 struct r5conf *conf = mddev->private;
7785 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7787 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7788 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7789 if (mddev->external_size &&
7790 mddev->array_sectors > newsize)
7792 if (mddev->bitmap) {
7793 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
7797 md_set_array_sectors(mddev, newsize);
7798 if (sectors > mddev->dev_sectors &&
7799 mddev->recovery_cp > mddev->dev_sectors) {
7800 mddev->recovery_cp = mddev->dev_sectors;
7801 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7803 mddev->dev_sectors = sectors;
7804 mddev->resync_max_sectors = sectors;
7808 static int check_stripe_cache(struct mddev *mddev)
7810 /* Can only proceed if there are plenty of stripe_heads.
7811 * We need a minimum of one full stripe,, and for sensible progress
7812 * it is best to have about 4 times that.
7813 * If we require 4 times, then the default 256 4K stripe_heads will
7814 * allow for chunk sizes up to 256K, which is probably OK.
7815 * If the chunk size is greater, user-space should request more
7816 * stripe_heads first.
7818 struct r5conf *conf = mddev->private;
7819 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7820 > conf->min_nr_stripes ||
7821 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7822 > conf->min_nr_stripes) {
7823 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7825 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7832 static int check_reshape(struct mddev *mddev)
7834 struct r5conf *conf = mddev->private;
7836 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7838 if (mddev->delta_disks == 0 &&
7839 mddev->new_layout == mddev->layout &&
7840 mddev->new_chunk_sectors == mddev->chunk_sectors)
7841 return 0; /* nothing to do */
7842 if (has_failed(conf))
7844 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7845 /* We might be able to shrink, but the devices must
7846 * be made bigger first.
7847 * For raid6, 4 is the minimum size.
7848 * Otherwise 2 is the minimum
7851 if (mddev->level == 6)
7853 if (mddev->raid_disks + mddev->delta_disks < min)
7857 if (!check_stripe_cache(mddev))
7860 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7861 mddev->delta_disks > 0)
7862 if (resize_chunks(conf,
7863 conf->previous_raid_disks
7864 + max(0, mddev->delta_disks),
7865 max(mddev->new_chunk_sectors,
7866 mddev->chunk_sectors)
7870 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
7871 return 0; /* never bother to shrink */
7872 return resize_stripes(conf, (conf->previous_raid_disks
7873 + mddev->delta_disks));
7876 static int raid5_start_reshape(struct mddev *mddev)
7878 struct r5conf *conf = mddev->private;
7879 struct md_rdev *rdev;
7881 unsigned long flags;
7883 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7886 if (!check_stripe_cache(mddev))
7889 if (has_failed(conf))
7892 rdev_for_each(rdev, mddev) {
7893 if (!test_bit(In_sync, &rdev->flags)
7894 && !test_bit(Faulty, &rdev->flags))
7898 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7899 /* Not enough devices even to make a degraded array
7904 /* Refuse to reduce size of the array. Any reductions in
7905 * array size must be through explicit setting of array_size
7908 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7909 < mddev->array_sectors) {
7910 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
7915 atomic_set(&conf->reshape_stripes, 0);
7916 spin_lock_irq(&conf->device_lock);
7917 write_seqcount_begin(&conf->gen_lock);
7918 conf->previous_raid_disks = conf->raid_disks;
7919 conf->raid_disks += mddev->delta_disks;
7920 conf->prev_chunk_sectors = conf->chunk_sectors;
7921 conf->chunk_sectors = mddev->new_chunk_sectors;
7922 conf->prev_algo = conf->algorithm;
7923 conf->algorithm = mddev->new_layout;
7925 /* Code that selects data_offset needs to see the generation update
7926 * if reshape_progress has been set - so a memory barrier needed.
7929 if (mddev->reshape_backwards)
7930 conf->reshape_progress = raid5_size(mddev, 0, 0);
7932 conf->reshape_progress = 0;
7933 conf->reshape_safe = conf->reshape_progress;
7934 write_seqcount_end(&conf->gen_lock);
7935 spin_unlock_irq(&conf->device_lock);
7937 /* Now make sure any requests that proceeded on the assumption
7938 * the reshape wasn't running - like Discard or Read - have
7941 mddev_suspend(mddev);
7942 mddev_resume(mddev);
7944 /* Add some new drives, as many as will fit.
7945 * We know there are enough to make the newly sized array work.
7946 * Don't add devices if we are reducing the number of
7947 * devices in the array. This is because it is not possible
7948 * to correctly record the "partially reconstructed" state of
7949 * such devices during the reshape and confusion could result.
7951 if (mddev->delta_disks >= 0) {
7952 rdev_for_each(rdev, mddev)
7953 if (rdev->raid_disk < 0 &&
7954 !test_bit(Faulty, &rdev->flags)) {
7955 if (raid5_add_disk(mddev, rdev) == 0) {
7957 >= conf->previous_raid_disks)
7958 set_bit(In_sync, &rdev->flags);
7960 rdev->recovery_offset = 0;
7962 if (sysfs_link_rdev(mddev, rdev))
7963 /* Failure here is OK */;
7965 } else if (rdev->raid_disk >= conf->previous_raid_disks
7966 && !test_bit(Faulty, &rdev->flags)) {
7967 /* This is a spare that was manually added */
7968 set_bit(In_sync, &rdev->flags);
7971 /* When a reshape changes the number of devices,
7972 * ->degraded is measured against the larger of the
7973 * pre and post number of devices.
7975 spin_lock_irqsave(&conf->device_lock, flags);
7976 mddev->degraded = raid5_calc_degraded(conf);
7977 spin_unlock_irqrestore(&conf->device_lock, flags);
7979 mddev->raid_disks = conf->raid_disks;
7980 mddev->reshape_position = conf->reshape_progress;
7981 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
7983 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7984 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7985 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7986 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7987 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7988 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7990 if (!mddev->sync_thread) {
7991 mddev->recovery = 0;
7992 spin_lock_irq(&conf->device_lock);
7993 write_seqcount_begin(&conf->gen_lock);
7994 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7995 mddev->new_chunk_sectors =
7996 conf->chunk_sectors = conf->prev_chunk_sectors;
7997 mddev->new_layout = conf->algorithm = conf->prev_algo;
7998 rdev_for_each(rdev, mddev)
7999 rdev->new_data_offset = rdev->data_offset;
8001 conf->generation --;
8002 conf->reshape_progress = MaxSector;
8003 mddev->reshape_position = MaxSector;
8004 write_seqcount_end(&conf->gen_lock);
8005 spin_unlock_irq(&conf->device_lock);
8008 conf->reshape_checkpoint = jiffies;
8009 md_wakeup_thread(mddev->sync_thread);
8010 md_new_event(mddev);
8014 /* This is called from the reshape thread and should make any
8015 * changes needed in 'conf'
8017 static void end_reshape(struct r5conf *conf)
8020 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8021 struct md_rdev *rdev;
8023 spin_lock_irq(&conf->device_lock);
8024 conf->previous_raid_disks = conf->raid_disks;
8025 md_finish_reshape(conf->mddev);
8027 conf->reshape_progress = MaxSector;
8028 conf->mddev->reshape_position = MaxSector;
8029 rdev_for_each(rdev, conf->mddev)
8030 if (rdev->raid_disk >= 0 &&
8031 !test_bit(Journal, &rdev->flags) &&
8032 !test_bit(In_sync, &rdev->flags))
8033 rdev->recovery_offset = MaxSector;
8034 spin_unlock_irq(&conf->device_lock);
8035 wake_up(&conf->wait_for_overlap);
8037 /* read-ahead size must cover two whole stripes, which is
8038 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
8040 if (conf->mddev->queue) {
8041 int data_disks = conf->raid_disks - conf->max_degraded;
8042 int stripe = data_disks * ((conf->chunk_sectors << 9)
8044 if (conf->mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
8045 conf->mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
8050 /* This is called from the raid5d thread with mddev_lock held.
8051 * It makes config changes to the device.
8053 static void raid5_finish_reshape(struct mddev *mddev)
8055 struct r5conf *conf = mddev->private;
8057 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8059 if (mddev->delta_disks <= 0) {
8061 spin_lock_irq(&conf->device_lock);
8062 mddev->degraded = raid5_calc_degraded(conf);
8063 spin_unlock_irq(&conf->device_lock);
8064 for (d = conf->raid_disks ;
8065 d < conf->raid_disks - mddev->delta_disks;
8067 struct md_rdev *rdev = conf->disks[d].rdev;
8069 clear_bit(In_sync, &rdev->flags);
8070 rdev = conf->disks[d].replacement;
8072 clear_bit(In_sync, &rdev->flags);
8075 mddev->layout = conf->algorithm;
8076 mddev->chunk_sectors = conf->chunk_sectors;
8077 mddev->reshape_position = MaxSector;
8078 mddev->delta_disks = 0;
8079 mddev->reshape_backwards = 0;
8083 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8085 struct r5conf *conf = mddev->private;
8088 /* stop all writes */
8089 lock_all_device_hash_locks_irq(conf);
8090 /* '2' tells resync/reshape to pause so that all
8091 * active stripes can drain
8093 r5c_flush_cache(conf, INT_MAX);
8095 wait_event_cmd(conf->wait_for_quiescent,
8096 atomic_read(&conf->active_stripes) == 0 &&
8097 atomic_read(&conf->active_aligned_reads) == 0,
8098 unlock_all_device_hash_locks_irq(conf),
8099 lock_all_device_hash_locks_irq(conf));
8101 unlock_all_device_hash_locks_irq(conf);
8102 /* allow reshape to continue */
8103 wake_up(&conf->wait_for_overlap);
8105 /* re-enable writes */
8106 lock_all_device_hash_locks_irq(conf);
8108 wake_up(&conf->wait_for_quiescent);
8109 wake_up(&conf->wait_for_overlap);
8110 unlock_all_device_hash_locks_irq(conf);
8112 log_quiesce(conf, quiesce);
8115 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8117 struct r0conf *raid0_conf = mddev->private;
8120 /* for raid0 takeover only one zone is supported */
8121 if (raid0_conf->nr_strip_zones > 1) {
8122 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8124 return ERR_PTR(-EINVAL);
8127 sectors = raid0_conf->strip_zone[0].zone_end;
8128 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8129 mddev->dev_sectors = sectors;
8130 mddev->new_level = level;
8131 mddev->new_layout = ALGORITHM_PARITY_N;
8132 mddev->new_chunk_sectors = mddev->chunk_sectors;
8133 mddev->raid_disks += 1;
8134 mddev->delta_disks = 1;
8135 /* make sure it will be not marked as dirty */
8136 mddev->recovery_cp = MaxSector;
8138 return setup_conf(mddev);
8141 static void *raid5_takeover_raid1(struct mddev *mddev)
8146 if (mddev->raid_disks != 2 ||
8147 mddev->degraded > 1)
8148 return ERR_PTR(-EINVAL);
8150 /* Should check if there are write-behind devices? */
8152 chunksect = 64*2; /* 64K by default */
8154 /* The array must be an exact multiple of chunksize */
8155 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8158 if ((chunksect<<9) < STRIPE_SIZE)
8159 /* array size does not allow a suitable chunk size */
8160 return ERR_PTR(-EINVAL);
8162 mddev->new_level = 5;
8163 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8164 mddev->new_chunk_sectors = chunksect;
8166 ret = setup_conf(mddev);
8168 mddev_clear_unsupported_flags(mddev,
8169 UNSUPPORTED_MDDEV_FLAGS);
8173 static void *raid5_takeover_raid6(struct mddev *mddev)
8177 switch (mddev->layout) {
8178 case ALGORITHM_LEFT_ASYMMETRIC_6:
8179 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8181 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8182 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8184 case ALGORITHM_LEFT_SYMMETRIC_6:
8185 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8187 case ALGORITHM_RIGHT_SYMMETRIC_6:
8188 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8190 case ALGORITHM_PARITY_0_6:
8191 new_layout = ALGORITHM_PARITY_0;
8193 case ALGORITHM_PARITY_N:
8194 new_layout = ALGORITHM_PARITY_N;
8197 return ERR_PTR(-EINVAL);
8199 mddev->new_level = 5;
8200 mddev->new_layout = new_layout;
8201 mddev->delta_disks = -1;
8202 mddev->raid_disks -= 1;
8203 return setup_conf(mddev);
8206 static int raid5_check_reshape(struct mddev *mddev)
8208 /* For a 2-drive array, the layout and chunk size can be changed
8209 * immediately as not restriping is needed.
8210 * For larger arrays we record the new value - after validation
8211 * to be used by a reshape pass.
8213 struct r5conf *conf = mddev->private;
8214 int new_chunk = mddev->new_chunk_sectors;
8216 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8218 if (new_chunk > 0) {
8219 if (!is_power_of_2(new_chunk))
8221 if (new_chunk < (PAGE_SIZE>>9))
8223 if (mddev->array_sectors & (new_chunk-1))
8224 /* not factor of array size */
8228 /* They look valid */
8230 if (mddev->raid_disks == 2) {
8231 /* can make the change immediately */
8232 if (mddev->new_layout >= 0) {
8233 conf->algorithm = mddev->new_layout;
8234 mddev->layout = mddev->new_layout;
8236 if (new_chunk > 0) {
8237 conf->chunk_sectors = new_chunk ;
8238 mddev->chunk_sectors = new_chunk;
8240 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8241 md_wakeup_thread(mddev->thread);
8243 return check_reshape(mddev);
8246 static int raid6_check_reshape(struct mddev *mddev)
8248 int new_chunk = mddev->new_chunk_sectors;
8250 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8252 if (new_chunk > 0) {
8253 if (!is_power_of_2(new_chunk))
8255 if (new_chunk < (PAGE_SIZE >> 9))
8257 if (mddev->array_sectors & (new_chunk-1))
8258 /* not factor of array size */
8262 /* They look valid */
8263 return check_reshape(mddev);
8266 static void *raid5_takeover(struct mddev *mddev)
8268 /* raid5 can take over:
8269 * raid0 - if there is only one strip zone - make it a raid4 layout
8270 * raid1 - if there are two drives. We need to know the chunk size
8271 * raid4 - trivial - just use a raid4 layout.
8272 * raid6 - Providing it is a *_6 layout
8274 if (mddev->level == 0)
8275 return raid45_takeover_raid0(mddev, 5);
8276 if (mddev->level == 1)
8277 return raid5_takeover_raid1(mddev);
8278 if (mddev->level == 4) {
8279 mddev->new_layout = ALGORITHM_PARITY_N;
8280 mddev->new_level = 5;
8281 return setup_conf(mddev);
8283 if (mddev->level == 6)
8284 return raid5_takeover_raid6(mddev);
8286 return ERR_PTR(-EINVAL);
8289 static void *raid4_takeover(struct mddev *mddev)
8291 /* raid4 can take over:
8292 * raid0 - if there is only one strip zone
8293 * raid5 - if layout is right
8295 if (mddev->level == 0)
8296 return raid45_takeover_raid0(mddev, 4);
8297 if (mddev->level == 5 &&
8298 mddev->layout == ALGORITHM_PARITY_N) {
8299 mddev->new_layout = 0;
8300 mddev->new_level = 4;
8301 return setup_conf(mddev);
8303 return ERR_PTR(-EINVAL);
8306 static struct md_personality raid5_personality;
8308 static void *raid6_takeover(struct mddev *mddev)
8310 /* Currently can only take over a raid5. We map the
8311 * personality to an equivalent raid6 personality
8312 * with the Q block at the end.
8316 if (mddev->pers != &raid5_personality)
8317 return ERR_PTR(-EINVAL);
8318 if (mddev->degraded > 1)
8319 return ERR_PTR(-EINVAL);
8320 if (mddev->raid_disks > 253)
8321 return ERR_PTR(-EINVAL);
8322 if (mddev->raid_disks < 3)
8323 return ERR_PTR(-EINVAL);
8325 switch (mddev->layout) {
8326 case ALGORITHM_LEFT_ASYMMETRIC:
8327 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8329 case ALGORITHM_RIGHT_ASYMMETRIC:
8330 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8332 case ALGORITHM_LEFT_SYMMETRIC:
8333 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8335 case ALGORITHM_RIGHT_SYMMETRIC:
8336 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8338 case ALGORITHM_PARITY_0:
8339 new_layout = ALGORITHM_PARITY_0_6;
8341 case ALGORITHM_PARITY_N:
8342 new_layout = ALGORITHM_PARITY_N;
8345 return ERR_PTR(-EINVAL);
8347 mddev->new_level = 6;
8348 mddev->new_layout = new_layout;
8349 mddev->delta_disks = 1;
8350 mddev->raid_disks += 1;
8351 return setup_conf(mddev);
8354 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8356 struct r5conf *conf;
8359 err = mddev_lock(mddev);
8362 conf = mddev->private;
8364 mddev_unlock(mddev);
8368 if (strncmp(buf, "ppl", 3) == 0) {
8369 /* ppl only works with RAID 5 */
8370 if (!raid5_has_ppl(conf) && conf->level == 5) {
8371 err = log_init(conf, NULL, true);
8373 err = resize_stripes(conf, conf->pool_size);
8379 } else if (strncmp(buf, "resync", 6) == 0) {
8380 if (raid5_has_ppl(conf)) {
8381 mddev_suspend(mddev);
8383 mddev_resume(mddev);
8384 err = resize_stripes(conf, conf->pool_size);
8385 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8386 r5l_log_disk_error(conf)) {
8387 bool journal_dev_exists = false;
8388 struct md_rdev *rdev;
8390 rdev_for_each(rdev, mddev)
8391 if (test_bit(Journal, &rdev->flags)) {
8392 journal_dev_exists = true;
8396 if (!journal_dev_exists) {
8397 mddev_suspend(mddev);
8398 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8399 mddev_resume(mddev);
8400 } else /* need remove journal device first */
8409 md_update_sb(mddev, 1);
8411 mddev_unlock(mddev);
8416 static int raid5_start(struct mddev *mddev)
8418 struct r5conf *conf = mddev->private;
8420 return r5l_start(conf->log);
8423 static struct md_personality raid6_personality =
8427 .owner = THIS_MODULE,
8428 .make_request = raid5_make_request,
8430 .start = raid5_start,
8432 .status = raid5_status,
8433 .error_handler = raid5_error,
8434 .hot_add_disk = raid5_add_disk,
8435 .hot_remove_disk= raid5_remove_disk,
8436 .spare_active = raid5_spare_active,
8437 .sync_request = raid5_sync_request,
8438 .resize = raid5_resize,
8440 .check_reshape = raid6_check_reshape,
8441 .start_reshape = raid5_start_reshape,
8442 .finish_reshape = raid5_finish_reshape,
8443 .quiesce = raid5_quiesce,
8444 .takeover = raid6_takeover,
8445 .congested = raid5_congested,
8446 .change_consistency_policy = raid5_change_consistency_policy,
8448 static struct md_personality raid5_personality =
8452 .owner = THIS_MODULE,
8453 .make_request = raid5_make_request,
8455 .start = raid5_start,
8457 .status = raid5_status,
8458 .error_handler = raid5_error,
8459 .hot_add_disk = raid5_add_disk,
8460 .hot_remove_disk= raid5_remove_disk,
8461 .spare_active = raid5_spare_active,
8462 .sync_request = raid5_sync_request,
8463 .resize = raid5_resize,
8465 .check_reshape = raid5_check_reshape,
8466 .start_reshape = raid5_start_reshape,
8467 .finish_reshape = raid5_finish_reshape,
8468 .quiesce = raid5_quiesce,
8469 .takeover = raid5_takeover,
8470 .congested = raid5_congested,
8471 .change_consistency_policy = raid5_change_consistency_policy,
8474 static struct md_personality raid4_personality =
8478 .owner = THIS_MODULE,
8479 .make_request = raid5_make_request,
8481 .start = raid5_start,
8483 .status = raid5_status,
8484 .error_handler = raid5_error,
8485 .hot_add_disk = raid5_add_disk,
8486 .hot_remove_disk= raid5_remove_disk,
8487 .spare_active = raid5_spare_active,
8488 .sync_request = raid5_sync_request,
8489 .resize = raid5_resize,
8491 .check_reshape = raid5_check_reshape,
8492 .start_reshape = raid5_start_reshape,
8493 .finish_reshape = raid5_finish_reshape,
8494 .quiesce = raid5_quiesce,
8495 .takeover = raid4_takeover,
8496 .congested = raid5_congested,
8497 .change_consistency_policy = raid5_change_consistency_policy,
8500 static int __init raid5_init(void)
8504 raid5_wq = alloc_workqueue("raid5wq",
8505 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8509 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8511 raid456_cpu_up_prepare,
8514 destroy_workqueue(raid5_wq);
8517 register_md_personality(&raid6_personality);
8518 register_md_personality(&raid5_personality);
8519 register_md_personality(&raid4_personality);
8523 static void raid5_exit(void)
8525 unregister_md_personality(&raid6_personality);
8526 unregister_md_personality(&raid5_personality);
8527 unregister_md_personality(&raid4_personality);
8528 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8529 destroy_workqueue(raid5_wq);
8532 module_init(raid5_init);
8533 module_exit(raid5_exit);
8534 MODULE_LICENSE("GPL");
8535 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8536 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8537 MODULE_ALIAS("md-raid5");
8538 MODULE_ALIAS("md-raid4");
8539 MODULE_ALIAS("md-level-5");
8540 MODULE_ALIAS("md-level-4");
8541 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8542 MODULE_ALIAS("md-raid6");
8543 MODULE_ALIAS("md-level-6");
8545 /* This used to be two separate modules, they were: */
8546 MODULE_ALIAS("raid5");
8547 MODULE_ALIAS("raid6");