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 #define RAID5_MAX_REQ_STRIPES 256
67 static bool devices_handle_discard_safely = false;
68 module_param(devices_handle_discard_safely, bool, 0644);
69 MODULE_PARM_DESC(devices_handle_discard_safely,
70 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
71 static struct workqueue_struct *raid5_wq;
73 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
75 int hash = (sect >> RAID5_STRIPE_SHIFT(conf)) & HASH_MASK;
76 return &conf->stripe_hashtbl[hash];
79 static inline int stripe_hash_locks_hash(struct r5conf *conf, sector_t sect)
81 return (sect >> RAID5_STRIPE_SHIFT(conf)) & STRIPE_HASH_LOCKS_MASK;
84 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
85 __acquires(&conf->device_lock)
87 spin_lock_irq(conf->hash_locks + hash);
88 spin_lock(&conf->device_lock);
91 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
92 __releases(&conf->device_lock)
94 spin_unlock(&conf->device_lock);
95 spin_unlock_irq(conf->hash_locks + hash);
98 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
99 __acquires(&conf->device_lock)
102 spin_lock_irq(conf->hash_locks);
103 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
104 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
105 spin_lock(&conf->device_lock);
108 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
109 __releases(&conf->device_lock)
112 spin_unlock(&conf->device_lock);
113 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
114 spin_unlock(conf->hash_locks + i);
115 spin_unlock_irq(conf->hash_locks);
118 /* Find first data disk in a raid6 stripe */
119 static inline int raid6_d0(struct stripe_head *sh)
122 /* ddf always start from first device */
124 /* md starts just after Q block */
125 if (sh->qd_idx == sh->disks - 1)
128 return sh->qd_idx + 1;
130 static inline int raid6_next_disk(int disk, int raid_disks)
133 return (disk < raid_disks) ? disk : 0;
136 /* When walking through the disks in a raid5, starting at raid6_d0,
137 * We need to map each disk to a 'slot', where the data disks are slot
138 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
139 * is raid_disks-1. This help does that mapping.
141 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
142 int *count, int syndrome_disks)
148 if (idx == sh->pd_idx)
149 return syndrome_disks;
150 if (idx == sh->qd_idx)
151 return syndrome_disks + 1;
157 static void print_raid5_conf (struct r5conf *conf);
159 static int stripe_operations_active(struct stripe_head *sh)
161 return sh->check_state || sh->reconstruct_state ||
162 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
163 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
166 static bool stripe_is_lowprio(struct stripe_head *sh)
168 return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
169 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
170 !test_bit(STRIPE_R5C_CACHING, &sh->state);
173 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
174 __must_hold(&sh->raid_conf->device_lock)
176 struct r5conf *conf = sh->raid_conf;
177 struct r5worker_group *group;
179 int i, cpu = sh->cpu;
181 if (!cpu_online(cpu)) {
182 cpu = cpumask_any(cpu_online_mask);
186 if (list_empty(&sh->lru)) {
187 struct r5worker_group *group;
188 group = conf->worker_groups + cpu_to_group(cpu);
189 if (stripe_is_lowprio(sh))
190 list_add_tail(&sh->lru, &group->loprio_list);
192 list_add_tail(&sh->lru, &group->handle_list);
193 group->stripes_cnt++;
197 if (conf->worker_cnt_per_group == 0) {
198 md_wakeup_thread(conf->mddev->thread);
202 group = conf->worker_groups + cpu_to_group(sh->cpu);
204 group->workers[0].working = true;
205 /* at least one worker should run to avoid race */
206 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
208 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
209 /* wakeup more workers */
210 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
211 if (group->workers[i].working == false) {
212 group->workers[i].working = true;
213 queue_work_on(sh->cpu, raid5_wq,
214 &group->workers[i].work);
220 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
221 struct list_head *temp_inactive_list)
222 __must_hold(&conf->device_lock)
225 int injournal = 0; /* number of date pages with R5_InJournal */
227 BUG_ON(!list_empty(&sh->lru));
228 BUG_ON(atomic_read(&conf->active_stripes)==0);
230 if (r5c_is_writeback(conf->log))
231 for (i = sh->disks; i--; )
232 if (test_bit(R5_InJournal, &sh->dev[i].flags))
235 * In the following cases, the stripe cannot be released to cached
236 * lists. Therefore, we make the stripe write out and set
238 * 1. when quiesce in r5c write back;
239 * 2. when resync is requested fot the stripe.
241 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
242 (conf->quiesce && r5c_is_writeback(conf->log) &&
243 !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
244 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
245 r5c_make_stripe_write_out(sh);
246 set_bit(STRIPE_HANDLE, &sh->state);
249 if (test_bit(STRIPE_HANDLE, &sh->state)) {
250 if (test_bit(STRIPE_DELAYED, &sh->state) &&
251 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
252 list_add_tail(&sh->lru, &conf->delayed_list);
253 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
254 sh->bm_seq - conf->seq_write > 0)
255 list_add_tail(&sh->lru, &conf->bitmap_list);
257 clear_bit(STRIPE_DELAYED, &sh->state);
258 clear_bit(STRIPE_BIT_DELAY, &sh->state);
259 if (conf->worker_cnt_per_group == 0) {
260 if (stripe_is_lowprio(sh))
261 list_add_tail(&sh->lru,
264 list_add_tail(&sh->lru,
267 raid5_wakeup_stripe_thread(sh);
271 md_wakeup_thread(conf->mddev->thread);
273 BUG_ON(stripe_operations_active(sh));
274 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
275 if (atomic_dec_return(&conf->preread_active_stripes)
277 md_wakeup_thread(conf->mddev->thread);
278 atomic_dec(&conf->active_stripes);
279 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
280 if (!r5c_is_writeback(conf->log))
281 list_add_tail(&sh->lru, temp_inactive_list);
283 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
285 list_add_tail(&sh->lru, temp_inactive_list);
286 else if (injournal == conf->raid_disks - conf->max_degraded) {
288 if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
289 atomic_inc(&conf->r5c_cached_full_stripes);
290 if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
291 atomic_dec(&conf->r5c_cached_partial_stripes);
292 list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
293 r5c_check_cached_full_stripe(conf);
296 * STRIPE_R5C_PARTIAL_STRIPE is set in
297 * r5c_try_caching_write(). No need to
300 list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
306 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
307 struct list_head *temp_inactive_list)
308 __must_hold(&conf->device_lock)
310 if (atomic_dec_and_test(&sh->count))
311 do_release_stripe(conf, sh, temp_inactive_list);
315 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
317 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
318 * given time. Adding stripes only takes device lock, while deleting stripes
319 * only takes hash lock.
321 static void release_inactive_stripe_list(struct r5conf *conf,
322 struct list_head *temp_inactive_list,
326 bool do_wakeup = false;
329 if (hash == NR_STRIPE_HASH_LOCKS) {
330 size = NR_STRIPE_HASH_LOCKS;
331 hash = NR_STRIPE_HASH_LOCKS - 1;
335 struct list_head *list = &temp_inactive_list[size - 1];
338 * We don't hold any lock here yet, raid5_get_active_stripe() might
339 * remove stripes from the list
341 if (!list_empty_careful(list)) {
342 spin_lock_irqsave(conf->hash_locks + hash, flags);
343 if (list_empty(conf->inactive_list + hash) &&
345 atomic_dec(&conf->empty_inactive_list_nr);
346 list_splice_tail_init(list, conf->inactive_list + hash);
348 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
355 wake_up(&conf->wait_for_stripe);
356 if (atomic_read(&conf->active_stripes) == 0)
357 wake_up(&conf->wait_for_quiescent);
358 if (conf->retry_read_aligned)
359 md_wakeup_thread(conf->mddev->thread);
363 static int release_stripe_list(struct r5conf *conf,
364 struct list_head *temp_inactive_list)
365 __must_hold(&conf->device_lock)
367 struct stripe_head *sh, *t;
369 struct llist_node *head;
371 head = llist_del_all(&conf->released_stripes);
372 head = llist_reverse_order(head);
373 llist_for_each_entry_safe(sh, t, head, release_list) {
376 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
378 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
380 * Don't worry the bit is set here, because if the bit is set
381 * again, the count is always > 1. This is true for
382 * STRIPE_ON_UNPLUG_LIST bit too.
384 hash = sh->hash_lock_index;
385 __release_stripe(conf, sh, &temp_inactive_list[hash]);
392 void raid5_release_stripe(struct stripe_head *sh)
394 struct r5conf *conf = sh->raid_conf;
396 struct list_head list;
400 /* Avoid release_list until the last reference.
402 if (atomic_add_unless(&sh->count, -1, 1))
405 if (unlikely(!conf->mddev->thread) ||
406 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
408 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
410 md_wakeup_thread(conf->mddev->thread);
413 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
414 if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
415 INIT_LIST_HEAD(&list);
416 hash = sh->hash_lock_index;
417 do_release_stripe(conf, sh, &list);
418 spin_unlock_irqrestore(&conf->device_lock, flags);
419 release_inactive_stripe_list(conf, &list, hash);
423 static inline void remove_hash(struct stripe_head *sh)
425 pr_debug("remove_hash(), stripe %llu\n",
426 (unsigned long long)sh->sector);
428 hlist_del_init(&sh->hash);
431 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
433 struct hlist_head *hp = stripe_hash(conf, sh->sector);
435 pr_debug("insert_hash(), stripe %llu\n",
436 (unsigned long long)sh->sector);
438 hlist_add_head(&sh->hash, hp);
441 /* find an idle stripe, make sure it is unhashed, and return it. */
442 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
444 struct stripe_head *sh = NULL;
445 struct list_head *first;
447 if (list_empty(conf->inactive_list + hash))
449 first = (conf->inactive_list + hash)->next;
450 sh = list_entry(first, struct stripe_head, lru);
451 list_del_init(first);
453 atomic_inc(&conf->active_stripes);
454 BUG_ON(hash != sh->hash_lock_index);
455 if (list_empty(conf->inactive_list + hash))
456 atomic_inc(&conf->empty_inactive_list_nr);
461 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
462 static void free_stripe_pages(struct stripe_head *sh)
467 /* Have not allocate page pool */
471 for (i = 0; i < sh->nr_pages; i++) {
479 static int alloc_stripe_pages(struct stripe_head *sh, gfp_t gfp)
484 for (i = 0; i < sh->nr_pages; i++) {
485 /* The page have allocated. */
491 free_stripe_pages(sh);
500 init_stripe_shared_pages(struct stripe_head *sh, struct r5conf *conf, int disks)
507 /* Each of the sh->dev[i] need one conf->stripe_size */
508 cnt = PAGE_SIZE / conf->stripe_size;
509 nr_pages = (disks + cnt - 1) / cnt;
511 sh->pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
514 sh->nr_pages = nr_pages;
515 sh->stripes_per_page = cnt;
520 static void shrink_buffers(struct stripe_head *sh)
523 int num = sh->raid_conf->pool_size;
525 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
526 for (i = 0; i < num ; i++) {
529 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
533 sh->dev[i].page = NULL;
537 for (i = 0; i < num; i++)
538 sh->dev[i].page = NULL;
539 free_stripe_pages(sh); /* Free pages */
543 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
546 int num = sh->raid_conf->pool_size;
548 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
549 for (i = 0; i < num; i++) {
552 if (!(page = alloc_page(gfp))) {
555 sh->dev[i].page = page;
556 sh->dev[i].orig_page = page;
557 sh->dev[i].offset = 0;
560 if (alloc_stripe_pages(sh, gfp))
563 for (i = 0; i < num; i++) {
564 sh->dev[i].page = raid5_get_dev_page(sh, i);
565 sh->dev[i].orig_page = sh->dev[i].page;
566 sh->dev[i].offset = raid5_get_page_offset(sh, i);
572 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
573 struct stripe_head *sh);
575 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
577 struct r5conf *conf = sh->raid_conf;
580 BUG_ON(atomic_read(&sh->count) != 0);
581 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
582 BUG_ON(stripe_operations_active(sh));
583 BUG_ON(sh->batch_head);
585 pr_debug("init_stripe called, stripe %llu\n",
586 (unsigned long long)sector);
588 seq = read_seqcount_begin(&conf->gen_lock);
589 sh->generation = conf->generation - previous;
590 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
592 stripe_set_idx(sector, conf, previous, sh);
595 for (i = sh->disks; i--; ) {
596 struct r5dev *dev = &sh->dev[i];
598 if (dev->toread || dev->read || dev->towrite || dev->written ||
599 test_bit(R5_LOCKED, &dev->flags)) {
600 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
601 (unsigned long long)sh->sector, i, dev->toread,
602 dev->read, dev->towrite, dev->written,
603 test_bit(R5_LOCKED, &dev->flags));
607 dev->sector = raid5_compute_blocknr(sh, i, previous);
609 if (read_seqcount_retry(&conf->gen_lock, seq))
611 sh->overwrite_disks = 0;
612 insert_hash(conf, sh);
613 sh->cpu = smp_processor_id();
614 set_bit(STRIPE_BATCH_READY, &sh->state);
617 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
620 struct stripe_head *sh;
622 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
623 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
624 if (sh->sector == sector && sh->generation == generation)
626 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
630 static struct stripe_head *find_get_stripe(struct r5conf *conf,
631 sector_t sector, short generation, int hash)
633 int inc_empty_inactive_list_flag;
634 struct stripe_head *sh;
636 sh = __find_stripe(conf, sector, generation);
640 if (atomic_inc_not_zero(&sh->count))
644 * Slow path. The reference count is zero which means the stripe must
645 * be on a list (sh->lru). Must remove the stripe from the list that
646 * references it with the device_lock held.
649 spin_lock(&conf->device_lock);
650 if (!atomic_read(&sh->count)) {
651 if (!test_bit(STRIPE_HANDLE, &sh->state))
652 atomic_inc(&conf->active_stripes);
653 BUG_ON(list_empty(&sh->lru) &&
654 !test_bit(STRIPE_EXPANDING, &sh->state));
655 inc_empty_inactive_list_flag = 0;
656 if (!list_empty(conf->inactive_list + hash))
657 inc_empty_inactive_list_flag = 1;
658 list_del_init(&sh->lru);
659 if (list_empty(conf->inactive_list + hash) &&
660 inc_empty_inactive_list_flag)
661 atomic_inc(&conf->empty_inactive_list_nr);
663 sh->group->stripes_cnt--;
667 atomic_inc(&sh->count);
668 spin_unlock(&conf->device_lock);
674 * Need to check if array has failed when deciding whether to:
676 * - remove non-faulty devices
679 * This determination is simple when no reshape is happening.
680 * However if there is a reshape, we need to carefully check
681 * both the before and after sections.
682 * This is because some failed devices may only affect one
683 * of the two sections, and some non-in_sync devices may
684 * be insync in the section most affected by failed devices.
686 * Most calls to this function hold &conf->device_lock. Calls
687 * in raid5_run() do not require the lock as no other threads
688 * have been started yet.
690 int raid5_calc_degraded(struct r5conf *conf)
692 int degraded, degraded2;
697 for (i = 0; i < conf->previous_raid_disks; i++) {
698 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
699 if (rdev && test_bit(Faulty, &rdev->flags))
700 rdev = rcu_dereference(conf->disks[i].replacement);
701 if (!rdev || test_bit(Faulty, &rdev->flags))
703 else if (test_bit(In_sync, &rdev->flags))
706 /* not in-sync or faulty.
707 * If the reshape increases the number of devices,
708 * this is being recovered by the reshape, so
709 * this 'previous' section is not in_sync.
710 * If the number of devices is being reduced however,
711 * the device can only be part of the array if
712 * we are reverting a reshape, so this section will
715 if (conf->raid_disks >= conf->previous_raid_disks)
719 if (conf->raid_disks == conf->previous_raid_disks)
723 for (i = 0; i < conf->raid_disks; i++) {
724 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
725 if (rdev && test_bit(Faulty, &rdev->flags))
726 rdev = rcu_dereference(conf->disks[i].replacement);
727 if (!rdev || test_bit(Faulty, &rdev->flags))
729 else if (test_bit(In_sync, &rdev->flags))
732 /* not in-sync or faulty.
733 * If reshape increases the number of devices, this
734 * section has already been recovered, else it
735 * almost certainly hasn't.
737 if (conf->raid_disks <= conf->previous_raid_disks)
741 if (degraded2 > degraded)
746 static bool has_failed(struct r5conf *conf)
748 int degraded = conf->mddev->degraded;
750 if (test_bit(MD_BROKEN, &conf->mddev->flags))
753 if (conf->mddev->reshape_position != MaxSector)
754 degraded = raid5_calc_degraded(conf);
756 return degraded > conf->max_degraded;
762 STRIPE_SCHEDULE_AND_RETRY,
766 struct stripe_request_ctx {
767 /* a reference to the last stripe_head for batching */
768 struct stripe_head *batch_last;
770 /* first sector in the request */
771 sector_t first_sector;
773 /* last sector in the request */
774 sector_t last_sector;
777 * bitmap to track stripe sectors that have been added to stripes
778 * add one to account for unaligned requests
780 DECLARE_BITMAP(sectors_to_do, RAID5_MAX_REQ_STRIPES + 1);
782 /* the request had REQ_PREFLUSH, cleared after the first stripe_head */
787 * Block until another thread clears R5_INACTIVE_BLOCKED or
788 * there are fewer than 3/4 the maximum number of active stripes
789 * and there is an inactive stripe available.
791 static bool is_inactive_blocked(struct r5conf *conf, int hash)
793 if (list_empty(conf->inactive_list + hash))
796 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
799 return (atomic_read(&conf->active_stripes) <
800 (conf->max_nr_stripes * 3 / 4));
803 struct stripe_head *raid5_get_active_stripe(struct r5conf *conf,
804 struct stripe_request_ctx *ctx, sector_t sector,
807 struct stripe_head *sh;
808 int hash = stripe_hash_locks_hash(conf, sector);
809 int previous = !!(flags & R5_GAS_PREVIOUS);
811 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
813 spin_lock_irq(conf->hash_locks + hash);
816 if (!(flags & R5_GAS_NOQUIESCE) && conf->quiesce) {
818 * Must release the reference to batch_last before
819 * waiting, on quiesce, otherwise the batch_last will
820 * hold a reference to a stripe and raid5_quiesce()
821 * will deadlock waiting for active_stripes to go to
824 if (ctx && ctx->batch_last) {
825 raid5_release_stripe(ctx->batch_last);
826 ctx->batch_last = NULL;
829 wait_event_lock_irq(conf->wait_for_quiescent,
831 *(conf->hash_locks + hash));
834 sh = find_get_stripe(conf, sector, conf->generation - previous,
839 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
840 sh = get_free_stripe(conf, hash);
842 r5c_check_stripe_cache_usage(conf);
843 init_stripe(sh, sector, previous);
844 atomic_inc(&sh->count);
848 if (!test_bit(R5_DID_ALLOC, &conf->cache_state))
849 set_bit(R5_ALLOC_MORE, &conf->cache_state);
852 if (flags & R5_GAS_NOBLOCK)
855 set_bit(R5_INACTIVE_BLOCKED, &conf->cache_state);
856 r5l_wake_reclaim(conf->log, 0);
858 /* release batch_last before wait to avoid risk of deadlock */
859 if (ctx && ctx->batch_last) {
860 raid5_release_stripe(ctx->batch_last);
861 ctx->batch_last = NULL;
864 wait_event_lock_irq(conf->wait_for_stripe,
865 is_inactive_blocked(conf, hash),
866 *(conf->hash_locks + hash));
867 clear_bit(R5_INACTIVE_BLOCKED, &conf->cache_state);
870 spin_unlock_irq(conf->hash_locks + hash);
874 static bool is_full_stripe_write(struct stripe_head *sh)
876 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
877 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
880 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
881 __acquires(&sh1->stripe_lock)
882 __acquires(&sh2->stripe_lock)
885 spin_lock_irq(&sh2->stripe_lock);
886 spin_lock_nested(&sh1->stripe_lock, 1);
888 spin_lock_irq(&sh1->stripe_lock);
889 spin_lock_nested(&sh2->stripe_lock, 1);
893 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
894 __releases(&sh1->stripe_lock)
895 __releases(&sh2->stripe_lock)
897 spin_unlock(&sh1->stripe_lock);
898 spin_unlock_irq(&sh2->stripe_lock);
901 /* Only freshly new full stripe normal write stripe can be added to a batch list */
902 static bool stripe_can_batch(struct stripe_head *sh)
904 struct r5conf *conf = sh->raid_conf;
906 if (raid5_has_log(conf) || raid5_has_ppl(conf))
908 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
909 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
910 is_full_stripe_write(sh);
913 /* we only do back search */
914 static void stripe_add_to_batch_list(struct r5conf *conf,
915 struct stripe_head *sh, struct stripe_head *last_sh)
917 struct stripe_head *head;
918 sector_t head_sector, tmp_sec;
922 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
923 tmp_sec = sh->sector;
924 if (!sector_div(tmp_sec, conf->chunk_sectors))
926 head_sector = sh->sector - RAID5_STRIPE_SECTORS(conf);
928 if (last_sh && head_sector == last_sh->sector) {
930 atomic_inc(&head->count);
932 hash = stripe_hash_locks_hash(conf, head_sector);
933 spin_lock_irq(conf->hash_locks + hash);
934 head = find_get_stripe(conf, head_sector, conf->generation,
936 spin_unlock_irq(conf->hash_locks + hash);
939 if (!stripe_can_batch(head))
943 lock_two_stripes(head, sh);
944 /* clear_batch_ready clear the flag */
945 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
952 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
954 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
955 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
958 if (head->batch_head) {
959 spin_lock(&head->batch_head->batch_lock);
960 /* This batch list is already running */
961 if (!stripe_can_batch(head)) {
962 spin_unlock(&head->batch_head->batch_lock);
966 * We must assign batch_head of this stripe within the
967 * batch_lock, otherwise clear_batch_ready of batch head
968 * stripe could clear BATCH_READY bit of this stripe and
969 * this stripe->batch_head doesn't get assigned, which
970 * could confuse clear_batch_ready for this stripe
972 sh->batch_head = head->batch_head;
975 * at this point, head's BATCH_READY could be cleared, but we
976 * can still add the stripe to batch list
978 list_add(&sh->batch_list, &head->batch_list);
979 spin_unlock(&head->batch_head->batch_lock);
981 head->batch_head = head;
982 sh->batch_head = head->batch_head;
983 spin_lock(&head->batch_lock);
984 list_add_tail(&sh->batch_list, &head->batch_list);
985 spin_unlock(&head->batch_lock);
988 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
989 if (atomic_dec_return(&conf->preread_active_stripes)
991 md_wakeup_thread(conf->mddev->thread);
993 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
994 int seq = sh->bm_seq;
995 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
996 sh->batch_head->bm_seq > seq)
997 seq = sh->batch_head->bm_seq;
998 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
999 sh->batch_head->bm_seq = seq;
1002 atomic_inc(&sh->count);
1004 unlock_two_stripes(head, sh);
1006 raid5_release_stripe(head);
1009 /* Determine if 'data_offset' or 'new_data_offset' should be used
1010 * in this stripe_head.
1012 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
1014 sector_t progress = conf->reshape_progress;
1015 /* Need a memory barrier to make sure we see the value
1016 * of conf->generation, or ->data_offset that was set before
1017 * reshape_progress was updated.
1020 if (progress == MaxSector)
1022 if (sh->generation == conf->generation - 1)
1024 /* We are in a reshape, and this is a new-generation stripe,
1025 * so use new_data_offset.
1030 static void dispatch_bio_list(struct bio_list *tmp)
1034 while ((bio = bio_list_pop(tmp)))
1035 submit_bio_noacct(bio);
1038 static int cmp_stripe(void *priv, const struct list_head *a,
1039 const struct list_head *b)
1041 const struct r5pending_data *da = list_entry(a,
1042 struct r5pending_data, sibling);
1043 const struct r5pending_data *db = list_entry(b,
1044 struct r5pending_data, sibling);
1045 if (da->sector > db->sector)
1047 if (da->sector < db->sector)
1052 static void dispatch_defer_bios(struct r5conf *conf, int target,
1053 struct bio_list *list)
1055 struct r5pending_data *data;
1056 struct list_head *first, *next = NULL;
1059 if (conf->pending_data_cnt == 0)
1062 list_sort(NULL, &conf->pending_list, cmp_stripe);
1064 first = conf->pending_list.next;
1066 /* temporarily move the head */
1067 if (conf->next_pending_data)
1068 list_move_tail(&conf->pending_list,
1069 &conf->next_pending_data->sibling);
1071 while (!list_empty(&conf->pending_list)) {
1072 data = list_first_entry(&conf->pending_list,
1073 struct r5pending_data, sibling);
1074 if (&data->sibling == first)
1075 first = data->sibling.next;
1076 next = data->sibling.next;
1078 bio_list_merge(list, &data->bios);
1079 list_move(&data->sibling, &conf->free_list);
1084 conf->pending_data_cnt -= cnt;
1085 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
1087 if (next != &conf->pending_list)
1088 conf->next_pending_data = list_entry(next,
1089 struct r5pending_data, sibling);
1091 conf->next_pending_data = NULL;
1092 /* list isn't empty */
1093 if (first != &conf->pending_list)
1094 list_move_tail(&conf->pending_list, first);
1097 static void flush_deferred_bios(struct r5conf *conf)
1099 struct bio_list tmp = BIO_EMPTY_LIST;
1101 if (conf->pending_data_cnt == 0)
1104 spin_lock(&conf->pending_bios_lock);
1105 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
1106 BUG_ON(conf->pending_data_cnt != 0);
1107 spin_unlock(&conf->pending_bios_lock);
1109 dispatch_bio_list(&tmp);
1112 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
1113 struct bio_list *bios)
1115 struct bio_list tmp = BIO_EMPTY_LIST;
1116 struct r5pending_data *ent;
1118 spin_lock(&conf->pending_bios_lock);
1119 ent = list_first_entry(&conf->free_list, struct r5pending_data,
1121 list_move_tail(&ent->sibling, &conf->pending_list);
1122 ent->sector = sector;
1123 bio_list_init(&ent->bios);
1124 bio_list_merge(&ent->bios, bios);
1125 conf->pending_data_cnt++;
1126 if (conf->pending_data_cnt >= PENDING_IO_MAX)
1127 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
1129 spin_unlock(&conf->pending_bios_lock);
1131 dispatch_bio_list(&tmp);
1135 raid5_end_read_request(struct bio *bi);
1137 raid5_end_write_request(struct bio *bi);
1139 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
1141 struct r5conf *conf = sh->raid_conf;
1142 int i, disks = sh->disks;
1143 struct stripe_head *head_sh = sh;
1144 struct bio_list pending_bios = BIO_EMPTY_LIST;
1150 if (log_stripe(sh, s) == 0)
1153 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1155 for (i = disks; i--; ) {
1157 blk_opf_t op_flags = 0;
1158 int replace_only = 0;
1159 struct bio *bi, *rbi;
1160 struct md_rdev *rdev, *rrdev = NULL;
1163 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1165 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1167 if (test_bit(R5_Discard, &sh->dev[i].flags))
1168 op = REQ_OP_DISCARD;
1169 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1171 else if (test_and_clear_bit(R5_WantReplace,
1172 &sh->dev[i].flags)) {
1177 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1178 op_flags |= REQ_SYNC;
1183 rbi = &dev->rreq; /* For writing to replacement */
1186 rrdev = rcu_dereference(conf->disks[i].replacement);
1187 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1188 rdev = rcu_dereference(conf->disks[i].rdev);
1193 if (op_is_write(op)) {
1197 /* We raced and saw duplicates */
1200 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1205 if (rdev && test_bit(Faulty, &rdev->flags))
1208 atomic_inc(&rdev->nr_pending);
1209 if (rrdev && test_bit(Faulty, &rrdev->flags))
1212 atomic_inc(&rrdev->nr_pending);
1215 /* We have already checked bad blocks for reads. Now
1216 * need to check for writes. We never accept write errors
1217 * on the replacement, so we don't to check rrdev.
1219 while (op_is_write(op) && rdev &&
1220 test_bit(WriteErrorSeen, &rdev->flags)) {
1223 int bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
1224 &first_bad, &bad_sectors);
1229 set_bit(BlockedBadBlocks, &rdev->flags);
1230 if (!conf->mddev->external &&
1231 conf->mddev->sb_flags) {
1232 /* It is very unlikely, but we might
1233 * still need to write out the
1234 * bad block log - better give it
1236 md_check_recovery(conf->mddev);
1239 * Because md_wait_for_blocked_rdev
1240 * will dec nr_pending, we must
1241 * increment it first.
1243 atomic_inc(&rdev->nr_pending);
1244 md_wait_for_blocked_rdev(rdev, conf->mddev);
1246 /* Acknowledged bad block - skip the write */
1247 rdev_dec_pending(rdev, conf->mddev);
1253 if (s->syncing || s->expanding || s->expanded
1255 md_sync_acct(rdev->bdev, RAID5_STRIPE_SECTORS(conf));
1257 set_bit(STRIPE_IO_STARTED, &sh->state);
1259 bio_init(bi, rdev->bdev, &dev->vec, 1, op | op_flags);
1260 bi->bi_end_io = op_is_write(op)
1261 ? raid5_end_write_request
1262 : raid5_end_read_request;
1263 bi->bi_private = sh;
1265 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1266 __func__, (unsigned long long)sh->sector,
1268 atomic_inc(&sh->count);
1270 atomic_inc(&head_sh->count);
1271 if (use_new_offset(conf, sh))
1272 bi->bi_iter.bi_sector = (sh->sector
1273 + rdev->new_data_offset);
1275 bi->bi_iter.bi_sector = (sh->sector
1276 + rdev->data_offset);
1277 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1278 bi->bi_opf |= REQ_NOMERGE;
1280 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1281 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1283 if (!op_is_write(op) &&
1284 test_bit(R5_InJournal, &sh->dev[i].flags))
1286 * issuing read for a page in journal, this
1287 * must be preparing for prexor in rmw; read
1288 * the data into orig_page
1290 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1292 sh->dev[i].vec.bv_page = sh->dev[i].page;
1294 bi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1295 bi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1296 bi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1298 * If this is discard request, set bi_vcnt 0. We don't
1299 * want to confuse SCSI because SCSI will replace payload
1301 if (op == REQ_OP_DISCARD)
1304 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1306 if (conf->mddev->gendisk)
1307 trace_block_bio_remap(bi,
1308 disk_devt(conf->mddev->gendisk),
1310 if (should_defer && op_is_write(op))
1311 bio_list_add(&pending_bios, bi);
1313 submit_bio_noacct(bi);
1316 if (s->syncing || s->expanding || s->expanded
1318 md_sync_acct(rrdev->bdev, RAID5_STRIPE_SECTORS(conf));
1320 set_bit(STRIPE_IO_STARTED, &sh->state);
1322 bio_init(rbi, rrdev->bdev, &dev->rvec, 1, op | op_flags);
1323 BUG_ON(!op_is_write(op));
1324 rbi->bi_end_io = raid5_end_write_request;
1325 rbi->bi_private = sh;
1327 pr_debug("%s: for %llu schedule op %d on "
1328 "replacement disc %d\n",
1329 __func__, (unsigned long long)sh->sector,
1331 atomic_inc(&sh->count);
1333 atomic_inc(&head_sh->count);
1334 if (use_new_offset(conf, sh))
1335 rbi->bi_iter.bi_sector = (sh->sector
1336 + rrdev->new_data_offset);
1338 rbi->bi_iter.bi_sector = (sh->sector
1339 + rrdev->data_offset);
1340 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1341 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1342 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1344 rbi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1345 rbi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1346 rbi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1348 * If this is discard request, set bi_vcnt 0. We don't
1349 * want to confuse SCSI because SCSI will replace payload
1351 if (op == REQ_OP_DISCARD)
1353 if (conf->mddev->gendisk)
1354 trace_block_bio_remap(rbi,
1355 disk_devt(conf->mddev->gendisk),
1357 if (should_defer && op_is_write(op))
1358 bio_list_add(&pending_bios, rbi);
1360 submit_bio_noacct(rbi);
1362 if (!rdev && !rrdev) {
1363 if (op_is_write(op))
1364 set_bit(STRIPE_DEGRADED, &sh->state);
1365 pr_debug("skip op %d on disc %d for sector %llu\n",
1366 bi->bi_opf, i, (unsigned long long)sh->sector);
1367 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1368 set_bit(STRIPE_HANDLE, &sh->state);
1371 if (!head_sh->batch_head)
1373 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1379 if (should_defer && !bio_list_empty(&pending_bios))
1380 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1383 static struct dma_async_tx_descriptor *
1384 async_copy_data(int frombio, struct bio *bio, struct page **page,
1385 unsigned int poff, sector_t sector, struct dma_async_tx_descriptor *tx,
1386 struct stripe_head *sh, int no_skipcopy)
1389 struct bvec_iter iter;
1390 struct page *bio_page;
1392 struct async_submit_ctl submit;
1393 enum async_tx_flags flags = 0;
1394 struct r5conf *conf = sh->raid_conf;
1396 if (bio->bi_iter.bi_sector >= sector)
1397 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1399 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1402 flags |= ASYNC_TX_FENCE;
1403 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1405 bio_for_each_segment(bvl, bio, iter) {
1406 int len = bvl.bv_len;
1410 if (page_offset < 0) {
1411 b_offset = -page_offset;
1412 page_offset += b_offset;
1416 if (len > 0 && page_offset + len > RAID5_STRIPE_SIZE(conf))
1417 clen = RAID5_STRIPE_SIZE(conf) - page_offset;
1422 b_offset += bvl.bv_offset;
1423 bio_page = bvl.bv_page;
1425 if (conf->skip_copy &&
1426 b_offset == 0 && page_offset == 0 &&
1427 clen == RAID5_STRIPE_SIZE(conf) &&
1431 tx = async_memcpy(*page, bio_page, page_offset + poff,
1432 b_offset, clen, &submit);
1434 tx = async_memcpy(bio_page, *page, b_offset,
1435 page_offset + poff, clen, &submit);
1437 /* chain the operations */
1438 submit.depend_tx = tx;
1440 if (clen < len) /* hit end of page */
1448 static void ops_complete_biofill(void *stripe_head_ref)
1450 struct stripe_head *sh = stripe_head_ref;
1452 struct r5conf *conf = sh->raid_conf;
1454 pr_debug("%s: stripe %llu\n", __func__,
1455 (unsigned long long)sh->sector);
1457 /* clear completed biofills */
1458 for (i = sh->disks; i--; ) {
1459 struct r5dev *dev = &sh->dev[i];
1461 /* acknowledge completion of a biofill operation */
1462 /* and check if we need to reply to a read request,
1463 * new R5_Wantfill requests are held off until
1464 * !STRIPE_BIOFILL_RUN
1466 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1467 struct bio *rbi, *rbi2;
1472 while (rbi && rbi->bi_iter.bi_sector <
1473 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1474 rbi2 = r5_next_bio(conf, rbi, dev->sector);
1480 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1482 set_bit(STRIPE_HANDLE, &sh->state);
1483 raid5_release_stripe(sh);
1486 static void ops_run_biofill(struct stripe_head *sh)
1488 struct dma_async_tx_descriptor *tx = NULL;
1489 struct async_submit_ctl submit;
1491 struct r5conf *conf = sh->raid_conf;
1493 BUG_ON(sh->batch_head);
1494 pr_debug("%s: stripe %llu\n", __func__,
1495 (unsigned long long)sh->sector);
1497 for (i = sh->disks; i--; ) {
1498 struct r5dev *dev = &sh->dev[i];
1499 if (test_bit(R5_Wantfill, &dev->flags)) {
1501 spin_lock_irq(&sh->stripe_lock);
1502 dev->read = rbi = dev->toread;
1504 spin_unlock_irq(&sh->stripe_lock);
1505 while (rbi && rbi->bi_iter.bi_sector <
1506 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1507 tx = async_copy_data(0, rbi, &dev->page,
1509 dev->sector, tx, sh, 0);
1510 rbi = r5_next_bio(conf, rbi, dev->sector);
1515 atomic_inc(&sh->count);
1516 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1517 async_trigger_callback(&submit);
1520 static void mark_target_uptodate(struct stripe_head *sh, int target)
1527 tgt = &sh->dev[target];
1528 set_bit(R5_UPTODATE, &tgt->flags);
1529 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1530 clear_bit(R5_Wantcompute, &tgt->flags);
1533 static void ops_complete_compute(void *stripe_head_ref)
1535 struct stripe_head *sh = stripe_head_ref;
1537 pr_debug("%s: stripe %llu\n", __func__,
1538 (unsigned long long)sh->sector);
1540 /* mark the computed target(s) as uptodate */
1541 mark_target_uptodate(sh, sh->ops.target);
1542 mark_target_uptodate(sh, sh->ops.target2);
1544 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1545 if (sh->check_state == check_state_compute_run)
1546 sh->check_state = check_state_compute_result;
1547 set_bit(STRIPE_HANDLE, &sh->state);
1548 raid5_release_stripe(sh);
1551 /* return a pointer to the address conversion region of the scribble buffer */
1552 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1554 return percpu->scribble + i * percpu->scribble_obj_size;
1557 /* return a pointer to the address conversion region of the scribble buffer */
1558 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1559 struct raid5_percpu *percpu, int i)
1561 return (void *) (to_addr_page(percpu, i) + sh->disks + 2);
1565 * Return a pointer to record offset address.
1567 static unsigned int *
1568 to_addr_offs(struct stripe_head *sh, struct raid5_percpu *percpu)
1570 return (unsigned int *) (to_addr_conv(sh, percpu, 0) + sh->disks + 2);
1573 static struct dma_async_tx_descriptor *
1574 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1576 int disks = sh->disks;
1577 struct page **xor_srcs = to_addr_page(percpu, 0);
1578 unsigned int *off_srcs = to_addr_offs(sh, percpu);
1579 int target = sh->ops.target;
1580 struct r5dev *tgt = &sh->dev[target];
1581 struct page *xor_dest = tgt->page;
1582 unsigned int off_dest = tgt->offset;
1584 struct dma_async_tx_descriptor *tx;
1585 struct async_submit_ctl submit;
1588 BUG_ON(sh->batch_head);
1590 pr_debug("%s: stripe %llu block: %d\n",
1591 __func__, (unsigned long long)sh->sector, target);
1592 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1594 for (i = disks; i--; ) {
1596 off_srcs[count] = sh->dev[i].offset;
1597 xor_srcs[count++] = sh->dev[i].page;
1601 atomic_inc(&sh->count);
1603 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1604 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1605 if (unlikely(count == 1))
1606 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
1607 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1609 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1610 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1615 /* set_syndrome_sources - populate source buffers for gen_syndrome
1616 * @srcs - (struct page *) array of size sh->disks
1617 * @offs - (unsigned int) array of offset for each page
1618 * @sh - stripe_head to parse
1620 * Populates srcs in proper layout order for the stripe and returns the
1621 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1622 * destination buffer is recorded in srcs[count] and the Q destination
1623 * is recorded in srcs[count+1]].
1625 static int set_syndrome_sources(struct page **srcs,
1627 struct stripe_head *sh,
1630 int disks = sh->disks;
1631 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1632 int d0_idx = raid6_d0(sh);
1636 for (i = 0; i < disks; i++)
1642 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1643 struct r5dev *dev = &sh->dev[i];
1645 if (i == sh->qd_idx || i == sh->pd_idx ||
1646 (srctype == SYNDROME_SRC_ALL) ||
1647 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1648 (test_bit(R5_Wantdrain, &dev->flags) ||
1649 test_bit(R5_InJournal, &dev->flags))) ||
1650 (srctype == SYNDROME_SRC_WRITTEN &&
1652 test_bit(R5_InJournal, &dev->flags)))) {
1653 if (test_bit(R5_InJournal, &dev->flags))
1654 srcs[slot] = sh->dev[i].orig_page;
1656 srcs[slot] = sh->dev[i].page;
1658 * For R5_InJournal, PAGE_SIZE must be 4KB and will
1659 * not shared page. In that case, dev[i].offset
1662 offs[slot] = sh->dev[i].offset;
1664 i = raid6_next_disk(i, disks);
1665 } while (i != d0_idx);
1667 return syndrome_disks;
1670 static struct dma_async_tx_descriptor *
1671 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1673 int disks = sh->disks;
1674 struct page **blocks = to_addr_page(percpu, 0);
1675 unsigned int *offs = to_addr_offs(sh, percpu);
1677 int qd_idx = sh->qd_idx;
1678 struct dma_async_tx_descriptor *tx;
1679 struct async_submit_ctl submit;
1682 unsigned int dest_off;
1686 BUG_ON(sh->batch_head);
1687 if (sh->ops.target < 0)
1688 target = sh->ops.target2;
1689 else if (sh->ops.target2 < 0)
1690 target = sh->ops.target;
1692 /* we should only have one valid target */
1695 pr_debug("%s: stripe %llu block: %d\n",
1696 __func__, (unsigned long long)sh->sector, target);
1698 tgt = &sh->dev[target];
1699 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1701 dest_off = tgt->offset;
1703 atomic_inc(&sh->count);
1705 if (target == qd_idx) {
1706 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1707 blocks[count] = NULL; /* regenerating p is not necessary */
1708 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1709 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1710 ops_complete_compute, sh,
1711 to_addr_conv(sh, percpu, 0));
1712 tx = async_gen_syndrome(blocks, offs, count+2,
1713 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1715 /* Compute any data- or p-drive using XOR */
1717 for (i = disks; i-- ; ) {
1718 if (i == target || i == qd_idx)
1720 offs[count] = sh->dev[i].offset;
1721 blocks[count++] = sh->dev[i].page;
1724 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1725 NULL, ops_complete_compute, sh,
1726 to_addr_conv(sh, percpu, 0));
1727 tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1728 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1734 static struct dma_async_tx_descriptor *
1735 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1737 int i, count, disks = sh->disks;
1738 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1739 int d0_idx = raid6_d0(sh);
1740 int faila = -1, failb = -1;
1741 int target = sh->ops.target;
1742 int target2 = sh->ops.target2;
1743 struct r5dev *tgt = &sh->dev[target];
1744 struct r5dev *tgt2 = &sh->dev[target2];
1745 struct dma_async_tx_descriptor *tx;
1746 struct page **blocks = to_addr_page(percpu, 0);
1747 unsigned int *offs = to_addr_offs(sh, percpu);
1748 struct async_submit_ctl submit;
1750 BUG_ON(sh->batch_head);
1751 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1752 __func__, (unsigned long long)sh->sector, target, target2);
1753 BUG_ON(target < 0 || target2 < 0);
1754 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1755 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1757 /* we need to open-code set_syndrome_sources to handle the
1758 * slot number conversion for 'faila' and 'failb'
1760 for (i = 0; i < disks ; i++) {
1767 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1769 offs[slot] = sh->dev[i].offset;
1770 blocks[slot] = sh->dev[i].page;
1776 i = raid6_next_disk(i, disks);
1777 } while (i != d0_idx);
1779 BUG_ON(faila == failb);
1782 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1783 __func__, (unsigned long long)sh->sector, faila, failb);
1785 atomic_inc(&sh->count);
1787 if (failb == syndrome_disks+1) {
1788 /* Q disk is one of the missing disks */
1789 if (faila == syndrome_disks) {
1790 /* Missing P+Q, just recompute */
1791 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1792 ops_complete_compute, sh,
1793 to_addr_conv(sh, percpu, 0));
1794 return async_gen_syndrome(blocks, offs, syndrome_disks+2,
1795 RAID5_STRIPE_SIZE(sh->raid_conf),
1799 unsigned int dest_off;
1801 int qd_idx = sh->qd_idx;
1803 /* Missing D+Q: recompute D from P, then recompute Q */
1804 if (target == qd_idx)
1805 data_target = target2;
1807 data_target = target;
1810 for (i = disks; i-- ; ) {
1811 if (i == data_target || i == qd_idx)
1813 offs[count] = sh->dev[i].offset;
1814 blocks[count++] = sh->dev[i].page;
1816 dest = sh->dev[data_target].page;
1817 dest_off = sh->dev[data_target].offset;
1818 init_async_submit(&submit,
1819 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1821 to_addr_conv(sh, percpu, 0));
1822 tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1823 RAID5_STRIPE_SIZE(sh->raid_conf),
1826 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1827 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1828 ops_complete_compute, sh,
1829 to_addr_conv(sh, percpu, 0));
1830 return async_gen_syndrome(blocks, offs, count+2,
1831 RAID5_STRIPE_SIZE(sh->raid_conf),
1835 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1836 ops_complete_compute, sh,
1837 to_addr_conv(sh, percpu, 0));
1838 if (failb == syndrome_disks) {
1839 /* We're missing D+P. */
1840 return async_raid6_datap_recov(syndrome_disks+2,
1841 RAID5_STRIPE_SIZE(sh->raid_conf),
1843 blocks, offs, &submit);
1845 /* We're missing D+D. */
1846 return async_raid6_2data_recov(syndrome_disks+2,
1847 RAID5_STRIPE_SIZE(sh->raid_conf),
1849 blocks, offs, &submit);
1854 static void ops_complete_prexor(void *stripe_head_ref)
1856 struct stripe_head *sh = stripe_head_ref;
1858 pr_debug("%s: stripe %llu\n", __func__,
1859 (unsigned long long)sh->sector);
1861 if (r5c_is_writeback(sh->raid_conf->log))
1863 * raid5-cache write back uses orig_page during prexor.
1864 * After prexor, it is time to free orig_page
1866 r5c_release_extra_page(sh);
1869 static struct dma_async_tx_descriptor *
1870 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1871 struct dma_async_tx_descriptor *tx)
1873 int disks = sh->disks;
1874 struct page **xor_srcs = to_addr_page(percpu, 0);
1875 unsigned int *off_srcs = to_addr_offs(sh, percpu);
1876 int count = 0, pd_idx = sh->pd_idx, i;
1877 struct async_submit_ctl submit;
1879 /* existing parity data subtracted */
1880 unsigned int off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
1881 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1883 BUG_ON(sh->batch_head);
1884 pr_debug("%s: stripe %llu\n", __func__,
1885 (unsigned long long)sh->sector);
1887 for (i = disks; i--; ) {
1888 struct r5dev *dev = &sh->dev[i];
1889 /* Only process blocks that are known to be uptodate */
1890 if (test_bit(R5_InJournal, &dev->flags)) {
1892 * For this case, PAGE_SIZE must be equal to 4KB and
1893 * page offset is zero.
1895 off_srcs[count] = dev->offset;
1896 xor_srcs[count++] = dev->orig_page;
1897 } else if (test_bit(R5_Wantdrain, &dev->flags)) {
1898 off_srcs[count] = dev->offset;
1899 xor_srcs[count++] = dev->page;
1903 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1904 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1905 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1906 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1911 static struct dma_async_tx_descriptor *
1912 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1913 struct dma_async_tx_descriptor *tx)
1915 struct page **blocks = to_addr_page(percpu, 0);
1916 unsigned int *offs = to_addr_offs(sh, percpu);
1918 struct async_submit_ctl submit;
1920 pr_debug("%s: stripe %llu\n", __func__,
1921 (unsigned long long)sh->sector);
1923 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_WANT_DRAIN);
1925 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1926 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1927 tx = async_gen_syndrome(blocks, offs, count+2,
1928 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1933 static struct dma_async_tx_descriptor *
1934 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1936 struct r5conf *conf = sh->raid_conf;
1937 int disks = sh->disks;
1939 struct stripe_head *head_sh = sh;
1941 pr_debug("%s: stripe %llu\n", __func__,
1942 (unsigned long long)sh->sector);
1944 for (i = disks; i--; ) {
1949 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1955 * clear R5_InJournal, so when rewriting a page in
1956 * journal, it is not skipped by r5l_log_stripe()
1958 clear_bit(R5_InJournal, &dev->flags);
1959 spin_lock_irq(&sh->stripe_lock);
1960 chosen = dev->towrite;
1961 dev->towrite = NULL;
1962 sh->overwrite_disks = 0;
1963 BUG_ON(dev->written);
1964 wbi = dev->written = chosen;
1965 spin_unlock_irq(&sh->stripe_lock);
1966 WARN_ON(dev->page != dev->orig_page);
1968 while (wbi && wbi->bi_iter.bi_sector <
1969 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1970 if (wbi->bi_opf & REQ_FUA)
1971 set_bit(R5_WantFUA, &dev->flags);
1972 if (wbi->bi_opf & REQ_SYNC)
1973 set_bit(R5_SyncIO, &dev->flags);
1974 if (bio_op(wbi) == REQ_OP_DISCARD)
1975 set_bit(R5_Discard, &dev->flags);
1977 tx = async_copy_data(1, wbi, &dev->page,
1979 dev->sector, tx, sh,
1980 r5c_is_writeback(conf->log));
1981 if (dev->page != dev->orig_page &&
1982 !r5c_is_writeback(conf->log)) {
1983 set_bit(R5_SkipCopy, &dev->flags);
1984 clear_bit(R5_UPTODATE, &dev->flags);
1985 clear_bit(R5_OVERWRITE, &dev->flags);
1988 wbi = r5_next_bio(conf, wbi, dev->sector);
1991 if (head_sh->batch_head) {
1992 sh = list_first_entry(&sh->batch_list,
2005 static void ops_complete_reconstruct(void *stripe_head_ref)
2007 struct stripe_head *sh = stripe_head_ref;
2008 int disks = sh->disks;
2009 int pd_idx = sh->pd_idx;
2010 int qd_idx = sh->qd_idx;
2012 bool fua = false, sync = false, discard = false;
2014 pr_debug("%s: stripe %llu\n", __func__,
2015 (unsigned long long)sh->sector);
2017 for (i = disks; i--; ) {
2018 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
2019 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
2020 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
2023 for (i = disks; i--; ) {
2024 struct r5dev *dev = &sh->dev[i];
2026 if (dev->written || i == pd_idx || i == qd_idx) {
2027 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
2028 set_bit(R5_UPTODATE, &dev->flags);
2029 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
2030 set_bit(R5_Expanded, &dev->flags);
2033 set_bit(R5_WantFUA, &dev->flags);
2035 set_bit(R5_SyncIO, &dev->flags);
2039 if (sh->reconstruct_state == reconstruct_state_drain_run)
2040 sh->reconstruct_state = reconstruct_state_drain_result;
2041 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
2042 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
2044 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
2045 sh->reconstruct_state = reconstruct_state_result;
2048 set_bit(STRIPE_HANDLE, &sh->state);
2049 raid5_release_stripe(sh);
2053 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
2054 struct dma_async_tx_descriptor *tx)
2056 int disks = sh->disks;
2057 struct page **xor_srcs;
2058 unsigned int *off_srcs;
2059 struct async_submit_ctl submit;
2060 int count, pd_idx = sh->pd_idx, i;
2061 struct page *xor_dest;
2062 unsigned int off_dest;
2064 unsigned long flags;
2066 struct stripe_head *head_sh = sh;
2069 pr_debug("%s: stripe %llu\n", __func__,
2070 (unsigned long long)sh->sector);
2072 for (i = 0; i < sh->disks; i++) {
2075 if (!test_bit(R5_Discard, &sh->dev[i].flags))
2078 if (i >= sh->disks) {
2079 atomic_inc(&sh->count);
2080 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
2081 ops_complete_reconstruct(sh);
2086 xor_srcs = to_addr_page(percpu, j);
2087 off_srcs = to_addr_offs(sh, percpu);
2088 /* check if prexor is active which means only process blocks
2089 * that are part of a read-modify-write (written)
2091 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2093 off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
2094 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
2095 for (i = disks; i--; ) {
2096 struct r5dev *dev = &sh->dev[i];
2097 if (head_sh->dev[i].written ||
2098 test_bit(R5_InJournal, &head_sh->dev[i].flags)) {
2099 off_srcs[count] = dev->offset;
2100 xor_srcs[count++] = dev->page;
2104 xor_dest = sh->dev[pd_idx].page;
2105 off_dest = sh->dev[pd_idx].offset;
2106 for (i = disks; i--; ) {
2107 struct r5dev *dev = &sh->dev[i];
2109 off_srcs[count] = dev->offset;
2110 xor_srcs[count++] = dev->page;
2115 /* 1/ if we prexor'd then the dest is reused as a source
2116 * 2/ if we did not prexor then we are redoing the parity
2117 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
2118 * for the synchronous xor case
2120 last_stripe = !head_sh->batch_head ||
2121 list_first_entry(&sh->batch_list,
2122 struct stripe_head, batch_list) == head_sh;
2124 flags = ASYNC_TX_ACK |
2125 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
2127 atomic_inc(&head_sh->count);
2128 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
2129 to_addr_conv(sh, percpu, j));
2131 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
2132 init_async_submit(&submit, flags, tx, NULL, NULL,
2133 to_addr_conv(sh, percpu, j));
2136 if (unlikely(count == 1))
2137 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
2138 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2140 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2141 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2144 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2151 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
2152 struct dma_async_tx_descriptor *tx)
2154 struct async_submit_ctl submit;
2155 struct page **blocks;
2157 int count, i, j = 0;
2158 struct stripe_head *head_sh = sh;
2161 unsigned long txflags;
2163 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
2165 for (i = 0; i < sh->disks; i++) {
2166 if (sh->pd_idx == i || sh->qd_idx == i)
2168 if (!test_bit(R5_Discard, &sh->dev[i].flags))
2171 if (i >= sh->disks) {
2172 atomic_inc(&sh->count);
2173 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2174 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2175 ops_complete_reconstruct(sh);
2180 blocks = to_addr_page(percpu, j);
2181 offs = to_addr_offs(sh, percpu);
2183 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2184 synflags = SYNDROME_SRC_WRITTEN;
2185 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
2187 synflags = SYNDROME_SRC_ALL;
2188 txflags = ASYNC_TX_ACK;
2191 count = set_syndrome_sources(blocks, offs, sh, synflags);
2192 last_stripe = !head_sh->batch_head ||
2193 list_first_entry(&sh->batch_list,
2194 struct stripe_head, batch_list) == head_sh;
2197 atomic_inc(&head_sh->count);
2198 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
2199 head_sh, to_addr_conv(sh, percpu, j));
2201 init_async_submit(&submit, 0, tx, NULL, NULL,
2202 to_addr_conv(sh, percpu, j));
2203 tx = async_gen_syndrome(blocks, offs, count+2,
2204 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2207 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2213 static void ops_complete_check(void *stripe_head_ref)
2215 struct stripe_head *sh = stripe_head_ref;
2217 pr_debug("%s: stripe %llu\n", __func__,
2218 (unsigned long long)sh->sector);
2220 sh->check_state = check_state_check_result;
2221 set_bit(STRIPE_HANDLE, &sh->state);
2222 raid5_release_stripe(sh);
2225 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2227 int disks = sh->disks;
2228 int pd_idx = sh->pd_idx;
2229 int qd_idx = sh->qd_idx;
2230 struct page *xor_dest;
2231 unsigned int off_dest;
2232 struct page **xor_srcs = to_addr_page(percpu, 0);
2233 unsigned int *off_srcs = to_addr_offs(sh, percpu);
2234 struct dma_async_tx_descriptor *tx;
2235 struct async_submit_ctl submit;
2239 pr_debug("%s: stripe %llu\n", __func__,
2240 (unsigned long long)sh->sector);
2242 BUG_ON(sh->batch_head);
2244 xor_dest = sh->dev[pd_idx].page;
2245 off_dest = sh->dev[pd_idx].offset;
2246 off_srcs[count] = off_dest;
2247 xor_srcs[count++] = xor_dest;
2248 for (i = disks; i--; ) {
2249 if (i == pd_idx || i == qd_idx)
2251 off_srcs[count] = sh->dev[i].offset;
2252 xor_srcs[count++] = sh->dev[i].page;
2255 init_async_submit(&submit, 0, NULL, NULL, NULL,
2256 to_addr_conv(sh, percpu, 0));
2257 tx = async_xor_val_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2258 RAID5_STRIPE_SIZE(sh->raid_conf),
2259 &sh->ops.zero_sum_result, &submit);
2261 atomic_inc(&sh->count);
2262 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2263 tx = async_trigger_callback(&submit);
2266 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2268 struct page **srcs = to_addr_page(percpu, 0);
2269 unsigned int *offs = to_addr_offs(sh, percpu);
2270 struct async_submit_ctl submit;
2273 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2274 (unsigned long long)sh->sector, checkp);
2276 BUG_ON(sh->batch_head);
2277 count = set_syndrome_sources(srcs, offs, sh, SYNDROME_SRC_ALL);
2281 atomic_inc(&sh->count);
2282 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2283 sh, to_addr_conv(sh, percpu, 0));
2284 async_syndrome_val(srcs, offs, count+2,
2285 RAID5_STRIPE_SIZE(sh->raid_conf),
2286 &sh->ops.zero_sum_result, percpu->spare_page, 0, &submit);
2289 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2291 int overlap_clear = 0, i, disks = sh->disks;
2292 struct dma_async_tx_descriptor *tx = NULL;
2293 struct r5conf *conf = sh->raid_conf;
2294 int level = conf->level;
2295 struct raid5_percpu *percpu;
2297 local_lock(&conf->percpu->lock);
2298 percpu = this_cpu_ptr(conf->percpu);
2299 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2300 ops_run_biofill(sh);
2304 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2306 tx = ops_run_compute5(sh, percpu);
2308 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2309 tx = ops_run_compute6_1(sh, percpu);
2311 tx = ops_run_compute6_2(sh, percpu);
2313 /* terminate the chain if reconstruct is not set to be run */
2314 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2318 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2320 tx = ops_run_prexor5(sh, percpu, tx);
2322 tx = ops_run_prexor6(sh, percpu, tx);
2325 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2326 tx = ops_run_partial_parity(sh, percpu, tx);
2328 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2329 tx = ops_run_biodrain(sh, tx);
2333 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2335 ops_run_reconstruct5(sh, percpu, tx);
2337 ops_run_reconstruct6(sh, percpu, tx);
2340 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2341 if (sh->check_state == check_state_run)
2342 ops_run_check_p(sh, percpu);
2343 else if (sh->check_state == check_state_run_q)
2344 ops_run_check_pq(sh, percpu, 0);
2345 else if (sh->check_state == check_state_run_pq)
2346 ops_run_check_pq(sh, percpu, 1);
2351 if (overlap_clear && !sh->batch_head) {
2352 for (i = disks; i--; ) {
2353 struct r5dev *dev = &sh->dev[i];
2354 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2355 wake_up(&sh->raid_conf->wait_for_overlap);
2358 local_unlock(&conf->percpu->lock);
2361 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2363 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2367 __free_page(sh->ppl_page);
2368 kmem_cache_free(sc, sh);
2371 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2372 int disks, struct r5conf *conf)
2374 struct stripe_head *sh;
2376 sh = kmem_cache_zalloc(sc, gfp);
2378 spin_lock_init(&sh->stripe_lock);
2379 spin_lock_init(&sh->batch_lock);
2380 INIT_LIST_HEAD(&sh->batch_list);
2381 INIT_LIST_HEAD(&sh->lru);
2382 INIT_LIST_HEAD(&sh->r5c);
2383 INIT_LIST_HEAD(&sh->log_list);
2384 atomic_set(&sh->count, 1);
2385 sh->raid_conf = conf;
2386 sh->log_start = MaxSector;
2388 if (raid5_has_ppl(conf)) {
2389 sh->ppl_page = alloc_page(gfp);
2390 if (!sh->ppl_page) {
2391 free_stripe(sc, sh);
2395 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2396 if (init_stripe_shared_pages(sh, conf, disks)) {
2397 free_stripe(sc, sh);
2404 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2406 struct stripe_head *sh;
2408 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2412 if (grow_buffers(sh, gfp)) {
2414 free_stripe(conf->slab_cache, sh);
2417 sh->hash_lock_index =
2418 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2419 /* we just created an active stripe so... */
2420 atomic_inc(&conf->active_stripes);
2422 raid5_release_stripe(sh);
2423 conf->max_nr_stripes++;
2427 static int grow_stripes(struct r5conf *conf, int num)
2429 struct kmem_cache *sc;
2430 size_t namelen = sizeof(conf->cache_name[0]);
2431 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2433 if (conf->mddev->gendisk)
2434 snprintf(conf->cache_name[0], namelen,
2435 "raid%d-%s", conf->level, mdname(conf->mddev));
2437 snprintf(conf->cache_name[0], namelen,
2438 "raid%d-%p", conf->level, conf->mddev);
2439 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2441 conf->active_name = 0;
2442 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2443 struct_size_t(struct stripe_head, dev, devs),
2447 conf->slab_cache = sc;
2448 conf->pool_size = devs;
2450 if (!grow_one_stripe(conf, GFP_KERNEL))
2457 * scribble_alloc - allocate percpu scribble buffer for required size
2458 * of the scribble region
2459 * @percpu: from for_each_present_cpu() of the caller
2460 * @num: total number of disks in the array
2461 * @cnt: scribble objs count for required size of the scribble region
2463 * The scribble buffer size must be enough to contain:
2464 * 1/ a struct page pointer for each device in the array +2
2465 * 2/ room to convert each entry in (1) to its corresponding dma
2466 * (dma_map_page()) or page (page_address()) address.
2468 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2469 * calculate over all devices (not just the data blocks), using zeros in place
2470 * of the P and Q blocks.
2472 static int scribble_alloc(struct raid5_percpu *percpu,
2476 sizeof(struct page *) * (num + 2) +
2477 sizeof(addr_conv_t) * (num + 2) +
2478 sizeof(unsigned int) * (num + 2);
2482 * If here is in raid array suspend context, it is in memalloc noio
2483 * context as well, there is no potential recursive memory reclaim
2484 * I/Os with the GFP_KERNEL flag.
2486 scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2490 kvfree(percpu->scribble);
2492 percpu->scribble = scribble;
2493 percpu->scribble_obj_size = obj_size;
2497 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2503 * Never shrink. And mddev_suspend() could deadlock if this is called
2504 * from raid5d. In that case, scribble_disks and scribble_sectors
2505 * should equal to new_disks and new_sectors
2507 if (conf->scribble_disks >= new_disks &&
2508 conf->scribble_sectors >= new_sectors)
2510 mddev_suspend(conf->mddev);
2513 for_each_present_cpu(cpu) {
2514 struct raid5_percpu *percpu;
2516 percpu = per_cpu_ptr(conf->percpu, cpu);
2517 err = scribble_alloc(percpu, new_disks,
2518 new_sectors / RAID5_STRIPE_SECTORS(conf));
2524 mddev_resume(conf->mddev);
2526 conf->scribble_disks = new_disks;
2527 conf->scribble_sectors = new_sectors;
2532 static int resize_stripes(struct r5conf *conf, int newsize)
2534 /* Make all the stripes able to hold 'newsize' devices.
2535 * New slots in each stripe get 'page' set to a new page.
2537 * This happens in stages:
2538 * 1/ create a new kmem_cache and allocate the required number of
2540 * 2/ gather all the old stripe_heads and transfer the pages across
2541 * to the new stripe_heads. This will have the side effect of
2542 * freezing the array as once all stripe_heads have been collected,
2543 * no IO will be possible. Old stripe heads are freed once their
2544 * pages have been transferred over, and the old kmem_cache is
2545 * freed when all stripes are done.
2546 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2547 * we simple return a failure status - no need to clean anything up.
2548 * 4/ allocate new pages for the new slots in the new stripe_heads.
2549 * If this fails, we don't bother trying the shrink the
2550 * stripe_heads down again, we just leave them as they are.
2551 * As each stripe_head is processed the new one is released into
2554 * Once step2 is started, we cannot afford to wait for a write,
2555 * so we use GFP_NOIO allocations.
2557 struct stripe_head *osh, *nsh;
2558 LIST_HEAD(newstripes);
2559 struct disk_info *ndisks;
2561 struct kmem_cache *sc;
2565 md_allow_write(conf->mddev);
2568 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2569 struct_size_t(struct stripe_head, dev, newsize),
2574 /* Need to ensure auto-resizing doesn't interfere */
2575 mutex_lock(&conf->cache_size_mutex);
2577 for (i = conf->max_nr_stripes; i; i--) {
2578 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2582 list_add(&nsh->lru, &newstripes);
2585 /* didn't get enough, give up */
2586 while (!list_empty(&newstripes)) {
2587 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2588 list_del(&nsh->lru);
2589 free_stripe(sc, nsh);
2591 kmem_cache_destroy(sc);
2592 mutex_unlock(&conf->cache_size_mutex);
2595 /* Step 2 - Must use GFP_NOIO now.
2596 * OK, we have enough stripes, start collecting inactive
2597 * stripes and copying them over
2601 list_for_each_entry(nsh, &newstripes, lru) {
2602 lock_device_hash_lock(conf, hash);
2603 wait_event_cmd(conf->wait_for_stripe,
2604 !list_empty(conf->inactive_list + hash),
2605 unlock_device_hash_lock(conf, hash),
2606 lock_device_hash_lock(conf, hash));
2607 osh = get_free_stripe(conf, hash);
2608 unlock_device_hash_lock(conf, hash);
2610 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2611 for (i = 0; i < osh->nr_pages; i++) {
2612 nsh->pages[i] = osh->pages[i];
2613 osh->pages[i] = NULL;
2616 for(i=0; i<conf->pool_size; i++) {
2617 nsh->dev[i].page = osh->dev[i].page;
2618 nsh->dev[i].orig_page = osh->dev[i].page;
2619 nsh->dev[i].offset = osh->dev[i].offset;
2621 nsh->hash_lock_index = hash;
2622 free_stripe(conf->slab_cache, osh);
2624 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2625 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2630 kmem_cache_destroy(conf->slab_cache);
2633 * At this point, we are holding all the stripes so the array
2634 * is completely stalled, so now is a good time to resize
2635 * conf->disks and the scribble region
2637 ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2639 for (i = 0; i < conf->pool_size; i++)
2640 ndisks[i] = conf->disks[i];
2642 for (i = conf->pool_size; i < newsize; i++) {
2643 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2644 if (!ndisks[i].extra_page)
2649 for (i = conf->pool_size; i < newsize; i++)
2650 if (ndisks[i].extra_page)
2651 put_page(ndisks[i].extra_page);
2655 conf->disks = ndisks;
2660 conf->slab_cache = sc;
2661 conf->active_name = 1-conf->active_name;
2663 /* Step 4, return new stripes to service */
2664 while(!list_empty(&newstripes)) {
2665 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2666 list_del_init(&nsh->lru);
2668 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2669 for (i = 0; i < nsh->nr_pages; i++) {
2672 nsh->pages[i] = alloc_page(GFP_NOIO);
2677 for (i = conf->raid_disks; i < newsize; i++) {
2678 if (nsh->dev[i].page)
2680 nsh->dev[i].page = raid5_get_dev_page(nsh, i);
2681 nsh->dev[i].orig_page = nsh->dev[i].page;
2682 nsh->dev[i].offset = raid5_get_page_offset(nsh, i);
2685 for (i=conf->raid_disks; i < newsize; i++)
2686 if (nsh->dev[i].page == NULL) {
2687 struct page *p = alloc_page(GFP_NOIO);
2688 nsh->dev[i].page = p;
2689 nsh->dev[i].orig_page = p;
2690 nsh->dev[i].offset = 0;
2695 raid5_release_stripe(nsh);
2697 /* critical section pass, GFP_NOIO no longer needed */
2700 conf->pool_size = newsize;
2701 mutex_unlock(&conf->cache_size_mutex);
2706 static int drop_one_stripe(struct r5conf *conf)
2708 struct stripe_head *sh;
2709 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2711 spin_lock_irq(conf->hash_locks + hash);
2712 sh = get_free_stripe(conf, hash);
2713 spin_unlock_irq(conf->hash_locks + hash);
2716 BUG_ON(atomic_read(&sh->count));
2718 free_stripe(conf->slab_cache, sh);
2719 atomic_dec(&conf->active_stripes);
2720 conf->max_nr_stripes--;
2724 static void shrink_stripes(struct r5conf *conf)
2726 while (conf->max_nr_stripes &&
2727 drop_one_stripe(conf))
2730 kmem_cache_destroy(conf->slab_cache);
2731 conf->slab_cache = NULL;
2735 * This helper wraps rcu_dereference_protected() and can be used when
2736 * it is known that the nr_pending of the rdev is elevated.
2738 static struct md_rdev *rdev_pend_deref(struct md_rdev __rcu *rdev)
2740 return rcu_dereference_protected(rdev,
2741 atomic_read(&rcu_access_pointer(rdev)->nr_pending));
2745 * This helper wraps rcu_dereference_protected() and should be used
2746 * when it is known that the mddev_lock() is held. This is safe
2747 * seeing raid5_remove_disk() has the same lock held.
2749 static struct md_rdev *rdev_mdlock_deref(struct mddev *mddev,
2750 struct md_rdev __rcu *rdev)
2752 return rcu_dereference_protected(rdev,
2753 lockdep_is_held(&mddev->reconfig_mutex));
2756 static void raid5_end_read_request(struct bio * bi)
2758 struct stripe_head *sh = bi->bi_private;
2759 struct r5conf *conf = sh->raid_conf;
2760 int disks = sh->disks, i;
2761 struct md_rdev *rdev = NULL;
2764 for (i=0 ; i<disks; i++)
2765 if (bi == &sh->dev[i].req)
2768 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2769 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2775 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2776 /* If replacement finished while this request was outstanding,
2777 * 'replacement' might be NULL already.
2778 * In that case it moved down to 'rdev'.
2779 * rdev is not removed until all requests are finished.
2781 rdev = rdev_pend_deref(conf->disks[i].replacement);
2783 rdev = rdev_pend_deref(conf->disks[i].rdev);
2785 if (use_new_offset(conf, sh))
2786 s = sh->sector + rdev->new_data_offset;
2788 s = sh->sector + rdev->data_offset;
2789 if (!bi->bi_status) {
2790 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2791 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2792 /* Note that this cannot happen on a
2793 * replacement device. We just fail those on
2796 pr_info_ratelimited(
2797 "md/raid:%s: read error corrected (%lu sectors at %llu on %pg)\n",
2798 mdname(conf->mddev), RAID5_STRIPE_SECTORS(conf),
2799 (unsigned long long)s,
2801 atomic_add(RAID5_STRIPE_SECTORS(conf), &rdev->corrected_errors);
2802 clear_bit(R5_ReadError, &sh->dev[i].flags);
2803 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2804 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2805 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2807 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2809 * end read for a page in journal, this
2810 * must be preparing for prexor in rmw
2812 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2814 if (atomic_read(&rdev->read_errors))
2815 atomic_set(&rdev->read_errors, 0);
2820 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2821 if (!(bi->bi_status == BLK_STS_PROTECTION))
2822 atomic_inc(&rdev->read_errors);
2823 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2824 pr_warn_ratelimited(
2825 "md/raid:%s: read error on replacement device (sector %llu on %pg).\n",
2826 mdname(conf->mddev),
2827 (unsigned long long)s,
2829 else if (conf->mddev->degraded >= conf->max_degraded) {
2831 pr_warn_ratelimited(
2832 "md/raid:%s: read error not correctable (sector %llu on %pg).\n",
2833 mdname(conf->mddev),
2834 (unsigned long long)s,
2836 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2839 pr_warn_ratelimited(
2840 "md/raid:%s: read error NOT corrected!! (sector %llu on %pg).\n",
2841 mdname(conf->mddev),
2842 (unsigned long long)s,
2844 } else if (atomic_read(&rdev->read_errors)
2845 > conf->max_nr_stripes) {
2846 if (!test_bit(Faulty, &rdev->flags)) {
2847 pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2848 mdname(conf->mddev),
2849 atomic_read(&rdev->read_errors),
2850 conf->max_nr_stripes);
2851 pr_warn("md/raid:%s: Too many read errors, failing device %pg.\n",
2852 mdname(conf->mddev), rdev->bdev);
2856 if (set_bad && test_bit(In_sync, &rdev->flags)
2857 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2860 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2861 set_bit(R5_ReadError, &sh->dev[i].flags);
2862 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2863 set_bit(R5_ReadError, &sh->dev[i].flags);
2864 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2866 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2868 clear_bit(R5_ReadError, &sh->dev[i].flags);
2869 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2871 && test_bit(In_sync, &rdev->flags)
2872 && rdev_set_badblocks(
2873 rdev, sh->sector, RAID5_STRIPE_SECTORS(conf), 0)))
2874 md_error(conf->mddev, rdev);
2877 rdev_dec_pending(rdev, conf->mddev);
2879 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2880 set_bit(STRIPE_HANDLE, &sh->state);
2881 raid5_release_stripe(sh);
2884 static void raid5_end_write_request(struct bio *bi)
2886 struct stripe_head *sh = bi->bi_private;
2887 struct r5conf *conf = sh->raid_conf;
2888 int disks = sh->disks, i;
2889 struct md_rdev *rdev;
2892 int replacement = 0;
2894 for (i = 0 ; i < disks; i++) {
2895 if (bi == &sh->dev[i].req) {
2896 rdev = rdev_pend_deref(conf->disks[i].rdev);
2899 if (bi == &sh->dev[i].rreq) {
2900 rdev = rdev_pend_deref(conf->disks[i].replacement);
2904 /* rdev was removed and 'replacement'
2905 * replaced it. rdev is not removed
2906 * until all requests are finished.
2908 rdev = rdev_pend_deref(conf->disks[i].rdev);
2912 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2913 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2922 md_error(conf->mddev, rdev);
2923 else if (is_badblock(rdev, sh->sector,
2924 RAID5_STRIPE_SECTORS(conf),
2925 &first_bad, &bad_sectors))
2926 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2928 if (bi->bi_status) {
2929 set_bit(STRIPE_DEGRADED, &sh->state);
2930 set_bit(WriteErrorSeen, &rdev->flags);
2931 set_bit(R5_WriteError, &sh->dev[i].flags);
2932 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2933 set_bit(MD_RECOVERY_NEEDED,
2934 &rdev->mddev->recovery);
2935 } else if (is_badblock(rdev, sh->sector,
2936 RAID5_STRIPE_SECTORS(conf),
2937 &first_bad, &bad_sectors)) {
2938 set_bit(R5_MadeGood, &sh->dev[i].flags);
2939 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2940 /* That was a successful write so make
2941 * sure it looks like we already did
2944 set_bit(R5_ReWrite, &sh->dev[i].flags);
2947 rdev_dec_pending(rdev, conf->mddev);
2949 if (sh->batch_head && bi->bi_status && !replacement)
2950 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2953 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2954 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2955 set_bit(STRIPE_HANDLE, &sh->state);
2957 if (sh->batch_head && sh != sh->batch_head)
2958 raid5_release_stripe(sh->batch_head);
2959 raid5_release_stripe(sh);
2962 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2964 struct r5conf *conf = mddev->private;
2965 unsigned long flags;
2966 pr_debug("raid456: error called\n");
2968 pr_crit("md/raid:%s: Disk failure on %pg, disabling device.\n",
2969 mdname(mddev), rdev->bdev);
2971 spin_lock_irqsave(&conf->device_lock, flags);
2972 set_bit(Faulty, &rdev->flags);
2973 clear_bit(In_sync, &rdev->flags);
2974 mddev->degraded = raid5_calc_degraded(conf);
2976 if (has_failed(conf)) {
2977 set_bit(MD_BROKEN, &conf->mddev->flags);
2978 conf->recovery_disabled = mddev->recovery_disabled;
2980 pr_crit("md/raid:%s: Cannot continue operation (%d/%d failed).\n",
2981 mdname(mddev), mddev->degraded, conf->raid_disks);
2983 pr_crit("md/raid:%s: Operation continuing on %d devices.\n",
2984 mdname(mddev), conf->raid_disks - mddev->degraded);
2987 spin_unlock_irqrestore(&conf->device_lock, flags);
2988 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2990 set_bit(Blocked, &rdev->flags);
2991 set_mask_bits(&mddev->sb_flags, 0,
2992 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2993 r5c_update_on_rdev_error(mddev, rdev);
2997 * Input: a 'big' sector number,
2998 * Output: index of the data and parity disk, and the sector # in them.
3000 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
3001 int previous, int *dd_idx,
3002 struct stripe_head *sh)
3004 sector_t stripe, stripe2;
3005 sector_t chunk_number;
3006 unsigned int chunk_offset;
3009 sector_t new_sector;
3010 int algorithm = previous ? conf->prev_algo
3012 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3013 : conf->chunk_sectors;
3014 int raid_disks = previous ? conf->previous_raid_disks
3016 int data_disks = raid_disks - conf->max_degraded;
3018 /* First compute the information on this sector */
3021 * Compute the chunk number and the sector offset inside the chunk
3023 chunk_offset = sector_div(r_sector, sectors_per_chunk);
3024 chunk_number = r_sector;
3027 * Compute the stripe number
3029 stripe = chunk_number;
3030 *dd_idx = sector_div(stripe, data_disks);
3033 * Select the parity disk based on the user selected algorithm.
3035 pd_idx = qd_idx = -1;
3036 switch(conf->level) {
3038 pd_idx = data_disks;
3041 switch (algorithm) {
3042 case ALGORITHM_LEFT_ASYMMETRIC:
3043 pd_idx = data_disks - sector_div(stripe2, raid_disks);
3044 if (*dd_idx >= pd_idx)
3047 case ALGORITHM_RIGHT_ASYMMETRIC:
3048 pd_idx = sector_div(stripe2, raid_disks);
3049 if (*dd_idx >= pd_idx)
3052 case ALGORITHM_LEFT_SYMMETRIC:
3053 pd_idx = data_disks - sector_div(stripe2, raid_disks);
3054 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3056 case ALGORITHM_RIGHT_SYMMETRIC:
3057 pd_idx = sector_div(stripe2, raid_disks);
3058 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3060 case ALGORITHM_PARITY_0:
3064 case ALGORITHM_PARITY_N:
3065 pd_idx = data_disks;
3073 switch (algorithm) {
3074 case ALGORITHM_LEFT_ASYMMETRIC:
3075 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3076 qd_idx = pd_idx + 1;
3077 if (pd_idx == raid_disks-1) {
3078 (*dd_idx)++; /* Q D D D P */
3080 } else if (*dd_idx >= pd_idx)
3081 (*dd_idx) += 2; /* D D P Q D */
3083 case ALGORITHM_RIGHT_ASYMMETRIC:
3084 pd_idx = sector_div(stripe2, raid_disks);
3085 qd_idx = pd_idx + 1;
3086 if (pd_idx == raid_disks-1) {
3087 (*dd_idx)++; /* Q D D D P */
3089 } else if (*dd_idx >= pd_idx)
3090 (*dd_idx) += 2; /* D D P Q D */
3092 case ALGORITHM_LEFT_SYMMETRIC:
3093 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3094 qd_idx = (pd_idx + 1) % raid_disks;
3095 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3097 case ALGORITHM_RIGHT_SYMMETRIC:
3098 pd_idx = sector_div(stripe2, raid_disks);
3099 qd_idx = (pd_idx + 1) % raid_disks;
3100 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3103 case ALGORITHM_PARITY_0:
3108 case ALGORITHM_PARITY_N:
3109 pd_idx = data_disks;
3110 qd_idx = data_disks + 1;
3113 case ALGORITHM_ROTATING_ZERO_RESTART:
3114 /* Exactly the same as RIGHT_ASYMMETRIC, but or
3115 * of blocks for computing Q is different.
3117 pd_idx = sector_div(stripe2, raid_disks);
3118 qd_idx = pd_idx + 1;
3119 if (pd_idx == raid_disks-1) {
3120 (*dd_idx)++; /* Q D D D P */
3122 } else if (*dd_idx >= pd_idx)
3123 (*dd_idx) += 2; /* D D P Q D */
3127 case ALGORITHM_ROTATING_N_RESTART:
3128 /* Same a left_asymmetric, by first stripe is
3129 * D D D P Q rather than
3133 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3134 qd_idx = pd_idx + 1;
3135 if (pd_idx == raid_disks-1) {
3136 (*dd_idx)++; /* Q D D D P */
3138 } else if (*dd_idx >= pd_idx)
3139 (*dd_idx) += 2; /* D D P Q D */
3143 case ALGORITHM_ROTATING_N_CONTINUE:
3144 /* Same as left_symmetric but Q is before P */
3145 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3146 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
3147 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3151 case ALGORITHM_LEFT_ASYMMETRIC_6:
3152 /* RAID5 left_asymmetric, with Q on last device */
3153 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3154 if (*dd_idx >= pd_idx)
3156 qd_idx = raid_disks - 1;
3159 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3160 pd_idx = sector_div(stripe2, raid_disks-1);
3161 if (*dd_idx >= pd_idx)
3163 qd_idx = raid_disks - 1;
3166 case ALGORITHM_LEFT_SYMMETRIC_6:
3167 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3168 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3169 qd_idx = raid_disks - 1;
3172 case ALGORITHM_RIGHT_SYMMETRIC_6:
3173 pd_idx = sector_div(stripe2, raid_disks-1);
3174 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3175 qd_idx = raid_disks - 1;
3178 case ALGORITHM_PARITY_0_6:
3181 qd_idx = raid_disks - 1;
3191 sh->pd_idx = pd_idx;
3192 sh->qd_idx = qd_idx;
3193 sh->ddf_layout = ddf_layout;
3196 * Finally, compute the new sector number
3198 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
3202 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
3204 struct r5conf *conf = sh->raid_conf;
3205 int raid_disks = sh->disks;
3206 int data_disks = raid_disks - conf->max_degraded;
3207 sector_t new_sector = sh->sector, check;
3208 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3209 : conf->chunk_sectors;
3210 int algorithm = previous ? conf->prev_algo
3214 sector_t chunk_number;
3215 int dummy1, dd_idx = i;
3217 struct stripe_head sh2;
3219 chunk_offset = sector_div(new_sector, sectors_per_chunk);
3220 stripe = new_sector;
3222 if (i == sh->pd_idx)
3224 switch(conf->level) {
3227 switch (algorithm) {
3228 case ALGORITHM_LEFT_ASYMMETRIC:
3229 case ALGORITHM_RIGHT_ASYMMETRIC:
3233 case ALGORITHM_LEFT_SYMMETRIC:
3234 case ALGORITHM_RIGHT_SYMMETRIC:
3237 i -= (sh->pd_idx + 1);
3239 case ALGORITHM_PARITY_0:
3242 case ALGORITHM_PARITY_N:
3249 if (i == sh->qd_idx)
3250 return 0; /* It is the Q disk */
3251 switch (algorithm) {
3252 case ALGORITHM_LEFT_ASYMMETRIC:
3253 case ALGORITHM_RIGHT_ASYMMETRIC:
3254 case ALGORITHM_ROTATING_ZERO_RESTART:
3255 case ALGORITHM_ROTATING_N_RESTART:
3256 if (sh->pd_idx == raid_disks-1)
3257 i--; /* Q D D D P */
3258 else if (i > sh->pd_idx)
3259 i -= 2; /* D D P Q D */
3261 case ALGORITHM_LEFT_SYMMETRIC:
3262 case ALGORITHM_RIGHT_SYMMETRIC:
3263 if (sh->pd_idx == raid_disks-1)
3264 i--; /* Q D D D P */
3269 i -= (sh->pd_idx + 2);
3272 case ALGORITHM_PARITY_0:
3275 case ALGORITHM_PARITY_N:
3277 case ALGORITHM_ROTATING_N_CONTINUE:
3278 /* Like left_symmetric, but P is before Q */
3279 if (sh->pd_idx == 0)
3280 i--; /* P D D D Q */
3285 i -= (sh->pd_idx + 1);
3288 case ALGORITHM_LEFT_ASYMMETRIC_6:
3289 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3293 case ALGORITHM_LEFT_SYMMETRIC_6:
3294 case ALGORITHM_RIGHT_SYMMETRIC_6:
3296 i += data_disks + 1;
3297 i -= (sh->pd_idx + 1);
3299 case ALGORITHM_PARITY_0_6:
3308 chunk_number = stripe * data_disks + i;
3309 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3311 check = raid5_compute_sector(conf, r_sector,
3312 previous, &dummy1, &sh2);
3313 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3314 || sh2.qd_idx != sh->qd_idx) {
3315 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3316 mdname(conf->mddev));
3323 * There are cases where we want handle_stripe_dirtying() and
3324 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3326 * This function checks whether we want to delay the towrite. Specifically,
3327 * we delay the towrite when:
3329 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3330 * stripe has data in journal (for other devices).
3332 * In this case, when reading data for the non-overwrite dev, it is
3333 * necessary to handle complex rmw of write back cache (prexor with
3334 * orig_page, and xor with page). To keep read path simple, we would
3335 * like to flush data in journal to RAID disks first, so complex rmw
3336 * is handled in the write patch (handle_stripe_dirtying).
3338 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3340 * It is important to be able to flush all stripes in raid5-cache.
3341 * Therefore, we need reserve some space on the journal device for
3342 * these flushes. If flush operation includes pending writes to the
3343 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3344 * for the flush out. If we exclude these pending writes from flush
3345 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3346 * Therefore, excluding pending writes in these cases enables more
3347 * efficient use of the journal device.
3349 * Note: To make sure the stripe makes progress, we only delay
3350 * towrite for stripes with data already in journal (injournal > 0).
3351 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3352 * no_space_stripes list.
3354 * 3. during journal failure
3355 * In journal failure, we try to flush all cached data to raid disks
3356 * based on data in stripe cache. The array is read-only to upper
3357 * layers, so we would skip all pending writes.
3360 static inline bool delay_towrite(struct r5conf *conf,
3362 struct stripe_head_state *s)
3365 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3366 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3369 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3373 if (s->log_failed && s->injournal)
3379 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3380 int rcw, int expand)
3382 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3383 struct r5conf *conf = sh->raid_conf;
3384 int level = conf->level;
3388 * In some cases, handle_stripe_dirtying initially decided to
3389 * run rmw and allocates extra page for prexor. However, rcw is
3390 * cheaper later on. We need to free the extra page now,
3391 * because we won't be able to do that in ops_complete_prexor().
3393 r5c_release_extra_page(sh);
3395 for (i = disks; i--; ) {
3396 struct r5dev *dev = &sh->dev[i];
3398 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3399 set_bit(R5_LOCKED, &dev->flags);
3400 set_bit(R5_Wantdrain, &dev->flags);
3402 clear_bit(R5_UPTODATE, &dev->flags);
3404 } else if (test_bit(R5_InJournal, &dev->flags)) {
3405 set_bit(R5_LOCKED, &dev->flags);
3409 /* if we are not expanding this is a proper write request, and
3410 * there will be bios with new data to be drained into the
3415 /* False alarm, nothing to do */
3417 sh->reconstruct_state = reconstruct_state_drain_run;
3418 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3420 sh->reconstruct_state = reconstruct_state_run;
3422 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3424 if (s->locked + conf->max_degraded == disks)
3425 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3426 atomic_inc(&conf->pending_full_writes);
3428 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3429 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3430 BUG_ON(level == 6 &&
3431 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3432 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3434 for (i = disks; i--; ) {
3435 struct r5dev *dev = &sh->dev[i];
3436 if (i == pd_idx || i == qd_idx)
3440 (test_bit(R5_UPTODATE, &dev->flags) ||
3441 test_bit(R5_Wantcompute, &dev->flags))) {
3442 set_bit(R5_Wantdrain, &dev->flags);
3443 set_bit(R5_LOCKED, &dev->flags);
3444 clear_bit(R5_UPTODATE, &dev->flags);
3446 } else if (test_bit(R5_InJournal, &dev->flags)) {
3447 set_bit(R5_LOCKED, &dev->flags);
3452 /* False alarm - nothing to do */
3454 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3455 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3456 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3457 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3460 /* keep the parity disk(s) locked while asynchronous operations
3463 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3464 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3468 int qd_idx = sh->qd_idx;
3469 struct r5dev *dev = &sh->dev[qd_idx];
3471 set_bit(R5_LOCKED, &dev->flags);
3472 clear_bit(R5_UPTODATE, &dev->flags);
3476 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3477 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3478 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3479 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3480 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3482 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3483 __func__, (unsigned long long)sh->sector,
3484 s->locked, s->ops_request);
3487 static bool stripe_bio_overlaps(struct stripe_head *sh, struct bio *bi,
3488 int dd_idx, int forwrite)
3490 struct r5conf *conf = sh->raid_conf;
3493 pr_debug("checking bi b#%llu to stripe s#%llu\n",
3494 bi->bi_iter.bi_sector, sh->sector);
3496 /* Don't allow new IO added to stripes in batch list */
3501 bip = &sh->dev[dd_idx].towrite;
3503 bip = &sh->dev[dd_idx].toread;
3505 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3506 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3508 bip = &(*bip)->bi_next;
3511 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3514 if (forwrite && raid5_has_ppl(conf)) {
3516 * With PPL only writes to consecutive data chunks within a
3517 * stripe are allowed because for a single stripe_head we can
3518 * only have one PPL entry at a time, which describes one data
3519 * range. Not really an overlap, but wait_for_overlap can be
3520 * used to handle this.
3528 for (i = 0; i < sh->disks; i++) {
3529 if (i != sh->pd_idx &&
3530 (i == dd_idx || sh->dev[i].towrite)) {
3531 sector = sh->dev[i].sector;
3532 if (count == 0 || sector < first)
3540 if (first + conf->chunk_sectors * (count - 1) != last)
3547 static void __add_stripe_bio(struct stripe_head *sh, struct bio *bi,
3548 int dd_idx, int forwrite, int previous)
3550 struct r5conf *conf = sh->raid_conf;
3555 bip = &sh->dev[dd_idx].towrite;
3559 bip = &sh->dev[dd_idx].toread;
3562 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector)
3563 bip = &(*bip)->bi_next;
3565 if (!forwrite || previous)
3566 clear_bit(STRIPE_BATCH_READY, &sh->state);
3568 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3572 bio_inc_remaining(bi);
3573 md_write_inc(conf->mddev, bi);
3576 /* check if page is covered */
3577 sector_t sector = sh->dev[dd_idx].sector;
3578 for (bi=sh->dev[dd_idx].towrite;
3579 sector < sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf) &&
3580 bi && bi->bi_iter.bi_sector <= sector;
3581 bi = r5_next_bio(conf, bi, sh->dev[dd_idx].sector)) {
3582 if (bio_end_sector(bi) >= sector)
3583 sector = bio_end_sector(bi);
3585 if (sector >= sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf))
3586 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3587 sh->overwrite_disks++;
3590 pr_debug("added bi b#%llu to stripe s#%llu, disk %d, logical %llu\n",
3591 (*bip)->bi_iter.bi_sector, sh->sector, dd_idx,
3592 sh->dev[dd_idx].sector);
3594 if (conf->mddev->bitmap && firstwrite) {
3595 /* Cannot hold spinlock over bitmap_startwrite,
3596 * but must ensure this isn't added to a batch until
3597 * we have added to the bitmap and set bm_seq.
3598 * So set STRIPE_BITMAP_PENDING to prevent
3600 * If multiple __add_stripe_bio() calls race here they
3601 * much all set STRIPE_BITMAP_PENDING. So only the first one
3602 * to complete "bitmap_startwrite" gets to set
3603 * STRIPE_BIT_DELAY. This is important as once a stripe
3604 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3607 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3608 spin_unlock_irq(&sh->stripe_lock);
3609 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3610 RAID5_STRIPE_SECTORS(conf), 0);
3611 spin_lock_irq(&sh->stripe_lock);
3612 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3613 if (!sh->batch_head) {
3614 sh->bm_seq = conf->seq_flush+1;
3615 set_bit(STRIPE_BIT_DELAY, &sh->state);
3621 * Each stripe/dev can have one or more bios attached.
3622 * toread/towrite point to the first in a chain.
3623 * The bi_next chain must be in order.
3625 static bool add_stripe_bio(struct stripe_head *sh, struct bio *bi,
3626 int dd_idx, int forwrite, int previous)
3628 spin_lock_irq(&sh->stripe_lock);
3630 if (stripe_bio_overlaps(sh, bi, dd_idx, forwrite)) {
3631 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3632 spin_unlock_irq(&sh->stripe_lock);
3636 __add_stripe_bio(sh, bi, dd_idx, forwrite, previous);
3637 spin_unlock_irq(&sh->stripe_lock);
3641 static void end_reshape(struct r5conf *conf);
3643 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3644 struct stripe_head *sh)
3646 int sectors_per_chunk =
3647 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3649 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3650 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3652 raid5_compute_sector(conf,
3653 stripe * (disks - conf->max_degraded)
3654 *sectors_per_chunk + chunk_offset,
3660 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3661 struct stripe_head_state *s, int disks)
3664 BUG_ON(sh->batch_head);
3665 for (i = disks; i--; ) {
3669 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3670 struct md_rdev *rdev;
3672 rdev = rcu_dereference(conf->disks[i].rdev);
3673 if (rdev && test_bit(In_sync, &rdev->flags) &&
3674 !test_bit(Faulty, &rdev->flags))
3675 atomic_inc(&rdev->nr_pending);
3680 if (!rdev_set_badblocks(
3683 RAID5_STRIPE_SECTORS(conf), 0))
3684 md_error(conf->mddev, rdev);
3685 rdev_dec_pending(rdev, conf->mddev);
3688 spin_lock_irq(&sh->stripe_lock);
3689 /* fail all writes first */
3690 bi = sh->dev[i].towrite;
3691 sh->dev[i].towrite = NULL;
3692 sh->overwrite_disks = 0;
3693 spin_unlock_irq(&sh->stripe_lock);
3697 log_stripe_write_finished(sh);
3699 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3700 wake_up(&conf->wait_for_overlap);
3702 while (bi && bi->bi_iter.bi_sector <
3703 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3704 struct bio *nextbi = r5_next_bio(conf, bi, sh->dev[i].sector);
3706 md_write_end(conf->mddev);
3711 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3712 RAID5_STRIPE_SECTORS(conf), 0, 0);
3714 /* and fail all 'written' */
3715 bi = sh->dev[i].written;
3716 sh->dev[i].written = NULL;
3717 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3718 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3719 sh->dev[i].page = sh->dev[i].orig_page;
3722 if (bi) bitmap_end = 1;
3723 while (bi && bi->bi_iter.bi_sector <
3724 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3725 struct bio *bi2 = r5_next_bio(conf, bi, sh->dev[i].sector);
3727 md_write_end(conf->mddev);
3732 /* fail any reads if this device is non-operational and
3733 * the data has not reached the cache yet.
3735 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3736 s->failed > conf->max_degraded &&
3737 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3738 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3739 spin_lock_irq(&sh->stripe_lock);
3740 bi = sh->dev[i].toread;
3741 sh->dev[i].toread = NULL;
3742 spin_unlock_irq(&sh->stripe_lock);
3743 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3744 wake_up(&conf->wait_for_overlap);
3747 while (bi && bi->bi_iter.bi_sector <
3748 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3749 struct bio *nextbi =
3750 r5_next_bio(conf, bi, sh->dev[i].sector);
3757 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3758 RAID5_STRIPE_SECTORS(conf), 0, 0);
3759 /* If we were in the middle of a write the parity block might
3760 * still be locked - so just clear all R5_LOCKED flags
3762 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3767 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3768 if (atomic_dec_and_test(&conf->pending_full_writes))
3769 md_wakeup_thread(conf->mddev->thread);
3773 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3774 struct stripe_head_state *s)
3779 BUG_ON(sh->batch_head);
3780 clear_bit(STRIPE_SYNCING, &sh->state);
3781 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3782 wake_up(&conf->wait_for_overlap);
3785 /* There is nothing more to do for sync/check/repair.
3786 * Don't even need to abort as that is handled elsewhere
3787 * if needed, and not always wanted e.g. if there is a known
3789 * For recover/replace we need to record a bad block on all
3790 * non-sync devices, or abort the recovery
3792 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3793 /* During recovery devices cannot be removed, so
3794 * locking and refcounting of rdevs is not needed
3797 for (i = 0; i < conf->raid_disks; i++) {
3798 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3800 && !test_bit(Faulty, &rdev->flags)
3801 && !test_bit(In_sync, &rdev->flags)
3802 && !rdev_set_badblocks(rdev, sh->sector,
3803 RAID5_STRIPE_SECTORS(conf), 0))
3805 rdev = rcu_dereference(conf->disks[i].replacement);
3807 && !test_bit(Faulty, &rdev->flags)
3808 && !test_bit(In_sync, &rdev->flags)
3809 && !rdev_set_badblocks(rdev, sh->sector,
3810 RAID5_STRIPE_SECTORS(conf), 0))
3815 conf->recovery_disabled =
3816 conf->mddev->recovery_disabled;
3818 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), !abort);
3821 static int want_replace(struct stripe_head *sh, int disk_idx)
3823 struct md_rdev *rdev;
3827 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3829 && !test_bit(Faulty, &rdev->flags)
3830 && !test_bit(In_sync, &rdev->flags)
3831 && (rdev->recovery_offset <= sh->sector
3832 || rdev->mddev->recovery_cp <= sh->sector))
3838 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3839 int disk_idx, int disks)
3841 struct r5dev *dev = &sh->dev[disk_idx];
3842 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3843 &sh->dev[s->failed_num[1]] };
3845 bool force_rcw = (sh->raid_conf->rmw_level == PARITY_DISABLE_RMW);
3848 if (test_bit(R5_LOCKED, &dev->flags) ||
3849 test_bit(R5_UPTODATE, &dev->flags))
3850 /* No point reading this as we already have it or have
3851 * decided to get it.
3856 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3857 /* We need this block to directly satisfy a request */
3860 if (s->syncing || s->expanding ||
3861 (s->replacing && want_replace(sh, disk_idx)))
3862 /* When syncing, or expanding we read everything.
3863 * When replacing, we need the replaced block.
3867 if ((s->failed >= 1 && fdev[0]->toread) ||
3868 (s->failed >= 2 && fdev[1]->toread))
3869 /* If we want to read from a failed device, then
3870 * we need to actually read every other device.
3874 /* Sometimes neither read-modify-write nor reconstruct-write
3875 * cycles can work. In those cases we read every block we
3876 * can. Then the parity-update is certain to have enough to
3878 * This can only be a problem when we need to write something,
3879 * and some device has failed. If either of those tests
3880 * fail we need look no further.
3882 if (!s->failed || !s->to_write)
3885 if (test_bit(R5_Insync, &dev->flags) &&
3886 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3887 /* Pre-reads at not permitted until after short delay
3888 * to gather multiple requests. However if this
3889 * device is no Insync, the block could only be computed
3890 * and there is no need to delay that.
3894 for (i = 0; i < s->failed && i < 2; i++) {
3895 if (fdev[i]->towrite &&
3896 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3897 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3898 /* If we have a partial write to a failed
3899 * device, then we will need to reconstruct
3900 * the content of that device, so all other
3901 * devices must be read.
3905 if (s->failed >= 2 &&
3906 (fdev[i]->towrite ||
3907 s->failed_num[i] == sh->pd_idx ||
3908 s->failed_num[i] == sh->qd_idx) &&
3909 !test_bit(R5_UPTODATE, &fdev[i]->flags))
3910 /* In max degraded raid6, If the failed disk is P, Q,
3911 * or we want to read the failed disk, we need to do
3912 * reconstruct-write.
3917 /* If we are forced to do a reconstruct-write, because parity
3918 * cannot be trusted and we are currently recovering it, there
3919 * is extra need to be careful.
3920 * If one of the devices that we would need to read, because
3921 * it is not being overwritten (and maybe not written at all)
3922 * is missing/faulty, then we need to read everything we can.
3925 sh->sector < sh->raid_conf->mddev->recovery_cp)
3926 /* reconstruct-write isn't being forced */
3928 for (i = 0; i < s->failed && i < 2; i++) {
3929 if (s->failed_num[i] != sh->pd_idx &&
3930 s->failed_num[i] != sh->qd_idx &&
3931 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3932 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3939 /* fetch_block - checks the given member device to see if its data needs
3940 * to be read or computed to satisfy a request.
3942 * Returns 1 when no more member devices need to be checked, otherwise returns
3943 * 0 to tell the loop in handle_stripe_fill to continue
3945 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3946 int disk_idx, int disks)
3948 struct r5dev *dev = &sh->dev[disk_idx];
3950 /* is the data in this block needed, and can we get it? */
3951 if (need_this_block(sh, s, disk_idx, disks)) {
3952 /* we would like to get this block, possibly by computing it,
3953 * otherwise read it if the backing disk is insync
3955 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3956 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3957 BUG_ON(sh->batch_head);
3960 * In the raid6 case if the only non-uptodate disk is P
3961 * then we already trusted P to compute the other failed
3962 * drives. It is safe to compute rather than re-read P.
3963 * In other cases we only compute blocks from failed
3964 * devices, otherwise check/repair might fail to detect
3965 * a real inconsistency.
3968 if ((s->uptodate == disks - 1) &&
3969 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3970 (s->failed && (disk_idx == s->failed_num[0] ||
3971 disk_idx == s->failed_num[1])))) {
3972 /* have disk failed, and we're requested to fetch it;
3975 pr_debug("Computing stripe %llu block %d\n",
3976 (unsigned long long)sh->sector, disk_idx);
3977 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3978 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3979 set_bit(R5_Wantcompute, &dev->flags);
3980 sh->ops.target = disk_idx;
3981 sh->ops.target2 = -1; /* no 2nd target */
3983 /* Careful: from this point on 'uptodate' is in the eye
3984 * of raid_run_ops which services 'compute' operations
3985 * before writes. R5_Wantcompute flags a block that will
3986 * be R5_UPTODATE by the time it is needed for a
3987 * subsequent operation.
3991 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3992 /* Computing 2-failure is *very* expensive; only
3993 * do it if failed >= 2
3996 for (other = disks; other--; ) {
3997 if (other == disk_idx)
3999 if (!test_bit(R5_UPTODATE,
4000 &sh->dev[other].flags))
4004 pr_debug("Computing stripe %llu blocks %d,%d\n",
4005 (unsigned long long)sh->sector,
4007 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4008 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4009 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
4010 set_bit(R5_Wantcompute, &sh->dev[other].flags);
4011 sh->ops.target = disk_idx;
4012 sh->ops.target2 = other;
4016 } else if (test_bit(R5_Insync, &dev->flags)) {
4017 set_bit(R5_LOCKED, &dev->flags);
4018 set_bit(R5_Wantread, &dev->flags);
4020 pr_debug("Reading block %d (sync=%d)\n",
4021 disk_idx, s->syncing);
4029 * handle_stripe_fill - read or compute data to satisfy pending requests.
4031 static void handle_stripe_fill(struct stripe_head *sh,
4032 struct stripe_head_state *s,
4037 /* look for blocks to read/compute, skip this if a compute
4038 * is already in flight, or if the stripe contents are in the
4039 * midst of changing due to a write
4041 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
4042 !sh->reconstruct_state) {
4045 * For degraded stripe with data in journal, do not handle
4046 * read requests yet, instead, flush the stripe to raid
4047 * disks first, this avoids handling complex rmw of write
4048 * back cache (prexor with orig_page, and then xor with
4049 * page) in the read path
4051 if (s->to_read && s->injournal && s->failed) {
4052 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
4053 r5c_make_stripe_write_out(sh);
4057 for (i = disks; i--; )
4058 if (fetch_block(sh, s, i, disks))
4062 set_bit(STRIPE_HANDLE, &sh->state);
4065 static void break_stripe_batch_list(struct stripe_head *head_sh,
4066 unsigned long handle_flags);
4067 /* handle_stripe_clean_event
4068 * any written block on an uptodate or failed drive can be returned.
4069 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
4070 * never LOCKED, so we don't need to test 'failed' directly.
4072 static void handle_stripe_clean_event(struct r5conf *conf,
4073 struct stripe_head *sh, int disks)
4077 int discard_pending = 0;
4078 struct stripe_head *head_sh = sh;
4079 bool do_endio = false;
4081 for (i = disks; i--; )
4082 if (sh->dev[i].written) {
4084 if (!test_bit(R5_LOCKED, &dev->flags) &&
4085 (test_bit(R5_UPTODATE, &dev->flags) ||
4086 test_bit(R5_Discard, &dev->flags) ||
4087 test_bit(R5_SkipCopy, &dev->flags))) {
4088 /* We can return any write requests */
4089 struct bio *wbi, *wbi2;
4090 pr_debug("Return write for disc %d\n", i);
4091 if (test_and_clear_bit(R5_Discard, &dev->flags))
4092 clear_bit(R5_UPTODATE, &dev->flags);
4093 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
4094 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
4099 dev->page = dev->orig_page;
4101 dev->written = NULL;
4102 while (wbi && wbi->bi_iter.bi_sector <
4103 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
4104 wbi2 = r5_next_bio(conf, wbi, dev->sector);
4105 md_write_end(conf->mddev);
4109 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
4110 RAID5_STRIPE_SECTORS(conf),
4111 !test_bit(STRIPE_DEGRADED, &sh->state),
4113 if (head_sh->batch_head) {
4114 sh = list_first_entry(&sh->batch_list,
4117 if (sh != head_sh) {
4124 } else if (test_bit(R5_Discard, &dev->flags))
4125 discard_pending = 1;
4128 log_stripe_write_finished(sh);
4130 if (!discard_pending &&
4131 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
4133 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
4134 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4135 if (sh->qd_idx >= 0) {
4136 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
4137 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
4139 /* now that discard is done we can proceed with any sync */
4140 clear_bit(STRIPE_DISCARD, &sh->state);
4142 * SCSI discard will change some bio fields and the stripe has
4143 * no updated data, so remove it from hash list and the stripe
4144 * will be reinitialized
4147 hash = sh->hash_lock_index;
4148 spin_lock_irq(conf->hash_locks + hash);
4150 spin_unlock_irq(conf->hash_locks + hash);
4151 if (head_sh->batch_head) {
4152 sh = list_first_entry(&sh->batch_list,
4153 struct stripe_head, batch_list);
4159 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
4160 set_bit(STRIPE_HANDLE, &sh->state);
4164 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
4165 if (atomic_dec_and_test(&conf->pending_full_writes))
4166 md_wakeup_thread(conf->mddev->thread);
4168 if (head_sh->batch_head && do_endio)
4169 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
4173 * For RMW in write back cache, we need extra page in prexor to store the
4174 * old data. This page is stored in dev->orig_page.
4176 * This function checks whether we have data for prexor. The exact logic
4178 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
4180 static inline bool uptodate_for_rmw(struct r5dev *dev)
4182 return (test_bit(R5_UPTODATE, &dev->flags)) &&
4183 (!test_bit(R5_InJournal, &dev->flags) ||
4184 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
4187 static int handle_stripe_dirtying(struct r5conf *conf,
4188 struct stripe_head *sh,
4189 struct stripe_head_state *s,
4192 int rmw = 0, rcw = 0, i;
4193 sector_t recovery_cp = conf->mddev->recovery_cp;
4195 /* Check whether resync is now happening or should start.
4196 * If yes, then the array is dirty (after unclean shutdown or
4197 * initial creation), so parity in some stripes might be inconsistent.
4198 * In this case, we need to always do reconstruct-write, to ensure
4199 * that in case of drive failure or read-error correction, we
4200 * generate correct data from the parity.
4202 if (conf->rmw_level == PARITY_DISABLE_RMW ||
4203 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
4205 /* Calculate the real rcw later - for now make it
4206 * look like rcw is cheaper
4209 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
4210 conf->rmw_level, (unsigned long long)recovery_cp,
4211 (unsigned long long)sh->sector);
4212 } else for (i = disks; i--; ) {
4213 /* would I have to read this buffer for read_modify_write */
4214 struct r5dev *dev = &sh->dev[i];
4215 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4216 i == sh->pd_idx || i == sh->qd_idx ||
4217 test_bit(R5_InJournal, &dev->flags)) &&
4218 !test_bit(R5_LOCKED, &dev->flags) &&
4219 !(uptodate_for_rmw(dev) ||
4220 test_bit(R5_Wantcompute, &dev->flags))) {
4221 if (test_bit(R5_Insync, &dev->flags))
4224 rmw += 2*disks; /* cannot read it */
4226 /* Would I have to read this buffer for reconstruct_write */
4227 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4228 i != sh->pd_idx && i != sh->qd_idx &&
4229 !test_bit(R5_LOCKED, &dev->flags) &&
4230 !(test_bit(R5_UPTODATE, &dev->flags) ||
4231 test_bit(R5_Wantcompute, &dev->flags))) {
4232 if (test_bit(R5_Insync, &dev->flags))
4239 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
4240 (unsigned long long)sh->sector, sh->state, rmw, rcw);
4241 set_bit(STRIPE_HANDLE, &sh->state);
4242 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
4243 /* prefer read-modify-write, but need to get some data */
4244 if (conf->mddev->queue)
4245 blk_add_trace_msg(conf->mddev->queue,
4246 "raid5 rmw %llu %d",
4247 (unsigned long long)sh->sector, rmw);
4248 for (i = disks; i--; ) {
4249 struct r5dev *dev = &sh->dev[i];
4250 if (test_bit(R5_InJournal, &dev->flags) &&
4251 dev->page == dev->orig_page &&
4252 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
4253 /* alloc page for prexor */
4254 struct page *p = alloc_page(GFP_NOIO);
4262 * alloc_page() failed, try use
4263 * disk_info->extra_page
4265 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
4266 &conf->cache_state)) {
4267 r5c_use_extra_page(sh);
4271 /* extra_page in use, add to delayed_list */
4272 set_bit(STRIPE_DELAYED, &sh->state);
4273 s->waiting_extra_page = 1;
4278 for (i = disks; i--; ) {
4279 struct r5dev *dev = &sh->dev[i];
4280 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4281 i == sh->pd_idx || i == sh->qd_idx ||
4282 test_bit(R5_InJournal, &dev->flags)) &&
4283 !test_bit(R5_LOCKED, &dev->flags) &&
4284 !(uptodate_for_rmw(dev) ||
4285 test_bit(R5_Wantcompute, &dev->flags)) &&
4286 test_bit(R5_Insync, &dev->flags)) {
4287 if (test_bit(STRIPE_PREREAD_ACTIVE,
4289 pr_debug("Read_old block %d for r-m-w\n",
4291 set_bit(R5_LOCKED, &dev->flags);
4292 set_bit(R5_Wantread, &dev->flags);
4295 set_bit(STRIPE_DELAYED, &sh->state);
4299 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
4300 /* want reconstruct write, but need to get some data */
4303 for (i = disks; i--; ) {
4304 struct r5dev *dev = &sh->dev[i];
4305 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4306 i != sh->pd_idx && i != sh->qd_idx &&
4307 !test_bit(R5_LOCKED, &dev->flags) &&
4308 !(test_bit(R5_UPTODATE, &dev->flags) ||
4309 test_bit(R5_Wantcompute, &dev->flags))) {
4311 if (test_bit(R5_Insync, &dev->flags) &&
4312 test_bit(STRIPE_PREREAD_ACTIVE,
4314 pr_debug("Read_old block "
4315 "%d for Reconstruct\n", i);
4316 set_bit(R5_LOCKED, &dev->flags);
4317 set_bit(R5_Wantread, &dev->flags);
4321 set_bit(STRIPE_DELAYED, &sh->state);
4324 if (rcw && conf->mddev->queue)
4325 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4326 (unsigned long long)sh->sector,
4327 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4330 if (rcw > disks && rmw > disks &&
4331 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4332 set_bit(STRIPE_DELAYED, &sh->state);
4334 /* now if nothing is locked, and if we have enough data,
4335 * we can start a write request
4337 /* since handle_stripe can be called at any time we need to handle the
4338 * case where a compute block operation has been submitted and then a
4339 * subsequent call wants to start a write request. raid_run_ops only
4340 * handles the case where compute block and reconstruct are requested
4341 * simultaneously. If this is not the case then new writes need to be
4342 * held off until the compute completes.
4344 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4345 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4346 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4347 schedule_reconstruction(sh, s, rcw == 0, 0);
4351 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4352 struct stripe_head_state *s, int disks)
4354 struct r5dev *dev = NULL;
4356 BUG_ON(sh->batch_head);
4357 set_bit(STRIPE_HANDLE, &sh->state);
4359 switch (sh->check_state) {
4360 case check_state_idle:
4361 /* start a new check operation if there are no failures */
4362 if (s->failed == 0) {
4363 BUG_ON(s->uptodate != disks);
4364 sh->check_state = check_state_run;
4365 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4366 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4370 dev = &sh->dev[s->failed_num[0]];
4372 case check_state_compute_result:
4373 sh->check_state = check_state_idle;
4375 dev = &sh->dev[sh->pd_idx];
4377 /* check that a write has not made the stripe insync */
4378 if (test_bit(STRIPE_INSYNC, &sh->state))
4381 /* either failed parity check, or recovery is happening */
4382 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4383 BUG_ON(s->uptodate != disks);
4385 set_bit(R5_LOCKED, &dev->flags);
4387 set_bit(R5_Wantwrite, &dev->flags);
4389 clear_bit(STRIPE_DEGRADED, &sh->state);
4390 set_bit(STRIPE_INSYNC, &sh->state);
4392 case check_state_run:
4393 break; /* we will be called again upon completion */
4394 case check_state_check_result:
4395 sh->check_state = check_state_idle;
4397 /* if a failure occurred during the check operation, leave
4398 * STRIPE_INSYNC not set and let the stripe be handled again
4403 /* handle a successful check operation, if parity is correct
4404 * we are done. Otherwise update the mismatch count and repair
4405 * parity if !MD_RECOVERY_CHECK
4407 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4408 /* parity is correct (on disc,
4409 * not in buffer any more)
4411 set_bit(STRIPE_INSYNC, &sh->state);
4413 atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4414 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4415 /* don't try to repair!! */
4416 set_bit(STRIPE_INSYNC, &sh->state);
4417 pr_warn_ratelimited("%s: mismatch sector in range "
4418 "%llu-%llu\n", mdname(conf->mddev),
4419 (unsigned long long) sh->sector,
4420 (unsigned long long) sh->sector +
4421 RAID5_STRIPE_SECTORS(conf));
4423 sh->check_state = check_state_compute_run;
4424 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4425 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4426 set_bit(R5_Wantcompute,
4427 &sh->dev[sh->pd_idx].flags);
4428 sh->ops.target = sh->pd_idx;
4429 sh->ops.target2 = -1;
4434 case check_state_compute_run:
4437 pr_err("%s: unknown check_state: %d sector: %llu\n",
4438 __func__, sh->check_state,
4439 (unsigned long long) sh->sector);
4444 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4445 struct stripe_head_state *s,
4448 int pd_idx = sh->pd_idx;
4449 int qd_idx = sh->qd_idx;
4452 BUG_ON(sh->batch_head);
4453 set_bit(STRIPE_HANDLE, &sh->state);
4455 BUG_ON(s->failed > 2);
4457 /* Want to check and possibly repair P and Q.
4458 * However there could be one 'failed' device, in which
4459 * case we can only check one of them, possibly using the
4460 * other to generate missing data
4463 switch (sh->check_state) {
4464 case check_state_idle:
4465 /* start a new check operation if there are < 2 failures */
4466 if (s->failed == s->q_failed) {
4467 /* The only possible failed device holds Q, so it
4468 * makes sense to check P (If anything else were failed,
4469 * we would have used P to recreate it).
4471 sh->check_state = check_state_run;
4473 if (!s->q_failed && s->failed < 2) {
4474 /* Q is not failed, and we didn't use it to generate
4475 * anything, so it makes sense to check it
4477 if (sh->check_state == check_state_run)
4478 sh->check_state = check_state_run_pq;
4480 sh->check_state = check_state_run_q;
4483 /* discard potentially stale zero_sum_result */
4484 sh->ops.zero_sum_result = 0;
4486 if (sh->check_state == check_state_run) {
4487 /* async_xor_zero_sum destroys the contents of P */
4488 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4491 if (sh->check_state >= check_state_run &&
4492 sh->check_state <= check_state_run_pq) {
4493 /* async_syndrome_zero_sum preserves P and Q, so
4494 * no need to mark them !uptodate here
4496 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4500 /* we have 2-disk failure */
4501 BUG_ON(s->failed != 2);
4503 case check_state_compute_result:
4504 sh->check_state = check_state_idle;
4506 /* check that a write has not made the stripe insync */
4507 if (test_bit(STRIPE_INSYNC, &sh->state))
4510 /* now write out any block on a failed drive,
4511 * or P or Q if they were recomputed
4514 if (s->failed == 2) {
4515 dev = &sh->dev[s->failed_num[1]];
4517 set_bit(R5_LOCKED, &dev->flags);
4518 set_bit(R5_Wantwrite, &dev->flags);
4520 if (s->failed >= 1) {
4521 dev = &sh->dev[s->failed_num[0]];
4523 set_bit(R5_LOCKED, &dev->flags);
4524 set_bit(R5_Wantwrite, &dev->flags);
4526 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4527 dev = &sh->dev[pd_idx];
4529 set_bit(R5_LOCKED, &dev->flags);
4530 set_bit(R5_Wantwrite, &dev->flags);
4532 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4533 dev = &sh->dev[qd_idx];
4535 set_bit(R5_LOCKED, &dev->flags);
4536 set_bit(R5_Wantwrite, &dev->flags);
4538 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4539 "%s: disk%td not up to date\n",
4540 mdname(conf->mddev),
4541 dev - (struct r5dev *) &sh->dev)) {
4542 clear_bit(R5_LOCKED, &dev->flags);
4543 clear_bit(R5_Wantwrite, &dev->flags);
4546 clear_bit(STRIPE_DEGRADED, &sh->state);
4548 set_bit(STRIPE_INSYNC, &sh->state);
4550 case check_state_run:
4551 case check_state_run_q:
4552 case check_state_run_pq:
4553 break; /* we will be called again upon completion */
4554 case check_state_check_result:
4555 sh->check_state = check_state_idle;
4557 /* handle a successful check operation, if parity is correct
4558 * we are done. Otherwise update the mismatch count and repair
4559 * parity if !MD_RECOVERY_CHECK
4561 if (sh->ops.zero_sum_result == 0) {
4562 /* both parities are correct */
4564 set_bit(STRIPE_INSYNC, &sh->state);
4566 /* in contrast to the raid5 case we can validate
4567 * parity, but still have a failure to write
4570 sh->check_state = check_state_compute_result;
4571 /* Returning at this point means that we may go
4572 * off and bring p and/or q uptodate again so
4573 * we make sure to check zero_sum_result again
4574 * to verify if p or q need writeback
4578 atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4579 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4580 /* don't try to repair!! */
4581 set_bit(STRIPE_INSYNC, &sh->state);
4582 pr_warn_ratelimited("%s: mismatch sector in range "
4583 "%llu-%llu\n", mdname(conf->mddev),
4584 (unsigned long long) sh->sector,
4585 (unsigned long long) sh->sector +
4586 RAID5_STRIPE_SECTORS(conf));
4588 int *target = &sh->ops.target;
4590 sh->ops.target = -1;
4591 sh->ops.target2 = -1;
4592 sh->check_state = check_state_compute_run;
4593 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4594 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4595 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4596 set_bit(R5_Wantcompute,
4597 &sh->dev[pd_idx].flags);
4599 target = &sh->ops.target2;
4602 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4603 set_bit(R5_Wantcompute,
4604 &sh->dev[qd_idx].flags);
4611 case check_state_compute_run:
4614 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4615 __func__, sh->check_state,
4616 (unsigned long long) sh->sector);
4621 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4625 /* We have read all the blocks in this stripe and now we need to
4626 * copy some of them into a target stripe for expand.
4628 struct dma_async_tx_descriptor *tx = NULL;
4629 BUG_ON(sh->batch_head);
4630 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4631 for (i = 0; i < sh->disks; i++)
4632 if (i != sh->pd_idx && i != sh->qd_idx) {
4634 struct stripe_head *sh2;
4635 struct async_submit_ctl submit;
4637 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4638 sector_t s = raid5_compute_sector(conf, bn, 0,
4640 sh2 = raid5_get_active_stripe(conf, NULL, s,
4641 R5_GAS_NOBLOCK | R5_GAS_NOQUIESCE);
4643 /* so far only the early blocks of this stripe
4644 * have been requested. When later blocks
4645 * get requested, we will try again
4648 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4649 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4650 /* must have already done this block */
4651 raid5_release_stripe(sh2);
4655 /* place all the copies on one channel */
4656 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4657 tx = async_memcpy(sh2->dev[dd_idx].page,
4658 sh->dev[i].page, sh2->dev[dd_idx].offset,
4659 sh->dev[i].offset, RAID5_STRIPE_SIZE(conf),
4662 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4663 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4664 for (j = 0; j < conf->raid_disks; j++)
4665 if (j != sh2->pd_idx &&
4667 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4669 if (j == conf->raid_disks) {
4670 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4671 set_bit(STRIPE_HANDLE, &sh2->state);
4673 raid5_release_stripe(sh2);
4676 /* done submitting copies, wait for them to complete */
4677 async_tx_quiesce(&tx);
4681 * handle_stripe - do things to a stripe.
4683 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4684 * state of various bits to see what needs to be done.
4686 * return some read requests which now have data
4687 * return some write requests which are safely on storage
4688 * schedule a read on some buffers
4689 * schedule a write of some buffers
4690 * return confirmation of parity correctness
4694 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4696 struct r5conf *conf = sh->raid_conf;
4697 int disks = sh->disks;
4700 int do_recovery = 0;
4702 memset(s, 0, sizeof(*s));
4704 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4705 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4706 s->failed_num[0] = -1;
4707 s->failed_num[1] = -1;
4708 s->log_failed = r5l_log_disk_error(conf);
4710 /* Now to look around and see what can be done */
4712 for (i=disks; i--; ) {
4713 struct md_rdev *rdev;
4720 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4722 dev->toread, dev->towrite, dev->written);
4723 /* maybe we can reply to a read
4725 * new wantfill requests are only permitted while
4726 * ops_complete_biofill is guaranteed to be inactive
4728 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4729 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4730 set_bit(R5_Wantfill, &dev->flags);
4732 /* now count some things */
4733 if (test_bit(R5_LOCKED, &dev->flags))
4735 if (test_bit(R5_UPTODATE, &dev->flags))
4737 if (test_bit(R5_Wantcompute, &dev->flags)) {
4739 BUG_ON(s->compute > 2);
4742 if (test_bit(R5_Wantfill, &dev->flags))
4744 else if (dev->toread)
4748 if (!test_bit(R5_OVERWRITE, &dev->flags))
4753 /* Prefer to use the replacement for reads, but only
4754 * if it is recovered enough and has no bad blocks.
4756 rdev = rcu_dereference(conf->disks[i].replacement);
4757 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4758 rdev->recovery_offset >= sh->sector + RAID5_STRIPE_SECTORS(conf) &&
4759 !is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4760 &first_bad, &bad_sectors))
4761 set_bit(R5_ReadRepl, &dev->flags);
4763 if (rdev && !test_bit(Faulty, &rdev->flags))
4764 set_bit(R5_NeedReplace, &dev->flags);
4766 clear_bit(R5_NeedReplace, &dev->flags);
4767 rdev = rcu_dereference(conf->disks[i].rdev);
4768 clear_bit(R5_ReadRepl, &dev->flags);
4770 if (rdev && test_bit(Faulty, &rdev->flags))
4773 is_bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4774 &first_bad, &bad_sectors);
4775 if (s->blocked_rdev == NULL
4776 && (test_bit(Blocked, &rdev->flags)
4779 set_bit(BlockedBadBlocks,
4781 s->blocked_rdev = rdev;
4782 atomic_inc(&rdev->nr_pending);
4785 clear_bit(R5_Insync, &dev->flags);
4789 /* also not in-sync */
4790 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4791 test_bit(R5_UPTODATE, &dev->flags)) {
4792 /* treat as in-sync, but with a read error
4793 * which we can now try to correct
4795 set_bit(R5_Insync, &dev->flags);
4796 set_bit(R5_ReadError, &dev->flags);
4798 } else if (test_bit(In_sync, &rdev->flags))
4799 set_bit(R5_Insync, &dev->flags);
4800 else if (sh->sector + RAID5_STRIPE_SECTORS(conf) <= rdev->recovery_offset)
4801 /* in sync if before recovery_offset */
4802 set_bit(R5_Insync, &dev->flags);
4803 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4804 test_bit(R5_Expanded, &dev->flags))
4805 /* If we've reshaped into here, we assume it is Insync.
4806 * We will shortly update recovery_offset to make
4809 set_bit(R5_Insync, &dev->flags);
4811 if (test_bit(R5_WriteError, &dev->flags)) {
4812 /* This flag does not apply to '.replacement'
4813 * only to .rdev, so make sure to check that*/
4814 struct md_rdev *rdev2 = rcu_dereference(
4815 conf->disks[i].rdev);
4817 clear_bit(R5_Insync, &dev->flags);
4818 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4819 s->handle_bad_blocks = 1;
4820 atomic_inc(&rdev2->nr_pending);
4822 clear_bit(R5_WriteError, &dev->flags);
4824 if (test_bit(R5_MadeGood, &dev->flags)) {
4825 /* This flag does not apply to '.replacement'
4826 * only to .rdev, so make sure to check that*/
4827 struct md_rdev *rdev2 = rcu_dereference(
4828 conf->disks[i].rdev);
4829 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4830 s->handle_bad_blocks = 1;
4831 atomic_inc(&rdev2->nr_pending);
4833 clear_bit(R5_MadeGood, &dev->flags);
4835 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4836 struct md_rdev *rdev2 = rcu_dereference(
4837 conf->disks[i].replacement);
4838 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4839 s->handle_bad_blocks = 1;
4840 atomic_inc(&rdev2->nr_pending);
4842 clear_bit(R5_MadeGoodRepl, &dev->flags);
4844 if (!test_bit(R5_Insync, &dev->flags)) {
4845 /* The ReadError flag will just be confusing now */
4846 clear_bit(R5_ReadError, &dev->flags);
4847 clear_bit(R5_ReWrite, &dev->flags);
4849 if (test_bit(R5_ReadError, &dev->flags))
4850 clear_bit(R5_Insync, &dev->flags);
4851 if (!test_bit(R5_Insync, &dev->flags)) {
4853 s->failed_num[s->failed] = i;
4855 if (rdev && !test_bit(Faulty, &rdev->flags))
4858 rdev = rcu_dereference(
4859 conf->disks[i].replacement);
4860 if (rdev && !test_bit(Faulty, &rdev->flags))
4865 if (test_bit(R5_InJournal, &dev->flags))
4867 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4870 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4871 /* If there is a failed device being replaced,
4872 * we must be recovering.
4873 * else if we are after recovery_cp, we must be syncing
4874 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4875 * else we can only be replacing
4876 * sync and recovery both need to read all devices, and so
4877 * use the same flag.
4880 sh->sector >= conf->mddev->recovery_cp ||
4881 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4890 * Return '1' if this is a member of batch, or '0' if it is a lone stripe or
4891 * a head which can now be handled.
4893 static int clear_batch_ready(struct stripe_head *sh)
4895 struct stripe_head *tmp;
4896 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4897 return (sh->batch_head && sh->batch_head != sh);
4898 spin_lock(&sh->stripe_lock);
4899 if (!sh->batch_head) {
4900 spin_unlock(&sh->stripe_lock);
4905 * this stripe could be added to a batch list before we check
4906 * BATCH_READY, skips it
4908 if (sh->batch_head != sh) {
4909 spin_unlock(&sh->stripe_lock);
4912 spin_lock(&sh->batch_lock);
4913 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4914 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4915 spin_unlock(&sh->batch_lock);
4916 spin_unlock(&sh->stripe_lock);
4919 * BATCH_READY is cleared, no new stripes can be added.
4920 * batch_list can be accessed without lock
4925 static void break_stripe_batch_list(struct stripe_head *head_sh,
4926 unsigned long handle_flags)
4928 struct stripe_head *sh, *next;
4932 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4934 list_del_init(&sh->batch_list);
4936 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4937 (1 << STRIPE_SYNCING) |
4938 (1 << STRIPE_REPLACED) |
4939 (1 << STRIPE_DELAYED) |
4940 (1 << STRIPE_BIT_DELAY) |
4941 (1 << STRIPE_FULL_WRITE) |
4942 (1 << STRIPE_BIOFILL_RUN) |
4943 (1 << STRIPE_COMPUTE_RUN) |
4944 (1 << STRIPE_DISCARD) |
4945 (1 << STRIPE_BATCH_READY) |
4946 (1 << STRIPE_BATCH_ERR) |
4947 (1 << STRIPE_BITMAP_PENDING)),
4948 "stripe state: %lx\n", sh->state);
4949 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4950 (1 << STRIPE_REPLACED)),
4951 "head stripe state: %lx\n", head_sh->state);
4953 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4954 (1 << STRIPE_PREREAD_ACTIVE) |
4955 (1 << STRIPE_DEGRADED) |
4956 (1 << STRIPE_ON_UNPLUG_LIST)),
4957 head_sh->state & (1 << STRIPE_INSYNC));
4959 sh->check_state = head_sh->check_state;
4960 sh->reconstruct_state = head_sh->reconstruct_state;
4961 spin_lock_irq(&sh->stripe_lock);
4962 sh->batch_head = NULL;
4963 spin_unlock_irq(&sh->stripe_lock);
4964 for (i = 0; i < sh->disks; i++) {
4965 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4967 sh->dev[i].flags = head_sh->dev[i].flags &
4968 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4970 if (handle_flags == 0 ||
4971 sh->state & handle_flags)
4972 set_bit(STRIPE_HANDLE, &sh->state);
4973 raid5_release_stripe(sh);
4975 spin_lock_irq(&head_sh->stripe_lock);
4976 head_sh->batch_head = NULL;
4977 spin_unlock_irq(&head_sh->stripe_lock);
4978 for (i = 0; i < head_sh->disks; i++)
4979 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4981 if (head_sh->state & handle_flags)
4982 set_bit(STRIPE_HANDLE, &head_sh->state);
4985 wake_up(&head_sh->raid_conf->wait_for_overlap);
4988 static void handle_stripe(struct stripe_head *sh)
4990 struct stripe_head_state s;
4991 struct r5conf *conf = sh->raid_conf;
4994 int disks = sh->disks;
4995 struct r5dev *pdev, *qdev;
4997 clear_bit(STRIPE_HANDLE, &sh->state);
5000 * handle_stripe should not continue handle the batched stripe, only
5001 * the head of batch list or lone stripe can continue. Otherwise we
5002 * could see break_stripe_batch_list warns about the STRIPE_ACTIVE
5003 * is set for the batched stripe.
5005 if (clear_batch_ready(sh))
5008 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
5009 /* already being handled, ensure it gets handled
5010 * again when current action finishes */
5011 set_bit(STRIPE_HANDLE, &sh->state);
5015 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
5016 break_stripe_batch_list(sh, 0);
5018 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
5019 spin_lock(&sh->stripe_lock);
5021 * Cannot process 'sync' concurrently with 'discard'.
5022 * Flush data in r5cache before 'sync'.
5024 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
5025 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
5026 !test_bit(STRIPE_DISCARD, &sh->state) &&
5027 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
5028 set_bit(STRIPE_SYNCING, &sh->state);
5029 clear_bit(STRIPE_INSYNC, &sh->state);
5030 clear_bit(STRIPE_REPLACED, &sh->state);
5032 spin_unlock(&sh->stripe_lock);
5034 clear_bit(STRIPE_DELAYED, &sh->state);
5036 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
5037 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
5038 (unsigned long long)sh->sector, sh->state,
5039 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
5040 sh->check_state, sh->reconstruct_state);
5042 analyse_stripe(sh, &s);
5044 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
5047 if (s.handle_bad_blocks ||
5048 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
5049 set_bit(STRIPE_HANDLE, &sh->state);
5053 if (unlikely(s.blocked_rdev)) {
5054 if (s.syncing || s.expanding || s.expanded ||
5055 s.replacing || s.to_write || s.written) {
5056 set_bit(STRIPE_HANDLE, &sh->state);
5059 /* There is nothing for the blocked_rdev to block */
5060 rdev_dec_pending(s.blocked_rdev, conf->mddev);
5061 s.blocked_rdev = NULL;
5064 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
5065 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
5066 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
5069 pr_debug("locked=%d uptodate=%d to_read=%d"
5070 " to_write=%d failed=%d failed_num=%d,%d\n",
5071 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
5072 s.failed_num[0], s.failed_num[1]);
5074 * check if the array has lost more than max_degraded devices and,
5075 * if so, some requests might need to be failed.
5077 * When journal device failed (log_failed), we will only process
5078 * the stripe if there is data need write to raid disks
5080 if (s.failed > conf->max_degraded ||
5081 (s.log_failed && s.injournal == 0)) {
5082 sh->check_state = 0;
5083 sh->reconstruct_state = 0;
5084 break_stripe_batch_list(sh, 0);
5085 if (s.to_read+s.to_write+s.written)
5086 handle_failed_stripe(conf, sh, &s, disks);
5087 if (s.syncing + s.replacing)
5088 handle_failed_sync(conf, sh, &s);
5091 /* Now we check to see if any write operations have recently
5095 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
5097 if (sh->reconstruct_state == reconstruct_state_drain_result ||
5098 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
5099 sh->reconstruct_state = reconstruct_state_idle;
5101 /* All the 'written' buffers and the parity block are ready to
5102 * be written back to disk
5104 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
5105 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
5106 BUG_ON(sh->qd_idx >= 0 &&
5107 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
5108 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
5109 for (i = disks; i--; ) {
5110 struct r5dev *dev = &sh->dev[i];
5111 if (test_bit(R5_LOCKED, &dev->flags) &&
5112 (i == sh->pd_idx || i == sh->qd_idx ||
5113 dev->written || test_bit(R5_InJournal,
5115 pr_debug("Writing block %d\n", i);
5116 set_bit(R5_Wantwrite, &dev->flags);
5121 if (!test_bit(R5_Insync, &dev->flags) ||
5122 ((i == sh->pd_idx || i == sh->qd_idx) &&
5124 set_bit(STRIPE_INSYNC, &sh->state);
5127 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5128 s.dec_preread_active = 1;
5132 * might be able to return some write requests if the parity blocks
5133 * are safe, or on a failed drive
5135 pdev = &sh->dev[sh->pd_idx];
5136 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
5137 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
5138 qdev = &sh->dev[sh->qd_idx];
5139 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
5140 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
5144 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
5145 && !test_bit(R5_LOCKED, &pdev->flags)
5146 && (test_bit(R5_UPTODATE, &pdev->flags) ||
5147 test_bit(R5_Discard, &pdev->flags))))) &&
5148 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
5149 && !test_bit(R5_LOCKED, &qdev->flags)
5150 && (test_bit(R5_UPTODATE, &qdev->flags) ||
5151 test_bit(R5_Discard, &qdev->flags))))))
5152 handle_stripe_clean_event(conf, sh, disks);
5155 r5c_handle_cached_data_endio(conf, sh, disks);
5156 log_stripe_write_finished(sh);
5158 /* Now we might consider reading some blocks, either to check/generate
5159 * parity, or to satisfy requests
5160 * or to load a block that is being partially written.
5162 if (s.to_read || s.non_overwrite
5163 || (s.to_write && s.failed)
5164 || (s.syncing && (s.uptodate + s.compute < disks))
5167 handle_stripe_fill(sh, &s, disks);
5170 * When the stripe finishes full journal write cycle (write to journal
5171 * and raid disk), this is the clean up procedure so it is ready for
5174 r5c_finish_stripe_write_out(conf, sh, &s);
5177 * Now to consider new write requests, cache write back and what else,
5178 * if anything should be read. We do not handle new writes when:
5179 * 1/ A 'write' operation (copy+xor) is already in flight.
5180 * 2/ A 'check' operation is in flight, as it may clobber the parity
5182 * 3/ A r5c cache log write is in flight.
5185 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
5186 if (!r5c_is_writeback(conf->log)) {
5188 handle_stripe_dirtying(conf, sh, &s, disks);
5189 } else { /* write back cache */
5192 /* First, try handle writes in caching phase */
5194 ret = r5c_try_caching_write(conf, sh, &s,
5197 * If caching phase failed: ret == -EAGAIN
5199 * stripe under reclaim: !caching && injournal
5201 * fall back to handle_stripe_dirtying()
5203 if (ret == -EAGAIN ||
5204 /* stripe under reclaim: !caching && injournal */
5205 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
5207 ret = handle_stripe_dirtying(conf, sh, &s,
5215 /* maybe we need to check and possibly fix the parity for this stripe
5216 * Any reads will already have been scheduled, so we just see if enough
5217 * data is available. The parity check is held off while parity
5218 * dependent operations are in flight.
5220 if (sh->check_state ||
5221 (s.syncing && s.locked == 0 &&
5222 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5223 !test_bit(STRIPE_INSYNC, &sh->state))) {
5224 if (conf->level == 6)
5225 handle_parity_checks6(conf, sh, &s, disks);
5227 handle_parity_checks5(conf, sh, &s, disks);
5230 if ((s.replacing || s.syncing) && s.locked == 0
5231 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
5232 && !test_bit(STRIPE_REPLACED, &sh->state)) {
5233 /* Write out to replacement devices where possible */
5234 for (i = 0; i < conf->raid_disks; i++)
5235 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
5236 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
5237 set_bit(R5_WantReplace, &sh->dev[i].flags);
5238 set_bit(R5_LOCKED, &sh->dev[i].flags);
5242 set_bit(STRIPE_INSYNC, &sh->state);
5243 set_bit(STRIPE_REPLACED, &sh->state);
5245 if ((s.syncing || s.replacing) && s.locked == 0 &&
5246 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5247 test_bit(STRIPE_INSYNC, &sh->state)) {
5248 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5249 clear_bit(STRIPE_SYNCING, &sh->state);
5250 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
5251 wake_up(&conf->wait_for_overlap);
5254 /* If the failed drives are just a ReadError, then we might need
5255 * to progress the repair/check process
5257 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
5258 for (i = 0; i < s.failed; i++) {
5259 struct r5dev *dev = &sh->dev[s.failed_num[i]];
5260 if (test_bit(R5_ReadError, &dev->flags)
5261 && !test_bit(R5_LOCKED, &dev->flags)
5262 && test_bit(R5_UPTODATE, &dev->flags)
5264 if (!test_bit(R5_ReWrite, &dev->flags)) {
5265 set_bit(R5_Wantwrite, &dev->flags);
5266 set_bit(R5_ReWrite, &dev->flags);
5268 /* let's read it back */
5269 set_bit(R5_Wantread, &dev->flags);
5270 set_bit(R5_LOCKED, &dev->flags);
5275 /* Finish reconstruct operations initiated by the expansion process */
5276 if (sh->reconstruct_state == reconstruct_state_result) {
5277 struct stripe_head *sh_src
5278 = raid5_get_active_stripe(conf, NULL, sh->sector,
5279 R5_GAS_PREVIOUS | R5_GAS_NOBLOCK |
5281 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
5282 /* sh cannot be written until sh_src has been read.
5283 * so arrange for sh to be delayed a little
5285 set_bit(STRIPE_DELAYED, &sh->state);
5286 set_bit(STRIPE_HANDLE, &sh->state);
5287 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
5289 atomic_inc(&conf->preread_active_stripes);
5290 raid5_release_stripe(sh_src);
5294 raid5_release_stripe(sh_src);
5296 sh->reconstruct_state = reconstruct_state_idle;
5297 clear_bit(STRIPE_EXPANDING, &sh->state);
5298 for (i = conf->raid_disks; i--; ) {
5299 set_bit(R5_Wantwrite, &sh->dev[i].flags);
5300 set_bit(R5_LOCKED, &sh->dev[i].flags);
5305 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
5306 !sh->reconstruct_state) {
5307 /* Need to write out all blocks after computing parity */
5308 sh->disks = conf->raid_disks;
5309 stripe_set_idx(sh->sector, conf, 0, sh);
5310 schedule_reconstruction(sh, &s, 1, 1);
5311 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
5312 clear_bit(STRIPE_EXPAND_READY, &sh->state);
5313 atomic_dec(&conf->reshape_stripes);
5314 wake_up(&conf->wait_for_overlap);
5315 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5318 if (s.expanding && s.locked == 0 &&
5319 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
5320 handle_stripe_expansion(conf, sh);
5323 /* wait for this device to become unblocked */
5324 if (unlikely(s.blocked_rdev)) {
5325 if (conf->mddev->external)
5326 md_wait_for_blocked_rdev(s.blocked_rdev,
5329 /* Internal metadata will immediately
5330 * be written by raid5d, so we don't
5331 * need to wait here.
5333 rdev_dec_pending(s.blocked_rdev,
5337 if (s.handle_bad_blocks)
5338 for (i = disks; i--; ) {
5339 struct md_rdev *rdev;
5340 struct r5dev *dev = &sh->dev[i];
5341 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5342 /* We own a safe reference to the rdev */
5343 rdev = rdev_pend_deref(conf->disks[i].rdev);
5344 if (!rdev_set_badblocks(rdev, sh->sector,
5345 RAID5_STRIPE_SECTORS(conf), 0))
5346 md_error(conf->mddev, rdev);
5347 rdev_dec_pending(rdev, conf->mddev);
5349 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5350 rdev = rdev_pend_deref(conf->disks[i].rdev);
5351 rdev_clear_badblocks(rdev, sh->sector,
5352 RAID5_STRIPE_SECTORS(conf), 0);
5353 rdev_dec_pending(rdev, conf->mddev);
5355 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5356 rdev = rdev_pend_deref(conf->disks[i].replacement);
5358 /* rdev have been moved down */
5359 rdev = rdev_pend_deref(conf->disks[i].rdev);
5360 rdev_clear_badblocks(rdev, sh->sector,
5361 RAID5_STRIPE_SECTORS(conf), 0);
5362 rdev_dec_pending(rdev, conf->mddev);
5367 raid_run_ops(sh, s.ops_request);
5371 if (s.dec_preread_active) {
5372 /* We delay this until after ops_run_io so that if make_request
5373 * is waiting on a flush, it won't continue until the writes
5374 * have actually been submitted.
5376 atomic_dec(&conf->preread_active_stripes);
5377 if (atomic_read(&conf->preread_active_stripes) <
5379 md_wakeup_thread(conf->mddev->thread);
5382 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5385 static void raid5_activate_delayed(struct r5conf *conf)
5386 __must_hold(&conf->device_lock)
5388 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5389 while (!list_empty(&conf->delayed_list)) {
5390 struct list_head *l = conf->delayed_list.next;
5391 struct stripe_head *sh;
5392 sh = list_entry(l, struct stripe_head, lru);
5394 clear_bit(STRIPE_DELAYED, &sh->state);
5395 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5396 atomic_inc(&conf->preread_active_stripes);
5397 list_add_tail(&sh->lru, &conf->hold_list);
5398 raid5_wakeup_stripe_thread(sh);
5403 static void activate_bit_delay(struct r5conf *conf,
5404 struct list_head *temp_inactive_list)
5405 __must_hold(&conf->device_lock)
5407 struct list_head head;
5408 list_add(&head, &conf->bitmap_list);
5409 list_del_init(&conf->bitmap_list);
5410 while (!list_empty(&head)) {
5411 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5413 list_del_init(&sh->lru);
5414 atomic_inc(&sh->count);
5415 hash = sh->hash_lock_index;
5416 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5420 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5422 struct r5conf *conf = mddev->private;
5423 sector_t sector = bio->bi_iter.bi_sector;
5424 unsigned int chunk_sectors;
5425 unsigned int bio_sectors = bio_sectors(bio);
5427 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5428 return chunk_sectors >=
5429 ((sector & (chunk_sectors - 1)) + bio_sectors);
5433 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5434 * later sampled by raid5d.
5436 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5438 unsigned long flags;
5440 spin_lock_irqsave(&conf->device_lock, flags);
5442 bi->bi_next = conf->retry_read_aligned_list;
5443 conf->retry_read_aligned_list = bi;
5445 spin_unlock_irqrestore(&conf->device_lock, flags);
5446 md_wakeup_thread(conf->mddev->thread);
5449 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5450 unsigned int *offset)
5454 bi = conf->retry_read_aligned;
5456 *offset = conf->retry_read_offset;
5457 conf->retry_read_aligned = NULL;
5460 bi = conf->retry_read_aligned_list;
5462 conf->retry_read_aligned_list = bi->bi_next;
5471 * The "raid5_align_endio" should check if the read succeeded and if it
5472 * did, call bio_endio on the original bio (having bio_put the new bio
5474 * If the read failed..
5476 static void raid5_align_endio(struct bio *bi)
5478 struct bio *raid_bi = bi->bi_private;
5479 struct md_rdev *rdev = (void *)raid_bi->bi_next;
5480 struct mddev *mddev = rdev->mddev;
5481 struct r5conf *conf = mddev->private;
5482 blk_status_t error = bi->bi_status;
5485 raid_bi->bi_next = NULL;
5486 rdev_dec_pending(rdev, conf->mddev);
5490 if (atomic_dec_and_test(&conf->active_aligned_reads))
5491 wake_up(&conf->wait_for_quiescent);
5495 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5497 add_bio_to_retry(raid_bi, conf);
5500 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5502 struct r5conf *conf = mddev->private;
5503 struct bio *align_bio;
5504 struct md_rdev *rdev;
5505 sector_t sector, end_sector, first_bad;
5506 int bad_sectors, dd_idx;
5509 if (!in_chunk_boundary(mddev, raid_bio)) {
5510 pr_debug("%s: non aligned\n", __func__);
5514 sector = raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector, 0,
5516 end_sector = sector + bio_sectors(raid_bio);
5519 if (r5c_big_stripe_cached(conf, sector))
5520 goto out_rcu_unlock;
5522 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5523 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5524 rdev->recovery_offset < end_sector) {
5525 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5527 goto out_rcu_unlock;
5528 if (test_bit(Faulty, &rdev->flags) ||
5529 !(test_bit(In_sync, &rdev->flags) ||
5530 rdev->recovery_offset >= end_sector))
5531 goto out_rcu_unlock;
5534 atomic_inc(&rdev->nr_pending);
5537 if (is_badblock(rdev, sector, bio_sectors(raid_bio), &first_bad,
5539 rdev_dec_pending(rdev, mddev);
5543 md_account_bio(mddev, &raid_bio);
5544 raid_bio->bi_next = (void *)rdev;
5546 align_bio = bio_alloc_clone(rdev->bdev, raid_bio, GFP_NOIO,
5548 align_bio->bi_end_io = raid5_align_endio;
5549 align_bio->bi_private = raid_bio;
5550 align_bio->bi_iter.bi_sector = sector;
5552 /* No reshape active, so we can trust rdev->data_offset */
5553 align_bio->bi_iter.bi_sector += rdev->data_offset;
5556 if (conf->quiesce == 0) {
5557 atomic_inc(&conf->active_aligned_reads);
5560 /* need a memory barrier to detect the race with raid5_quiesce() */
5561 if (!did_inc || smp_load_acquire(&conf->quiesce) != 0) {
5562 /* quiesce is in progress, so we need to undo io activation and wait
5565 if (did_inc && atomic_dec_and_test(&conf->active_aligned_reads))
5566 wake_up(&conf->wait_for_quiescent);
5567 spin_lock_irq(&conf->device_lock);
5568 wait_event_lock_irq(conf->wait_for_quiescent, conf->quiesce == 0,
5570 atomic_inc(&conf->active_aligned_reads);
5571 spin_unlock_irq(&conf->device_lock);
5575 trace_block_bio_remap(align_bio, disk_devt(mddev->gendisk),
5576 raid_bio->bi_iter.bi_sector);
5577 submit_bio_noacct(align_bio);
5585 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5588 sector_t sector = raid_bio->bi_iter.bi_sector;
5589 unsigned chunk_sects = mddev->chunk_sectors;
5590 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5592 if (sectors < bio_sectors(raid_bio)) {
5593 struct r5conf *conf = mddev->private;
5594 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5595 bio_chain(split, raid_bio);
5596 submit_bio_noacct(raid_bio);
5600 if (!raid5_read_one_chunk(mddev, raid_bio))
5606 /* __get_priority_stripe - get the next stripe to process
5608 * Full stripe writes are allowed to pass preread active stripes up until
5609 * the bypass_threshold is exceeded. In general the bypass_count
5610 * increments when the handle_list is handled before the hold_list; however, it
5611 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5612 * stripe with in flight i/o. The bypass_count will be reset when the
5613 * head of the hold_list has changed, i.e. the head was promoted to the
5616 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5617 __must_hold(&conf->device_lock)
5619 struct stripe_head *sh, *tmp;
5620 struct list_head *handle_list = NULL;
5621 struct r5worker_group *wg;
5622 bool second_try = !r5c_is_writeback(conf->log) &&
5623 !r5l_log_disk_error(conf);
5624 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5625 r5l_log_disk_error(conf);
5630 if (conf->worker_cnt_per_group == 0) {
5631 handle_list = try_loprio ? &conf->loprio_list :
5633 } else if (group != ANY_GROUP) {
5634 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5635 &conf->worker_groups[group].handle_list;
5636 wg = &conf->worker_groups[group];
5639 for (i = 0; i < conf->group_cnt; i++) {
5640 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5641 &conf->worker_groups[i].handle_list;
5642 wg = &conf->worker_groups[i];
5643 if (!list_empty(handle_list))
5648 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5650 list_empty(handle_list) ? "empty" : "busy",
5651 list_empty(&conf->hold_list) ? "empty" : "busy",
5652 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5654 if (!list_empty(handle_list)) {
5655 sh = list_entry(handle_list->next, typeof(*sh), lru);
5657 if (list_empty(&conf->hold_list))
5658 conf->bypass_count = 0;
5659 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5660 if (conf->hold_list.next == conf->last_hold)
5661 conf->bypass_count++;
5663 conf->last_hold = conf->hold_list.next;
5664 conf->bypass_count -= conf->bypass_threshold;
5665 if (conf->bypass_count < 0)
5666 conf->bypass_count = 0;
5669 } else if (!list_empty(&conf->hold_list) &&
5670 ((conf->bypass_threshold &&
5671 conf->bypass_count > conf->bypass_threshold) ||
5672 atomic_read(&conf->pending_full_writes) == 0)) {
5674 list_for_each_entry(tmp, &conf->hold_list, lru) {
5675 if (conf->worker_cnt_per_group == 0 ||
5676 group == ANY_GROUP ||
5677 !cpu_online(tmp->cpu) ||
5678 cpu_to_group(tmp->cpu) == group) {
5685 conf->bypass_count -= conf->bypass_threshold;
5686 if (conf->bypass_count < 0)
5687 conf->bypass_count = 0;
5696 try_loprio = !try_loprio;
5704 list_del_init(&sh->lru);
5705 BUG_ON(atomic_inc_return(&sh->count) != 1);
5709 struct raid5_plug_cb {
5710 struct blk_plug_cb cb;
5711 struct list_head list;
5712 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5715 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5717 struct raid5_plug_cb *cb = container_of(
5718 blk_cb, struct raid5_plug_cb, cb);
5719 struct stripe_head *sh;
5720 struct mddev *mddev = cb->cb.data;
5721 struct r5conf *conf = mddev->private;
5725 if (cb->list.next && !list_empty(&cb->list)) {
5726 spin_lock_irq(&conf->device_lock);
5727 while (!list_empty(&cb->list)) {
5728 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5729 list_del_init(&sh->lru);
5731 * avoid race release_stripe_plug() sees
5732 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5733 * is still in our list
5735 smp_mb__before_atomic();
5736 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5738 * STRIPE_ON_RELEASE_LIST could be set here. In that
5739 * case, the count is always > 1 here
5741 hash = sh->hash_lock_index;
5742 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5745 spin_unlock_irq(&conf->device_lock);
5747 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5748 NR_STRIPE_HASH_LOCKS);
5750 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5754 static void release_stripe_plug(struct mddev *mddev,
5755 struct stripe_head *sh)
5757 struct blk_plug_cb *blk_cb = blk_check_plugged(
5758 raid5_unplug, mddev,
5759 sizeof(struct raid5_plug_cb));
5760 struct raid5_plug_cb *cb;
5763 raid5_release_stripe(sh);
5767 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5769 if (cb->list.next == NULL) {
5771 INIT_LIST_HEAD(&cb->list);
5772 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5773 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5776 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5777 list_add_tail(&sh->lru, &cb->list);
5779 raid5_release_stripe(sh);
5782 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5784 struct r5conf *conf = mddev->private;
5785 sector_t logical_sector, last_sector;
5786 struct stripe_head *sh;
5789 /* We need to handle this when io_uring supports discard/trim */
5790 if (WARN_ON_ONCE(bi->bi_opf & REQ_NOWAIT))
5793 if (mddev->reshape_position != MaxSector)
5794 /* Skip discard while reshape is happening */
5797 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5798 last_sector = bio_end_sector(bi);
5802 stripe_sectors = conf->chunk_sectors *
5803 (conf->raid_disks - conf->max_degraded);
5804 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5806 sector_div(last_sector, stripe_sectors);
5808 logical_sector *= conf->chunk_sectors;
5809 last_sector *= conf->chunk_sectors;
5811 for (; logical_sector < last_sector;
5812 logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5816 sh = raid5_get_active_stripe(conf, NULL, logical_sector, 0);
5817 prepare_to_wait(&conf->wait_for_overlap, &w,
5818 TASK_UNINTERRUPTIBLE);
5819 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5820 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5821 raid5_release_stripe(sh);
5825 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5826 spin_lock_irq(&sh->stripe_lock);
5827 for (d = 0; d < conf->raid_disks; d++) {
5828 if (d == sh->pd_idx || d == sh->qd_idx)
5830 if (sh->dev[d].towrite || sh->dev[d].toread) {
5831 set_bit(R5_Overlap, &sh->dev[d].flags);
5832 spin_unlock_irq(&sh->stripe_lock);
5833 raid5_release_stripe(sh);
5838 set_bit(STRIPE_DISCARD, &sh->state);
5839 finish_wait(&conf->wait_for_overlap, &w);
5840 sh->overwrite_disks = 0;
5841 for (d = 0; d < conf->raid_disks; d++) {
5842 if (d == sh->pd_idx || d == sh->qd_idx)
5844 sh->dev[d].towrite = bi;
5845 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5846 bio_inc_remaining(bi);
5847 md_write_inc(mddev, bi);
5848 sh->overwrite_disks++;
5850 spin_unlock_irq(&sh->stripe_lock);
5851 if (conf->mddev->bitmap) {
5853 d < conf->raid_disks - conf->max_degraded;
5855 md_bitmap_startwrite(mddev->bitmap,
5857 RAID5_STRIPE_SECTORS(conf),
5859 sh->bm_seq = conf->seq_flush + 1;
5860 set_bit(STRIPE_BIT_DELAY, &sh->state);
5863 set_bit(STRIPE_HANDLE, &sh->state);
5864 clear_bit(STRIPE_DELAYED, &sh->state);
5865 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5866 atomic_inc(&conf->preread_active_stripes);
5867 release_stripe_plug(mddev, sh);
5873 static bool ahead_of_reshape(struct mddev *mddev, sector_t sector,
5874 sector_t reshape_sector)
5876 return mddev->reshape_backwards ? sector < reshape_sector :
5877 sector >= reshape_sector;
5880 static bool range_ahead_of_reshape(struct mddev *mddev, sector_t min,
5881 sector_t max, sector_t reshape_sector)
5883 return mddev->reshape_backwards ? max < reshape_sector :
5884 min >= reshape_sector;
5887 static bool stripe_ahead_of_reshape(struct mddev *mddev, struct r5conf *conf,
5888 struct stripe_head *sh)
5890 sector_t max_sector = 0, min_sector = MaxSector;
5894 for (dd_idx = 0; dd_idx < sh->disks; dd_idx++) {
5895 if (dd_idx == sh->pd_idx)
5898 min_sector = min(min_sector, sh->dev[dd_idx].sector);
5899 max_sector = min(max_sector, sh->dev[dd_idx].sector);
5902 spin_lock_irq(&conf->device_lock);
5904 if (!range_ahead_of_reshape(mddev, min_sector, max_sector,
5905 conf->reshape_progress))
5906 /* mismatch, need to try again */
5909 spin_unlock_irq(&conf->device_lock);
5914 static int add_all_stripe_bios(struct r5conf *conf,
5915 struct stripe_request_ctx *ctx, struct stripe_head *sh,
5916 struct bio *bi, int forwrite, int previous)
5921 spin_lock_irq(&sh->stripe_lock);
5923 for (dd_idx = 0; dd_idx < sh->disks; dd_idx++) {
5924 struct r5dev *dev = &sh->dev[dd_idx];
5926 if (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
5929 if (dev->sector < ctx->first_sector ||
5930 dev->sector >= ctx->last_sector)
5933 if (stripe_bio_overlaps(sh, bi, dd_idx, forwrite)) {
5934 set_bit(R5_Overlap, &dev->flags);
5943 for (dd_idx = 0; dd_idx < sh->disks; dd_idx++) {
5944 struct r5dev *dev = &sh->dev[dd_idx];
5946 if (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
5949 if (dev->sector < ctx->first_sector ||
5950 dev->sector >= ctx->last_sector)
5953 __add_stripe_bio(sh, bi, dd_idx, forwrite, previous);
5954 clear_bit((dev->sector - ctx->first_sector) >>
5955 RAID5_STRIPE_SHIFT(conf), ctx->sectors_to_do);
5959 spin_unlock_irq(&sh->stripe_lock);
5963 static bool reshape_inprogress(struct mddev *mddev)
5965 return test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
5966 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
5967 !test_bit(MD_RECOVERY_DONE, &mddev->recovery) &&
5968 !test_bit(MD_RECOVERY_INTR, &mddev->recovery);
5971 static bool reshape_disabled(struct mddev *mddev)
5973 return is_md_suspended(mddev) || !md_is_rdwr(mddev);
5976 static enum stripe_result make_stripe_request(struct mddev *mddev,
5977 struct r5conf *conf, struct stripe_request_ctx *ctx,
5978 sector_t logical_sector, struct bio *bi)
5980 const int rw = bio_data_dir(bi);
5981 enum stripe_result ret;
5982 struct stripe_head *sh;
5983 sector_t new_sector;
5984 int previous = 0, flags = 0;
5987 seq = read_seqcount_begin(&conf->gen_lock);
5989 if (unlikely(conf->reshape_progress != MaxSector)) {
5991 * Spinlock is needed as reshape_progress may be
5992 * 64bit on a 32bit platform, and so it might be
5993 * possible to see a half-updated value
5994 * Of course reshape_progress could change after
5995 * the lock is dropped, so once we get a reference
5996 * to the stripe that we think it is, we will have
5999 spin_lock_irq(&conf->device_lock);
6000 if (ahead_of_reshape(mddev, logical_sector,
6001 conf->reshape_progress)) {
6004 if (ahead_of_reshape(mddev, logical_sector,
6005 conf->reshape_safe)) {
6006 spin_unlock_irq(&conf->device_lock);
6007 ret = STRIPE_SCHEDULE_AND_RETRY;
6011 spin_unlock_irq(&conf->device_lock);
6014 new_sector = raid5_compute_sector(conf, logical_sector, previous,
6016 pr_debug("raid456: %s, sector %llu logical %llu\n", __func__,
6017 new_sector, logical_sector);
6020 flags |= R5_GAS_PREVIOUS;
6021 if (bi->bi_opf & REQ_RAHEAD)
6022 flags |= R5_GAS_NOBLOCK;
6023 sh = raid5_get_active_stripe(conf, ctx, new_sector, flags);
6024 if (unlikely(!sh)) {
6025 /* cannot get stripe, just give-up */
6026 bi->bi_status = BLK_STS_IOERR;
6030 if (unlikely(previous) &&
6031 stripe_ahead_of_reshape(mddev, conf, sh)) {
6033 * Expansion moved on while waiting for a stripe.
6034 * Expansion could still move past after this
6035 * test, but as we are holding a reference to
6036 * 'sh', we know that if that happens,
6037 * STRIPE_EXPANDING will get set and the expansion
6038 * won't proceed until we finish with the stripe.
6040 ret = STRIPE_SCHEDULE_AND_RETRY;
6044 if (read_seqcount_retry(&conf->gen_lock, seq)) {
6045 /* Might have got the wrong stripe_head by accident */
6050 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
6051 !add_all_stripe_bios(conf, ctx, sh, bi, rw, previous)) {
6053 * Stripe is busy expanding or add failed due to
6054 * overlap. Flush everything and wait a while.
6056 md_wakeup_thread(mddev->thread);
6057 ret = STRIPE_SCHEDULE_AND_RETRY;
6061 if (stripe_can_batch(sh)) {
6062 stripe_add_to_batch_list(conf, sh, ctx->batch_last);
6063 if (ctx->batch_last)
6064 raid5_release_stripe(ctx->batch_last);
6065 atomic_inc(&sh->count);
6066 ctx->batch_last = sh;
6069 if (ctx->do_flush) {
6070 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
6071 /* we only need flush for one stripe */
6072 ctx->do_flush = false;
6075 set_bit(STRIPE_HANDLE, &sh->state);
6076 clear_bit(STRIPE_DELAYED, &sh->state);
6077 if ((!sh->batch_head || sh == sh->batch_head) &&
6078 (bi->bi_opf & REQ_SYNC) &&
6079 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
6080 atomic_inc(&conf->preread_active_stripes);
6082 release_stripe_plug(mddev, sh);
6083 return STRIPE_SUCCESS;
6086 raid5_release_stripe(sh);
6088 if (ret == STRIPE_SCHEDULE_AND_RETRY && !reshape_inprogress(mddev) &&
6089 reshape_disabled(mddev)) {
6090 bi->bi_status = BLK_STS_IOERR;
6092 pr_err("md/raid456:%s: io failed across reshape position while reshape can't make progress.\n",
6100 * If the bio covers multiple data disks, find sector within the bio that has
6101 * the lowest chunk offset in the first chunk.
6103 static sector_t raid5_bio_lowest_chunk_sector(struct r5conf *conf,
6106 int sectors_per_chunk = conf->chunk_sectors;
6107 int raid_disks = conf->raid_disks;
6109 struct stripe_head sh;
6110 unsigned int chunk_offset;
6111 sector_t r_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6114 /* We pass in fake stripe_head to get back parity disk numbers */
6115 sector = raid5_compute_sector(conf, r_sector, 0, &dd_idx, &sh);
6116 chunk_offset = sector_div(sector, sectors_per_chunk);
6117 if (sectors_per_chunk - chunk_offset >= bio_sectors(bi))
6120 * Bio crosses to the next data disk. Check whether it's in the same
6124 while (dd_idx == sh.pd_idx || dd_idx == sh.qd_idx)
6126 if (dd_idx >= raid_disks)
6128 return r_sector + sectors_per_chunk - chunk_offset;
6131 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
6133 DEFINE_WAIT_FUNC(wait, woken_wake_function);
6134 struct r5conf *conf = mddev->private;
6135 sector_t logical_sector;
6136 struct stripe_request_ctx ctx = {};
6137 const int rw = bio_data_dir(bi);
6138 enum stripe_result res;
6141 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
6142 int ret = log_handle_flush_request(conf, bi);
6146 if (ret == -ENODEV) {
6147 if (md_flush_request(mddev, bi))
6150 /* ret == -EAGAIN, fallback */
6152 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
6153 * we need to flush journal device
6155 ctx.do_flush = bi->bi_opf & REQ_PREFLUSH;
6158 if (!md_write_start(mddev, bi))
6161 * If array is degraded, better not do chunk aligned read because
6162 * later we might have to read it again in order to reconstruct
6163 * data on failed drives.
6165 if (rw == READ && mddev->degraded == 0 &&
6166 mddev->reshape_position == MaxSector) {
6167 bi = chunk_aligned_read(mddev, bi);
6172 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
6173 make_discard_request(mddev, bi);
6174 md_write_end(mddev);
6178 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6179 ctx.first_sector = logical_sector;
6180 ctx.last_sector = bio_end_sector(bi);
6183 stripe_cnt = DIV_ROUND_UP_SECTOR_T(ctx.last_sector - logical_sector,
6184 RAID5_STRIPE_SECTORS(conf));
6185 bitmap_set(ctx.sectors_to_do, 0, stripe_cnt);
6187 pr_debug("raid456: %s, logical %llu to %llu\n", __func__,
6188 bi->bi_iter.bi_sector, ctx.last_sector);
6190 /* Bail out if conflicts with reshape and REQ_NOWAIT is set */
6191 if ((bi->bi_opf & REQ_NOWAIT) &&
6192 (conf->reshape_progress != MaxSector) &&
6193 !ahead_of_reshape(mddev, logical_sector, conf->reshape_progress) &&
6194 ahead_of_reshape(mddev, logical_sector, conf->reshape_safe)) {
6195 bio_wouldblock_error(bi);
6197 md_write_end(mddev);
6200 md_account_bio(mddev, &bi);
6203 * Lets start with the stripe with the lowest chunk offset in the first
6204 * chunk. That has the best chances of creating IOs adjacent to
6205 * previous IOs in case of sequential IO and thus creates the most
6206 * sequential IO pattern. We don't bother with the optimization when
6207 * reshaping as the performance benefit is not worth the complexity.
6209 if (likely(conf->reshape_progress == MaxSector))
6210 logical_sector = raid5_bio_lowest_chunk_sector(conf, bi);
6211 s = (logical_sector - ctx.first_sector) >> RAID5_STRIPE_SHIFT(conf);
6213 add_wait_queue(&conf->wait_for_overlap, &wait);
6215 res = make_stripe_request(mddev, conf, &ctx, logical_sector,
6217 if (res == STRIPE_FAIL)
6220 if (res == STRIPE_RETRY)
6223 if (res == STRIPE_SCHEDULE_AND_RETRY) {
6225 * Must release the reference to batch_last before
6226 * scheduling and waiting for work to be done,
6227 * otherwise the batch_last stripe head could prevent
6228 * raid5_activate_delayed() from making progress
6229 * and thus deadlocking.
6231 if (ctx.batch_last) {
6232 raid5_release_stripe(ctx.batch_last);
6233 ctx.batch_last = NULL;
6236 wait_woken(&wait, TASK_UNINTERRUPTIBLE,
6237 MAX_SCHEDULE_TIMEOUT);
6241 s = find_next_bit_wrap(ctx.sectors_to_do, stripe_cnt, s);
6242 if (s == stripe_cnt)
6245 logical_sector = ctx.first_sector +
6246 (s << RAID5_STRIPE_SHIFT(conf));
6248 remove_wait_queue(&conf->wait_for_overlap, &wait);
6251 raid5_release_stripe(ctx.batch_last);
6254 md_write_end(mddev);
6259 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
6261 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
6263 /* reshaping is quite different to recovery/resync so it is
6264 * handled quite separately ... here.
6266 * On each call to sync_request, we gather one chunk worth of
6267 * destination stripes and flag them as expanding.
6268 * Then we find all the source stripes and request reads.
6269 * As the reads complete, handle_stripe will copy the data
6270 * into the destination stripe and release that stripe.
6272 struct r5conf *conf = mddev->private;
6273 struct stripe_head *sh;
6274 struct md_rdev *rdev;
6275 sector_t first_sector, last_sector;
6276 int raid_disks = conf->previous_raid_disks;
6277 int data_disks = raid_disks - conf->max_degraded;
6278 int new_data_disks = conf->raid_disks - conf->max_degraded;
6281 sector_t writepos, readpos, safepos;
6282 sector_t stripe_addr;
6283 int reshape_sectors;
6284 struct list_head stripes;
6287 if (sector_nr == 0) {
6288 /* If restarting in the middle, skip the initial sectors */
6289 if (mddev->reshape_backwards &&
6290 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
6291 sector_nr = raid5_size(mddev, 0, 0)
6292 - conf->reshape_progress;
6293 } else if (mddev->reshape_backwards &&
6294 conf->reshape_progress == MaxSector) {
6295 /* shouldn't happen, but just in case, finish up.*/
6296 sector_nr = MaxSector;
6297 } else if (!mddev->reshape_backwards &&
6298 conf->reshape_progress > 0)
6299 sector_nr = conf->reshape_progress;
6300 sector_div(sector_nr, new_data_disks);
6302 mddev->curr_resync_completed = sector_nr;
6303 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6310 /* We need to process a full chunk at a time.
6311 * If old and new chunk sizes differ, we need to process the
6315 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
6317 /* We update the metadata at least every 10 seconds, or when
6318 * the data about to be copied would over-write the source of
6319 * the data at the front of the range. i.e. one new_stripe
6320 * along from reshape_progress new_maps to after where
6321 * reshape_safe old_maps to
6323 writepos = conf->reshape_progress;
6324 sector_div(writepos, new_data_disks);
6325 readpos = conf->reshape_progress;
6326 sector_div(readpos, data_disks);
6327 safepos = conf->reshape_safe;
6328 sector_div(safepos, data_disks);
6329 if (mddev->reshape_backwards) {
6330 BUG_ON(writepos < reshape_sectors);
6331 writepos -= reshape_sectors;
6332 readpos += reshape_sectors;
6333 safepos += reshape_sectors;
6335 writepos += reshape_sectors;
6336 /* readpos and safepos are worst-case calculations.
6337 * A negative number is overly pessimistic, and causes
6338 * obvious problems for unsigned storage. So clip to 0.
6340 readpos -= min_t(sector_t, reshape_sectors, readpos);
6341 safepos -= min_t(sector_t, reshape_sectors, safepos);
6344 /* Having calculated the 'writepos' possibly use it
6345 * to set 'stripe_addr' which is where we will write to.
6347 if (mddev->reshape_backwards) {
6348 BUG_ON(conf->reshape_progress == 0);
6349 stripe_addr = writepos;
6350 BUG_ON((mddev->dev_sectors &
6351 ~((sector_t)reshape_sectors - 1))
6352 - reshape_sectors - stripe_addr
6355 BUG_ON(writepos != sector_nr + reshape_sectors);
6356 stripe_addr = sector_nr;
6359 /* 'writepos' is the most advanced device address we might write.
6360 * 'readpos' is the least advanced device address we might read.
6361 * 'safepos' is the least address recorded in the metadata as having
6363 * If there is a min_offset_diff, these are adjusted either by
6364 * increasing the safepos/readpos if diff is negative, or
6365 * increasing writepos if diff is positive.
6366 * If 'readpos' is then behind 'writepos', there is no way that we can
6367 * ensure safety in the face of a crash - that must be done by userspace
6368 * making a backup of the data. So in that case there is no particular
6369 * rush to update metadata.
6370 * Otherwise if 'safepos' is behind 'writepos', then we really need to
6371 * update the metadata to advance 'safepos' to match 'readpos' so that
6372 * we can be safe in the event of a crash.
6373 * So we insist on updating metadata if safepos is behind writepos and
6374 * readpos is beyond writepos.
6375 * In any case, update the metadata every 10 seconds.
6376 * Maybe that number should be configurable, but I'm not sure it is
6377 * worth it.... maybe it could be a multiple of safemode_delay???
6379 if (conf->min_offset_diff < 0) {
6380 safepos += -conf->min_offset_diff;
6381 readpos += -conf->min_offset_diff;
6383 writepos += conf->min_offset_diff;
6385 if ((mddev->reshape_backwards
6386 ? (safepos > writepos && readpos < writepos)
6387 : (safepos < writepos && readpos > writepos)) ||
6388 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6389 /* Cannot proceed until we've updated the superblock... */
6390 wait_event(conf->wait_for_overlap,
6391 atomic_read(&conf->reshape_stripes)==0
6392 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6393 if (atomic_read(&conf->reshape_stripes) != 0)
6395 mddev->reshape_position = conf->reshape_progress;
6396 mddev->curr_resync_completed = sector_nr;
6397 if (!mddev->reshape_backwards)
6398 /* Can update recovery_offset */
6399 rdev_for_each(rdev, mddev)
6400 if (rdev->raid_disk >= 0 &&
6401 !test_bit(Journal, &rdev->flags) &&
6402 !test_bit(In_sync, &rdev->flags) &&
6403 rdev->recovery_offset < sector_nr)
6404 rdev->recovery_offset = sector_nr;
6406 conf->reshape_checkpoint = jiffies;
6407 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6408 md_wakeup_thread(mddev->thread);
6409 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6410 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6411 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6413 spin_lock_irq(&conf->device_lock);
6414 conf->reshape_safe = mddev->reshape_position;
6415 spin_unlock_irq(&conf->device_lock);
6416 wake_up(&conf->wait_for_overlap);
6417 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6420 INIT_LIST_HEAD(&stripes);
6421 for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6423 int skipped_disk = 0;
6424 sh = raid5_get_active_stripe(conf, NULL, stripe_addr+i,
6426 set_bit(STRIPE_EXPANDING, &sh->state);
6427 atomic_inc(&conf->reshape_stripes);
6428 /* If any of this stripe is beyond the end of the old
6429 * array, then we need to zero those blocks
6431 for (j=sh->disks; j--;) {
6433 if (j == sh->pd_idx)
6435 if (conf->level == 6 &&
6438 s = raid5_compute_blocknr(sh, j, 0);
6439 if (s < raid5_size(mddev, 0, 0)) {
6443 memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6444 set_bit(R5_Expanded, &sh->dev[j].flags);
6445 set_bit(R5_UPTODATE, &sh->dev[j].flags);
6447 if (!skipped_disk) {
6448 set_bit(STRIPE_EXPAND_READY, &sh->state);
6449 set_bit(STRIPE_HANDLE, &sh->state);
6451 list_add(&sh->lru, &stripes);
6453 spin_lock_irq(&conf->device_lock);
6454 if (mddev->reshape_backwards)
6455 conf->reshape_progress -= reshape_sectors * new_data_disks;
6457 conf->reshape_progress += reshape_sectors * new_data_disks;
6458 spin_unlock_irq(&conf->device_lock);
6459 /* Ok, those stripe are ready. We can start scheduling
6460 * reads on the source stripes.
6461 * The source stripes are determined by mapping the first and last
6462 * block on the destination stripes.
6465 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6468 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6469 * new_data_disks - 1),
6471 if (last_sector >= mddev->dev_sectors)
6472 last_sector = mddev->dev_sectors - 1;
6473 while (first_sector <= last_sector) {
6474 sh = raid5_get_active_stripe(conf, NULL, first_sector,
6475 R5_GAS_PREVIOUS | R5_GAS_NOQUIESCE);
6476 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6477 set_bit(STRIPE_HANDLE, &sh->state);
6478 raid5_release_stripe(sh);
6479 first_sector += RAID5_STRIPE_SECTORS(conf);
6481 /* Now that the sources are clearly marked, we can release
6482 * the destination stripes
6484 while (!list_empty(&stripes)) {
6485 sh = list_entry(stripes.next, struct stripe_head, lru);
6486 list_del_init(&sh->lru);
6487 raid5_release_stripe(sh);
6489 /* If this takes us to the resync_max point where we have to pause,
6490 * then we need to write out the superblock.
6492 sector_nr += reshape_sectors;
6493 retn = reshape_sectors;
6495 if (mddev->curr_resync_completed > mddev->resync_max ||
6496 (sector_nr - mddev->curr_resync_completed) * 2
6497 >= mddev->resync_max - mddev->curr_resync_completed) {
6498 /* Cannot proceed until we've updated the superblock... */
6499 wait_event(conf->wait_for_overlap,
6500 atomic_read(&conf->reshape_stripes) == 0
6501 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6502 if (atomic_read(&conf->reshape_stripes) != 0)
6504 mddev->reshape_position = conf->reshape_progress;
6505 mddev->curr_resync_completed = sector_nr;
6506 if (!mddev->reshape_backwards)
6507 /* Can update recovery_offset */
6508 rdev_for_each(rdev, mddev)
6509 if (rdev->raid_disk >= 0 &&
6510 !test_bit(Journal, &rdev->flags) &&
6511 !test_bit(In_sync, &rdev->flags) &&
6512 rdev->recovery_offset < sector_nr)
6513 rdev->recovery_offset = sector_nr;
6514 conf->reshape_checkpoint = jiffies;
6515 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6516 md_wakeup_thread(mddev->thread);
6517 wait_event(mddev->sb_wait,
6518 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6519 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6520 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6522 spin_lock_irq(&conf->device_lock);
6523 conf->reshape_safe = mddev->reshape_position;
6524 spin_unlock_irq(&conf->device_lock);
6525 wake_up(&conf->wait_for_overlap);
6526 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6532 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6535 struct r5conf *conf = mddev->private;
6536 struct stripe_head *sh;
6537 sector_t max_sector = mddev->dev_sectors;
6538 sector_t sync_blocks;
6539 int still_degraded = 0;
6542 if (sector_nr >= max_sector) {
6543 /* just being told to finish up .. nothing much to do */
6545 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6550 if (mddev->curr_resync < max_sector) /* aborted */
6551 md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6553 else /* completed sync */
6555 md_bitmap_close_sync(mddev->bitmap);
6560 /* Allow raid5_quiesce to complete */
6561 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6563 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6564 return reshape_request(mddev, sector_nr, skipped);
6566 /* No need to check resync_max as we never do more than one
6567 * stripe, and as resync_max will always be on a chunk boundary,
6568 * if the check in md_do_sync didn't fire, there is no chance
6569 * of overstepping resync_max here
6572 /* if there is too many failed drives and we are trying
6573 * to resync, then assert that we are finished, because there is
6574 * nothing we can do.
6576 if (mddev->degraded >= conf->max_degraded &&
6577 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6578 sector_t rv = mddev->dev_sectors - sector_nr;
6582 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6584 !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6585 sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6586 /* we can skip this block, and probably more */
6587 do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6589 /* keep things rounded to whole stripes */
6590 return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6593 md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6595 sh = raid5_get_active_stripe(conf, NULL, sector_nr,
6598 sh = raid5_get_active_stripe(conf, NULL, sector_nr, 0);
6599 /* make sure we don't swamp the stripe cache if someone else
6600 * is trying to get access
6602 schedule_timeout_uninterruptible(1);
6604 /* Need to check if array will still be degraded after recovery/resync
6605 * Note in case of > 1 drive failures it's possible we're rebuilding
6606 * one drive while leaving another faulty drive in array.
6609 for (i = 0; i < conf->raid_disks; i++) {
6610 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
6612 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6617 md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6619 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6620 set_bit(STRIPE_HANDLE, &sh->state);
6622 raid5_release_stripe(sh);
6624 return RAID5_STRIPE_SECTORS(conf);
6627 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6628 unsigned int offset)
6630 /* We may not be able to submit a whole bio at once as there
6631 * may not be enough stripe_heads available.
6632 * We cannot pre-allocate enough stripe_heads as we may need
6633 * more than exist in the cache (if we allow ever large chunks).
6634 * So we do one stripe head at a time and record in
6635 * ->bi_hw_segments how many have been done.
6637 * We *know* that this entire raid_bio is in one chunk, so
6638 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6640 struct stripe_head *sh;
6642 sector_t sector, logical_sector, last_sector;
6646 logical_sector = raid_bio->bi_iter.bi_sector &
6647 ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6648 sector = raid5_compute_sector(conf, logical_sector,
6650 last_sector = bio_end_sector(raid_bio);
6652 for (; logical_sector < last_sector;
6653 logical_sector += RAID5_STRIPE_SECTORS(conf),
6654 sector += RAID5_STRIPE_SECTORS(conf),
6658 /* already done this stripe */
6661 sh = raid5_get_active_stripe(conf, NULL, sector,
6662 R5_GAS_NOBLOCK | R5_GAS_NOQUIESCE);
6664 /* failed to get a stripe - must wait */
6665 conf->retry_read_aligned = raid_bio;
6666 conf->retry_read_offset = scnt;
6670 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6671 raid5_release_stripe(sh);
6672 conf->retry_read_aligned = raid_bio;
6673 conf->retry_read_offset = scnt;
6677 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6679 raid5_release_stripe(sh);
6683 bio_endio(raid_bio);
6685 if (atomic_dec_and_test(&conf->active_aligned_reads))
6686 wake_up(&conf->wait_for_quiescent);
6690 static int handle_active_stripes(struct r5conf *conf, int group,
6691 struct r5worker *worker,
6692 struct list_head *temp_inactive_list)
6693 __must_hold(&conf->device_lock)
6695 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6696 int i, batch_size = 0, hash;
6697 bool release_inactive = false;
6699 while (batch_size < MAX_STRIPE_BATCH &&
6700 (sh = __get_priority_stripe(conf, group)) != NULL)
6701 batch[batch_size++] = sh;
6703 if (batch_size == 0) {
6704 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6705 if (!list_empty(temp_inactive_list + i))
6707 if (i == NR_STRIPE_HASH_LOCKS) {
6708 spin_unlock_irq(&conf->device_lock);
6709 log_flush_stripe_to_raid(conf);
6710 spin_lock_irq(&conf->device_lock);
6713 release_inactive = true;
6715 spin_unlock_irq(&conf->device_lock);
6717 release_inactive_stripe_list(conf, temp_inactive_list,
6718 NR_STRIPE_HASH_LOCKS);
6720 r5l_flush_stripe_to_raid(conf->log);
6721 if (release_inactive) {
6722 spin_lock_irq(&conf->device_lock);
6726 for (i = 0; i < batch_size; i++)
6727 handle_stripe(batch[i]);
6728 log_write_stripe_run(conf);
6732 spin_lock_irq(&conf->device_lock);
6733 for (i = 0; i < batch_size; i++) {
6734 hash = batch[i]->hash_lock_index;
6735 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6740 static void raid5_do_work(struct work_struct *work)
6742 struct r5worker *worker = container_of(work, struct r5worker, work);
6743 struct r5worker_group *group = worker->group;
6744 struct r5conf *conf = group->conf;
6745 struct mddev *mddev = conf->mddev;
6746 int group_id = group - conf->worker_groups;
6748 struct blk_plug plug;
6750 pr_debug("+++ raid5worker active\n");
6752 blk_start_plug(&plug);
6754 spin_lock_irq(&conf->device_lock);
6756 int batch_size, released;
6758 released = release_stripe_list(conf, worker->temp_inactive_list);
6760 batch_size = handle_active_stripes(conf, group_id, worker,
6761 worker->temp_inactive_list);
6762 worker->working = false;
6763 if (!batch_size && !released)
6765 handled += batch_size;
6766 wait_event_lock_irq(mddev->sb_wait,
6767 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6770 pr_debug("%d stripes handled\n", handled);
6772 spin_unlock_irq(&conf->device_lock);
6774 flush_deferred_bios(conf);
6776 r5l_flush_stripe_to_raid(conf->log);
6778 async_tx_issue_pending_all();
6779 blk_finish_plug(&plug);
6781 pr_debug("--- raid5worker inactive\n");
6785 * This is our raid5 kernel thread.
6787 * We scan the hash table for stripes which can be handled now.
6788 * During the scan, completed stripes are saved for us by the interrupt
6789 * handler, so that they will not have to wait for our next wakeup.
6791 static void raid5d(struct md_thread *thread)
6793 struct mddev *mddev = thread->mddev;
6794 struct r5conf *conf = mddev->private;
6796 struct blk_plug plug;
6798 pr_debug("+++ raid5d active\n");
6800 md_check_recovery(mddev);
6802 blk_start_plug(&plug);
6804 spin_lock_irq(&conf->device_lock);
6807 int batch_size, released;
6808 unsigned int offset;
6810 released = release_stripe_list(conf, conf->temp_inactive_list);
6812 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6815 !list_empty(&conf->bitmap_list)) {
6816 /* Now is a good time to flush some bitmap updates */
6818 spin_unlock_irq(&conf->device_lock);
6819 md_bitmap_unplug(mddev->bitmap);
6820 spin_lock_irq(&conf->device_lock);
6821 conf->seq_write = conf->seq_flush;
6822 activate_bit_delay(conf, conf->temp_inactive_list);
6824 raid5_activate_delayed(conf);
6826 while ((bio = remove_bio_from_retry(conf, &offset))) {
6828 spin_unlock_irq(&conf->device_lock);
6829 ok = retry_aligned_read(conf, bio, offset);
6830 spin_lock_irq(&conf->device_lock);
6836 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6837 conf->temp_inactive_list);
6838 if (!batch_size && !released)
6840 handled += batch_size;
6842 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6843 spin_unlock_irq(&conf->device_lock);
6844 md_check_recovery(mddev);
6845 spin_lock_irq(&conf->device_lock);
6848 * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6849 * seeing md_check_recovery() is needed to clear
6850 * the flag when using mdmon.
6855 wait_event_lock_irq(mddev->sb_wait,
6856 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6859 pr_debug("%d stripes handled\n", handled);
6861 spin_unlock_irq(&conf->device_lock);
6862 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6863 mutex_trylock(&conf->cache_size_mutex)) {
6864 grow_one_stripe(conf, __GFP_NOWARN);
6865 /* Set flag even if allocation failed. This helps
6866 * slow down allocation requests when mem is short
6868 set_bit(R5_DID_ALLOC, &conf->cache_state);
6869 mutex_unlock(&conf->cache_size_mutex);
6872 flush_deferred_bios(conf);
6874 r5l_flush_stripe_to_raid(conf->log);
6876 async_tx_issue_pending_all();
6877 blk_finish_plug(&plug);
6879 pr_debug("--- raid5d inactive\n");
6883 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6885 struct r5conf *conf;
6887 spin_lock(&mddev->lock);
6888 conf = mddev->private;
6890 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6891 spin_unlock(&mddev->lock);
6896 raid5_set_cache_size(struct mddev *mddev, int size)
6899 struct r5conf *conf = mddev->private;
6901 if (size <= 16 || size > 32768)
6904 conf->min_nr_stripes = size;
6905 mutex_lock(&conf->cache_size_mutex);
6906 while (size < conf->max_nr_stripes &&
6907 drop_one_stripe(conf))
6909 mutex_unlock(&conf->cache_size_mutex);
6911 md_allow_write(mddev);
6913 mutex_lock(&conf->cache_size_mutex);
6914 while (size > conf->max_nr_stripes)
6915 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6916 conf->min_nr_stripes = conf->max_nr_stripes;
6920 mutex_unlock(&conf->cache_size_mutex);
6924 EXPORT_SYMBOL(raid5_set_cache_size);
6927 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6929 struct r5conf *conf;
6933 if (len >= PAGE_SIZE)
6935 if (kstrtoul(page, 10, &new))
6937 err = mddev_lock(mddev);
6940 conf = mddev->private;
6944 err = raid5_set_cache_size(mddev, new);
6945 mddev_unlock(mddev);
6950 static struct md_sysfs_entry
6951 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6952 raid5_show_stripe_cache_size,
6953 raid5_store_stripe_cache_size);
6956 raid5_show_rmw_level(struct mddev *mddev, char *page)
6958 struct r5conf *conf = mddev->private;
6960 return sprintf(page, "%d\n", conf->rmw_level);
6966 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6968 struct r5conf *conf = mddev->private;
6974 if (len >= PAGE_SIZE)
6977 if (kstrtoul(page, 10, &new))
6980 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6983 if (new != PARITY_DISABLE_RMW &&
6984 new != PARITY_ENABLE_RMW &&
6985 new != PARITY_PREFER_RMW)
6988 conf->rmw_level = new;
6992 static struct md_sysfs_entry
6993 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6994 raid5_show_rmw_level,
6995 raid5_store_rmw_level);
6998 raid5_show_stripe_size(struct mddev *mddev, char *page)
7000 struct r5conf *conf;
7003 spin_lock(&mddev->lock);
7004 conf = mddev->private;
7006 ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
7007 spin_unlock(&mddev->lock);
7011 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7013 raid5_store_stripe_size(struct mddev *mddev, const char *page, size_t len)
7015 struct r5conf *conf;
7020 if (len >= PAGE_SIZE)
7022 if (kstrtoul(page, 10, &new))
7026 * The value should not be bigger than PAGE_SIZE. It requires to
7027 * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
7030 if (new % DEFAULT_STRIPE_SIZE != 0 ||
7031 new > PAGE_SIZE || new == 0 ||
7032 new != roundup_pow_of_two(new))
7035 err = mddev_lock(mddev);
7039 conf = mddev->private;
7045 if (new == conf->stripe_size)
7048 pr_debug("md/raid: change stripe_size from %lu to %lu\n",
7049 conf->stripe_size, new);
7051 if (mddev->sync_thread ||
7052 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
7053 mddev->reshape_position != MaxSector ||
7054 mddev->sysfs_active) {
7059 mddev_suspend(mddev);
7060 mutex_lock(&conf->cache_size_mutex);
7061 size = conf->max_nr_stripes;
7063 shrink_stripes(conf);
7065 conf->stripe_size = new;
7066 conf->stripe_shift = ilog2(new) - 9;
7067 conf->stripe_sectors = new >> 9;
7068 if (grow_stripes(conf, size)) {
7069 pr_warn("md/raid:%s: couldn't allocate buffers\n",
7073 mutex_unlock(&conf->cache_size_mutex);
7074 mddev_resume(mddev);
7077 mddev_unlock(mddev);
7081 static struct md_sysfs_entry
7082 raid5_stripe_size = __ATTR(stripe_size, 0644,
7083 raid5_show_stripe_size,
7084 raid5_store_stripe_size);
7086 static struct md_sysfs_entry
7087 raid5_stripe_size = __ATTR(stripe_size, 0444,
7088 raid5_show_stripe_size,
7093 raid5_show_preread_threshold(struct mddev *mddev, char *page)
7095 struct r5conf *conf;
7097 spin_lock(&mddev->lock);
7098 conf = mddev->private;
7100 ret = sprintf(page, "%d\n", conf->bypass_threshold);
7101 spin_unlock(&mddev->lock);
7106 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
7108 struct r5conf *conf;
7112 if (len >= PAGE_SIZE)
7114 if (kstrtoul(page, 10, &new))
7117 err = mddev_lock(mddev);
7120 conf = mddev->private;
7123 else if (new > conf->min_nr_stripes)
7126 conf->bypass_threshold = new;
7127 mddev_unlock(mddev);
7131 static struct md_sysfs_entry
7132 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
7134 raid5_show_preread_threshold,
7135 raid5_store_preread_threshold);
7138 raid5_show_skip_copy(struct mddev *mddev, char *page)
7140 struct r5conf *conf;
7142 spin_lock(&mddev->lock);
7143 conf = mddev->private;
7145 ret = sprintf(page, "%d\n", conf->skip_copy);
7146 spin_unlock(&mddev->lock);
7151 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
7153 struct r5conf *conf;
7157 if (len >= PAGE_SIZE)
7159 if (kstrtoul(page, 10, &new))
7163 err = mddev_lock(mddev);
7166 conf = mddev->private;
7169 else if (new != conf->skip_copy) {
7170 struct request_queue *q = mddev->queue;
7172 mddev_suspend(mddev);
7173 conf->skip_copy = new;
7175 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
7177 blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
7178 mddev_resume(mddev);
7180 mddev_unlock(mddev);
7184 static struct md_sysfs_entry
7185 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
7186 raid5_show_skip_copy,
7187 raid5_store_skip_copy);
7190 stripe_cache_active_show(struct mddev *mddev, char *page)
7192 struct r5conf *conf = mddev->private;
7194 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
7199 static struct md_sysfs_entry
7200 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
7203 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
7205 struct r5conf *conf;
7207 spin_lock(&mddev->lock);
7208 conf = mddev->private;
7210 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
7211 spin_unlock(&mddev->lock);
7215 static int alloc_thread_groups(struct r5conf *conf, int cnt,
7217 struct r5worker_group **worker_groups);
7219 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
7221 struct r5conf *conf;
7224 struct r5worker_group *new_groups, *old_groups;
7227 if (len >= PAGE_SIZE)
7229 if (kstrtouint(page, 10, &new))
7231 /* 8192 should be big enough */
7235 err = mddev_lock(mddev);
7238 conf = mddev->private;
7241 else if (new != conf->worker_cnt_per_group) {
7242 mddev_suspend(mddev);
7244 old_groups = conf->worker_groups;
7246 flush_workqueue(raid5_wq);
7248 err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
7250 spin_lock_irq(&conf->device_lock);
7251 conf->group_cnt = group_cnt;
7252 conf->worker_cnt_per_group = new;
7253 conf->worker_groups = new_groups;
7254 spin_unlock_irq(&conf->device_lock);
7257 kfree(old_groups[0].workers);
7260 mddev_resume(mddev);
7262 mddev_unlock(mddev);
7267 static struct md_sysfs_entry
7268 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
7269 raid5_show_group_thread_cnt,
7270 raid5_store_group_thread_cnt);
7272 static struct attribute *raid5_attrs[] = {
7273 &raid5_stripecache_size.attr,
7274 &raid5_stripecache_active.attr,
7275 &raid5_preread_bypass_threshold.attr,
7276 &raid5_group_thread_cnt.attr,
7277 &raid5_skip_copy.attr,
7278 &raid5_rmw_level.attr,
7279 &raid5_stripe_size.attr,
7280 &r5c_journal_mode.attr,
7281 &ppl_write_hint.attr,
7284 static const struct attribute_group raid5_attrs_group = {
7286 .attrs = raid5_attrs,
7289 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
7290 struct r5worker_group **worker_groups)
7294 struct r5worker *workers;
7298 *worker_groups = NULL;
7301 *group_cnt = num_possible_nodes();
7302 size = sizeof(struct r5worker) * cnt;
7303 workers = kcalloc(size, *group_cnt, GFP_NOIO);
7304 *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
7306 if (!*worker_groups || !workers) {
7308 kfree(*worker_groups);
7312 for (i = 0; i < *group_cnt; i++) {
7313 struct r5worker_group *group;
7315 group = &(*worker_groups)[i];
7316 INIT_LIST_HEAD(&group->handle_list);
7317 INIT_LIST_HEAD(&group->loprio_list);
7319 group->workers = workers + i * cnt;
7321 for (j = 0; j < cnt; j++) {
7322 struct r5worker *worker = group->workers + j;
7323 worker->group = group;
7324 INIT_WORK(&worker->work, raid5_do_work);
7326 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
7327 INIT_LIST_HEAD(worker->temp_inactive_list + k);
7334 static void free_thread_groups(struct r5conf *conf)
7336 if (conf->worker_groups)
7337 kfree(conf->worker_groups[0].workers);
7338 kfree(conf->worker_groups);
7339 conf->worker_groups = NULL;
7343 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
7345 struct r5conf *conf = mddev->private;
7348 sectors = mddev->dev_sectors;
7350 /* size is defined by the smallest of previous and new size */
7351 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7353 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7354 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7355 return sectors * (raid_disks - conf->max_degraded);
7358 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7360 safe_put_page(percpu->spare_page);
7361 percpu->spare_page = NULL;
7362 kvfree(percpu->scribble);
7363 percpu->scribble = NULL;
7366 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7368 if (conf->level == 6 && !percpu->spare_page) {
7369 percpu->spare_page = alloc_page(GFP_KERNEL);
7370 if (!percpu->spare_page)
7374 if (scribble_alloc(percpu,
7375 max(conf->raid_disks,
7376 conf->previous_raid_disks),
7377 max(conf->chunk_sectors,
7378 conf->prev_chunk_sectors)
7379 / RAID5_STRIPE_SECTORS(conf))) {
7380 free_scratch_buffer(conf, percpu);
7384 local_lock_init(&percpu->lock);
7388 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7390 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7392 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7396 static void raid5_free_percpu(struct r5conf *conf)
7401 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7402 free_percpu(conf->percpu);
7405 static void free_conf(struct r5conf *conf)
7411 unregister_shrinker(&conf->shrinker);
7412 free_thread_groups(conf);
7413 shrink_stripes(conf);
7414 raid5_free_percpu(conf);
7415 for (i = 0; i < conf->pool_size; i++)
7416 if (conf->disks[i].extra_page)
7417 put_page(conf->disks[i].extra_page);
7419 bioset_exit(&conf->bio_split);
7420 kfree(conf->stripe_hashtbl);
7421 kfree(conf->pending_data);
7425 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7427 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7428 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7430 if (alloc_scratch_buffer(conf, percpu)) {
7431 pr_warn("%s: failed memory allocation for cpu%u\n",
7438 static int raid5_alloc_percpu(struct r5conf *conf)
7442 conf->percpu = alloc_percpu(struct raid5_percpu);
7446 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7448 conf->scribble_disks = max(conf->raid_disks,
7449 conf->previous_raid_disks);
7450 conf->scribble_sectors = max(conf->chunk_sectors,
7451 conf->prev_chunk_sectors);
7456 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7457 struct shrink_control *sc)
7459 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7460 unsigned long ret = SHRINK_STOP;
7462 if (mutex_trylock(&conf->cache_size_mutex)) {
7464 while (ret < sc->nr_to_scan &&
7465 conf->max_nr_stripes > conf->min_nr_stripes) {
7466 if (drop_one_stripe(conf) == 0) {
7472 mutex_unlock(&conf->cache_size_mutex);
7477 static unsigned long raid5_cache_count(struct shrinker *shrink,
7478 struct shrink_control *sc)
7480 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7482 if (conf->max_nr_stripes < conf->min_nr_stripes)
7483 /* unlikely, but not impossible */
7485 return conf->max_nr_stripes - conf->min_nr_stripes;
7488 static struct r5conf *setup_conf(struct mddev *mddev)
7490 struct r5conf *conf;
7491 int raid_disk, memory, max_disks;
7492 struct md_rdev *rdev;
7493 struct disk_info *disk;
7497 struct r5worker_group *new_group;
7500 if (mddev->new_level != 5
7501 && mddev->new_level != 4
7502 && mddev->new_level != 6) {
7503 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7504 mdname(mddev), mddev->new_level);
7505 return ERR_PTR(-EIO);
7507 if ((mddev->new_level == 5
7508 && !algorithm_valid_raid5(mddev->new_layout)) ||
7509 (mddev->new_level == 6
7510 && !algorithm_valid_raid6(mddev->new_layout))) {
7511 pr_warn("md/raid:%s: layout %d not supported\n",
7512 mdname(mddev), mddev->new_layout);
7513 return ERR_PTR(-EIO);
7515 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7516 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7517 mdname(mddev), mddev->raid_disks);
7518 return ERR_PTR(-EINVAL);
7521 if (!mddev->new_chunk_sectors ||
7522 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7523 !is_power_of_2(mddev->new_chunk_sectors)) {
7524 pr_warn("md/raid:%s: invalid chunk size %d\n",
7525 mdname(mddev), mddev->new_chunk_sectors << 9);
7526 return ERR_PTR(-EINVAL);
7529 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7533 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7534 conf->stripe_size = DEFAULT_STRIPE_SIZE;
7535 conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7536 conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7538 INIT_LIST_HEAD(&conf->free_list);
7539 INIT_LIST_HEAD(&conf->pending_list);
7540 conf->pending_data = kcalloc(PENDING_IO_MAX,
7541 sizeof(struct r5pending_data),
7543 if (!conf->pending_data)
7545 for (i = 0; i < PENDING_IO_MAX; i++)
7546 list_add(&conf->pending_data[i].sibling, &conf->free_list);
7547 /* Don't enable multi-threading by default*/
7548 if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7549 conf->group_cnt = group_cnt;
7550 conf->worker_cnt_per_group = 0;
7551 conf->worker_groups = new_group;
7554 spin_lock_init(&conf->device_lock);
7555 seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7556 mutex_init(&conf->cache_size_mutex);
7558 init_waitqueue_head(&conf->wait_for_quiescent);
7559 init_waitqueue_head(&conf->wait_for_stripe);
7560 init_waitqueue_head(&conf->wait_for_overlap);
7561 INIT_LIST_HEAD(&conf->handle_list);
7562 INIT_LIST_HEAD(&conf->loprio_list);
7563 INIT_LIST_HEAD(&conf->hold_list);
7564 INIT_LIST_HEAD(&conf->delayed_list);
7565 INIT_LIST_HEAD(&conf->bitmap_list);
7566 init_llist_head(&conf->released_stripes);
7567 atomic_set(&conf->active_stripes, 0);
7568 atomic_set(&conf->preread_active_stripes, 0);
7569 atomic_set(&conf->active_aligned_reads, 0);
7570 spin_lock_init(&conf->pending_bios_lock);
7571 conf->batch_bio_dispatch = true;
7572 rdev_for_each(rdev, mddev) {
7573 if (test_bit(Journal, &rdev->flags))
7575 if (bdev_nonrot(rdev->bdev)) {
7576 conf->batch_bio_dispatch = false;
7581 conf->bypass_threshold = BYPASS_THRESHOLD;
7582 conf->recovery_disabled = mddev->recovery_disabled - 1;
7584 conf->raid_disks = mddev->raid_disks;
7585 if (mddev->reshape_position == MaxSector)
7586 conf->previous_raid_disks = mddev->raid_disks;
7588 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7589 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7591 conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7597 for (i = 0; i < max_disks; i++) {
7598 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7599 if (!conf->disks[i].extra_page)
7603 ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7606 conf->mddev = mddev;
7609 conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL);
7610 if (!conf->stripe_hashtbl)
7613 /* We init hash_locks[0] separately to that it can be used
7614 * as the reference lock in the spin_lock_nest_lock() call
7615 * in lock_all_device_hash_locks_irq in order to convince
7616 * lockdep that we know what we are doing.
7618 spin_lock_init(conf->hash_locks);
7619 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7620 spin_lock_init(conf->hash_locks + i);
7622 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7623 INIT_LIST_HEAD(conf->inactive_list + i);
7625 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7626 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7628 atomic_set(&conf->r5c_cached_full_stripes, 0);
7629 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7630 atomic_set(&conf->r5c_cached_partial_stripes, 0);
7631 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7632 atomic_set(&conf->r5c_flushing_full_stripes, 0);
7633 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7635 conf->level = mddev->new_level;
7636 conf->chunk_sectors = mddev->new_chunk_sectors;
7637 ret = raid5_alloc_percpu(conf);
7641 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7644 rdev_for_each(rdev, mddev) {
7645 raid_disk = rdev->raid_disk;
7646 if (raid_disk >= max_disks
7647 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7649 disk = conf->disks + raid_disk;
7651 if (test_bit(Replacement, &rdev->flags)) {
7652 if (disk->replacement)
7654 RCU_INIT_POINTER(disk->replacement, rdev);
7658 RCU_INIT_POINTER(disk->rdev, rdev);
7661 if (test_bit(In_sync, &rdev->flags)) {
7662 pr_info("md/raid:%s: device %pg operational as raid disk %d\n",
7663 mdname(mddev), rdev->bdev, raid_disk);
7664 } else if (rdev->saved_raid_disk != raid_disk)
7665 /* Cannot rely on bitmap to complete recovery */
7669 conf->level = mddev->new_level;
7670 if (conf->level == 6) {
7671 conf->max_degraded = 2;
7672 if (raid6_call.xor_syndrome)
7673 conf->rmw_level = PARITY_ENABLE_RMW;
7675 conf->rmw_level = PARITY_DISABLE_RMW;
7677 conf->max_degraded = 1;
7678 conf->rmw_level = PARITY_ENABLE_RMW;
7680 conf->algorithm = mddev->new_layout;
7681 conf->reshape_progress = mddev->reshape_position;
7682 if (conf->reshape_progress != MaxSector) {
7683 conf->prev_chunk_sectors = mddev->chunk_sectors;
7684 conf->prev_algo = mddev->layout;
7686 conf->prev_chunk_sectors = conf->chunk_sectors;
7687 conf->prev_algo = conf->algorithm;
7690 conf->min_nr_stripes = NR_STRIPES;
7691 if (mddev->reshape_position != MaxSector) {
7692 int stripes = max_t(int,
7693 ((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7694 ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7695 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7696 if (conf->min_nr_stripes != NR_STRIPES)
7697 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7698 mdname(mddev), conf->min_nr_stripes);
7700 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7701 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7702 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7703 if (grow_stripes(conf, conf->min_nr_stripes)) {
7704 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7705 mdname(mddev), memory);
7709 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7711 * Losing a stripe head costs more than the time to refill it,
7712 * it reduces the queue depth and so can hurt throughput.
7713 * So set it rather large, scaled by number of devices.
7715 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7716 conf->shrinker.scan_objects = raid5_cache_scan;
7717 conf->shrinker.count_objects = raid5_cache_count;
7718 conf->shrinker.batch = 128;
7719 conf->shrinker.flags = 0;
7720 ret = register_shrinker(&conf->shrinker, "md-raid5:%s", mdname(mddev));
7722 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7727 sprintf(pers_name, "raid%d", mddev->new_level);
7728 rcu_assign_pointer(conf->thread,
7729 md_register_thread(raid5d, mddev, pers_name));
7730 if (!conf->thread) {
7731 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7742 return ERR_PTR(ret);
7745 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7748 case ALGORITHM_PARITY_0:
7749 if (raid_disk < max_degraded)
7752 case ALGORITHM_PARITY_N:
7753 if (raid_disk >= raid_disks - max_degraded)
7756 case ALGORITHM_PARITY_0_6:
7757 if (raid_disk == 0 ||
7758 raid_disk == raid_disks - 1)
7761 case ALGORITHM_LEFT_ASYMMETRIC_6:
7762 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7763 case ALGORITHM_LEFT_SYMMETRIC_6:
7764 case ALGORITHM_RIGHT_SYMMETRIC_6:
7765 if (raid_disk == raid_disks - 1)
7771 static void raid5_set_io_opt(struct r5conf *conf)
7773 blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7774 (conf->raid_disks - conf->max_degraded));
7777 static int raid5_run(struct mddev *mddev)
7779 struct r5conf *conf;
7780 int dirty_parity_disks = 0;
7781 struct md_rdev *rdev;
7782 struct md_rdev *journal_dev = NULL;
7783 sector_t reshape_offset = 0;
7785 long long min_offset_diff = 0;
7788 if (mddev_init_writes_pending(mddev) < 0)
7791 if (mddev->recovery_cp != MaxSector)
7792 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7795 rdev_for_each(rdev, mddev) {
7798 if (test_bit(Journal, &rdev->flags)) {
7802 if (rdev->raid_disk < 0)
7804 diff = (rdev->new_data_offset - rdev->data_offset);
7806 min_offset_diff = diff;
7808 } else if (mddev->reshape_backwards &&
7809 diff < min_offset_diff)
7810 min_offset_diff = diff;
7811 else if (!mddev->reshape_backwards &&
7812 diff > min_offset_diff)
7813 min_offset_diff = diff;
7816 if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7817 (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7818 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7823 if (mddev->reshape_position != MaxSector) {
7824 /* Check that we can continue the reshape.
7825 * Difficulties arise if the stripe we would write to
7826 * next is at or after the stripe we would read from next.
7827 * For a reshape that changes the number of devices, this
7828 * is only possible for a very short time, and mdadm makes
7829 * sure that time appears to have past before assembling
7830 * the array. So we fail if that time hasn't passed.
7831 * For a reshape that keeps the number of devices the same
7832 * mdadm must be monitoring the reshape can keeping the
7833 * critical areas read-only and backed up. It will start
7834 * the array in read-only mode, so we check for that.
7836 sector_t here_new, here_old;
7838 int max_degraded = (mddev->level == 6 ? 2 : 1);
7843 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7848 if (mddev->new_level != mddev->level) {
7849 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7853 old_disks = mddev->raid_disks - mddev->delta_disks;
7854 /* reshape_position must be on a new-stripe boundary, and one
7855 * further up in new geometry must map after here in old
7857 * If the chunk sizes are different, then as we perform reshape
7858 * in units of the largest of the two, reshape_position needs
7859 * be a multiple of the largest chunk size times new data disks.
7861 here_new = mddev->reshape_position;
7862 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7863 new_data_disks = mddev->raid_disks - max_degraded;
7864 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7865 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7869 reshape_offset = here_new * chunk_sectors;
7870 /* here_new is the stripe we will write to */
7871 here_old = mddev->reshape_position;
7872 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7873 /* here_old is the first stripe that we might need to read
7875 if (mddev->delta_disks == 0) {
7876 /* We cannot be sure it is safe to start an in-place
7877 * reshape. It is only safe if user-space is monitoring
7878 * and taking constant backups.
7879 * mdadm always starts a situation like this in
7880 * readonly mode so it can take control before
7881 * allowing any writes. So just check for that.
7883 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7884 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7885 /* not really in-place - so OK */;
7886 else if (mddev->ro == 0) {
7887 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7891 } else if (mddev->reshape_backwards
7892 ? (here_new * chunk_sectors + min_offset_diff <=
7893 here_old * chunk_sectors)
7894 : (here_new * chunk_sectors >=
7895 here_old * chunk_sectors + (-min_offset_diff))) {
7896 /* Reading from the same stripe as writing to - bad */
7897 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7901 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7902 /* OK, we should be able to continue; */
7904 BUG_ON(mddev->level != mddev->new_level);
7905 BUG_ON(mddev->layout != mddev->new_layout);
7906 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7907 BUG_ON(mddev->delta_disks != 0);
7910 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7911 test_bit(MD_HAS_PPL, &mddev->flags)) {
7912 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7914 clear_bit(MD_HAS_PPL, &mddev->flags);
7915 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7918 if (mddev->private == NULL)
7919 conf = setup_conf(mddev);
7921 conf = mddev->private;
7924 return PTR_ERR(conf);
7926 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7928 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7931 set_disk_ro(mddev->gendisk, 1);
7932 } else if (mddev->recovery_cp == MaxSector)
7933 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7936 conf->min_offset_diff = min_offset_diff;
7937 rcu_assign_pointer(mddev->thread, conf->thread);
7938 rcu_assign_pointer(conf->thread, NULL);
7939 mddev->private = conf;
7941 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7943 rdev = rdev_mdlock_deref(mddev, conf->disks[i].rdev);
7944 if (!rdev && conf->disks[i].replacement) {
7945 /* The replacement is all we have yet */
7946 rdev = rdev_mdlock_deref(mddev,
7947 conf->disks[i].replacement);
7948 conf->disks[i].replacement = NULL;
7949 clear_bit(Replacement, &rdev->flags);
7950 rcu_assign_pointer(conf->disks[i].rdev, rdev);
7954 if (rcu_access_pointer(conf->disks[i].replacement) &&
7955 conf->reshape_progress != MaxSector) {
7956 /* replacements and reshape simply do not mix. */
7957 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7960 if (test_bit(In_sync, &rdev->flags))
7962 /* This disc is not fully in-sync. However if it
7963 * just stored parity (beyond the recovery_offset),
7964 * when we don't need to be concerned about the
7965 * array being dirty.
7966 * When reshape goes 'backwards', we never have
7967 * partially completed devices, so we only need
7968 * to worry about reshape going forwards.
7970 /* Hack because v0.91 doesn't store recovery_offset properly. */
7971 if (mddev->major_version == 0 &&
7972 mddev->minor_version > 90)
7973 rdev->recovery_offset = reshape_offset;
7975 if (rdev->recovery_offset < reshape_offset) {
7976 /* We need to check old and new layout */
7977 if (!only_parity(rdev->raid_disk,
7980 conf->max_degraded))
7983 if (!only_parity(rdev->raid_disk,
7985 conf->previous_raid_disks,
7986 conf->max_degraded))
7988 dirty_parity_disks++;
7992 * 0 for a fully functional array, 1 or 2 for a degraded array.
7994 mddev->degraded = raid5_calc_degraded(conf);
7996 if (has_failed(conf)) {
7997 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7998 mdname(mddev), mddev->degraded, conf->raid_disks);
8002 /* device size must be a multiple of chunk size */
8003 mddev->dev_sectors &= ~((sector_t)mddev->chunk_sectors - 1);
8004 mddev->resync_max_sectors = mddev->dev_sectors;
8006 if (mddev->degraded > dirty_parity_disks &&
8007 mddev->recovery_cp != MaxSector) {
8008 if (test_bit(MD_HAS_PPL, &mddev->flags))
8009 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
8011 else if (mddev->ok_start_degraded)
8012 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
8015 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
8021 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
8022 mdname(mddev), conf->level,
8023 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
8026 print_raid5_conf(conf);
8028 if (conf->reshape_progress != MaxSector) {
8029 conf->reshape_safe = conf->reshape_progress;
8030 atomic_set(&conf->reshape_stripes, 0);
8031 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8032 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8033 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8034 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8035 rcu_assign_pointer(mddev->sync_thread,
8036 md_register_thread(md_do_sync, mddev, "reshape"));
8037 if (!mddev->sync_thread)
8041 /* Ok, everything is just fine now */
8042 if (mddev->to_remove == &raid5_attrs_group)
8043 mddev->to_remove = NULL;
8044 else if (mddev->kobj.sd &&
8045 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
8046 pr_warn("raid5: failed to create sysfs attributes for %s\n",
8048 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
8052 /* read-ahead size must cover two whole stripes, which
8053 * is 2 * (datadisks) * chunksize where 'n' is the
8054 * number of raid devices
8056 int data_disks = conf->previous_raid_disks - conf->max_degraded;
8057 int stripe = data_disks *
8058 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
8060 chunk_size = mddev->chunk_sectors << 9;
8061 blk_queue_io_min(mddev->queue, chunk_size);
8062 raid5_set_io_opt(conf);
8063 mddev->queue->limits.raid_partial_stripes_expensive = 1;
8065 * We can only discard a whole stripe. It doesn't make sense to
8066 * discard data disk but write parity disk
8068 stripe = stripe * PAGE_SIZE;
8069 stripe = roundup_pow_of_two(stripe);
8070 mddev->queue->limits.discard_granularity = stripe;
8072 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
8074 rdev_for_each(rdev, mddev) {
8075 disk_stack_limits(mddev->gendisk, rdev->bdev,
8076 rdev->data_offset << 9);
8077 disk_stack_limits(mddev->gendisk, rdev->bdev,
8078 rdev->new_data_offset << 9);
8082 * zeroing is required, otherwise data
8083 * could be lost. Consider a scenario: discard a stripe
8084 * (the stripe could be inconsistent if
8085 * discard_zeroes_data is 0); write one disk of the
8086 * stripe (the stripe could be inconsistent again
8087 * depending on which disks are used to calculate
8088 * parity); the disk is broken; The stripe data of this
8091 * We only allow DISCARD if the sysadmin has confirmed that
8092 * only safe devices are in use by setting a module parameter.
8093 * A better idea might be to turn DISCARD into WRITE_ZEROES
8094 * requests, as that is required to be safe.
8096 if (!devices_handle_discard_safely ||
8097 mddev->queue->limits.max_discard_sectors < (stripe >> 9) ||
8098 mddev->queue->limits.discard_granularity < stripe)
8099 blk_queue_max_discard_sectors(mddev->queue, 0);
8102 * Requests require having a bitmap for each stripe.
8103 * Limit the max sectors based on this.
8105 blk_queue_max_hw_sectors(mddev->queue,
8106 RAID5_MAX_REQ_STRIPES << RAID5_STRIPE_SHIFT(conf));
8108 /* No restrictions on the number of segments in the request */
8109 blk_queue_max_segments(mddev->queue, USHRT_MAX);
8112 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
8117 md_unregister_thread(mddev, &mddev->thread);
8118 print_raid5_conf(conf);
8120 mddev->private = NULL;
8121 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
8125 static void raid5_free(struct mddev *mddev, void *priv)
8127 struct r5conf *conf = priv;
8130 mddev->to_remove = &raid5_attrs_group;
8133 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
8135 struct r5conf *conf = mddev->private;
8138 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
8139 conf->chunk_sectors / 2, mddev->layout);
8140 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
8142 for (i = 0; i < conf->raid_disks; i++) {
8143 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
8144 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
8147 seq_printf (seq, "]");
8150 static void print_raid5_conf (struct r5conf *conf)
8152 struct md_rdev *rdev;
8155 pr_debug("RAID conf printout:\n");
8157 pr_debug("(conf==NULL)\n");
8160 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
8162 conf->raid_disks - conf->mddev->degraded);
8165 for (i = 0; i < conf->raid_disks; i++) {
8166 rdev = rcu_dereference(conf->disks[i].rdev);
8168 pr_debug(" disk %d, o:%d, dev:%pg\n",
8169 i, !test_bit(Faulty, &rdev->flags),
8175 static int raid5_spare_active(struct mddev *mddev)
8178 struct r5conf *conf = mddev->private;
8179 struct md_rdev *rdev, *replacement;
8181 unsigned long flags;
8183 for (i = 0; i < conf->raid_disks; i++) {
8184 rdev = rdev_mdlock_deref(mddev, conf->disks[i].rdev);
8185 replacement = rdev_mdlock_deref(mddev,
8186 conf->disks[i].replacement);
8188 && replacement->recovery_offset == MaxSector
8189 && !test_bit(Faulty, &replacement->flags)
8190 && !test_and_set_bit(In_sync, &replacement->flags)) {
8191 /* Replacement has just become active. */
8193 || !test_and_clear_bit(In_sync, &rdev->flags))
8196 /* Replaced device not technically faulty,
8197 * but we need to be sure it gets removed
8198 * and never re-added.
8200 set_bit(Faulty, &rdev->flags);
8201 sysfs_notify_dirent_safe(
8204 sysfs_notify_dirent_safe(replacement->sysfs_state);
8206 && rdev->recovery_offset == MaxSector
8207 && !test_bit(Faulty, &rdev->flags)
8208 && !test_and_set_bit(In_sync, &rdev->flags)) {
8210 sysfs_notify_dirent_safe(rdev->sysfs_state);
8213 spin_lock_irqsave(&conf->device_lock, flags);
8214 mddev->degraded = raid5_calc_degraded(conf);
8215 spin_unlock_irqrestore(&conf->device_lock, flags);
8216 print_raid5_conf(conf);
8220 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
8222 struct r5conf *conf = mddev->private;
8224 int number = rdev->raid_disk;
8225 struct md_rdev __rcu **rdevp;
8226 struct disk_info *p;
8227 struct md_rdev *tmp;
8229 print_raid5_conf(conf);
8230 if (test_bit(Journal, &rdev->flags) && conf->log) {
8232 * we can't wait pending write here, as this is called in
8233 * raid5d, wait will deadlock.
8234 * neilb: there is no locking about new writes here,
8235 * so this cannot be safe.
8237 if (atomic_read(&conf->active_stripes) ||
8238 atomic_read(&conf->r5c_cached_full_stripes) ||
8239 atomic_read(&conf->r5c_cached_partial_stripes)) {
8245 if (unlikely(number >= conf->pool_size))
8247 p = conf->disks + number;
8248 if (rdev == rcu_access_pointer(p->rdev))
8250 else if (rdev == rcu_access_pointer(p->replacement))
8251 rdevp = &p->replacement;
8255 if (number >= conf->raid_disks &&
8256 conf->reshape_progress == MaxSector)
8257 clear_bit(In_sync, &rdev->flags);
8259 if (test_bit(In_sync, &rdev->flags) ||
8260 atomic_read(&rdev->nr_pending)) {
8264 /* Only remove non-faulty devices if recovery
8267 if (!test_bit(Faulty, &rdev->flags) &&
8268 mddev->recovery_disabled != conf->recovery_disabled &&
8269 !has_failed(conf) &&
8270 (!rcu_access_pointer(p->replacement) ||
8271 rcu_access_pointer(p->replacement) == rdev) &&
8272 number < conf->raid_disks) {
8277 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
8278 lockdep_assert_held(&mddev->reconfig_mutex);
8280 if (atomic_read(&rdev->nr_pending)) {
8281 /* lost the race, try later */
8283 rcu_assign_pointer(*rdevp, rdev);
8287 err = log_modify(conf, rdev, false);
8292 tmp = rcu_access_pointer(p->replacement);
8294 /* We must have just cleared 'rdev' */
8295 rcu_assign_pointer(p->rdev, tmp);
8296 clear_bit(Replacement, &tmp->flags);
8297 smp_mb(); /* Make sure other CPUs may see both as identical
8298 * but will never see neither - if they are careful
8300 rcu_assign_pointer(p->replacement, NULL);
8303 err = log_modify(conf, tmp, true);
8306 clear_bit(WantReplacement, &rdev->flags);
8309 print_raid5_conf(conf);
8313 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
8315 struct r5conf *conf = mddev->private;
8316 int ret, err = -EEXIST;
8318 struct disk_info *p;
8319 struct md_rdev *tmp;
8321 int last = conf->raid_disks - 1;
8323 if (test_bit(Journal, &rdev->flags)) {
8327 rdev->raid_disk = 0;
8329 * The array is in readonly mode if journal is missing, so no
8330 * write requests running. We should be safe
8332 ret = log_init(conf, rdev, false);
8336 ret = r5l_start(conf->log);
8342 if (mddev->recovery_disabled == conf->recovery_disabled)
8345 if (rdev->saved_raid_disk < 0 && has_failed(conf))
8346 /* no point adding a device */
8349 if (rdev->raid_disk >= 0)
8350 first = last = rdev->raid_disk;
8353 * find the disk ... but prefer rdev->saved_raid_disk
8356 if (rdev->saved_raid_disk >= first &&
8357 rdev->saved_raid_disk <= last &&
8358 conf->disks[rdev->saved_raid_disk].rdev == NULL)
8359 first = rdev->saved_raid_disk;
8361 for (disk = first; disk <= last; disk++) {
8362 p = conf->disks + disk;
8363 if (p->rdev == NULL) {
8364 clear_bit(In_sync, &rdev->flags);
8365 rdev->raid_disk = disk;
8366 if (rdev->saved_raid_disk != disk)
8368 rcu_assign_pointer(p->rdev, rdev);
8370 err = log_modify(conf, rdev, true);
8375 for (disk = first; disk <= last; disk++) {
8376 p = conf->disks + disk;
8377 tmp = rdev_mdlock_deref(mddev, p->rdev);
8378 if (test_bit(WantReplacement, &tmp->flags) &&
8379 mddev->reshape_position == MaxSector &&
8380 p->replacement == NULL) {
8381 clear_bit(In_sync, &rdev->flags);
8382 set_bit(Replacement, &rdev->flags);
8383 rdev->raid_disk = disk;
8386 rcu_assign_pointer(p->replacement, rdev);
8391 print_raid5_conf(conf);
8395 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8397 /* no resync is happening, and there is enough space
8398 * on all devices, so we can resize.
8399 * We need to make sure resync covers any new space.
8400 * If the array is shrinking we should possibly wait until
8401 * any io in the removed space completes, but it hardly seems
8405 struct r5conf *conf = mddev->private;
8407 if (raid5_has_log(conf) || raid5_has_ppl(conf))
8409 sectors &= ~((sector_t)conf->chunk_sectors - 1);
8410 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8411 if (mddev->external_size &&
8412 mddev->array_sectors > newsize)
8414 if (mddev->bitmap) {
8415 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8419 md_set_array_sectors(mddev, newsize);
8420 if (sectors > mddev->dev_sectors &&
8421 mddev->recovery_cp > mddev->dev_sectors) {
8422 mddev->recovery_cp = mddev->dev_sectors;
8423 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8425 mddev->dev_sectors = sectors;
8426 mddev->resync_max_sectors = sectors;
8430 static int check_stripe_cache(struct mddev *mddev)
8432 /* Can only proceed if there are plenty of stripe_heads.
8433 * We need a minimum of one full stripe,, and for sensible progress
8434 * it is best to have about 4 times that.
8435 * If we require 4 times, then the default 256 4K stripe_heads will
8436 * allow for chunk sizes up to 256K, which is probably OK.
8437 * If the chunk size is greater, user-space should request more
8438 * stripe_heads first.
8440 struct r5conf *conf = mddev->private;
8441 if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8442 > conf->min_nr_stripes ||
8443 ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8444 > conf->min_nr_stripes) {
8445 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
8447 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8448 / RAID5_STRIPE_SIZE(conf))*4);
8454 static int check_reshape(struct mddev *mddev)
8456 struct r5conf *conf = mddev->private;
8458 if (raid5_has_log(conf) || raid5_has_ppl(conf))
8460 if (mddev->delta_disks == 0 &&
8461 mddev->new_layout == mddev->layout &&
8462 mddev->new_chunk_sectors == mddev->chunk_sectors)
8463 return 0; /* nothing to do */
8464 if (has_failed(conf))
8466 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8467 /* We might be able to shrink, but the devices must
8468 * be made bigger first.
8469 * For raid6, 4 is the minimum size.
8470 * Otherwise 2 is the minimum
8473 if (mddev->level == 6)
8475 if (mddev->raid_disks + mddev->delta_disks < min)
8479 if (!check_stripe_cache(mddev))
8482 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8483 mddev->delta_disks > 0)
8484 if (resize_chunks(conf,
8485 conf->previous_raid_disks
8486 + max(0, mddev->delta_disks),
8487 max(mddev->new_chunk_sectors,
8488 mddev->chunk_sectors)
8492 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8493 return 0; /* never bother to shrink */
8494 return resize_stripes(conf, (conf->previous_raid_disks
8495 + mddev->delta_disks));
8498 static int raid5_start_reshape(struct mddev *mddev)
8500 struct r5conf *conf = mddev->private;
8501 struct md_rdev *rdev;
8504 unsigned long flags;
8506 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8509 if (!check_stripe_cache(mddev))
8512 if (has_failed(conf))
8515 /* raid5 can't handle concurrent reshape and recovery */
8516 if (mddev->recovery_cp < MaxSector)
8518 for (i = 0; i < conf->raid_disks; i++)
8519 if (rdev_mdlock_deref(mddev, conf->disks[i].replacement))
8522 rdev_for_each(rdev, mddev) {
8523 if (!test_bit(In_sync, &rdev->flags)
8524 && !test_bit(Faulty, &rdev->flags))
8528 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8529 /* Not enough devices even to make a degraded array
8534 /* Refuse to reduce size of the array. Any reductions in
8535 * array size must be through explicit setting of array_size
8538 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8539 < mddev->array_sectors) {
8540 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8545 atomic_set(&conf->reshape_stripes, 0);
8546 spin_lock_irq(&conf->device_lock);
8547 write_seqcount_begin(&conf->gen_lock);
8548 conf->previous_raid_disks = conf->raid_disks;
8549 conf->raid_disks += mddev->delta_disks;
8550 conf->prev_chunk_sectors = conf->chunk_sectors;
8551 conf->chunk_sectors = mddev->new_chunk_sectors;
8552 conf->prev_algo = conf->algorithm;
8553 conf->algorithm = mddev->new_layout;
8555 /* Code that selects data_offset needs to see the generation update
8556 * if reshape_progress has been set - so a memory barrier needed.
8559 if (mddev->reshape_backwards)
8560 conf->reshape_progress = raid5_size(mddev, 0, 0);
8562 conf->reshape_progress = 0;
8563 conf->reshape_safe = conf->reshape_progress;
8564 write_seqcount_end(&conf->gen_lock);
8565 spin_unlock_irq(&conf->device_lock);
8567 /* Now make sure any requests that proceeded on the assumption
8568 * the reshape wasn't running - like Discard or Read - have
8571 mddev_suspend(mddev);
8572 mddev_resume(mddev);
8574 /* Add some new drives, as many as will fit.
8575 * We know there are enough to make the newly sized array work.
8576 * Don't add devices if we are reducing the number of
8577 * devices in the array. This is because it is not possible
8578 * to correctly record the "partially reconstructed" state of
8579 * such devices during the reshape and confusion could result.
8581 if (mddev->delta_disks >= 0) {
8582 rdev_for_each(rdev, mddev)
8583 if (rdev->raid_disk < 0 &&
8584 !test_bit(Faulty, &rdev->flags)) {
8585 if (raid5_add_disk(mddev, rdev) == 0) {
8587 >= conf->previous_raid_disks)
8588 set_bit(In_sync, &rdev->flags);
8590 rdev->recovery_offset = 0;
8592 /* Failure here is OK */
8593 sysfs_link_rdev(mddev, rdev);
8595 } else if (rdev->raid_disk >= conf->previous_raid_disks
8596 && !test_bit(Faulty, &rdev->flags)) {
8597 /* This is a spare that was manually added */
8598 set_bit(In_sync, &rdev->flags);
8601 /* When a reshape changes the number of devices,
8602 * ->degraded is measured against the larger of the
8603 * pre and post number of devices.
8605 spin_lock_irqsave(&conf->device_lock, flags);
8606 mddev->degraded = raid5_calc_degraded(conf);
8607 spin_unlock_irqrestore(&conf->device_lock, flags);
8609 mddev->raid_disks = conf->raid_disks;
8610 mddev->reshape_position = conf->reshape_progress;
8611 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8613 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8614 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8615 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8616 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8617 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8618 rcu_assign_pointer(mddev->sync_thread,
8619 md_register_thread(md_do_sync, mddev, "reshape"));
8620 if (!mddev->sync_thread) {
8621 mddev->recovery = 0;
8622 spin_lock_irq(&conf->device_lock);
8623 write_seqcount_begin(&conf->gen_lock);
8624 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8625 mddev->new_chunk_sectors =
8626 conf->chunk_sectors = conf->prev_chunk_sectors;
8627 mddev->new_layout = conf->algorithm = conf->prev_algo;
8628 rdev_for_each(rdev, mddev)
8629 rdev->new_data_offset = rdev->data_offset;
8631 conf->generation --;
8632 conf->reshape_progress = MaxSector;
8633 mddev->reshape_position = MaxSector;
8634 write_seqcount_end(&conf->gen_lock);
8635 spin_unlock_irq(&conf->device_lock);
8638 conf->reshape_checkpoint = jiffies;
8639 md_wakeup_thread(mddev->sync_thread);
8644 /* This is called from the reshape thread and should make any
8645 * changes needed in 'conf'
8647 static void end_reshape(struct r5conf *conf)
8650 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8651 struct md_rdev *rdev;
8653 spin_lock_irq(&conf->device_lock);
8654 conf->previous_raid_disks = conf->raid_disks;
8655 md_finish_reshape(conf->mddev);
8657 conf->reshape_progress = MaxSector;
8658 conf->mddev->reshape_position = MaxSector;
8659 rdev_for_each(rdev, conf->mddev)
8660 if (rdev->raid_disk >= 0 &&
8661 !test_bit(Journal, &rdev->flags) &&
8662 !test_bit(In_sync, &rdev->flags))
8663 rdev->recovery_offset = MaxSector;
8664 spin_unlock_irq(&conf->device_lock);
8665 wake_up(&conf->wait_for_overlap);
8667 if (conf->mddev->queue)
8668 raid5_set_io_opt(conf);
8672 /* This is called from the raid5d thread with mddev_lock held.
8673 * It makes config changes to the device.
8675 static void raid5_finish_reshape(struct mddev *mddev)
8677 struct r5conf *conf = mddev->private;
8678 struct md_rdev *rdev;
8680 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8682 if (mddev->delta_disks <= 0) {
8684 spin_lock_irq(&conf->device_lock);
8685 mddev->degraded = raid5_calc_degraded(conf);
8686 spin_unlock_irq(&conf->device_lock);
8687 for (d = conf->raid_disks ;
8688 d < conf->raid_disks - mddev->delta_disks;
8690 rdev = rdev_mdlock_deref(mddev,
8691 conf->disks[d].rdev);
8693 clear_bit(In_sync, &rdev->flags);
8694 rdev = rdev_mdlock_deref(mddev,
8695 conf->disks[d].replacement);
8697 clear_bit(In_sync, &rdev->flags);
8700 mddev->layout = conf->algorithm;
8701 mddev->chunk_sectors = conf->chunk_sectors;
8702 mddev->reshape_position = MaxSector;
8703 mddev->delta_disks = 0;
8704 mddev->reshape_backwards = 0;
8708 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8710 struct r5conf *conf = mddev->private;
8713 /* stop all writes */
8714 lock_all_device_hash_locks_irq(conf);
8715 /* '2' tells resync/reshape to pause so that all
8716 * active stripes can drain
8718 r5c_flush_cache(conf, INT_MAX);
8719 /* need a memory barrier to make sure read_one_chunk() sees
8720 * quiesce started and reverts to slow (locked) path.
8722 smp_store_release(&conf->quiesce, 2);
8723 wait_event_cmd(conf->wait_for_quiescent,
8724 atomic_read(&conf->active_stripes) == 0 &&
8725 atomic_read(&conf->active_aligned_reads) == 0,
8726 unlock_all_device_hash_locks_irq(conf),
8727 lock_all_device_hash_locks_irq(conf));
8729 unlock_all_device_hash_locks_irq(conf);
8730 /* allow reshape to continue */
8731 wake_up(&conf->wait_for_overlap);
8733 /* re-enable writes */
8734 lock_all_device_hash_locks_irq(conf);
8736 wake_up(&conf->wait_for_quiescent);
8737 wake_up(&conf->wait_for_overlap);
8738 unlock_all_device_hash_locks_irq(conf);
8740 log_quiesce(conf, quiesce);
8743 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8745 struct r0conf *raid0_conf = mddev->private;
8748 /* for raid0 takeover only one zone is supported */
8749 if (raid0_conf->nr_strip_zones > 1) {
8750 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8752 return ERR_PTR(-EINVAL);
8755 sectors = raid0_conf->strip_zone[0].zone_end;
8756 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8757 mddev->dev_sectors = sectors;
8758 mddev->new_level = level;
8759 mddev->new_layout = ALGORITHM_PARITY_N;
8760 mddev->new_chunk_sectors = mddev->chunk_sectors;
8761 mddev->raid_disks += 1;
8762 mddev->delta_disks = 1;
8763 /* make sure it will be not marked as dirty */
8764 mddev->recovery_cp = MaxSector;
8766 return setup_conf(mddev);
8769 static void *raid5_takeover_raid1(struct mddev *mddev)
8774 if (mddev->raid_disks != 2 ||
8775 mddev->degraded > 1)
8776 return ERR_PTR(-EINVAL);
8778 /* Should check if there are write-behind devices? */
8780 chunksect = 64*2; /* 64K by default */
8782 /* The array must be an exact multiple of chunksize */
8783 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8786 if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8787 /* array size does not allow a suitable chunk size */
8788 return ERR_PTR(-EINVAL);
8790 mddev->new_level = 5;
8791 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8792 mddev->new_chunk_sectors = chunksect;
8794 ret = setup_conf(mddev);
8796 mddev_clear_unsupported_flags(mddev,
8797 UNSUPPORTED_MDDEV_FLAGS);
8801 static void *raid5_takeover_raid6(struct mddev *mddev)
8805 switch (mddev->layout) {
8806 case ALGORITHM_LEFT_ASYMMETRIC_6:
8807 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8809 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8810 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8812 case ALGORITHM_LEFT_SYMMETRIC_6:
8813 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8815 case ALGORITHM_RIGHT_SYMMETRIC_6:
8816 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8818 case ALGORITHM_PARITY_0_6:
8819 new_layout = ALGORITHM_PARITY_0;
8821 case ALGORITHM_PARITY_N:
8822 new_layout = ALGORITHM_PARITY_N;
8825 return ERR_PTR(-EINVAL);
8827 mddev->new_level = 5;
8828 mddev->new_layout = new_layout;
8829 mddev->delta_disks = -1;
8830 mddev->raid_disks -= 1;
8831 return setup_conf(mddev);
8834 static int raid5_check_reshape(struct mddev *mddev)
8836 /* For a 2-drive array, the layout and chunk size can be changed
8837 * immediately as not restriping is needed.
8838 * For larger arrays we record the new value - after validation
8839 * to be used by a reshape pass.
8841 struct r5conf *conf = mddev->private;
8842 int new_chunk = mddev->new_chunk_sectors;
8844 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8846 if (new_chunk > 0) {
8847 if (!is_power_of_2(new_chunk))
8849 if (new_chunk < (PAGE_SIZE>>9))
8851 if (mddev->array_sectors & (new_chunk-1))
8852 /* not factor of array size */
8856 /* They look valid */
8858 if (mddev->raid_disks == 2) {
8859 /* can make the change immediately */
8860 if (mddev->new_layout >= 0) {
8861 conf->algorithm = mddev->new_layout;
8862 mddev->layout = mddev->new_layout;
8864 if (new_chunk > 0) {
8865 conf->chunk_sectors = new_chunk ;
8866 mddev->chunk_sectors = new_chunk;
8868 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8869 md_wakeup_thread(mddev->thread);
8871 return check_reshape(mddev);
8874 static int raid6_check_reshape(struct mddev *mddev)
8876 int new_chunk = mddev->new_chunk_sectors;
8878 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8880 if (new_chunk > 0) {
8881 if (!is_power_of_2(new_chunk))
8883 if (new_chunk < (PAGE_SIZE >> 9))
8885 if (mddev->array_sectors & (new_chunk-1))
8886 /* not factor of array size */
8890 /* They look valid */
8891 return check_reshape(mddev);
8894 static void *raid5_takeover(struct mddev *mddev)
8896 /* raid5 can take over:
8897 * raid0 - if there is only one strip zone - make it a raid4 layout
8898 * raid1 - if there are two drives. We need to know the chunk size
8899 * raid4 - trivial - just use a raid4 layout.
8900 * raid6 - Providing it is a *_6 layout
8902 if (mddev->level == 0)
8903 return raid45_takeover_raid0(mddev, 5);
8904 if (mddev->level == 1)
8905 return raid5_takeover_raid1(mddev);
8906 if (mddev->level == 4) {
8907 mddev->new_layout = ALGORITHM_PARITY_N;
8908 mddev->new_level = 5;
8909 return setup_conf(mddev);
8911 if (mddev->level == 6)
8912 return raid5_takeover_raid6(mddev);
8914 return ERR_PTR(-EINVAL);
8917 static void *raid4_takeover(struct mddev *mddev)
8919 /* raid4 can take over:
8920 * raid0 - if there is only one strip zone
8921 * raid5 - if layout is right
8923 if (mddev->level == 0)
8924 return raid45_takeover_raid0(mddev, 4);
8925 if (mddev->level == 5 &&
8926 mddev->layout == ALGORITHM_PARITY_N) {
8927 mddev->new_layout = 0;
8928 mddev->new_level = 4;
8929 return setup_conf(mddev);
8931 return ERR_PTR(-EINVAL);
8934 static struct md_personality raid5_personality;
8936 static void *raid6_takeover(struct mddev *mddev)
8938 /* Currently can only take over a raid5. We map the
8939 * personality to an equivalent raid6 personality
8940 * with the Q block at the end.
8944 if (mddev->pers != &raid5_personality)
8945 return ERR_PTR(-EINVAL);
8946 if (mddev->degraded > 1)
8947 return ERR_PTR(-EINVAL);
8948 if (mddev->raid_disks > 253)
8949 return ERR_PTR(-EINVAL);
8950 if (mddev->raid_disks < 3)
8951 return ERR_PTR(-EINVAL);
8953 switch (mddev->layout) {
8954 case ALGORITHM_LEFT_ASYMMETRIC:
8955 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8957 case ALGORITHM_RIGHT_ASYMMETRIC:
8958 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8960 case ALGORITHM_LEFT_SYMMETRIC:
8961 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8963 case ALGORITHM_RIGHT_SYMMETRIC:
8964 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8966 case ALGORITHM_PARITY_0:
8967 new_layout = ALGORITHM_PARITY_0_6;
8969 case ALGORITHM_PARITY_N:
8970 new_layout = ALGORITHM_PARITY_N;
8973 return ERR_PTR(-EINVAL);
8975 mddev->new_level = 6;
8976 mddev->new_layout = new_layout;
8977 mddev->delta_disks = 1;
8978 mddev->raid_disks += 1;
8979 return setup_conf(mddev);
8982 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8984 struct r5conf *conf;
8987 err = mddev_lock(mddev);
8990 conf = mddev->private;
8992 mddev_unlock(mddev);
8996 if (strncmp(buf, "ppl", 3) == 0) {
8997 /* ppl only works with RAID 5 */
8998 if (!raid5_has_ppl(conf) && conf->level == 5) {
8999 err = log_init(conf, NULL, true);
9001 err = resize_stripes(conf, conf->pool_size);
9003 mddev_suspend(mddev);
9005 mddev_resume(mddev);
9010 } else if (strncmp(buf, "resync", 6) == 0) {
9011 if (raid5_has_ppl(conf)) {
9012 mddev_suspend(mddev);
9014 mddev_resume(mddev);
9015 err = resize_stripes(conf, conf->pool_size);
9016 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
9017 r5l_log_disk_error(conf)) {
9018 bool journal_dev_exists = false;
9019 struct md_rdev *rdev;
9021 rdev_for_each(rdev, mddev)
9022 if (test_bit(Journal, &rdev->flags)) {
9023 journal_dev_exists = true;
9027 if (!journal_dev_exists) {
9028 mddev_suspend(mddev);
9029 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
9030 mddev_resume(mddev);
9031 } else /* need remove journal device first */
9040 md_update_sb(mddev, 1);
9042 mddev_unlock(mddev);
9047 static int raid5_start(struct mddev *mddev)
9049 struct r5conf *conf = mddev->private;
9051 return r5l_start(conf->log);
9054 static void raid5_prepare_suspend(struct mddev *mddev)
9056 struct r5conf *conf = mddev->private;
9058 wait_event(mddev->sb_wait, !reshape_inprogress(mddev) ||
9059 percpu_ref_is_zero(&mddev->active_io));
9060 if (percpu_ref_is_zero(&mddev->active_io))
9064 * Reshape is not in progress, and array is suspended, io that is
9065 * waiting for reshpape can never be done.
9067 wake_up(&conf->wait_for_overlap);
9070 static struct md_personality raid6_personality =
9074 .owner = THIS_MODULE,
9075 .make_request = raid5_make_request,
9077 .start = raid5_start,
9079 .status = raid5_status,
9080 .error_handler = raid5_error,
9081 .hot_add_disk = raid5_add_disk,
9082 .hot_remove_disk= raid5_remove_disk,
9083 .spare_active = raid5_spare_active,
9084 .sync_request = raid5_sync_request,
9085 .resize = raid5_resize,
9087 .check_reshape = raid6_check_reshape,
9088 .start_reshape = raid5_start_reshape,
9089 .finish_reshape = raid5_finish_reshape,
9090 .prepare_suspend = raid5_prepare_suspend,
9091 .quiesce = raid5_quiesce,
9092 .takeover = raid6_takeover,
9093 .change_consistency_policy = raid5_change_consistency_policy,
9095 static struct md_personality raid5_personality =
9099 .owner = THIS_MODULE,
9100 .make_request = raid5_make_request,
9102 .start = raid5_start,
9104 .status = raid5_status,
9105 .error_handler = raid5_error,
9106 .hot_add_disk = raid5_add_disk,
9107 .hot_remove_disk= raid5_remove_disk,
9108 .spare_active = raid5_spare_active,
9109 .sync_request = raid5_sync_request,
9110 .resize = raid5_resize,
9112 .check_reshape = raid5_check_reshape,
9113 .start_reshape = raid5_start_reshape,
9114 .finish_reshape = raid5_finish_reshape,
9115 .prepare_suspend = raid5_prepare_suspend,
9116 .quiesce = raid5_quiesce,
9117 .takeover = raid5_takeover,
9118 .change_consistency_policy = raid5_change_consistency_policy,
9121 static struct md_personality raid4_personality =
9125 .owner = THIS_MODULE,
9126 .make_request = raid5_make_request,
9128 .start = raid5_start,
9130 .status = raid5_status,
9131 .error_handler = raid5_error,
9132 .hot_add_disk = raid5_add_disk,
9133 .hot_remove_disk= raid5_remove_disk,
9134 .spare_active = raid5_spare_active,
9135 .sync_request = raid5_sync_request,
9136 .resize = raid5_resize,
9138 .check_reshape = raid5_check_reshape,
9139 .start_reshape = raid5_start_reshape,
9140 .finish_reshape = raid5_finish_reshape,
9141 .prepare_suspend = raid5_prepare_suspend,
9142 .quiesce = raid5_quiesce,
9143 .takeover = raid4_takeover,
9144 .change_consistency_policy = raid5_change_consistency_policy,
9147 static int __init raid5_init(void)
9151 raid5_wq = alloc_workqueue("raid5wq",
9152 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
9156 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
9158 raid456_cpu_up_prepare,
9161 destroy_workqueue(raid5_wq);
9164 register_md_personality(&raid6_personality);
9165 register_md_personality(&raid5_personality);
9166 register_md_personality(&raid4_personality);
9170 static void raid5_exit(void)
9172 unregister_md_personality(&raid6_personality);
9173 unregister_md_personality(&raid5_personality);
9174 unregister_md_personality(&raid4_personality);
9175 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
9176 destroy_workqueue(raid5_wq);
9179 module_init(raid5_init);
9180 module_exit(raid5_exit);
9181 MODULE_LICENSE("GPL");
9182 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
9183 MODULE_ALIAS("md-personality-4"); /* RAID5 */
9184 MODULE_ALIAS("md-raid5");
9185 MODULE_ALIAS("md-raid4");
9186 MODULE_ALIAS("md-level-5");
9187 MODULE_ALIAS("md-level-4");
9188 MODULE_ALIAS("md-personality-8"); /* RAID6 */
9189 MODULE_ALIAS("md-raid6");
9190 MODULE_ALIAS("md-level-6");
9192 /* This used to be two separate modules, they were: */
9193 MODULE_ALIAS("raid5");
9194 MODULE_ALIAS("raid6");