2 * raid5.c : Multiple Devices driver for Linux
3 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4 * Copyright (C) 1999, 2000 Ingo Molnar
5 * Copyright (C) 2002, 2003 H. Peter Anvin
7 * RAID-4/5/6 management functions.
8 * Thanks to Penguin Computing for making the RAID-6 development possible
9 * by donating a test server!
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2, or (at your option)
16 * You should have received a copy of the GNU General Public License
17 * (for example /usr/src/linux/COPYING); if not, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 * The sequencing for updating the bitmap reliably is a little
25 * subtle (and I got it wrong the first time) so it deserves some
28 * We group bitmap updates into batches. Each batch has a number.
29 * We may write out several batches at once, but that isn't very important.
30 * conf->seq_write is the number of the last batch successfully written.
31 * conf->seq_flush is the number of the last batch that was closed to
33 * When we discover that we will need to write to any block in a stripe
34 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35 * the number of the batch it will be in. This is seq_flush+1.
36 * When we are ready to do a write, if that batch hasn't been written yet,
37 * we plug the array and queue the stripe for later.
38 * When an unplug happens, we increment bm_flush, thus closing the current
40 * When we notice that bm_flush > bm_write, we write out all pending updates
41 * to the bitmap, and advance bm_write to where bm_flush was.
42 * This may occasionally write a bit out twice, but is sure never to
46 #include <linux/blkdev.h>
47 #include <linux/delay.h>
48 #include <linux/kthread.h>
49 #include <linux/raid/pq.h>
50 #include <linux/async_tx.h>
51 #include <linux/module.h>
52 #include <linux/async.h>
53 #include <linux/seq_file.h>
54 #include <linux/cpu.h>
55 #include <linux/slab.h>
56 #include <linux/ratelimit.h>
57 #include <linux/nodemask.h>
58 #include <linux/flex_array.h>
59 #include <linux/sched/signal.h>
61 #include <trace/events/block.h>
62 #include <linux/list_sort.h>
68 #include "raid5-log.h"
70 #define UNSUPPORTED_MDDEV_FLAGS (1L << MD_FAILFAST_SUPPORTED)
72 #define cpu_to_group(cpu) cpu_to_node(cpu)
73 #define ANY_GROUP NUMA_NO_NODE
75 static bool devices_handle_discard_safely = false;
76 module_param(devices_handle_discard_safely, bool, 0644);
77 MODULE_PARM_DESC(devices_handle_discard_safely,
78 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
79 static struct workqueue_struct *raid5_wq;
81 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
83 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
84 return &conf->stripe_hashtbl[hash];
87 static inline int stripe_hash_locks_hash(sector_t sect)
89 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
92 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
94 spin_lock_irq(conf->hash_locks + hash);
95 spin_lock(&conf->device_lock);
98 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
100 spin_unlock(&conf->device_lock);
101 spin_unlock_irq(conf->hash_locks + hash);
104 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
107 spin_lock_irq(conf->hash_locks);
108 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
109 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
110 spin_lock(&conf->device_lock);
113 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
116 spin_unlock(&conf->device_lock);
117 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
118 spin_unlock(conf->hash_locks + i);
119 spin_unlock_irq(conf->hash_locks);
122 /* Find first data disk in a raid6 stripe */
123 static inline int raid6_d0(struct stripe_head *sh)
126 /* ddf always start from first device */
128 /* md starts just after Q block */
129 if (sh->qd_idx == sh->disks - 1)
132 return sh->qd_idx + 1;
134 static inline int raid6_next_disk(int disk, int raid_disks)
137 return (disk < raid_disks) ? disk : 0;
140 /* When walking through the disks in a raid5, starting at raid6_d0,
141 * We need to map each disk to a 'slot', where the data disks are slot
142 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
143 * is raid_disks-1. This help does that mapping.
145 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
146 int *count, int syndrome_disks)
152 if (idx == sh->pd_idx)
153 return syndrome_disks;
154 if (idx == sh->qd_idx)
155 return syndrome_disks + 1;
161 static void print_raid5_conf (struct r5conf *conf);
163 static int stripe_operations_active(struct stripe_head *sh)
165 return sh->check_state || sh->reconstruct_state ||
166 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
167 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
170 static bool stripe_is_lowprio(struct stripe_head *sh)
172 return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
173 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
174 !test_bit(STRIPE_R5C_CACHING, &sh->state);
177 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
179 struct r5conf *conf = sh->raid_conf;
180 struct r5worker_group *group;
182 int i, cpu = sh->cpu;
184 if (!cpu_online(cpu)) {
185 cpu = cpumask_any(cpu_online_mask);
189 if (list_empty(&sh->lru)) {
190 struct r5worker_group *group;
191 group = conf->worker_groups + cpu_to_group(cpu);
192 if (stripe_is_lowprio(sh))
193 list_add_tail(&sh->lru, &group->loprio_list);
195 list_add_tail(&sh->lru, &group->handle_list);
196 group->stripes_cnt++;
200 if (conf->worker_cnt_per_group == 0) {
201 md_wakeup_thread(conf->mddev->thread);
205 group = conf->worker_groups + cpu_to_group(sh->cpu);
207 group->workers[0].working = true;
208 /* at least one worker should run to avoid race */
209 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
211 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
212 /* wakeup more workers */
213 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
214 if (group->workers[i].working == false) {
215 group->workers[i].working = true;
216 queue_work_on(sh->cpu, raid5_wq,
217 &group->workers[i].work);
223 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
224 struct list_head *temp_inactive_list)
227 int injournal = 0; /* number of date pages with R5_InJournal */
229 BUG_ON(!list_empty(&sh->lru));
230 BUG_ON(atomic_read(&conf->active_stripes)==0);
232 if (r5c_is_writeback(conf->log))
233 for (i = sh->disks; i--; )
234 if (test_bit(R5_InJournal, &sh->dev[i].flags))
237 * In the following cases, the stripe cannot be released to cached
238 * lists. Therefore, we make the stripe write out and set
240 * 1. when quiesce in r5c write back;
241 * 2. when resync is requested fot the stripe.
243 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
244 (conf->quiesce && r5c_is_writeback(conf->log) &&
245 !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
246 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
247 r5c_make_stripe_write_out(sh);
248 set_bit(STRIPE_HANDLE, &sh->state);
251 if (test_bit(STRIPE_HANDLE, &sh->state)) {
252 if (test_bit(STRIPE_DELAYED, &sh->state) &&
253 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
254 list_add_tail(&sh->lru, &conf->delayed_list);
255 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
256 sh->bm_seq - conf->seq_write > 0)
257 list_add_tail(&sh->lru, &conf->bitmap_list);
259 clear_bit(STRIPE_DELAYED, &sh->state);
260 clear_bit(STRIPE_BIT_DELAY, &sh->state);
261 if (conf->worker_cnt_per_group == 0) {
262 if (stripe_is_lowprio(sh))
263 list_add_tail(&sh->lru,
266 list_add_tail(&sh->lru,
269 raid5_wakeup_stripe_thread(sh);
273 md_wakeup_thread(conf->mddev->thread);
275 BUG_ON(stripe_operations_active(sh));
276 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
277 if (atomic_dec_return(&conf->preread_active_stripes)
279 md_wakeup_thread(conf->mddev->thread);
280 atomic_dec(&conf->active_stripes);
281 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
282 if (!r5c_is_writeback(conf->log))
283 list_add_tail(&sh->lru, temp_inactive_list);
285 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
287 list_add_tail(&sh->lru, temp_inactive_list);
288 else if (injournal == conf->raid_disks - conf->max_degraded) {
290 if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
291 atomic_inc(&conf->r5c_cached_full_stripes);
292 if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
293 atomic_dec(&conf->r5c_cached_partial_stripes);
294 list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
295 r5c_check_cached_full_stripe(conf);
298 * STRIPE_R5C_PARTIAL_STRIPE is set in
299 * r5c_try_caching_write(). No need to
302 list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
308 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
309 struct list_head *temp_inactive_list)
311 if (atomic_dec_and_test(&sh->count))
312 do_release_stripe(conf, sh, temp_inactive_list);
316 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
318 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
319 * given time. Adding stripes only takes device lock, while deleting stripes
320 * only takes hash lock.
322 static void release_inactive_stripe_list(struct r5conf *conf,
323 struct list_head *temp_inactive_list,
327 bool do_wakeup = false;
330 if (hash == NR_STRIPE_HASH_LOCKS) {
331 size = NR_STRIPE_HASH_LOCKS;
332 hash = NR_STRIPE_HASH_LOCKS - 1;
336 struct list_head *list = &temp_inactive_list[size - 1];
339 * We don't hold any lock here yet, raid5_get_active_stripe() might
340 * remove stripes from the list
342 if (!list_empty_careful(list)) {
343 spin_lock_irqsave(conf->hash_locks + hash, flags);
344 if (list_empty(conf->inactive_list + hash) &&
346 atomic_dec(&conf->empty_inactive_list_nr);
347 list_splice_tail_init(list, conf->inactive_list + hash);
349 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
356 wake_up(&conf->wait_for_stripe);
357 if (atomic_read(&conf->active_stripes) == 0)
358 wake_up(&conf->wait_for_quiescent);
359 if (conf->retry_read_aligned)
360 md_wakeup_thread(conf->mddev->thread);
364 /* should hold conf->device_lock already */
365 static int release_stripe_list(struct r5conf *conf,
366 struct list_head *temp_inactive_list)
368 struct stripe_head *sh, *t;
370 struct llist_node *head;
372 head = llist_del_all(&conf->released_stripes);
373 head = llist_reverse_order(head);
374 llist_for_each_entry_safe(sh, t, head, release_list) {
377 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
379 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
381 * Don't worry the bit is set here, because if the bit is set
382 * again, the count is always > 1. This is true for
383 * STRIPE_ON_UNPLUG_LIST bit too.
385 hash = sh->hash_lock_index;
386 __release_stripe(conf, sh, &temp_inactive_list[hash]);
393 void raid5_release_stripe(struct stripe_head *sh)
395 struct r5conf *conf = sh->raid_conf;
397 struct list_head list;
401 /* Avoid release_list until the last reference.
403 if (atomic_add_unless(&sh->count, -1, 1))
406 if (unlikely(!conf->mddev->thread) ||
407 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
409 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
411 md_wakeup_thread(conf->mddev->thread);
414 local_irq_save(flags);
415 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
416 if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
417 INIT_LIST_HEAD(&list);
418 hash = sh->hash_lock_index;
419 do_release_stripe(conf, sh, &list);
420 spin_unlock(&conf->device_lock);
421 release_inactive_stripe_list(conf, &list, hash);
423 local_irq_restore(flags);
426 static inline void remove_hash(struct stripe_head *sh)
428 pr_debug("remove_hash(), stripe %llu\n",
429 (unsigned long long)sh->sector);
431 hlist_del_init(&sh->hash);
434 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
436 struct hlist_head *hp = stripe_hash(conf, sh->sector);
438 pr_debug("insert_hash(), stripe %llu\n",
439 (unsigned long long)sh->sector);
441 hlist_add_head(&sh->hash, hp);
444 /* find an idle stripe, make sure it is unhashed, and return it. */
445 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
447 struct stripe_head *sh = NULL;
448 struct list_head *first;
450 if (list_empty(conf->inactive_list + hash))
452 first = (conf->inactive_list + hash)->next;
453 sh = list_entry(first, struct stripe_head, lru);
454 list_del_init(first);
456 atomic_inc(&conf->active_stripes);
457 BUG_ON(hash != sh->hash_lock_index);
458 if (list_empty(conf->inactive_list + hash))
459 atomic_inc(&conf->empty_inactive_list_nr);
464 static void shrink_buffers(struct stripe_head *sh)
468 int num = sh->raid_conf->pool_size;
470 for (i = 0; i < num ; i++) {
471 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
475 sh->dev[i].page = NULL;
480 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
483 int num = sh->raid_conf->pool_size;
485 for (i = 0; i < num; i++) {
488 if (!(page = alloc_page(gfp))) {
491 sh->dev[i].page = page;
492 sh->dev[i].orig_page = page;
498 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
499 struct stripe_head *sh);
501 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
503 struct r5conf *conf = sh->raid_conf;
506 BUG_ON(atomic_read(&sh->count) != 0);
507 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
508 BUG_ON(stripe_operations_active(sh));
509 BUG_ON(sh->batch_head);
511 pr_debug("init_stripe called, stripe %llu\n",
512 (unsigned long long)sector);
514 seq = read_seqcount_begin(&conf->gen_lock);
515 sh->generation = conf->generation - previous;
516 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
518 stripe_set_idx(sector, conf, previous, sh);
521 for (i = sh->disks; i--; ) {
522 struct r5dev *dev = &sh->dev[i];
524 if (dev->toread || dev->read || dev->towrite || dev->written ||
525 test_bit(R5_LOCKED, &dev->flags)) {
526 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
527 (unsigned long long)sh->sector, i, dev->toread,
528 dev->read, dev->towrite, dev->written,
529 test_bit(R5_LOCKED, &dev->flags));
533 dev->sector = raid5_compute_blocknr(sh, i, previous);
535 if (read_seqcount_retry(&conf->gen_lock, seq))
537 sh->overwrite_disks = 0;
538 insert_hash(conf, sh);
539 sh->cpu = smp_processor_id();
540 set_bit(STRIPE_BATCH_READY, &sh->state);
543 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
546 struct stripe_head *sh;
548 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
549 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
550 if (sh->sector == sector && sh->generation == generation)
552 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
557 * Need to check if array has failed when deciding whether to:
559 * - remove non-faulty devices
562 * This determination is simple when no reshape is happening.
563 * However if there is a reshape, we need to carefully check
564 * both the before and after sections.
565 * This is because some failed devices may only affect one
566 * of the two sections, and some non-in_sync devices may
567 * be insync in the section most affected by failed devices.
569 int raid5_calc_degraded(struct r5conf *conf)
571 int degraded, degraded2;
576 for (i = 0; i < conf->previous_raid_disks; i++) {
577 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
578 if (rdev && test_bit(Faulty, &rdev->flags))
579 rdev = rcu_dereference(conf->disks[i].replacement);
580 if (!rdev || test_bit(Faulty, &rdev->flags))
582 else if (test_bit(In_sync, &rdev->flags))
585 /* not in-sync or faulty.
586 * If the reshape increases the number of devices,
587 * this is being recovered by the reshape, so
588 * this 'previous' section is not in_sync.
589 * If the number of devices is being reduced however,
590 * the device can only be part of the array if
591 * we are reverting a reshape, so this section will
594 if (conf->raid_disks >= conf->previous_raid_disks)
598 if (conf->raid_disks == conf->previous_raid_disks)
602 for (i = 0; i < conf->raid_disks; i++) {
603 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
604 if (rdev && test_bit(Faulty, &rdev->flags))
605 rdev = rcu_dereference(conf->disks[i].replacement);
606 if (!rdev || test_bit(Faulty, &rdev->flags))
608 else if (test_bit(In_sync, &rdev->flags))
611 /* not in-sync or faulty.
612 * If reshape increases the number of devices, this
613 * section has already been recovered, else it
614 * almost certainly hasn't.
616 if (conf->raid_disks <= conf->previous_raid_disks)
620 if (degraded2 > degraded)
625 static int has_failed(struct r5conf *conf)
629 if (conf->mddev->reshape_position == MaxSector)
630 return conf->mddev->degraded > conf->max_degraded;
632 degraded = raid5_calc_degraded(conf);
633 if (degraded > conf->max_degraded)
639 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
640 int previous, int noblock, int noquiesce)
642 struct stripe_head *sh;
643 int hash = stripe_hash_locks_hash(sector);
644 int inc_empty_inactive_list_flag;
646 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
648 spin_lock_irq(conf->hash_locks + hash);
651 wait_event_lock_irq(conf->wait_for_quiescent,
652 conf->quiesce == 0 || noquiesce,
653 *(conf->hash_locks + hash));
654 sh = __find_stripe(conf, sector, conf->generation - previous);
656 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
657 sh = get_free_stripe(conf, hash);
658 if (!sh && !test_bit(R5_DID_ALLOC,
660 set_bit(R5_ALLOC_MORE,
663 if (noblock && sh == NULL)
666 r5c_check_stripe_cache_usage(conf);
668 set_bit(R5_INACTIVE_BLOCKED,
670 r5l_wake_reclaim(conf->log, 0);
672 conf->wait_for_stripe,
673 !list_empty(conf->inactive_list + hash) &&
674 (atomic_read(&conf->active_stripes)
675 < (conf->max_nr_stripes * 3 / 4)
676 || !test_bit(R5_INACTIVE_BLOCKED,
677 &conf->cache_state)),
678 *(conf->hash_locks + hash));
679 clear_bit(R5_INACTIVE_BLOCKED,
682 init_stripe(sh, sector, previous);
683 atomic_inc(&sh->count);
685 } else if (!atomic_inc_not_zero(&sh->count)) {
686 spin_lock(&conf->device_lock);
687 if (!atomic_read(&sh->count)) {
688 if (!test_bit(STRIPE_HANDLE, &sh->state))
689 atomic_inc(&conf->active_stripes);
690 BUG_ON(list_empty(&sh->lru) &&
691 !test_bit(STRIPE_EXPANDING, &sh->state));
692 inc_empty_inactive_list_flag = 0;
693 if (!list_empty(conf->inactive_list + hash))
694 inc_empty_inactive_list_flag = 1;
695 list_del_init(&sh->lru);
696 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
697 atomic_inc(&conf->empty_inactive_list_nr);
699 sh->group->stripes_cnt--;
703 atomic_inc(&sh->count);
704 spin_unlock(&conf->device_lock);
706 } while (sh == NULL);
708 spin_unlock_irq(conf->hash_locks + hash);
712 static bool is_full_stripe_write(struct stripe_head *sh)
714 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
715 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
718 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
721 spin_lock_irq(&sh2->stripe_lock);
722 spin_lock_nested(&sh1->stripe_lock, 1);
724 spin_lock_irq(&sh1->stripe_lock);
725 spin_lock_nested(&sh2->stripe_lock, 1);
729 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
731 spin_unlock(&sh1->stripe_lock);
732 spin_unlock_irq(&sh2->stripe_lock);
735 /* Only freshly new full stripe normal write stripe can be added to a batch list */
736 static bool stripe_can_batch(struct stripe_head *sh)
738 struct r5conf *conf = sh->raid_conf;
740 if (raid5_has_log(conf) || raid5_has_ppl(conf))
742 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
743 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
744 is_full_stripe_write(sh);
747 /* we only do back search */
748 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
750 struct stripe_head *head;
751 sector_t head_sector, tmp_sec;
754 int inc_empty_inactive_list_flag;
756 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
757 tmp_sec = sh->sector;
758 if (!sector_div(tmp_sec, conf->chunk_sectors))
760 head_sector = sh->sector - STRIPE_SECTORS;
762 hash = stripe_hash_locks_hash(head_sector);
763 spin_lock_irq(conf->hash_locks + hash);
764 head = __find_stripe(conf, head_sector, conf->generation);
765 if (head && !atomic_inc_not_zero(&head->count)) {
766 spin_lock(&conf->device_lock);
767 if (!atomic_read(&head->count)) {
768 if (!test_bit(STRIPE_HANDLE, &head->state))
769 atomic_inc(&conf->active_stripes);
770 BUG_ON(list_empty(&head->lru) &&
771 !test_bit(STRIPE_EXPANDING, &head->state));
772 inc_empty_inactive_list_flag = 0;
773 if (!list_empty(conf->inactive_list + hash))
774 inc_empty_inactive_list_flag = 1;
775 list_del_init(&head->lru);
776 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
777 atomic_inc(&conf->empty_inactive_list_nr);
779 head->group->stripes_cnt--;
783 atomic_inc(&head->count);
784 spin_unlock(&conf->device_lock);
786 spin_unlock_irq(conf->hash_locks + hash);
790 if (!stripe_can_batch(head))
793 lock_two_stripes(head, sh);
794 /* clear_batch_ready clear the flag */
795 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
802 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
804 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
805 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
808 if (head->batch_head) {
809 spin_lock(&head->batch_head->batch_lock);
810 /* This batch list is already running */
811 if (!stripe_can_batch(head)) {
812 spin_unlock(&head->batch_head->batch_lock);
816 * We must assign batch_head of this stripe within the
817 * batch_lock, otherwise clear_batch_ready of batch head
818 * stripe could clear BATCH_READY bit of this stripe and
819 * this stripe->batch_head doesn't get assigned, which
820 * could confuse clear_batch_ready for this stripe
822 sh->batch_head = head->batch_head;
825 * at this point, head's BATCH_READY could be cleared, but we
826 * can still add the stripe to batch list
828 list_add(&sh->batch_list, &head->batch_list);
829 spin_unlock(&head->batch_head->batch_lock);
831 head->batch_head = head;
832 sh->batch_head = head->batch_head;
833 spin_lock(&head->batch_lock);
834 list_add_tail(&sh->batch_list, &head->batch_list);
835 spin_unlock(&head->batch_lock);
838 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
839 if (atomic_dec_return(&conf->preread_active_stripes)
841 md_wakeup_thread(conf->mddev->thread);
843 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
844 int seq = sh->bm_seq;
845 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
846 sh->batch_head->bm_seq > seq)
847 seq = sh->batch_head->bm_seq;
848 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
849 sh->batch_head->bm_seq = seq;
852 atomic_inc(&sh->count);
854 unlock_two_stripes(head, sh);
856 raid5_release_stripe(head);
859 /* Determine if 'data_offset' or 'new_data_offset' should be used
860 * in this stripe_head.
862 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
864 sector_t progress = conf->reshape_progress;
865 /* Need a memory barrier to make sure we see the value
866 * of conf->generation, or ->data_offset that was set before
867 * reshape_progress was updated.
870 if (progress == MaxSector)
872 if (sh->generation == conf->generation - 1)
874 /* We are in a reshape, and this is a new-generation stripe,
875 * so use new_data_offset.
880 static void dispatch_bio_list(struct bio_list *tmp)
884 while ((bio = bio_list_pop(tmp)))
885 generic_make_request(bio);
888 static int cmp_stripe(void *priv, struct list_head *a, struct list_head *b)
890 const struct r5pending_data *da = list_entry(a,
891 struct r5pending_data, sibling);
892 const struct r5pending_data *db = list_entry(b,
893 struct r5pending_data, sibling);
894 if (da->sector > db->sector)
896 if (da->sector < db->sector)
901 static void dispatch_defer_bios(struct r5conf *conf, int target,
902 struct bio_list *list)
904 struct r5pending_data *data;
905 struct list_head *first, *next = NULL;
908 if (conf->pending_data_cnt == 0)
911 list_sort(NULL, &conf->pending_list, cmp_stripe);
913 first = conf->pending_list.next;
915 /* temporarily move the head */
916 if (conf->next_pending_data)
917 list_move_tail(&conf->pending_list,
918 &conf->next_pending_data->sibling);
920 while (!list_empty(&conf->pending_list)) {
921 data = list_first_entry(&conf->pending_list,
922 struct r5pending_data, sibling);
923 if (&data->sibling == first)
924 first = data->sibling.next;
925 next = data->sibling.next;
927 bio_list_merge(list, &data->bios);
928 list_move(&data->sibling, &conf->free_list);
933 conf->pending_data_cnt -= cnt;
934 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
936 if (next != &conf->pending_list)
937 conf->next_pending_data = list_entry(next,
938 struct r5pending_data, sibling);
940 conf->next_pending_data = NULL;
941 /* list isn't empty */
942 if (first != &conf->pending_list)
943 list_move_tail(&conf->pending_list, first);
946 static void flush_deferred_bios(struct r5conf *conf)
948 struct bio_list tmp = BIO_EMPTY_LIST;
950 if (conf->pending_data_cnt == 0)
953 spin_lock(&conf->pending_bios_lock);
954 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
955 BUG_ON(conf->pending_data_cnt != 0);
956 spin_unlock(&conf->pending_bios_lock);
958 dispatch_bio_list(&tmp);
961 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
962 struct bio_list *bios)
964 struct bio_list tmp = BIO_EMPTY_LIST;
965 struct r5pending_data *ent;
967 spin_lock(&conf->pending_bios_lock);
968 ent = list_first_entry(&conf->free_list, struct r5pending_data,
970 list_move_tail(&ent->sibling, &conf->pending_list);
971 ent->sector = sector;
972 bio_list_init(&ent->bios);
973 bio_list_merge(&ent->bios, bios);
974 conf->pending_data_cnt++;
975 if (conf->pending_data_cnt >= PENDING_IO_MAX)
976 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
978 spin_unlock(&conf->pending_bios_lock);
980 dispatch_bio_list(&tmp);
984 raid5_end_read_request(struct bio *bi);
986 raid5_end_write_request(struct bio *bi);
988 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
990 struct r5conf *conf = sh->raid_conf;
991 int i, disks = sh->disks;
992 struct stripe_head *head_sh = sh;
993 struct bio_list pending_bios = BIO_EMPTY_LIST;
998 if (log_stripe(sh, s) == 0)
1001 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1003 for (i = disks; i--; ) {
1004 int op, op_flags = 0;
1005 int replace_only = 0;
1006 struct bio *bi, *rbi;
1007 struct md_rdev *rdev, *rrdev = NULL;
1010 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1012 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1014 if (test_bit(R5_Discard, &sh->dev[i].flags))
1015 op = REQ_OP_DISCARD;
1016 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1018 else if (test_and_clear_bit(R5_WantReplace,
1019 &sh->dev[i].flags)) {
1024 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1025 op_flags |= REQ_SYNC;
1028 bi = &sh->dev[i].req;
1029 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1032 rrdev = rcu_dereference(conf->disks[i].replacement);
1033 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1034 rdev = rcu_dereference(conf->disks[i].rdev);
1039 if (op_is_write(op)) {
1043 /* We raced and saw duplicates */
1046 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1051 if (rdev && test_bit(Faulty, &rdev->flags))
1054 atomic_inc(&rdev->nr_pending);
1055 if (rrdev && test_bit(Faulty, &rrdev->flags))
1058 atomic_inc(&rrdev->nr_pending);
1061 /* We have already checked bad blocks for reads. Now
1062 * need to check for writes. We never accept write errors
1063 * on the replacement, so we don't to check rrdev.
1065 while (op_is_write(op) && rdev &&
1066 test_bit(WriteErrorSeen, &rdev->flags)) {
1069 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
1070 &first_bad, &bad_sectors);
1075 set_bit(BlockedBadBlocks, &rdev->flags);
1076 if (!conf->mddev->external &&
1077 conf->mddev->sb_flags) {
1078 /* It is very unlikely, but we might
1079 * still need to write out the
1080 * bad block log - better give it
1082 md_check_recovery(conf->mddev);
1085 * Because md_wait_for_blocked_rdev
1086 * will dec nr_pending, we must
1087 * increment it first.
1089 atomic_inc(&rdev->nr_pending);
1090 md_wait_for_blocked_rdev(rdev, conf->mddev);
1092 /* Acknowledged bad block - skip the write */
1093 rdev_dec_pending(rdev, conf->mddev);
1099 if (s->syncing || s->expanding || s->expanded
1101 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
1103 set_bit(STRIPE_IO_STARTED, &sh->state);
1105 bio_set_dev(bi, rdev->bdev);
1106 bio_set_op_attrs(bi, op, op_flags);
1107 bi->bi_end_io = op_is_write(op)
1108 ? raid5_end_write_request
1109 : raid5_end_read_request;
1110 bi->bi_private = sh;
1112 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1113 __func__, (unsigned long long)sh->sector,
1115 atomic_inc(&sh->count);
1117 atomic_inc(&head_sh->count);
1118 if (use_new_offset(conf, sh))
1119 bi->bi_iter.bi_sector = (sh->sector
1120 + rdev->new_data_offset);
1122 bi->bi_iter.bi_sector = (sh->sector
1123 + rdev->data_offset);
1124 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1125 bi->bi_opf |= REQ_NOMERGE;
1127 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1128 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1130 if (!op_is_write(op) &&
1131 test_bit(R5_InJournal, &sh->dev[i].flags))
1133 * issuing read for a page in journal, this
1134 * must be preparing for prexor in rmw; read
1135 * the data into orig_page
1137 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1139 sh->dev[i].vec.bv_page = sh->dev[i].page;
1141 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1142 bi->bi_io_vec[0].bv_offset = 0;
1143 bi->bi_iter.bi_size = STRIPE_SIZE;
1145 * If this is discard request, set bi_vcnt 0. We don't
1146 * want to confuse SCSI because SCSI will replace payload
1148 if (op == REQ_OP_DISCARD)
1151 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1153 if (conf->mddev->gendisk)
1154 trace_block_bio_remap(bi->bi_disk->queue,
1155 bi, disk_devt(conf->mddev->gendisk),
1157 if (should_defer && op_is_write(op))
1158 bio_list_add(&pending_bios, bi);
1160 generic_make_request(bi);
1163 if (s->syncing || s->expanding || s->expanded
1165 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1167 set_bit(STRIPE_IO_STARTED, &sh->state);
1169 bio_set_dev(rbi, rrdev->bdev);
1170 bio_set_op_attrs(rbi, op, op_flags);
1171 BUG_ON(!op_is_write(op));
1172 rbi->bi_end_io = raid5_end_write_request;
1173 rbi->bi_private = sh;
1175 pr_debug("%s: for %llu schedule op %d on "
1176 "replacement disc %d\n",
1177 __func__, (unsigned long long)sh->sector,
1179 atomic_inc(&sh->count);
1181 atomic_inc(&head_sh->count);
1182 if (use_new_offset(conf, sh))
1183 rbi->bi_iter.bi_sector = (sh->sector
1184 + rrdev->new_data_offset);
1186 rbi->bi_iter.bi_sector = (sh->sector
1187 + rrdev->data_offset);
1188 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1189 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1190 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1192 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1193 rbi->bi_io_vec[0].bv_offset = 0;
1194 rbi->bi_iter.bi_size = STRIPE_SIZE;
1196 * If this is discard request, set bi_vcnt 0. We don't
1197 * want to confuse SCSI because SCSI will replace payload
1199 if (op == REQ_OP_DISCARD)
1201 if (conf->mddev->gendisk)
1202 trace_block_bio_remap(rbi->bi_disk->queue,
1203 rbi, disk_devt(conf->mddev->gendisk),
1205 if (should_defer && op_is_write(op))
1206 bio_list_add(&pending_bios, rbi);
1208 generic_make_request(rbi);
1210 if (!rdev && !rrdev) {
1211 if (op_is_write(op))
1212 set_bit(STRIPE_DEGRADED, &sh->state);
1213 pr_debug("skip op %d on disc %d for sector %llu\n",
1214 bi->bi_opf, i, (unsigned long long)sh->sector);
1215 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1216 set_bit(STRIPE_HANDLE, &sh->state);
1219 if (!head_sh->batch_head)
1221 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1227 if (should_defer && !bio_list_empty(&pending_bios))
1228 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1231 static struct dma_async_tx_descriptor *
1232 async_copy_data(int frombio, struct bio *bio, struct page **page,
1233 sector_t sector, struct dma_async_tx_descriptor *tx,
1234 struct stripe_head *sh, int no_skipcopy)
1237 struct bvec_iter iter;
1238 struct page *bio_page;
1240 struct async_submit_ctl submit;
1241 enum async_tx_flags flags = 0;
1243 if (bio->bi_iter.bi_sector >= sector)
1244 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1246 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1249 flags |= ASYNC_TX_FENCE;
1250 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1252 bio_for_each_segment(bvl, bio, iter) {
1253 int len = bvl.bv_len;
1257 if (page_offset < 0) {
1258 b_offset = -page_offset;
1259 page_offset += b_offset;
1263 if (len > 0 && page_offset + len > STRIPE_SIZE)
1264 clen = STRIPE_SIZE - page_offset;
1269 b_offset += bvl.bv_offset;
1270 bio_page = bvl.bv_page;
1272 if (sh->raid_conf->skip_copy &&
1273 b_offset == 0 && page_offset == 0 &&
1274 clen == STRIPE_SIZE &&
1278 tx = async_memcpy(*page, bio_page, page_offset,
1279 b_offset, clen, &submit);
1281 tx = async_memcpy(bio_page, *page, b_offset,
1282 page_offset, clen, &submit);
1284 /* chain the operations */
1285 submit.depend_tx = tx;
1287 if (clen < len) /* hit end of page */
1295 static void ops_complete_biofill(void *stripe_head_ref)
1297 struct stripe_head *sh = stripe_head_ref;
1300 pr_debug("%s: stripe %llu\n", __func__,
1301 (unsigned long long)sh->sector);
1303 /* clear completed biofills */
1304 for (i = sh->disks; i--; ) {
1305 struct r5dev *dev = &sh->dev[i];
1307 /* acknowledge completion of a biofill operation */
1308 /* and check if we need to reply to a read request,
1309 * new R5_Wantfill requests are held off until
1310 * !STRIPE_BIOFILL_RUN
1312 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1313 struct bio *rbi, *rbi2;
1318 while (rbi && rbi->bi_iter.bi_sector <
1319 dev->sector + STRIPE_SECTORS) {
1320 rbi2 = r5_next_bio(rbi, dev->sector);
1326 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1328 set_bit(STRIPE_HANDLE, &sh->state);
1329 raid5_release_stripe(sh);
1332 static void ops_run_biofill(struct stripe_head *sh)
1334 struct dma_async_tx_descriptor *tx = NULL;
1335 struct async_submit_ctl submit;
1338 BUG_ON(sh->batch_head);
1339 pr_debug("%s: stripe %llu\n", __func__,
1340 (unsigned long long)sh->sector);
1342 for (i = sh->disks; i--; ) {
1343 struct r5dev *dev = &sh->dev[i];
1344 if (test_bit(R5_Wantfill, &dev->flags)) {
1346 spin_lock_irq(&sh->stripe_lock);
1347 dev->read = rbi = dev->toread;
1349 spin_unlock_irq(&sh->stripe_lock);
1350 while (rbi && rbi->bi_iter.bi_sector <
1351 dev->sector + STRIPE_SECTORS) {
1352 tx = async_copy_data(0, rbi, &dev->page,
1353 dev->sector, tx, sh, 0);
1354 rbi = r5_next_bio(rbi, dev->sector);
1359 atomic_inc(&sh->count);
1360 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1361 async_trigger_callback(&submit);
1364 static void mark_target_uptodate(struct stripe_head *sh, int target)
1371 tgt = &sh->dev[target];
1372 set_bit(R5_UPTODATE, &tgt->flags);
1373 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1374 clear_bit(R5_Wantcompute, &tgt->flags);
1377 static void ops_complete_compute(void *stripe_head_ref)
1379 struct stripe_head *sh = stripe_head_ref;
1381 pr_debug("%s: stripe %llu\n", __func__,
1382 (unsigned long long)sh->sector);
1384 /* mark the computed target(s) as uptodate */
1385 mark_target_uptodate(sh, sh->ops.target);
1386 mark_target_uptodate(sh, sh->ops.target2);
1388 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1389 if (sh->check_state == check_state_compute_run)
1390 sh->check_state = check_state_compute_result;
1391 set_bit(STRIPE_HANDLE, &sh->state);
1392 raid5_release_stripe(sh);
1395 /* return a pointer to the address conversion region of the scribble buffer */
1396 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1397 struct raid5_percpu *percpu, int i)
1401 addr = flex_array_get(percpu->scribble, i);
1402 return addr + sizeof(struct page *) * (sh->disks + 2);
1405 /* return a pointer to the address conversion region of the scribble buffer */
1406 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1410 addr = flex_array_get(percpu->scribble, i);
1414 static struct dma_async_tx_descriptor *
1415 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1417 int disks = sh->disks;
1418 struct page **xor_srcs = to_addr_page(percpu, 0);
1419 int target = sh->ops.target;
1420 struct r5dev *tgt = &sh->dev[target];
1421 struct page *xor_dest = tgt->page;
1423 struct dma_async_tx_descriptor *tx;
1424 struct async_submit_ctl submit;
1427 BUG_ON(sh->batch_head);
1429 pr_debug("%s: stripe %llu block: %d\n",
1430 __func__, (unsigned long long)sh->sector, target);
1431 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1433 for (i = disks; i--; )
1435 xor_srcs[count++] = sh->dev[i].page;
1437 atomic_inc(&sh->count);
1439 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1440 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1441 if (unlikely(count == 1))
1442 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1444 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1449 /* set_syndrome_sources - populate source buffers for gen_syndrome
1450 * @srcs - (struct page *) array of size sh->disks
1451 * @sh - stripe_head to parse
1453 * Populates srcs in proper layout order for the stripe and returns the
1454 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1455 * destination buffer is recorded in srcs[count] and the Q destination
1456 * is recorded in srcs[count+1]].
1458 static int set_syndrome_sources(struct page **srcs,
1459 struct stripe_head *sh,
1462 int disks = sh->disks;
1463 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1464 int d0_idx = raid6_d0(sh);
1468 for (i = 0; i < disks; i++)
1474 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1475 struct r5dev *dev = &sh->dev[i];
1477 if (i == sh->qd_idx || i == sh->pd_idx ||
1478 (srctype == SYNDROME_SRC_ALL) ||
1479 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1480 (test_bit(R5_Wantdrain, &dev->flags) ||
1481 test_bit(R5_InJournal, &dev->flags))) ||
1482 (srctype == SYNDROME_SRC_WRITTEN &&
1484 test_bit(R5_InJournal, &dev->flags)))) {
1485 if (test_bit(R5_InJournal, &dev->flags))
1486 srcs[slot] = sh->dev[i].orig_page;
1488 srcs[slot] = sh->dev[i].page;
1490 i = raid6_next_disk(i, disks);
1491 } while (i != d0_idx);
1493 return syndrome_disks;
1496 static struct dma_async_tx_descriptor *
1497 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1499 int disks = sh->disks;
1500 struct page **blocks = to_addr_page(percpu, 0);
1502 int qd_idx = sh->qd_idx;
1503 struct dma_async_tx_descriptor *tx;
1504 struct async_submit_ctl submit;
1510 BUG_ON(sh->batch_head);
1511 if (sh->ops.target < 0)
1512 target = sh->ops.target2;
1513 else if (sh->ops.target2 < 0)
1514 target = sh->ops.target;
1516 /* we should only have one valid target */
1519 pr_debug("%s: stripe %llu block: %d\n",
1520 __func__, (unsigned long long)sh->sector, target);
1522 tgt = &sh->dev[target];
1523 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1526 atomic_inc(&sh->count);
1528 if (target == qd_idx) {
1529 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1530 blocks[count] = NULL; /* regenerating p is not necessary */
1531 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1532 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1533 ops_complete_compute, sh,
1534 to_addr_conv(sh, percpu, 0));
1535 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1537 /* Compute any data- or p-drive using XOR */
1539 for (i = disks; i-- ; ) {
1540 if (i == target || i == qd_idx)
1542 blocks[count++] = sh->dev[i].page;
1545 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1546 NULL, ops_complete_compute, sh,
1547 to_addr_conv(sh, percpu, 0));
1548 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1554 static struct dma_async_tx_descriptor *
1555 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1557 int i, count, disks = sh->disks;
1558 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1559 int d0_idx = raid6_d0(sh);
1560 int faila = -1, failb = -1;
1561 int target = sh->ops.target;
1562 int target2 = sh->ops.target2;
1563 struct r5dev *tgt = &sh->dev[target];
1564 struct r5dev *tgt2 = &sh->dev[target2];
1565 struct dma_async_tx_descriptor *tx;
1566 struct page **blocks = to_addr_page(percpu, 0);
1567 struct async_submit_ctl submit;
1569 BUG_ON(sh->batch_head);
1570 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1571 __func__, (unsigned long long)sh->sector, target, target2);
1572 BUG_ON(target < 0 || target2 < 0);
1573 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1574 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1576 /* we need to open-code set_syndrome_sources to handle the
1577 * slot number conversion for 'faila' and 'failb'
1579 for (i = 0; i < disks ; i++)
1584 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1586 blocks[slot] = sh->dev[i].page;
1592 i = raid6_next_disk(i, disks);
1593 } while (i != d0_idx);
1595 BUG_ON(faila == failb);
1598 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1599 __func__, (unsigned long long)sh->sector, faila, failb);
1601 atomic_inc(&sh->count);
1603 if (failb == syndrome_disks+1) {
1604 /* Q disk is one of the missing disks */
1605 if (faila == syndrome_disks) {
1606 /* Missing P+Q, just recompute */
1607 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1608 ops_complete_compute, sh,
1609 to_addr_conv(sh, percpu, 0));
1610 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1611 STRIPE_SIZE, &submit);
1615 int qd_idx = sh->qd_idx;
1617 /* Missing D+Q: recompute D from P, then recompute Q */
1618 if (target == qd_idx)
1619 data_target = target2;
1621 data_target = target;
1624 for (i = disks; i-- ; ) {
1625 if (i == data_target || i == qd_idx)
1627 blocks[count++] = sh->dev[i].page;
1629 dest = sh->dev[data_target].page;
1630 init_async_submit(&submit,
1631 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1633 to_addr_conv(sh, percpu, 0));
1634 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1637 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1638 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1639 ops_complete_compute, sh,
1640 to_addr_conv(sh, percpu, 0));
1641 return async_gen_syndrome(blocks, 0, count+2,
1642 STRIPE_SIZE, &submit);
1645 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1646 ops_complete_compute, sh,
1647 to_addr_conv(sh, percpu, 0));
1648 if (failb == syndrome_disks) {
1649 /* We're missing D+P. */
1650 return async_raid6_datap_recov(syndrome_disks+2,
1654 /* We're missing D+D. */
1655 return async_raid6_2data_recov(syndrome_disks+2,
1656 STRIPE_SIZE, faila, failb,
1662 static void ops_complete_prexor(void *stripe_head_ref)
1664 struct stripe_head *sh = stripe_head_ref;
1666 pr_debug("%s: stripe %llu\n", __func__,
1667 (unsigned long long)sh->sector);
1669 if (r5c_is_writeback(sh->raid_conf->log))
1671 * raid5-cache write back uses orig_page during prexor.
1672 * After prexor, it is time to free orig_page
1674 r5c_release_extra_page(sh);
1677 static struct dma_async_tx_descriptor *
1678 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1679 struct dma_async_tx_descriptor *tx)
1681 int disks = sh->disks;
1682 struct page **xor_srcs = to_addr_page(percpu, 0);
1683 int count = 0, pd_idx = sh->pd_idx, i;
1684 struct async_submit_ctl submit;
1686 /* existing parity data subtracted */
1687 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1689 BUG_ON(sh->batch_head);
1690 pr_debug("%s: stripe %llu\n", __func__,
1691 (unsigned long long)sh->sector);
1693 for (i = disks; i--; ) {
1694 struct r5dev *dev = &sh->dev[i];
1695 /* Only process blocks that are known to be uptodate */
1696 if (test_bit(R5_InJournal, &dev->flags))
1697 xor_srcs[count++] = dev->orig_page;
1698 else if (test_bit(R5_Wantdrain, &dev->flags))
1699 xor_srcs[count++] = dev->page;
1702 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1703 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1704 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1709 static struct dma_async_tx_descriptor *
1710 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1711 struct dma_async_tx_descriptor *tx)
1713 struct page **blocks = to_addr_page(percpu, 0);
1715 struct async_submit_ctl submit;
1717 pr_debug("%s: stripe %llu\n", __func__,
1718 (unsigned long long)sh->sector);
1720 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1722 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1723 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1724 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1729 static struct dma_async_tx_descriptor *
1730 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1732 struct r5conf *conf = sh->raid_conf;
1733 int disks = sh->disks;
1735 struct stripe_head *head_sh = sh;
1737 pr_debug("%s: stripe %llu\n", __func__,
1738 (unsigned long long)sh->sector);
1740 for (i = disks; i--; ) {
1745 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1751 * clear R5_InJournal, so when rewriting a page in
1752 * journal, it is not skipped by r5l_log_stripe()
1754 clear_bit(R5_InJournal, &dev->flags);
1755 spin_lock_irq(&sh->stripe_lock);
1756 chosen = dev->towrite;
1757 dev->towrite = NULL;
1758 sh->overwrite_disks = 0;
1759 BUG_ON(dev->written);
1760 wbi = dev->written = chosen;
1761 spin_unlock_irq(&sh->stripe_lock);
1762 WARN_ON(dev->page != dev->orig_page);
1764 while (wbi && wbi->bi_iter.bi_sector <
1765 dev->sector + STRIPE_SECTORS) {
1766 if (wbi->bi_opf & REQ_FUA)
1767 set_bit(R5_WantFUA, &dev->flags);
1768 if (wbi->bi_opf & REQ_SYNC)
1769 set_bit(R5_SyncIO, &dev->flags);
1770 if (bio_op(wbi) == REQ_OP_DISCARD)
1771 set_bit(R5_Discard, &dev->flags);
1773 tx = async_copy_data(1, wbi, &dev->page,
1774 dev->sector, tx, sh,
1775 r5c_is_writeback(conf->log));
1776 if (dev->page != dev->orig_page &&
1777 !r5c_is_writeback(conf->log)) {
1778 set_bit(R5_SkipCopy, &dev->flags);
1779 clear_bit(R5_UPTODATE, &dev->flags);
1780 clear_bit(R5_OVERWRITE, &dev->flags);
1783 wbi = r5_next_bio(wbi, dev->sector);
1786 if (head_sh->batch_head) {
1787 sh = list_first_entry(&sh->batch_list,
1800 static void ops_complete_reconstruct(void *stripe_head_ref)
1802 struct stripe_head *sh = stripe_head_ref;
1803 int disks = sh->disks;
1804 int pd_idx = sh->pd_idx;
1805 int qd_idx = sh->qd_idx;
1807 bool fua = false, sync = false, discard = false;
1809 pr_debug("%s: stripe %llu\n", __func__,
1810 (unsigned long long)sh->sector);
1812 for (i = disks; i--; ) {
1813 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1814 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1815 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1818 for (i = disks; i--; ) {
1819 struct r5dev *dev = &sh->dev[i];
1821 if (dev->written || i == pd_idx || i == qd_idx) {
1822 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1823 set_bit(R5_UPTODATE, &dev->flags);
1824 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1825 set_bit(R5_Expanded, &dev->flags);
1828 set_bit(R5_WantFUA, &dev->flags);
1830 set_bit(R5_SyncIO, &dev->flags);
1834 if (sh->reconstruct_state == reconstruct_state_drain_run)
1835 sh->reconstruct_state = reconstruct_state_drain_result;
1836 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1837 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1839 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1840 sh->reconstruct_state = reconstruct_state_result;
1843 set_bit(STRIPE_HANDLE, &sh->state);
1844 raid5_release_stripe(sh);
1848 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1849 struct dma_async_tx_descriptor *tx)
1851 int disks = sh->disks;
1852 struct page **xor_srcs;
1853 struct async_submit_ctl submit;
1854 int count, pd_idx = sh->pd_idx, i;
1855 struct page *xor_dest;
1857 unsigned long flags;
1859 struct stripe_head *head_sh = sh;
1862 pr_debug("%s: stripe %llu\n", __func__,
1863 (unsigned long long)sh->sector);
1865 for (i = 0; i < sh->disks; i++) {
1868 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1871 if (i >= sh->disks) {
1872 atomic_inc(&sh->count);
1873 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1874 ops_complete_reconstruct(sh);
1879 xor_srcs = to_addr_page(percpu, j);
1880 /* check if prexor is active which means only process blocks
1881 * that are part of a read-modify-write (written)
1883 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1885 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1886 for (i = disks; i--; ) {
1887 struct r5dev *dev = &sh->dev[i];
1888 if (head_sh->dev[i].written ||
1889 test_bit(R5_InJournal, &head_sh->dev[i].flags))
1890 xor_srcs[count++] = dev->page;
1893 xor_dest = sh->dev[pd_idx].page;
1894 for (i = disks; i--; ) {
1895 struct r5dev *dev = &sh->dev[i];
1897 xor_srcs[count++] = dev->page;
1901 /* 1/ if we prexor'd then the dest is reused as a source
1902 * 2/ if we did not prexor then we are redoing the parity
1903 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1904 * for the synchronous xor case
1906 last_stripe = !head_sh->batch_head ||
1907 list_first_entry(&sh->batch_list,
1908 struct stripe_head, batch_list) == head_sh;
1910 flags = ASYNC_TX_ACK |
1911 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1913 atomic_inc(&head_sh->count);
1914 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1915 to_addr_conv(sh, percpu, j));
1917 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1918 init_async_submit(&submit, flags, tx, NULL, NULL,
1919 to_addr_conv(sh, percpu, j));
1922 if (unlikely(count == 1))
1923 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1925 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1928 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1935 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1936 struct dma_async_tx_descriptor *tx)
1938 struct async_submit_ctl submit;
1939 struct page **blocks;
1940 int count, i, j = 0;
1941 struct stripe_head *head_sh = sh;
1944 unsigned long txflags;
1946 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1948 for (i = 0; i < sh->disks; i++) {
1949 if (sh->pd_idx == i || sh->qd_idx == i)
1951 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1954 if (i >= sh->disks) {
1955 atomic_inc(&sh->count);
1956 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1957 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1958 ops_complete_reconstruct(sh);
1963 blocks = to_addr_page(percpu, j);
1965 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1966 synflags = SYNDROME_SRC_WRITTEN;
1967 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1969 synflags = SYNDROME_SRC_ALL;
1970 txflags = ASYNC_TX_ACK;
1973 count = set_syndrome_sources(blocks, sh, synflags);
1974 last_stripe = !head_sh->batch_head ||
1975 list_first_entry(&sh->batch_list,
1976 struct stripe_head, batch_list) == head_sh;
1979 atomic_inc(&head_sh->count);
1980 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1981 head_sh, to_addr_conv(sh, percpu, j));
1983 init_async_submit(&submit, 0, tx, NULL, NULL,
1984 to_addr_conv(sh, percpu, j));
1985 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1988 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1994 static void ops_complete_check(void *stripe_head_ref)
1996 struct stripe_head *sh = stripe_head_ref;
1998 pr_debug("%s: stripe %llu\n", __func__,
1999 (unsigned long long)sh->sector);
2001 sh->check_state = check_state_check_result;
2002 set_bit(STRIPE_HANDLE, &sh->state);
2003 raid5_release_stripe(sh);
2006 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2008 int disks = sh->disks;
2009 int pd_idx = sh->pd_idx;
2010 int qd_idx = sh->qd_idx;
2011 struct page *xor_dest;
2012 struct page **xor_srcs = to_addr_page(percpu, 0);
2013 struct dma_async_tx_descriptor *tx;
2014 struct async_submit_ctl submit;
2018 pr_debug("%s: stripe %llu\n", __func__,
2019 (unsigned long long)sh->sector);
2021 BUG_ON(sh->batch_head);
2023 xor_dest = sh->dev[pd_idx].page;
2024 xor_srcs[count++] = xor_dest;
2025 for (i = disks; i--; ) {
2026 if (i == pd_idx || i == qd_idx)
2028 xor_srcs[count++] = sh->dev[i].page;
2031 init_async_submit(&submit, 0, NULL, NULL, NULL,
2032 to_addr_conv(sh, percpu, 0));
2033 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
2034 &sh->ops.zero_sum_result, &submit);
2036 atomic_inc(&sh->count);
2037 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2038 tx = async_trigger_callback(&submit);
2041 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2043 struct page **srcs = to_addr_page(percpu, 0);
2044 struct async_submit_ctl submit;
2047 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2048 (unsigned long long)sh->sector, checkp);
2050 BUG_ON(sh->batch_head);
2051 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
2055 atomic_inc(&sh->count);
2056 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2057 sh, to_addr_conv(sh, percpu, 0));
2058 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
2059 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
2062 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2064 int overlap_clear = 0, i, disks = sh->disks;
2065 struct dma_async_tx_descriptor *tx = NULL;
2066 struct r5conf *conf = sh->raid_conf;
2067 int level = conf->level;
2068 struct raid5_percpu *percpu;
2072 percpu = per_cpu_ptr(conf->percpu, cpu);
2073 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2074 ops_run_biofill(sh);
2078 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2080 tx = ops_run_compute5(sh, percpu);
2082 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2083 tx = ops_run_compute6_1(sh, percpu);
2085 tx = ops_run_compute6_2(sh, percpu);
2087 /* terminate the chain if reconstruct is not set to be run */
2088 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2092 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2094 tx = ops_run_prexor5(sh, percpu, tx);
2096 tx = ops_run_prexor6(sh, percpu, tx);
2099 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2100 tx = ops_run_partial_parity(sh, percpu, tx);
2102 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2103 tx = ops_run_biodrain(sh, tx);
2107 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2109 ops_run_reconstruct5(sh, percpu, tx);
2111 ops_run_reconstruct6(sh, percpu, tx);
2114 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2115 if (sh->check_state == check_state_run)
2116 ops_run_check_p(sh, percpu);
2117 else if (sh->check_state == check_state_run_q)
2118 ops_run_check_pq(sh, percpu, 0);
2119 else if (sh->check_state == check_state_run_pq)
2120 ops_run_check_pq(sh, percpu, 1);
2125 if (overlap_clear && !sh->batch_head)
2126 for (i = disks; i--; ) {
2127 struct r5dev *dev = &sh->dev[i];
2128 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2129 wake_up(&sh->raid_conf->wait_for_overlap);
2134 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2137 __free_page(sh->ppl_page);
2138 kmem_cache_free(sc, sh);
2141 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2142 int disks, struct r5conf *conf)
2144 struct stripe_head *sh;
2147 sh = kmem_cache_zalloc(sc, gfp);
2149 spin_lock_init(&sh->stripe_lock);
2150 spin_lock_init(&sh->batch_lock);
2151 INIT_LIST_HEAD(&sh->batch_list);
2152 INIT_LIST_HEAD(&sh->lru);
2153 INIT_LIST_HEAD(&sh->r5c);
2154 INIT_LIST_HEAD(&sh->log_list);
2155 atomic_set(&sh->count, 1);
2156 sh->raid_conf = conf;
2157 sh->log_start = MaxSector;
2158 for (i = 0; i < disks; i++) {
2159 struct r5dev *dev = &sh->dev[i];
2161 bio_init(&dev->req, &dev->vec, 1);
2162 bio_init(&dev->rreq, &dev->rvec, 1);
2165 if (raid5_has_ppl(conf)) {
2166 sh->ppl_page = alloc_page(gfp);
2167 if (!sh->ppl_page) {
2168 free_stripe(sc, sh);
2175 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2177 struct stripe_head *sh;
2179 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2183 if (grow_buffers(sh, gfp)) {
2185 free_stripe(conf->slab_cache, sh);
2188 sh->hash_lock_index =
2189 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2190 /* we just created an active stripe so... */
2191 atomic_inc(&conf->active_stripes);
2193 raid5_release_stripe(sh);
2194 conf->max_nr_stripes++;
2198 static int grow_stripes(struct r5conf *conf, int num)
2200 struct kmem_cache *sc;
2201 size_t namelen = sizeof(conf->cache_name[0]);
2202 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2204 if (conf->mddev->gendisk)
2205 snprintf(conf->cache_name[0], namelen,
2206 "raid%d-%s", conf->level, mdname(conf->mddev));
2208 snprintf(conf->cache_name[0], namelen,
2209 "raid%d-%p", conf->level, conf->mddev);
2210 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2212 conf->active_name = 0;
2213 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2214 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2218 conf->slab_cache = sc;
2219 conf->pool_size = devs;
2221 if (!grow_one_stripe(conf, GFP_KERNEL))
2228 * scribble_len - return the required size of the scribble region
2229 * @num - total number of disks in the array
2231 * The size must be enough to contain:
2232 * 1/ a struct page pointer for each device in the array +2
2233 * 2/ room to convert each entry in (1) to its corresponding dma
2234 * (dma_map_page()) or page (page_address()) address.
2236 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2237 * calculate over all devices (not just the data blocks), using zeros in place
2238 * of the P and Q blocks.
2240 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2242 struct flex_array *ret;
2245 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2246 ret = flex_array_alloc(len, cnt, flags);
2249 /* always prealloc all elements, so no locking is required */
2250 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2251 flex_array_free(ret);
2257 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2263 * Never shrink. And mddev_suspend() could deadlock if this is called
2264 * from raid5d. In that case, scribble_disks and scribble_sectors
2265 * should equal to new_disks and new_sectors
2267 if (conf->scribble_disks >= new_disks &&
2268 conf->scribble_sectors >= new_sectors)
2270 mddev_suspend(conf->mddev);
2272 for_each_present_cpu(cpu) {
2273 struct raid5_percpu *percpu;
2274 struct flex_array *scribble;
2276 percpu = per_cpu_ptr(conf->percpu, cpu);
2277 scribble = scribble_alloc(new_disks,
2278 new_sectors / STRIPE_SECTORS,
2282 flex_array_free(percpu->scribble);
2283 percpu->scribble = scribble;
2290 mddev_resume(conf->mddev);
2292 conf->scribble_disks = new_disks;
2293 conf->scribble_sectors = new_sectors;
2298 static int resize_stripes(struct r5conf *conf, int newsize)
2300 /* Make all the stripes able to hold 'newsize' devices.
2301 * New slots in each stripe get 'page' set to a new page.
2303 * This happens in stages:
2304 * 1/ create a new kmem_cache and allocate the required number of
2306 * 2/ gather all the old stripe_heads and transfer the pages across
2307 * to the new stripe_heads. This will have the side effect of
2308 * freezing the array as once all stripe_heads have been collected,
2309 * no IO will be possible. Old stripe heads are freed once their
2310 * pages have been transferred over, and the old kmem_cache is
2311 * freed when all stripes are done.
2312 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2313 * we simple return a failure status - no need to clean anything up.
2314 * 4/ allocate new pages for the new slots in the new stripe_heads.
2315 * If this fails, we don't bother trying the shrink the
2316 * stripe_heads down again, we just leave them as they are.
2317 * As each stripe_head is processed the new one is released into
2320 * Once step2 is started, we cannot afford to wait for a write,
2321 * so we use GFP_NOIO allocations.
2323 struct stripe_head *osh, *nsh;
2324 LIST_HEAD(newstripes);
2325 struct disk_info *ndisks;
2327 struct kmem_cache *sc;
2331 md_allow_write(conf->mddev);
2334 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2335 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2340 /* Need to ensure auto-resizing doesn't interfere */
2341 mutex_lock(&conf->cache_size_mutex);
2343 for (i = conf->max_nr_stripes; i; i--) {
2344 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2348 list_add(&nsh->lru, &newstripes);
2351 /* didn't get enough, give up */
2352 while (!list_empty(&newstripes)) {
2353 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2354 list_del(&nsh->lru);
2355 free_stripe(sc, nsh);
2357 kmem_cache_destroy(sc);
2358 mutex_unlock(&conf->cache_size_mutex);
2361 /* Step 2 - Must use GFP_NOIO now.
2362 * OK, we have enough stripes, start collecting inactive
2363 * stripes and copying them over
2367 list_for_each_entry(nsh, &newstripes, lru) {
2368 lock_device_hash_lock(conf, hash);
2369 wait_event_cmd(conf->wait_for_stripe,
2370 !list_empty(conf->inactive_list + hash),
2371 unlock_device_hash_lock(conf, hash),
2372 lock_device_hash_lock(conf, hash));
2373 osh = get_free_stripe(conf, hash);
2374 unlock_device_hash_lock(conf, hash);
2376 for(i=0; i<conf->pool_size; i++) {
2377 nsh->dev[i].page = osh->dev[i].page;
2378 nsh->dev[i].orig_page = osh->dev[i].page;
2380 nsh->hash_lock_index = hash;
2381 free_stripe(conf->slab_cache, osh);
2383 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2384 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2389 kmem_cache_destroy(conf->slab_cache);
2392 * At this point, we are holding all the stripes so the array
2393 * is completely stalled, so now is a good time to resize
2394 * conf->disks and the scribble region
2396 ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2398 for (i = 0; i < conf->pool_size; i++)
2399 ndisks[i] = conf->disks[i];
2401 for (i = conf->pool_size; i < newsize; i++) {
2402 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2403 if (!ndisks[i].extra_page)
2408 for (i = conf->pool_size; i < newsize; i++)
2409 if (ndisks[i].extra_page)
2410 put_page(ndisks[i].extra_page);
2414 conf->disks = ndisks;
2419 conf->slab_cache = sc;
2420 conf->active_name = 1-conf->active_name;
2422 /* Step 4, return new stripes to service */
2423 while(!list_empty(&newstripes)) {
2424 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2425 list_del_init(&nsh->lru);
2427 for (i=conf->raid_disks; i < newsize; i++)
2428 if (nsh->dev[i].page == NULL) {
2429 struct page *p = alloc_page(GFP_NOIO);
2430 nsh->dev[i].page = p;
2431 nsh->dev[i].orig_page = p;
2435 raid5_release_stripe(nsh);
2437 /* critical section pass, GFP_NOIO no longer needed */
2440 conf->pool_size = newsize;
2441 mutex_unlock(&conf->cache_size_mutex);
2446 static int drop_one_stripe(struct r5conf *conf)
2448 struct stripe_head *sh;
2449 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2451 spin_lock_irq(conf->hash_locks + hash);
2452 sh = get_free_stripe(conf, hash);
2453 spin_unlock_irq(conf->hash_locks + hash);
2456 BUG_ON(atomic_read(&sh->count));
2458 free_stripe(conf->slab_cache, sh);
2459 atomic_dec(&conf->active_stripes);
2460 conf->max_nr_stripes--;
2464 static void shrink_stripes(struct r5conf *conf)
2466 while (conf->max_nr_stripes &&
2467 drop_one_stripe(conf))
2470 kmem_cache_destroy(conf->slab_cache);
2471 conf->slab_cache = NULL;
2474 static void raid5_end_read_request(struct bio * bi)
2476 struct stripe_head *sh = bi->bi_private;
2477 struct r5conf *conf = sh->raid_conf;
2478 int disks = sh->disks, i;
2479 char b[BDEVNAME_SIZE];
2480 struct md_rdev *rdev = NULL;
2483 for (i=0 ; i<disks; i++)
2484 if (bi == &sh->dev[i].req)
2487 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2488 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2495 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2496 /* If replacement finished while this request was outstanding,
2497 * 'replacement' might be NULL already.
2498 * In that case it moved down to 'rdev'.
2499 * rdev is not removed until all requests are finished.
2501 rdev = conf->disks[i].replacement;
2503 rdev = conf->disks[i].rdev;
2505 if (use_new_offset(conf, sh))
2506 s = sh->sector + rdev->new_data_offset;
2508 s = sh->sector + rdev->data_offset;
2509 if (!bi->bi_status) {
2510 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2511 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2512 /* Note that this cannot happen on a
2513 * replacement device. We just fail those on
2516 pr_info_ratelimited(
2517 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2518 mdname(conf->mddev), STRIPE_SECTORS,
2519 (unsigned long long)s,
2520 bdevname(rdev->bdev, b));
2521 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2522 clear_bit(R5_ReadError, &sh->dev[i].flags);
2523 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2524 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2525 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2527 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2529 * end read for a page in journal, this
2530 * must be preparing for prexor in rmw
2532 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2534 if (atomic_read(&rdev->read_errors))
2535 atomic_set(&rdev->read_errors, 0);
2537 const char *bdn = bdevname(rdev->bdev, b);
2541 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2542 if (!(bi->bi_status == BLK_STS_PROTECTION))
2543 atomic_inc(&rdev->read_errors);
2544 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2545 pr_warn_ratelimited(
2546 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2547 mdname(conf->mddev),
2548 (unsigned long long)s,
2550 else if (conf->mddev->degraded >= conf->max_degraded) {
2552 pr_warn_ratelimited(
2553 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2554 mdname(conf->mddev),
2555 (unsigned long long)s,
2557 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2560 pr_warn_ratelimited(
2561 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2562 mdname(conf->mddev),
2563 (unsigned long long)s,
2565 } else if (atomic_read(&rdev->read_errors)
2566 > conf->max_nr_stripes)
2567 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2568 mdname(conf->mddev), bdn);
2571 if (set_bad && test_bit(In_sync, &rdev->flags)
2572 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2575 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2576 set_bit(R5_ReadError, &sh->dev[i].flags);
2577 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2578 set_bit(R5_ReadError, &sh->dev[i].flags);
2579 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2581 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2583 clear_bit(R5_ReadError, &sh->dev[i].flags);
2584 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2586 && test_bit(In_sync, &rdev->flags)
2587 && rdev_set_badblocks(
2588 rdev, sh->sector, STRIPE_SECTORS, 0)))
2589 md_error(conf->mddev, rdev);
2592 rdev_dec_pending(rdev, conf->mddev);
2594 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2595 set_bit(STRIPE_HANDLE, &sh->state);
2596 raid5_release_stripe(sh);
2599 static void raid5_end_write_request(struct bio *bi)
2601 struct stripe_head *sh = bi->bi_private;
2602 struct r5conf *conf = sh->raid_conf;
2603 int disks = sh->disks, i;
2604 struct md_rdev *rdev;
2607 int replacement = 0;
2609 for (i = 0 ; i < disks; i++) {
2610 if (bi == &sh->dev[i].req) {
2611 rdev = conf->disks[i].rdev;
2614 if (bi == &sh->dev[i].rreq) {
2615 rdev = conf->disks[i].replacement;
2619 /* rdev was removed and 'replacement'
2620 * replaced it. rdev is not removed
2621 * until all requests are finished.
2623 rdev = conf->disks[i].rdev;
2627 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2628 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2638 md_error(conf->mddev, rdev);
2639 else if (is_badblock(rdev, sh->sector,
2641 &first_bad, &bad_sectors))
2642 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2644 if (bi->bi_status) {
2645 set_bit(STRIPE_DEGRADED, &sh->state);
2646 set_bit(WriteErrorSeen, &rdev->flags);
2647 set_bit(R5_WriteError, &sh->dev[i].flags);
2648 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2649 set_bit(MD_RECOVERY_NEEDED,
2650 &rdev->mddev->recovery);
2651 } else if (is_badblock(rdev, sh->sector,
2653 &first_bad, &bad_sectors)) {
2654 set_bit(R5_MadeGood, &sh->dev[i].flags);
2655 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2656 /* That was a successful write so make
2657 * sure it looks like we already did
2660 set_bit(R5_ReWrite, &sh->dev[i].flags);
2663 rdev_dec_pending(rdev, conf->mddev);
2665 if (sh->batch_head && bi->bi_status && !replacement)
2666 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2669 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2670 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2671 set_bit(STRIPE_HANDLE, &sh->state);
2673 if (sh->batch_head && sh != sh->batch_head)
2674 raid5_release_stripe(sh->batch_head);
2675 raid5_release_stripe(sh);
2678 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2680 char b[BDEVNAME_SIZE];
2681 struct r5conf *conf = mddev->private;
2682 unsigned long flags;
2683 pr_debug("raid456: error called\n");
2685 spin_lock_irqsave(&conf->device_lock, flags);
2686 set_bit(Faulty, &rdev->flags);
2687 clear_bit(In_sync, &rdev->flags);
2688 mddev->degraded = raid5_calc_degraded(conf);
2689 spin_unlock_irqrestore(&conf->device_lock, flags);
2690 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2692 set_bit(Blocked, &rdev->flags);
2693 set_mask_bits(&mddev->sb_flags, 0,
2694 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2695 pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n"
2696 "md/raid:%s: Operation continuing on %d devices.\n",
2698 bdevname(rdev->bdev, b),
2700 conf->raid_disks - mddev->degraded);
2701 r5c_update_on_rdev_error(mddev, rdev);
2705 * Input: a 'big' sector number,
2706 * Output: index of the data and parity disk, and the sector # in them.
2708 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2709 int previous, int *dd_idx,
2710 struct stripe_head *sh)
2712 sector_t stripe, stripe2;
2713 sector_t chunk_number;
2714 unsigned int chunk_offset;
2717 sector_t new_sector;
2718 int algorithm = previous ? conf->prev_algo
2720 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2721 : conf->chunk_sectors;
2722 int raid_disks = previous ? conf->previous_raid_disks
2724 int data_disks = raid_disks - conf->max_degraded;
2726 /* First compute the information on this sector */
2729 * Compute the chunk number and the sector offset inside the chunk
2731 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2732 chunk_number = r_sector;
2735 * Compute the stripe number
2737 stripe = chunk_number;
2738 *dd_idx = sector_div(stripe, data_disks);
2741 * Select the parity disk based on the user selected algorithm.
2743 pd_idx = qd_idx = -1;
2744 switch(conf->level) {
2746 pd_idx = data_disks;
2749 switch (algorithm) {
2750 case ALGORITHM_LEFT_ASYMMETRIC:
2751 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2752 if (*dd_idx >= pd_idx)
2755 case ALGORITHM_RIGHT_ASYMMETRIC:
2756 pd_idx = sector_div(stripe2, raid_disks);
2757 if (*dd_idx >= pd_idx)
2760 case ALGORITHM_LEFT_SYMMETRIC:
2761 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2762 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2764 case ALGORITHM_RIGHT_SYMMETRIC:
2765 pd_idx = sector_div(stripe2, raid_disks);
2766 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2768 case ALGORITHM_PARITY_0:
2772 case ALGORITHM_PARITY_N:
2773 pd_idx = data_disks;
2781 switch (algorithm) {
2782 case ALGORITHM_LEFT_ASYMMETRIC:
2783 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2784 qd_idx = pd_idx + 1;
2785 if (pd_idx == raid_disks-1) {
2786 (*dd_idx)++; /* Q D D D P */
2788 } else if (*dd_idx >= pd_idx)
2789 (*dd_idx) += 2; /* D D P Q D */
2791 case ALGORITHM_RIGHT_ASYMMETRIC:
2792 pd_idx = sector_div(stripe2, raid_disks);
2793 qd_idx = pd_idx + 1;
2794 if (pd_idx == raid_disks-1) {
2795 (*dd_idx)++; /* Q D D D P */
2797 } else if (*dd_idx >= pd_idx)
2798 (*dd_idx) += 2; /* D D P Q D */
2800 case ALGORITHM_LEFT_SYMMETRIC:
2801 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2802 qd_idx = (pd_idx + 1) % raid_disks;
2803 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2805 case ALGORITHM_RIGHT_SYMMETRIC:
2806 pd_idx = sector_div(stripe2, raid_disks);
2807 qd_idx = (pd_idx + 1) % raid_disks;
2808 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2811 case ALGORITHM_PARITY_0:
2816 case ALGORITHM_PARITY_N:
2817 pd_idx = data_disks;
2818 qd_idx = data_disks + 1;
2821 case ALGORITHM_ROTATING_ZERO_RESTART:
2822 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2823 * of blocks for computing Q is different.
2825 pd_idx = sector_div(stripe2, raid_disks);
2826 qd_idx = pd_idx + 1;
2827 if (pd_idx == raid_disks-1) {
2828 (*dd_idx)++; /* Q D D D P */
2830 } else if (*dd_idx >= pd_idx)
2831 (*dd_idx) += 2; /* D D P Q D */
2835 case ALGORITHM_ROTATING_N_RESTART:
2836 /* Same a left_asymmetric, by first stripe is
2837 * D D D P Q rather than
2841 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2842 qd_idx = pd_idx + 1;
2843 if (pd_idx == raid_disks-1) {
2844 (*dd_idx)++; /* Q D D D P */
2846 } else if (*dd_idx >= pd_idx)
2847 (*dd_idx) += 2; /* D D P Q D */
2851 case ALGORITHM_ROTATING_N_CONTINUE:
2852 /* Same as left_symmetric but Q is before P */
2853 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2854 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2855 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2859 case ALGORITHM_LEFT_ASYMMETRIC_6:
2860 /* RAID5 left_asymmetric, with Q on last device */
2861 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2862 if (*dd_idx >= pd_idx)
2864 qd_idx = raid_disks - 1;
2867 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2868 pd_idx = sector_div(stripe2, raid_disks-1);
2869 if (*dd_idx >= pd_idx)
2871 qd_idx = raid_disks - 1;
2874 case ALGORITHM_LEFT_SYMMETRIC_6:
2875 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2876 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2877 qd_idx = raid_disks - 1;
2880 case ALGORITHM_RIGHT_SYMMETRIC_6:
2881 pd_idx = sector_div(stripe2, raid_disks-1);
2882 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2883 qd_idx = raid_disks - 1;
2886 case ALGORITHM_PARITY_0_6:
2889 qd_idx = raid_disks - 1;
2899 sh->pd_idx = pd_idx;
2900 sh->qd_idx = qd_idx;
2901 sh->ddf_layout = ddf_layout;
2904 * Finally, compute the new sector number
2906 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2910 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2912 struct r5conf *conf = sh->raid_conf;
2913 int raid_disks = sh->disks;
2914 int data_disks = raid_disks - conf->max_degraded;
2915 sector_t new_sector = sh->sector, check;
2916 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2917 : conf->chunk_sectors;
2918 int algorithm = previous ? conf->prev_algo
2922 sector_t chunk_number;
2923 int dummy1, dd_idx = i;
2925 struct stripe_head sh2;
2927 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2928 stripe = new_sector;
2930 if (i == sh->pd_idx)
2932 switch(conf->level) {
2935 switch (algorithm) {
2936 case ALGORITHM_LEFT_ASYMMETRIC:
2937 case ALGORITHM_RIGHT_ASYMMETRIC:
2941 case ALGORITHM_LEFT_SYMMETRIC:
2942 case ALGORITHM_RIGHT_SYMMETRIC:
2945 i -= (sh->pd_idx + 1);
2947 case ALGORITHM_PARITY_0:
2950 case ALGORITHM_PARITY_N:
2957 if (i == sh->qd_idx)
2958 return 0; /* It is the Q disk */
2959 switch (algorithm) {
2960 case ALGORITHM_LEFT_ASYMMETRIC:
2961 case ALGORITHM_RIGHT_ASYMMETRIC:
2962 case ALGORITHM_ROTATING_ZERO_RESTART:
2963 case ALGORITHM_ROTATING_N_RESTART:
2964 if (sh->pd_idx == raid_disks-1)
2965 i--; /* Q D D D P */
2966 else if (i > sh->pd_idx)
2967 i -= 2; /* D D P Q D */
2969 case ALGORITHM_LEFT_SYMMETRIC:
2970 case ALGORITHM_RIGHT_SYMMETRIC:
2971 if (sh->pd_idx == raid_disks-1)
2972 i--; /* Q D D D P */
2977 i -= (sh->pd_idx + 2);
2980 case ALGORITHM_PARITY_0:
2983 case ALGORITHM_PARITY_N:
2985 case ALGORITHM_ROTATING_N_CONTINUE:
2986 /* Like left_symmetric, but P is before Q */
2987 if (sh->pd_idx == 0)
2988 i--; /* P D D D Q */
2993 i -= (sh->pd_idx + 1);
2996 case ALGORITHM_LEFT_ASYMMETRIC_6:
2997 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3001 case ALGORITHM_LEFT_SYMMETRIC_6:
3002 case ALGORITHM_RIGHT_SYMMETRIC_6:
3004 i += data_disks + 1;
3005 i -= (sh->pd_idx + 1);
3007 case ALGORITHM_PARITY_0_6:
3016 chunk_number = stripe * data_disks + i;
3017 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3019 check = raid5_compute_sector(conf, r_sector,
3020 previous, &dummy1, &sh2);
3021 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3022 || sh2.qd_idx != sh->qd_idx) {
3023 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3024 mdname(conf->mddev));
3031 * There are cases where we want handle_stripe_dirtying() and
3032 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3034 * This function checks whether we want to delay the towrite. Specifically,
3035 * we delay the towrite when:
3037 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3038 * stripe has data in journal (for other devices).
3040 * In this case, when reading data for the non-overwrite dev, it is
3041 * necessary to handle complex rmw of write back cache (prexor with
3042 * orig_page, and xor with page). To keep read path simple, we would
3043 * like to flush data in journal to RAID disks first, so complex rmw
3044 * is handled in the write patch (handle_stripe_dirtying).
3046 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3048 * It is important to be able to flush all stripes in raid5-cache.
3049 * Therefore, we need reserve some space on the journal device for
3050 * these flushes. If flush operation includes pending writes to the
3051 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3052 * for the flush out. If we exclude these pending writes from flush
3053 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3054 * Therefore, excluding pending writes in these cases enables more
3055 * efficient use of the journal device.
3057 * Note: To make sure the stripe makes progress, we only delay
3058 * towrite for stripes with data already in journal (injournal > 0).
3059 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3060 * no_space_stripes list.
3062 * 3. during journal failure
3063 * In journal failure, we try to flush all cached data to raid disks
3064 * based on data in stripe cache. The array is read-only to upper
3065 * layers, so we would skip all pending writes.
3068 static inline bool delay_towrite(struct r5conf *conf,
3070 struct stripe_head_state *s)
3073 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3074 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3077 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3081 if (s->log_failed && s->injournal)
3087 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3088 int rcw, int expand)
3090 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3091 struct r5conf *conf = sh->raid_conf;
3092 int level = conf->level;
3096 * In some cases, handle_stripe_dirtying initially decided to
3097 * run rmw and allocates extra page for prexor. However, rcw is
3098 * cheaper later on. We need to free the extra page now,
3099 * because we won't be able to do that in ops_complete_prexor().
3101 r5c_release_extra_page(sh);
3103 for (i = disks; i--; ) {
3104 struct r5dev *dev = &sh->dev[i];
3106 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3107 set_bit(R5_LOCKED, &dev->flags);
3108 set_bit(R5_Wantdrain, &dev->flags);
3110 clear_bit(R5_UPTODATE, &dev->flags);
3112 } else if (test_bit(R5_InJournal, &dev->flags)) {
3113 set_bit(R5_LOCKED, &dev->flags);
3117 /* if we are not expanding this is a proper write request, and
3118 * there will be bios with new data to be drained into the
3123 /* False alarm, nothing to do */
3125 sh->reconstruct_state = reconstruct_state_drain_run;
3126 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3128 sh->reconstruct_state = reconstruct_state_run;
3130 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3132 if (s->locked + conf->max_degraded == disks)
3133 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3134 atomic_inc(&conf->pending_full_writes);
3136 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3137 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3138 BUG_ON(level == 6 &&
3139 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3140 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3142 for (i = disks; i--; ) {
3143 struct r5dev *dev = &sh->dev[i];
3144 if (i == pd_idx || i == qd_idx)
3148 (test_bit(R5_UPTODATE, &dev->flags) ||
3149 test_bit(R5_Wantcompute, &dev->flags))) {
3150 set_bit(R5_Wantdrain, &dev->flags);
3151 set_bit(R5_LOCKED, &dev->flags);
3152 clear_bit(R5_UPTODATE, &dev->flags);
3154 } else if (test_bit(R5_InJournal, &dev->flags)) {
3155 set_bit(R5_LOCKED, &dev->flags);
3160 /* False alarm - nothing to do */
3162 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3163 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3164 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3165 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3168 /* keep the parity disk(s) locked while asynchronous operations
3171 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3172 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3176 int qd_idx = sh->qd_idx;
3177 struct r5dev *dev = &sh->dev[qd_idx];
3179 set_bit(R5_LOCKED, &dev->flags);
3180 clear_bit(R5_UPTODATE, &dev->flags);
3184 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3185 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3186 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3187 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3188 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3190 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3191 __func__, (unsigned long long)sh->sector,
3192 s->locked, s->ops_request);
3196 * Each stripe/dev can have one or more bion attached.
3197 * toread/towrite point to the first in a chain.
3198 * The bi_next chain must be in order.
3200 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3201 int forwrite, int previous)
3204 struct r5conf *conf = sh->raid_conf;
3207 pr_debug("adding bi b#%llu to stripe s#%llu\n",
3208 (unsigned long long)bi->bi_iter.bi_sector,
3209 (unsigned long long)sh->sector);
3211 spin_lock_irq(&sh->stripe_lock);
3212 /* Don't allow new IO added to stripes in batch list */
3216 bip = &sh->dev[dd_idx].towrite;
3220 bip = &sh->dev[dd_idx].toread;
3221 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3222 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3224 bip = & (*bip)->bi_next;
3226 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3229 if (forwrite && raid5_has_ppl(conf)) {
3231 * With PPL only writes to consecutive data chunks within a
3232 * stripe are allowed because for a single stripe_head we can
3233 * only have one PPL entry at a time, which describes one data
3234 * range. Not really an overlap, but wait_for_overlap can be
3235 * used to handle this.
3243 for (i = 0; i < sh->disks; i++) {
3244 if (i != sh->pd_idx &&
3245 (i == dd_idx || sh->dev[i].towrite)) {
3246 sector = sh->dev[i].sector;
3247 if (count == 0 || sector < first)
3255 if (first + conf->chunk_sectors * (count - 1) != last)
3259 if (!forwrite || previous)
3260 clear_bit(STRIPE_BATCH_READY, &sh->state);
3262 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3266 bio_inc_remaining(bi);
3267 md_write_inc(conf->mddev, bi);
3270 /* check if page is covered */
3271 sector_t sector = sh->dev[dd_idx].sector;
3272 for (bi=sh->dev[dd_idx].towrite;
3273 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3274 bi && bi->bi_iter.bi_sector <= sector;
3275 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3276 if (bio_end_sector(bi) >= sector)
3277 sector = bio_end_sector(bi);
3279 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3280 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3281 sh->overwrite_disks++;
3284 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3285 (unsigned long long)(*bip)->bi_iter.bi_sector,
3286 (unsigned long long)sh->sector, dd_idx);
3288 if (conf->mddev->bitmap && firstwrite) {
3289 /* Cannot hold spinlock over bitmap_startwrite,
3290 * but must ensure this isn't added to a batch until
3291 * we have added to the bitmap and set bm_seq.
3292 * So set STRIPE_BITMAP_PENDING to prevent
3294 * If multiple add_stripe_bio() calls race here they
3295 * much all set STRIPE_BITMAP_PENDING. So only the first one
3296 * to complete "bitmap_startwrite" gets to set
3297 * STRIPE_BIT_DELAY. This is important as once a stripe
3298 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3301 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3302 spin_unlock_irq(&sh->stripe_lock);
3303 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3305 spin_lock_irq(&sh->stripe_lock);
3306 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3307 if (!sh->batch_head) {
3308 sh->bm_seq = conf->seq_flush+1;
3309 set_bit(STRIPE_BIT_DELAY, &sh->state);
3312 spin_unlock_irq(&sh->stripe_lock);
3314 if (stripe_can_batch(sh))
3315 stripe_add_to_batch_list(conf, sh);
3319 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3320 spin_unlock_irq(&sh->stripe_lock);
3324 static void end_reshape(struct r5conf *conf);
3326 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3327 struct stripe_head *sh)
3329 int sectors_per_chunk =
3330 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3332 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3333 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3335 raid5_compute_sector(conf,
3336 stripe * (disks - conf->max_degraded)
3337 *sectors_per_chunk + chunk_offset,
3343 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3344 struct stripe_head_state *s, int disks)
3347 BUG_ON(sh->batch_head);
3348 for (i = disks; i--; ) {
3352 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3353 struct md_rdev *rdev;
3355 rdev = rcu_dereference(conf->disks[i].rdev);
3356 if (rdev && test_bit(In_sync, &rdev->flags) &&
3357 !test_bit(Faulty, &rdev->flags))
3358 atomic_inc(&rdev->nr_pending);
3363 if (!rdev_set_badblocks(
3367 md_error(conf->mddev, rdev);
3368 rdev_dec_pending(rdev, conf->mddev);
3371 spin_lock_irq(&sh->stripe_lock);
3372 /* fail all writes first */
3373 bi = sh->dev[i].towrite;
3374 sh->dev[i].towrite = NULL;
3375 sh->overwrite_disks = 0;
3376 spin_unlock_irq(&sh->stripe_lock);
3380 log_stripe_write_finished(sh);
3382 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3383 wake_up(&conf->wait_for_overlap);
3385 while (bi && bi->bi_iter.bi_sector <
3386 sh->dev[i].sector + STRIPE_SECTORS) {
3387 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3389 md_write_end(conf->mddev);
3394 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3395 STRIPE_SECTORS, 0, 0);
3397 /* and fail all 'written' */
3398 bi = sh->dev[i].written;
3399 sh->dev[i].written = NULL;
3400 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3401 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3402 sh->dev[i].page = sh->dev[i].orig_page;
3405 if (bi) bitmap_end = 1;
3406 while (bi && bi->bi_iter.bi_sector <
3407 sh->dev[i].sector + STRIPE_SECTORS) {
3408 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3410 md_write_end(conf->mddev);
3415 /* fail any reads if this device is non-operational and
3416 * the data has not reached the cache yet.
3418 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3419 s->failed > conf->max_degraded &&
3420 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3421 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3422 spin_lock_irq(&sh->stripe_lock);
3423 bi = sh->dev[i].toread;
3424 sh->dev[i].toread = NULL;
3425 spin_unlock_irq(&sh->stripe_lock);
3426 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3427 wake_up(&conf->wait_for_overlap);
3430 while (bi && bi->bi_iter.bi_sector <
3431 sh->dev[i].sector + STRIPE_SECTORS) {
3432 struct bio *nextbi =
3433 r5_next_bio(bi, sh->dev[i].sector);
3440 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3441 STRIPE_SECTORS, 0, 0);
3442 /* If we were in the middle of a write the parity block might
3443 * still be locked - so just clear all R5_LOCKED flags
3445 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3450 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3451 if (atomic_dec_and_test(&conf->pending_full_writes))
3452 md_wakeup_thread(conf->mddev->thread);
3456 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3457 struct stripe_head_state *s)
3462 BUG_ON(sh->batch_head);
3463 clear_bit(STRIPE_SYNCING, &sh->state);
3464 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3465 wake_up(&conf->wait_for_overlap);
3468 /* There is nothing more to do for sync/check/repair.
3469 * Don't even need to abort as that is handled elsewhere
3470 * if needed, and not always wanted e.g. if there is a known
3472 * For recover/replace we need to record a bad block on all
3473 * non-sync devices, or abort the recovery
3475 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3476 /* During recovery devices cannot be removed, so
3477 * locking and refcounting of rdevs is not needed
3480 for (i = 0; i < conf->raid_disks; i++) {
3481 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3483 && !test_bit(Faulty, &rdev->flags)
3484 && !test_bit(In_sync, &rdev->flags)
3485 && !rdev_set_badblocks(rdev, sh->sector,
3488 rdev = rcu_dereference(conf->disks[i].replacement);
3490 && !test_bit(Faulty, &rdev->flags)
3491 && !test_bit(In_sync, &rdev->flags)
3492 && !rdev_set_badblocks(rdev, sh->sector,
3498 conf->recovery_disabled =
3499 conf->mddev->recovery_disabled;
3501 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3504 static int want_replace(struct stripe_head *sh, int disk_idx)
3506 struct md_rdev *rdev;
3510 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3512 && !test_bit(Faulty, &rdev->flags)
3513 && !test_bit(In_sync, &rdev->flags)
3514 && (rdev->recovery_offset <= sh->sector
3515 || rdev->mddev->recovery_cp <= sh->sector))
3521 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3522 int disk_idx, int disks)
3524 struct r5dev *dev = &sh->dev[disk_idx];
3525 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3526 &sh->dev[s->failed_num[1]] };
3530 if (test_bit(R5_LOCKED, &dev->flags) ||
3531 test_bit(R5_UPTODATE, &dev->flags))
3532 /* No point reading this as we already have it or have
3533 * decided to get it.
3538 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3539 /* We need this block to directly satisfy a request */
3542 if (s->syncing || s->expanding ||
3543 (s->replacing && want_replace(sh, disk_idx)))
3544 /* When syncing, or expanding we read everything.
3545 * When replacing, we need the replaced block.
3549 if ((s->failed >= 1 && fdev[0]->toread) ||
3550 (s->failed >= 2 && fdev[1]->toread))
3551 /* If we want to read from a failed device, then
3552 * we need to actually read every other device.
3556 /* Sometimes neither read-modify-write nor reconstruct-write
3557 * cycles can work. In those cases we read every block we
3558 * can. Then the parity-update is certain to have enough to
3560 * This can only be a problem when we need to write something,
3561 * and some device has failed. If either of those tests
3562 * fail we need look no further.
3564 if (!s->failed || !s->to_write)
3567 if (test_bit(R5_Insync, &dev->flags) &&
3568 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3569 /* Pre-reads at not permitted until after short delay
3570 * to gather multiple requests. However if this
3571 * device is no Insync, the block could only be computed
3572 * and there is no need to delay that.
3576 for (i = 0; i < s->failed && i < 2; i++) {
3577 if (fdev[i]->towrite &&
3578 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3579 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3580 /* If we have a partial write to a failed
3581 * device, then we will need to reconstruct
3582 * the content of that device, so all other
3583 * devices must be read.
3588 /* If we are forced to do a reconstruct-write, either because
3589 * the current RAID6 implementation only supports that, or
3590 * because parity cannot be trusted and we are currently
3591 * recovering it, there is extra need to be careful.
3592 * If one of the devices that we would need to read, because
3593 * it is not being overwritten (and maybe not written at all)
3594 * is missing/faulty, then we need to read everything we can.
3596 if (sh->raid_conf->level != 6 &&
3597 sh->raid_conf->rmw_level != PARITY_DISABLE_RMW &&
3598 sh->sector < sh->raid_conf->mddev->recovery_cp)
3599 /* reconstruct-write isn't being forced */
3601 for (i = 0; i < s->failed && i < 2; i++) {
3602 if (s->failed_num[i] != sh->pd_idx &&
3603 s->failed_num[i] != sh->qd_idx &&
3604 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3605 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3612 /* fetch_block - checks the given member device to see if its data needs
3613 * to be read or computed to satisfy a request.
3615 * Returns 1 when no more member devices need to be checked, otherwise returns
3616 * 0 to tell the loop in handle_stripe_fill to continue
3618 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3619 int disk_idx, int disks)
3621 struct r5dev *dev = &sh->dev[disk_idx];
3623 /* is the data in this block needed, and can we get it? */
3624 if (need_this_block(sh, s, disk_idx, disks)) {
3625 /* we would like to get this block, possibly by computing it,
3626 * otherwise read it if the backing disk is insync
3628 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3629 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3630 BUG_ON(sh->batch_head);
3633 * In the raid6 case if the only non-uptodate disk is P
3634 * then we already trusted P to compute the other failed
3635 * drives. It is safe to compute rather than re-read P.
3636 * In other cases we only compute blocks from failed
3637 * devices, otherwise check/repair might fail to detect
3638 * a real inconsistency.
3641 if ((s->uptodate == disks - 1) &&
3642 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3643 (s->failed && (disk_idx == s->failed_num[0] ||
3644 disk_idx == s->failed_num[1])))) {
3645 /* have disk failed, and we're requested to fetch it;
3648 pr_debug("Computing stripe %llu block %d\n",
3649 (unsigned long long)sh->sector, disk_idx);
3650 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3651 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3652 set_bit(R5_Wantcompute, &dev->flags);
3653 sh->ops.target = disk_idx;
3654 sh->ops.target2 = -1; /* no 2nd target */
3656 /* Careful: from this point on 'uptodate' is in the eye
3657 * of raid_run_ops which services 'compute' operations
3658 * before writes. R5_Wantcompute flags a block that will
3659 * be R5_UPTODATE by the time it is needed for a
3660 * subsequent operation.
3664 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3665 /* Computing 2-failure is *very* expensive; only
3666 * do it if failed >= 2
3669 for (other = disks; other--; ) {
3670 if (other == disk_idx)
3672 if (!test_bit(R5_UPTODATE,
3673 &sh->dev[other].flags))
3677 pr_debug("Computing stripe %llu blocks %d,%d\n",
3678 (unsigned long long)sh->sector,
3680 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3681 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3682 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3683 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3684 sh->ops.target = disk_idx;
3685 sh->ops.target2 = other;
3689 } else if (test_bit(R5_Insync, &dev->flags)) {
3690 set_bit(R5_LOCKED, &dev->flags);
3691 set_bit(R5_Wantread, &dev->flags);
3693 pr_debug("Reading block %d (sync=%d)\n",
3694 disk_idx, s->syncing);
3702 * handle_stripe_fill - read or compute data to satisfy pending requests.
3704 static void handle_stripe_fill(struct stripe_head *sh,
3705 struct stripe_head_state *s,
3710 /* look for blocks to read/compute, skip this if a compute
3711 * is already in flight, or if the stripe contents are in the
3712 * midst of changing due to a write
3714 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3715 !sh->reconstruct_state) {
3718 * For degraded stripe with data in journal, do not handle
3719 * read requests yet, instead, flush the stripe to raid
3720 * disks first, this avoids handling complex rmw of write
3721 * back cache (prexor with orig_page, and then xor with
3722 * page) in the read path
3724 if (s->to_read && s->injournal && s->failed) {
3725 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3726 r5c_make_stripe_write_out(sh);
3730 for (i = disks; i--; )
3731 if (fetch_block(sh, s, i, disks))
3735 set_bit(STRIPE_HANDLE, &sh->state);
3738 static void break_stripe_batch_list(struct stripe_head *head_sh,
3739 unsigned long handle_flags);
3740 /* handle_stripe_clean_event
3741 * any written block on an uptodate or failed drive can be returned.
3742 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3743 * never LOCKED, so we don't need to test 'failed' directly.
3745 static void handle_stripe_clean_event(struct r5conf *conf,
3746 struct stripe_head *sh, int disks)
3750 int discard_pending = 0;
3751 struct stripe_head *head_sh = sh;
3752 bool do_endio = false;
3754 for (i = disks; i--; )
3755 if (sh->dev[i].written) {
3757 if (!test_bit(R5_LOCKED, &dev->flags) &&
3758 (test_bit(R5_UPTODATE, &dev->flags) ||
3759 test_bit(R5_Discard, &dev->flags) ||
3760 test_bit(R5_SkipCopy, &dev->flags))) {
3761 /* We can return any write requests */
3762 struct bio *wbi, *wbi2;
3763 pr_debug("Return write for disc %d\n", i);
3764 if (test_and_clear_bit(R5_Discard, &dev->flags))
3765 clear_bit(R5_UPTODATE, &dev->flags);
3766 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3767 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3772 dev->page = dev->orig_page;
3774 dev->written = NULL;
3775 while (wbi && wbi->bi_iter.bi_sector <
3776 dev->sector + STRIPE_SECTORS) {
3777 wbi2 = r5_next_bio(wbi, dev->sector);
3778 md_write_end(conf->mddev);
3782 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3784 !test_bit(STRIPE_DEGRADED, &sh->state),
3786 if (head_sh->batch_head) {
3787 sh = list_first_entry(&sh->batch_list,
3790 if (sh != head_sh) {
3797 } else if (test_bit(R5_Discard, &dev->flags))
3798 discard_pending = 1;
3801 log_stripe_write_finished(sh);
3803 if (!discard_pending &&
3804 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3806 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3807 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3808 if (sh->qd_idx >= 0) {
3809 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3810 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3812 /* now that discard is done we can proceed with any sync */
3813 clear_bit(STRIPE_DISCARD, &sh->state);
3815 * SCSI discard will change some bio fields and the stripe has
3816 * no updated data, so remove it from hash list and the stripe
3817 * will be reinitialized
3820 hash = sh->hash_lock_index;
3821 spin_lock_irq(conf->hash_locks + hash);
3823 spin_unlock_irq(conf->hash_locks + hash);
3824 if (head_sh->batch_head) {
3825 sh = list_first_entry(&sh->batch_list,
3826 struct stripe_head, batch_list);
3832 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3833 set_bit(STRIPE_HANDLE, &sh->state);
3837 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3838 if (atomic_dec_and_test(&conf->pending_full_writes))
3839 md_wakeup_thread(conf->mddev->thread);
3841 if (head_sh->batch_head && do_endio)
3842 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3846 * For RMW in write back cache, we need extra page in prexor to store the
3847 * old data. This page is stored in dev->orig_page.
3849 * This function checks whether we have data for prexor. The exact logic
3851 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
3853 static inline bool uptodate_for_rmw(struct r5dev *dev)
3855 return (test_bit(R5_UPTODATE, &dev->flags)) &&
3856 (!test_bit(R5_InJournal, &dev->flags) ||
3857 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
3860 static int handle_stripe_dirtying(struct r5conf *conf,
3861 struct stripe_head *sh,
3862 struct stripe_head_state *s,
3865 int rmw = 0, rcw = 0, i;
3866 sector_t recovery_cp = conf->mddev->recovery_cp;
3868 /* Check whether resync is now happening or should start.
3869 * If yes, then the array is dirty (after unclean shutdown or
3870 * initial creation), so parity in some stripes might be inconsistent.
3871 * In this case, we need to always do reconstruct-write, to ensure
3872 * that in case of drive failure or read-error correction, we
3873 * generate correct data from the parity.
3875 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3876 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3878 /* Calculate the real rcw later - for now make it
3879 * look like rcw is cheaper
3882 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3883 conf->rmw_level, (unsigned long long)recovery_cp,
3884 (unsigned long long)sh->sector);
3885 } else for (i = disks; i--; ) {
3886 /* would I have to read this buffer for read_modify_write */
3887 struct r5dev *dev = &sh->dev[i];
3888 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3889 i == sh->pd_idx || i == sh->qd_idx ||
3890 test_bit(R5_InJournal, &dev->flags)) &&
3891 !test_bit(R5_LOCKED, &dev->flags) &&
3892 !(uptodate_for_rmw(dev) ||
3893 test_bit(R5_Wantcompute, &dev->flags))) {
3894 if (test_bit(R5_Insync, &dev->flags))
3897 rmw += 2*disks; /* cannot read it */
3899 /* Would I have to read this buffer for reconstruct_write */
3900 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3901 i != sh->pd_idx && i != sh->qd_idx &&
3902 !test_bit(R5_LOCKED, &dev->flags) &&
3903 !(test_bit(R5_UPTODATE, &dev->flags) ||
3904 test_bit(R5_Wantcompute, &dev->flags))) {
3905 if (test_bit(R5_Insync, &dev->flags))
3912 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
3913 (unsigned long long)sh->sector, sh->state, rmw, rcw);
3914 set_bit(STRIPE_HANDLE, &sh->state);
3915 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
3916 /* prefer read-modify-write, but need to get some data */
3917 if (conf->mddev->queue)
3918 blk_add_trace_msg(conf->mddev->queue,
3919 "raid5 rmw %llu %d",
3920 (unsigned long long)sh->sector, rmw);
3921 for (i = disks; i--; ) {
3922 struct r5dev *dev = &sh->dev[i];
3923 if (test_bit(R5_InJournal, &dev->flags) &&
3924 dev->page == dev->orig_page &&
3925 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
3926 /* alloc page for prexor */
3927 struct page *p = alloc_page(GFP_NOIO);
3935 * alloc_page() failed, try use
3936 * disk_info->extra_page
3938 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
3939 &conf->cache_state)) {
3940 r5c_use_extra_page(sh);
3944 /* extra_page in use, add to delayed_list */
3945 set_bit(STRIPE_DELAYED, &sh->state);
3946 s->waiting_extra_page = 1;
3951 for (i = disks; i--; ) {
3952 struct r5dev *dev = &sh->dev[i];
3953 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3954 i == sh->pd_idx || i == sh->qd_idx ||
3955 test_bit(R5_InJournal, &dev->flags)) &&
3956 !test_bit(R5_LOCKED, &dev->flags) &&
3957 !(uptodate_for_rmw(dev) ||
3958 test_bit(R5_Wantcompute, &dev->flags)) &&
3959 test_bit(R5_Insync, &dev->flags)) {
3960 if (test_bit(STRIPE_PREREAD_ACTIVE,
3962 pr_debug("Read_old block %d for r-m-w\n",
3964 set_bit(R5_LOCKED, &dev->flags);
3965 set_bit(R5_Wantread, &dev->flags);
3968 set_bit(STRIPE_DELAYED, &sh->state);
3969 set_bit(STRIPE_HANDLE, &sh->state);
3974 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
3975 /* want reconstruct write, but need to get some data */
3978 for (i = disks; i--; ) {
3979 struct r5dev *dev = &sh->dev[i];
3980 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3981 i != sh->pd_idx && i != sh->qd_idx &&
3982 !test_bit(R5_LOCKED, &dev->flags) &&
3983 !(test_bit(R5_UPTODATE, &dev->flags) ||
3984 test_bit(R5_Wantcompute, &dev->flags))) {
3986 if (test_bit(R5_Insync, &dev->flags) &&
3987 test_bit(STRIPE_PREREAD_ACTIVE,
3989 pr_debug("Read_old block "
3990 "%d for Reconstruct\n", i);
3991 set_bit(R5_LOCKED, &dev->flags);
3992 set_bit(R5_Wantread, &dev->flags);
3996 set_bit(STRIPE_DELAYED, &sh->state);
3997 set_bit(STRIPE_HANDLE, &sh->state);
4001 if (rcw && conf->mddev->queue)
4002 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4003 (unsigned long long)sh->sector,
4004 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4007 if (rcw > disks && rmw > disks &&
4008 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4009 set_bit(STRIPE_DELAYED, &sh->state);
4011 /* now if nothing is locked, and if we have enough data,
4012 * we can start a write request
4014 /* since handle_stripe can be called at any time we need to handle the
4015 * case where a compute block operation has been submitted and then a
4016 * subsequent call wants to start a write request. raid_run_ops only
4017 * handles the case where compute block and reconstruct are requested
4018 * simultaneously. If this is not the case then new writes need to be
4019 * held off until the compute completes.
4021 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4022 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4023 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4024 schedule_reconstruction(sh, s, rcw == 0, 0);
4028 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4029 struct stripe_head_state *s, int disks)
4031 struct r5dev *dev = NULL;
4033 BUG_ON(sh->batch_head);
4034 set_bit(STRIPE_HANDLE, &sh->state);
4036 switch (sh->check_state) {
4037 case check_state_idle:
4038 /* start a new check operation if there are no failures */
4039 if (s->failed == 0) {
4040 BUG_ON(s->uptodate != disks);
4041 sh->check_state = check_state_run;
4042 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4043 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4047 dev = &sh->dev[s->failed_num[0]];
4049 case check_state_compute_result:
4050 sh->check_state = check_state_idle;
4052 dev = &sh->dev[sh->pd_idx];
4054 /* check that a write has not made the stripe insync */
4055 if (test_bit(STRIPE_INSYNC, &sh->state))
4058 /* either failed parity check, or recovery is happening */
4059 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4060 BUG_ON(s->uptodate != disks);
4062 set_bit(R5_LOCKED, &dev->flags);
4064 set_bit(R5_Wantwrite, &dev->flags);
4066 clear_bit(STRIPE_DEGRADED, &sh->state);
4067 set_bit(STRIPE_INSYNC, &sh->state);
4069 case check_state_run:
4070 break; /* we will be called again upon completion */
4071 case check_state_check_result:
4072 sh->check_state = check_state_idle;
4074 /* if a failure occurred during the check operation, leave
4075 * STRIPE_INSYNC not set and let the stripe be handled again
4080 /* handle a successful check operation, if parity is correct
4081 * we are done. Otherwise update the mismatch count and repair
4082 * parity if !MD_RECOVERY_CHECK
4084 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4085 /* parity is correct (on disc,
4086 * not in buffer any more)
4088 set_bit(STRIPE_INSYNC, &sh->state);
4090 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4091 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4092 /* don't try to repair!! */
4093 set_bit(STRIPE_INSYNC, &sh->state);
4094 pr_warn_ratelimited("%s: mismatch sector in range "
4095 "%llu-%llu\n", mdname(conf->mddev),
4096 (unsigned long long) sh->sector,
4097 (unsigned long long) sh->sector +
4100 sh->check_state = check_state_compute_run;
4101 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4102 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4103 set_bit(R5_Wantcompute,
4104 &sh->dev[sh->pd_idx].flags);
4105 sh->ops.target = sh->pd_idx;
4106 sh->ops.target2 = -1;
4111 case check_state_compute_run:
4114 pr_err("%s: unknown check_state: %d sector: %llu\n",
4115 __func__, sh->check_state,
4116 (unsigned long long) sh->sector);
4121 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4122 struct stripe_head_state *s,
4125 int pd_idx = sh->pd_idx;
4126 int qd_idx = sh->qd_idx;
4129 BUG_ON(sh->batch_head);
4130 set_bit(STRIPE_HANDLE, &sh->state);
4132 BUG_ON(s->failed > 2);
4134 /* Want to check and possibly repair P and Q.
4135 * However there could be one 'failed' device, in which
4136 * case we can only check one of them, possibly using the
4137 * other to generate missing data
4140 switch (sh->check_state) {
4141 case check_state_idle:
4142 /* start a new check operation if there are < 2 failures */
4143 if (s->failed == s->q_failed) {
4144 /* The only possible failed device holds Q, so it
4145 * makes sense to check P (If anything else were failed,
4146 * we would have used P to recreate it).
4148 sh->check_state = check_state_run;
4150 if (!s->q_failed && s->failed < 2) {
4151 /* Q is not failed, and we didn't use it to generate
4152 * anything, so it makes sense to check it
4154 if (sh->check_state == check_state_run)
4155 sh->check_state = check_state_run_pq;
4157 sh->check_state = check_state_run_q;
4160 /* discard potentially stale zero_sum_result */
4161 sh->ops.zero_sum_result = 0;
4163 if (sh->check_state == check_state_run) {
4164 /* async_xor_zero_sum destroys the contents of P */
4165 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4168 if (sh->check_state >= check_state_run &&
4169 sh->check_state <= check_state_run_pq) {
4170 /* async_syndrome_zero_sum preserves P and Q, so
4171 * no need to mark them !uptodate here
4173 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4177 /* we have 2-disk failure */
4178 BUG_ON(s->failed != 2);
4180 case check_state_compute_result:
4181 sh->check_state = check_state_idle;
4183 /* check that a write has not made the stripe insync */
4184 if (test_bit(STRIPE_INSYNC, &sh->state))
4187 /* now write out any block on a failed drive,
4188 * or P or Q if they were recomputed
4191 if (s->failed == 2) {
4192 dev = &sh->dev[s->failed_num[1]];
4194 set_bit(R5_LOCKED, &dev->flags);
4195 set_bit(R5_Wantwrite, &dev->flags);
4197 if (s->failed >= 1) {
4198 dev = &sh->dev[s->failed_num[0]];
4200 set_bit(R5_LOCKED, &dev->flags);
4201 set_bit(R5_Wantwrite, &dev->flags);
4203 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4204 dev = &sh->dev[pd_idx];
4206 set_bit(R5_LOCKED, &dev->flags);
4207 set_bit(R5_Wantwrite, &dev->flags);
4209 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4210 dev = &sh->dev[qd_idx];
4212 set_bit(R5_LOCKED, &dev->flags);
4213 set_bit(R5_Wantwrite, &dev->flags);
4215 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4216 "%s: disk%td not up to date\n",
4217 mdname(conf->mddev),
4218 dev - (struct r5dev *) &sh->dev)) {
4219 clear_bit(R5_LOCKED, &dev->flags);
4220 clear_bit(R5_Wantwrite, &dev->flags);
4223 clear_bit(STRIPE_DEGRADED, &sh->state);
4225 set_bit(STRIPE_INSYNC, &sh->state);
4227 case check_state_run:
4228 case check_state_run_q:
4229 case check_state_run_pq:
4230 break; /* we will be called again upon completion */
4231 case check_state_check_result:
4232 sh->check_state = check_state_idle;
4234 /* handle a successful check operation, if parity is correct
4235 * we are done. Otherwise update the mismatch count and repair
4236 * parity if !MD_RECOVERY_CHECK
4238 if (sh->ops.zero_sum_result == 0) {
4239 /* both parities are correct */
4241 set_bit(STRIPE_INSYNC, &sh->state);
4243 /* in contrast to the raid5 case we can validate
4244 * parity, but still have a failure to write
4247 sh->check_state = check_state_compute_result;
4248 /* Returning at this point means that we may go
4249 * off and bring p and/or q uptodate again so
4250 * we make sure to check zero_sum_result again
4251 * to verify if p or q need writeback
4255 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4256 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4257 /* don't try to repair!! */
4258 set_bit(STRIPE_INSYNC, &sh->state);
4259 pr_warn_ratelimited("%s: mismatch sector in range "
4260 "%llu-%llu\n", mdname(conf->mddev),
4261 (unsigned long long) sh->sector,
4262 (unsigned long long) sh->sector +
4265 int *target = &sh->ops.target;
4267 sh->ops.target = -1;
4268 sh->ops.target2 = -1;
4269 sh->check_state = check_state_compute_run;
4270 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4271 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4272 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4273 set_bit(R5_Wantcompute,
4274 &sh->dev[pd_idx].flags);
4276 target = &sh->ops.target2;
4279 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4280 set_bit(R5_Wantcompute,
4281 &sh->dev[qd_idx].flags);
4288 case check_state_compute_run:
4291 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4292 __func__, sh->check_state,
4293 (unsigned long long) sh->sector);
4298 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4302 /* We have read all the blocks in this stripe and now we need to
4303 * copy some of them into a target stripe for expand.
4305 struct dma_async_tx_descriptor *tx = NULL;
4306 BUG_ON(sh->batch_head);
4307 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4308 for (i = 0; i < sh->disks; i++)
4309 if (i != sh->pd_idx && i != sh->qd_idx) {
4311 struct stripe_head *sh2;
4312 struct async_submit_ctl submit;
4314 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4315 sector_t s = raid5_compute_sector(conf, bn, 0,
4317 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4319 /* so far only the early blocks of this stripe
4320 * have been requested. When later blocks
4321 * get requested, we will try again
4324 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4325 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4326 /* must have already done this block */
4327 raid5_release_stripe(sh2);
4331 /* place all the copies on one channel */
4332 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4333 tx = async_memcpy(sh2->dev[dd_idx].page,
4334 sh->dev[i].page, 0, 0, STRIPE_SIZE,
4337 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4338 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4339 for (j = 0; j < conf->raid_disks; j++)
4340 if (j != sh2->pd_idx &&
4342 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4344 if (j == conf->raid_disks) {
4345 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4346 set_bit(STRIPE_HANDLE, &sh2->state);
4348 raid5_release_stripe(sh2);
4351 /* done submitting copies, wait for them to complete */
4352 async_tx_quiesce(&tx);
4356 * handle_stripe - do things to a stripe.
4358 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4359 * state of various bits to see what needs to be done.
4361 * return some read requests which now have data
4362 * return some write requests which are safely on storage
4363 * schedule a read on some buffers
4364 * schedule a write of some buffers
4365 * return confirmation of parity correctness
4369 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4371 struct r5conf *conf = sh->raid_conf;
4372 int disks = sh->disks;
4375 int do_recovery = 0;
4377 memset(s, 0, sizeof(*s));
4379 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4380 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4381 s->failed_num[0] = -1;
4382 s->failed_num[1] = -1;
4383 s->log_failed = r5l_log_disk_error(conf);
4385 /* Now to look around and see what can be done */
4387 for (i=disks; i--; ) {
4388 struct md_rdev *rdev;
4395 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4397 dev->toread, dev->towrite, dev->written);
4398 /* maybe we can reply to a read
4400 * new wantfill requests are only permitted while
4401 * ops_complete_biofill is guaranteed to be inactive
4403 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4404 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4405 set_bit(R5_Wantfill, &dev->flags);
4407 /* now count some things */
4408 if (test_bit(R5_LOCKED, &dev->flags))
4410 if (test_bit(R5_UPTODATE, &dev->flags))
4412 if (test_bit(R5_Wantcompute, &dev->flags)) {
4414 BUG_ON(s->compute > 2);
4417 if (test_bit(R5_Wantfill, &dev->flags))
4419 else if (dev->toread)
4423 if (!test_bit(R5_OVERWRITE, &dev->flags))
4428 /* Prefer to use the replacement for reads, but only
4429 * if it is recovered enough and has no bad blocks.
4431 rdev = rcu_dereference(conf->disks[i].replacement);
4432 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4433 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4434 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4435 &first_bad, &bad_sectors))
4436 set_bit(R5_ReadRepl, &dev->flags);
4438 if (rdev && !test_bit(Faulty, &rdev->flags))
4439 set_bit(R5_NeedReplace, &dev->flags);
4441 clear_bit(R5_NeedReplace, &dev->flags);
4442 rdev = rcu_dereference(conf->disks[i].rdev);
4443 clear_bit(R5_ReadRepl, &dev->flags);
4445 if (rdev && test_bit(Faulty, &rdev->flags))
4448 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4449 &first_bad, &bad_sectors);
4450 if (s->blocked_rdev == NULL
4451 && (test_bit(Blocked, &rdev->flags)
4454 set_bit(BlockedBadBlocks,
4456 s->blocked_rdev = rdev;
4457 atomic_inc(&rdev->nr_pending);
4460 clear_bit(R5_Insync, &dev->flags);
4464 /* also not in-sync */
4465 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4466 test_bit(R5_UPTODATE, &dev->flags)) {
4467 /* treat as in-sync, but with a read error
4468 * which we can now try to correct
4470 set_bit(R5_Insync, &dev->flags);
4471 set_bit(R5_ReadError, &dev->flags);
4473 } else if (test_bit(In_sync, &rdev->flags))
4474 set_bit(R5_Insync, &dev->flags);
4475 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4476 /* in sync if before recovery_offset */
4477 set_bit(R5_Insync, &dev->flags);
4478 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4479 test_bit(R5_Expanded, &dev->flags))
4480 /* If we've reshaped into here, we assume it is Insync.
4481 * We will shortly update recovery_offset to make
4484 set_bit(R5_Insync, &dev->flags);
4486 if (test_bit(R5_WriteError, &dev->flags)) {
4487 /* This flag does not apply to '.replacement'
4488 * only to .rdev, so make sure to check that*/
4489 struct md_rdev *rdev2 = rcu_dereference(
4490 conf->disks[i].rdev);
4492 clear_bit(R5_Insync, &dev->flags);
4493 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4494 s->handle_bad_blocks = 1;
4495 atomic_inc(&rdev2->nr_pending);
4497 clear_bit(R5_WriteError, &dev->flags);
4499 if (test_bit(R5_MadeGood, &dev->flags)) {
4500 /* This flag does not apply to '.replacement'
4501 * only to .rdev, so make sure to check that*/
4502 struct md_rdev *rdev2 = rcu_dereference(
4503 conf->disks[i].rdev);
4504 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4505 s->handle_bad_blocks = 1;
4506 atomic_inc(&rdev2->nr_pending);
4508 clear_bit(R5_MadeGood, &dev->flags);
4510 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4511 struct md_rdev *rdev2 = rcu_dereference(
4512 conf->disks[i].replacement);
4513 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4514 s->handle_bad_blocks = 1;
4515 atomic_inc(&rdev2->nr_pending);
4517 clear_bit(R5_MadeGoodRepl, &dev->flags);
4519 if (!test_bit(R5_Insync, &dev->flags)) {
4520 /* The ReadError flag will just be confusing now */
4521 clear_bit(R5_ReadError, &dev->flags);
4522 clear_bit(R5_ReWrite, &dev->flags);
4524 if (test_bit(R5_ReadError, &dev->flags))
4525 clear_bit(R5_Insync, &dev->flags);
4526 if (!test_bit(R5_Insync, &dev->flags)) {
4528 s->failed_num[s->failed] = i;
4530 if (rdev && !test_bit(Faulty, &rdev->flags))
4533 rdev = rcu_dereference(
4534 conf->disks[i].replacement);
4535 if (rdev && !test_bit(Faulty, &rdev->flags))
4540 if (test_bit(R5_InJournal, &dev->flags))
4542 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4545 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4546 /* If there is a failed device being replaced,
4547 * we must be recovering.
4548 * else if we are after recovery_cp, we must be syncing
4549 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4550 * else we can only be replacing
4551 * sync and recovery both need to read all devices, and so
4552 * use the same flag.
4555 sh->sector >= conf->mddev->recovery_cp ||
4556 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4564 static int clear_batch_ready(struct stripe_head *sh)
4566 /* Return '1' if this is a member of batch, or
4567 * '0' if it is a lone stripe or a head which can now be
4570 struct stripe_head *tmp;
4571 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4572 return (sh->batch_head && sh->batch_head != sh);
4573 spin_lock(&sh->stripe_lock);
4574 if (!sh->batch_head) {
4575 spin_unlock(&sh->stripe_lock);
4580 * this stripe could be added to a batch list before we check
4581 * BATCH_READY, skips it
4583 if (sh->batch_head != sh) {
4584 spin_unlock(&sh->stripe_lock);
4587 spin_lock(&sh->batch_lock);
4588 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4589 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4590 spin_unlock(&sh->batch_lock);
4591 spin_unlock(&sh->stripe_lock);
4594 * BATCH_READY is cleared, no new stripes can be added.
4595 * batch_list can be accessed without lock
4600 static void break_stripe_batch_list(struct stripe_head *head_sh,
4601 unsigned long handle_flags)
4603 struct stripe_head *sh, *next;
4607 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4609 list_del_init(&sh->batch_list);
4611 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4612 (1 << STRIPE_SYNCING) |
4613 (1 << STRIPE_REPLACED) |
4614 (1 << STRIPE_DELAYED) |
4615 (1 << STRIPE_BIT_DELAY) |
4616 (1 << STRIPE_FULL_WRITE) |
4617 (1 << STRIPE_BIOFILL_RUN) |
4618 (1 << STRIPE_COMPUTE_RUN) |
4619 (1 << STRIPE_OPS_REQ_PENDING) |
4620 (1 << STRIPE_DISCARD) |
4621 (1 << STRIPE_BATCH_READY) |
4622 (1 << STRIPE_BATCH_ERR) |
4623 (1 << STRIPE_BITMAP_PENDING)),
4624 "stripe state: %lx\n", sh->state);
4625 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4626 (1 << STRIPE_REPLACED)),
4627 "head stripe state: %lx\n", head_sh->state);
4629 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4630 (1 << STRIPE_PREREAD_ACTIVE) |
4631 (1 << STRIPE_DEGRADED) |
4632 (1 << STRIPE_ON_UNPLUG_LIST)),
4633 head_sh->state & (1 << STRIPE_INSYNC));
4635 sh->check_state = head_sh->check_state;
4636 sh->reconstruct_state = head_sh->reconstruct_state;
4637 for (i = 0; i < sh->disks; i++) {
4638 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4640 sh->dev[i].flags = head_sh->dev[i].flags &
4641 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4643 spin_lock_irq(&sh->stripe_lock);
4644 sh->batch_head = NULL;
4645 spin_unlock_irq(&sh->stripe_lock);
4646 if (handle_flags == 0 ||
4647 sh->state & handle_flags)
4648 set_bit(STRIPE_HANDLE, &sh->state);
4649 raid5_release_stripe(sh);
4651 spin_lock_irq(&head_sh->stripe_lock);
4652 head_sh->batch_head = NULL;
4653 spin_unlock_irq(&head_sh->stripe_lock);
4654 for (i = 0; i < head_sh->disks; i++)
4655 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4657 if (head_sh->state & handle_flags)
4658 set_bit(STRIPE_HANDLE, &head_sh->state);
4661 wake_up(&head_sh->raid_conf->wait_for_overlap);
4664 static void handle_stripe(struct stripe_head *sh)
4666 struct stripe_head_state s;
4667 struct r5conf *conf = sh->raid_conf;
4670 int disks = sh->disks;
4671 struct r5dev *pdev, *qdev;
4673 clear_bit(STRIPE_HANDLE, &sh->state);
4674 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4675 /* already being handled, ensure it gets handled
4676 * again when current action finishes */
4677 set_bit(STRIPE_HANDLE, &sh->state);
4681 if (clear_batch_ready(sh) ) {
4682 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4686 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4687 break_stripe_batch_list(sh, 0);
4689 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4690 spin_lock(&sh->stripe_lock);
4692 * Cannot process 'sync' concurrently with 'discard'.
4693 * Flush data in r5cache before 'sync'.
4695 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4696 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4697 !test_bit(STRIPE_DISCARD, &sh->state) &&
4698 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4699 set_bit(STRIPE_SYNCING, &sh->state);
4700 clear_bit(STRIPE_INSYNC, &sh->state);
4701 clear_bit(STRIPE_REPLACED, &sh->state);
4703 spin_unlock(&sh->stripe_lock);
4705 clear_bit(STRIPE_DELAYED, &sh->state);
4707 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4708 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4709 (unsigned long long)sh->sector, sh->state,
4710 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4711 sh->check_state, sh->reconstruct_state);
4713 analyse_stripe(sh, &s);
4715 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4718 if (s.handle_bad_blocks ||
4719 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4720 set_bit(STRIPE_HANDLE, &sh->state);
4724 if (unlikely(s.blocked_rdev)) {
4725 if (s.syncing || s.expanding || s.expanded ||
4726 s.replacing || s.to_write || s.written) {
4727 set_bit(STRIPE_HANDLE, &sh->state);
4730 /* There is nothing for the blocked_rdev to block */
4731 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4732 s.blocked_rdev = NULL;
4735 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4736 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4737 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4740 pr_debug("locked=%d uptodate=%d to_read=%d"
4741 " to_write=%d failed=%d failed_num=%d,%d\n",
4742 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4743 s.failed_num[0], s.failed_num[1]);
4745 * check if the array has lost more than max_degraded devices and,
4746 * if so, some requests might need to be failed.
4748 * When journal device failed (log_failed), we will only process
4749 * the stripe if there is data need write to raid disks
4751 if (s.failed > conf->max_degraded ||
4752 (s.log_failed && s.injournal == 0)) {
4753 sh->check_state = 0;
4754 sh->reconstruct_state = 0;
4755 break_stripe_batch_list(sh, 0);
4756 if (s.to_read+s.to_write+s.written)
4757 handle_failed_stripe(conf, sh, &s, disks);
4758 if (s.syncing + s.replacing)
4759 handle_failed_sync(conf, sh, &s);
4762 /* Now we check to see if any write operations have recently
4766 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4768 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4769 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4770 sh->reconstruct_state = reconstruct_state_idle;
4772 /* All the 'written' buffers and the parity block are ready to
4773 * be written back to disk
4775 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4776 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4777 BUG_ON(sh->qd_idx >= 0 &&
4778 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4779 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4780 for (i = disks; i--; ) {
4781 struct r5dev *dev = &sh->dev[i];
4782 if (test_bit(R5_LOCKED, &dev->flags) &&
4783 (i == sh->pd_idx || i == sh->qd_idx ||
4784 dev->written || test_bit(R5_InJournal,
4786 pr_debug("Writing block %d\n", i);
4787 set_bit(R5_Wantwrite, &dev->flags);
4792 if (!test_bit(R5_Insync, &dev->flags) ||
4793 ((i == sh->pd_idx || i == sh->qd_idx) &&
4795 set_bit(STRIPE_INSYNC, &sh->state);
4798 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4799 s.dec_preread_active = 1;
4803 * might be able to return some write requests if the parity blocks
4804 * are safe, or on a failed drive
4806 pdev = &sh->dev[sh->pd_idx];
4807 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4808 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4809 qdev = &sh->dev[sh->qd_idx];
4810 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4811 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4815 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4816 && !test_bit(R5_LOCKED, &pdev->flags)
4817 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4818 test_bit(R5_Discard, &pdev->flags))))) &&
4819 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4820 && !test_bit(R5_LOCKED, &qdev->flags)
4821 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4822 test_bit(R5_Discard, &qdev->flags))))))
4823 handle_stripe_clean_event(conf, sh, disks);
4826 r5c_handle_cached_data_endio(conf, sh, disks);
4827 log_stripe_write_finished(sh);
4829 /* Now we might consider reading some blocks, either to check/generate
4830 * parity, or to satisfy requests
4831 * or to load a block that is being partially written.
4833 if (s.to_read || s.non_overwrite
4834 || (s.to_write && s.failed)
4835 || (s.syncing && (s.uptodate + s.compute < disks))
4838 handle_stripe_fill(sh, &s, disks);
4841 * When the stripe finishes full journal write cycle (write to journal
4842 * and raid disk), this is the clean up procedure so it is ready for
4845 r5c_finish_stripe_write_out(conf, sh, &s);
4848 * Now to consider new write requests, cache write back and what else,
4849 * if anything should be read. We do not handle new writes when:
4850 * 1/ A 'write' operation (copy+xor) is already in flight.
4851 * 2/ A 'check' operation is in flight, as it may clobber the parity
4853 * 3/ A r5c cache log write is in flight.
4856 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
4857 if (!r5c_is_writeback(conf->log)) {
4859 handle_stripe_dirtying(conf, sh, &s, disks);
4860 } else { /* write back cache */
4863 /* First, try handle writes in caching phase */
4865 ret = r5c_try_caching_write(conf, sh, &s,
4868 * If caching phase failed: ret == -EAGAIN
4870 * stripe under reclaim: !caching && injournal
4872 * fall back to handle_stripe_dirtying()
4874 if (ret == -EAGAIN ||
4875 /* stripe under reclaim: !caching && injournal */
4876 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
4878 ret = handle_stripe_dirtying(conf, sh, &s,
4886 /* maybe we need to check and possibly fix the parity for this stripe
4887 * Any reads will already have been scheduled, so we just see if enough
4888 * data is available. The parity check is held off while parity
4889 * dependent operations are in flight.
4891 if (sh->check_state ||
4892 (s.syncing && s.locked == 0 &&
4893 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4894 !test_bit(STRIPE_INSYNC, &sh->state))) {
4895 if (conf->level == 6)
4896 handle_parity_checks6(conf, sh, &s, disks);
4898 handle_parity_checks5(conf, sh, &s, disks);
4901 if ((s.replacing || s.syncing) && s.locked == 0
4902 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4903 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4904 /* Write out to replacement devices where possible */
4905 for (i = 0; i < conf->raid_disks; i++)
4906 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4907 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4908 set_bit(R5_WantReplace, &sh->dev[i].flags);
4909 set_bit(R5_LOCKED, &sh->dev[i].flags);
4913 set_bit(STRIPE_INSYNC, &sh->state);
4914 set_bit(STRIPE_REPLACED, &sh->state);
4916 if ((s.syncing || s.replacing) && s.locked == 0 &&
4917 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4918 test_bit(STRIPE_INSYNC, &sh->state)) {
4919 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4920 clear_bit(STRIPE_SYNCING, &sh->state);
4921 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4922 wake_up(&conf->wait_for_overlap);
4925 /* If the failed drives are just a ReadError, then we might need
4926 * to progress the repair/check process
4928 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4929 for (i = 0; i < s.failed; i++) {
4930 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4931 if (test_bit(R5_ReadError, &dev->flags)
4932 && !test_bit(R5_LOCKED, &dev->flags)
4933 && test_bit(R5_UPTODATE, &dev->flags)
4935 if (!test_bit(R5_ReWrite, &dev->flags)) {
4936 set_bit(R5_Wantwrite, &dev->flags);
4937 set_bit(R5_ReWrite, &dev->flags);
4938 set_bit(R5_LOCKED, &dev->flags);
4941 /* let's read it back */
4942 set_bit(R5_Wantread, &dev->flags);
4943 set_bit(R5_LOCKED, &dev->flags);
4949 /* Finish reconstruct operations initiated by the expansion process */
4950 if (sh->reconstruct_state == reconstruct_state_result) {
4951 struct stripe_head *sh_src
4952 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4953 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4954 /* sh cannot be written until sh_src has been read.
4955 * so arrange for sh to be delayed a little
4957 set_bit(STRIPE_DELAYED, &sh->state);
4958 set_bit(STRIPE_HANDLE, &sh->state);
4959 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4961 atomic_inc(&conf->preread_active_stripes);
4962 raid5_release_stripe(sh_src);
4966 raid5_release_stripe(sh_src);
4968 sh->reconstruct_state = reconstruct_state_idle;
4969 clear_bit(STRIPE_EXPANDING, &sh->state);
4970 for (i = conf->raid_disks; i--; ) {
4971 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4972 set_bit(R5_LOCKED, &sh->dev[i].flags);
4977 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4978 !sh->reconstruct_state) {
4979 /* Need to write out all blocks after computing parity */
4980 sh->disks = conf->raid_disks;
4981 stripe_set_idx(sh->sector, conf, 0, sh);
4982 schedule_reconstruction(sh, &s, 1, 1);
4983 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4984 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4985 atomic_dec(&conf->reshape_stripes);
4986 wake_up(&conf->wait_for_overlap);
4987 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4990 if (s.expanding && s.locked == 0 &&
4991 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4992 handle_stripe_expansion(conf, sh);
4995 /* wait for this device to become unblocked */
4996 if (unlikely(s.blocked_rdev)) {
4997 if (conf->mddev->external)
4998 md_wait_for_blocked_rdev(s.blocked_rdev,
5001 /* Internal metadata will immediately
5002 * be written by raid5d, so we don't
5003 * need to wait here.
5005 rdev_dec_pending(s.blocked_rdev,
5009 if (s.handle_bad_blocks)
5010 for (i = disks; i--; ) {
5011 struct md_rdev *rdev;
5012 struct r5dev *dev = &sh->dev[i];
5013 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5014 /* We own a safe reference to the rdev */
5015 rdev = conf->disks[i].rdev;
5016 if (!rdev_set_badblocks(rdev, sh->sector,
5018 md_error(conf->mddev, rdev);
5019 rdev_dec_pending(rdev, conf->mddev);
5021 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5022 rdev = conf->disks[i].rdev;
5023 rdev_clear_badblocks(rdev, sh->sector,
5025 rdev_dec_pending(rdev, conf->mddev);
5027 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5028 rdev = conf->disks[i].replacement;
5030 /* rdev have been moved down */
5031 rdev = conf->disks[i].rdev;
5032 rdev_clear_badblocks(rdev, sh->sector,
5034 rdev_dec_pending(rdev, conf->mddev);
5039 raid_run_ops(sh, s.ops_request);
5043 if (s.dec_preread_active) {
5044 /* We delay this until after ops_run_io so that if make_request
5045 * is waiting on a flush, it won't continue until the writes
5046 * have actually been submitted.
5048 atomic_dec(&conf->preread_active_stripes);
5049 if (atomic_read(&conf->preread_active_stripes) <
5051 md_wakeup_thread(conf->mddev->thread);
5054 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5057 static void raid5_activate_delayed(struct r5conf *conf)
5059 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5060 while (!list_empty(&conf->delayed_list)) {
5061 struct list_head *l = conf->delayed_list.next;
5062 struct stripe_head *sh;
5063 sh = list_entry(l, struct stripe_head, lru);
5065 clear_bit(STRIPE_DELAYED, &sh->state);
5066 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5067 atomic_inc(&conf->preread_active_stripes);
5068 list_add_tail(&sh->lru, &conf->hold_list);
5069 raid5_wakeup_stripe_thread(sh);
5074 static void activate_bit_delay(struct r5conf *conf,
5075 struct list_head *temp_inactive_list)
5077 /* device_lock is held */
5078 struct list_head head;
5079 list_add(&head, &conf->bitmap_list);
5080 list_del_init(&conf->bitmap_list);
5081 while (!list_empty(&head)) {
5082 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5084 list_del_init(&sh->lru);
5085 atomic_inc(&sh->count);
5086 hash = sh->hash_lock_index;
5087 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5091 static int raid5_congested(struct mddev *mddev, int bits)
5093 struct r5conf *conf = mddev->private;
5095 /* No difference between reads and writes. Just check
5096 * how busy the stripe_cache is
5099 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
5102 /* Also checks whether there is pressure on r5cache log space */
5103 if (test_bit(R5C_LOG_TIGHT, &conf->cache_state))
5107 if (atomic_read(&conf->empty_inactive_list_nr))
5113 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5115 struct r5conf *conf = mddev->private;
5116 sector_t sector = bio->bi_iter.bi_sector;
5117 unsigned int chunk_sectors;
5118 unsigned int bio_sectors = bio_sectors(bio);
5120 WARN_ON_ONCE(bio->bi_partno);
5122 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5123 return chunk_sectors >=
5124 ((sector & (chunk_sectors - 1)) + bio_sectors);
5128 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5129 * later sampled by raid5d.
5131 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5133 unsigned long flags;
5135 spin_lock_irqsave(&conf->device_lock, flags);
5137 bi->bi_next = conf->retry_read_aligned_list;
5138 conf->retry_read_aligned_list = bi;
5140 spin_unlock_irqrestore(&conf->device_lock, flags);
5141 md_wakeup_thread(conf->mddev->thread);
5144 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5145 unsigned int *offset)
5149 bi = conf->retry_read_aligned;
5151 *offset = conf->retry_read_offset;
5152 conf->retry_read_aligned = NULL;
5155 bi = conf->retry_read_aligned_list;
5157 conf->retry_read_aligned_list = bi->bi_next;
5166 * The "raid5_align_endio" should check if the read succeeded and if it
5167 * did, call bio_endio on the original bio (having bio_put the new bio
5169 * If the read failed..
5171 static void raid5_align_endio(struct bio *bi)
5173 struct bio* raid_bi = bi->bi_private;
5174 struct mddev *mddev;
5175 struct r5conf *conf;
5176 struct md_rdev *rdev;
5177 blk_status_t error = bi->bi_status;
5181 rdev = (void*)raid_bi->bi_next;
5182 raid_bi->bi_next = NULL;
5183 mddev = rdev->mddev;
5184 conf = mddev->private;
5186 rdev_dec_pending(rdev, conf->mddev);
5190 if (atomic_dec_and_test(&conf->active_aligned_reads))
5191 wake_up(&conf->wait_for_quiescent);
5195 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5197 add_bio_to_retry(raid_bi, conf);
5200 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5202 struct r5conf *conf = mddev->private;
5204 struct bio* align_bi;
5205 struct md_rdev *rdev;
5206 sector_t end_sector;
5208 if (!in_chunk_boundary(mddev, raid_bio)) {
5209 pr_debug("%s: non aligned\n", __func__);
5213 * use bio_clone_fast to make a copy of the bio
5215 align_bi = bio_clone_fast(raid_bio, GFP_NOIO, mddev->bio_set);
5219 * set bi_end_io to a new function, and set bi_private to the
5222 align_bi->bi_end_io = raid5_align_endio;
5223 align_bi->bi_private = raid_bio;
5227 align_bi->bi_iter.bi_sector =
5228 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5231 end_sector = bio_end_sector(align_bi);
5233 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5234 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5235 rdev->recovery_offset < end_sector) {
5236 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5238 (test_bit(Faulty, &rdev->flags) ||
5239 !(test_bit(In_sync, &rdev->flags) ||
5240 rdev->recovery_offset >= end_sector)))
5244 if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5254 atomic_inc(&rdev->nr_pending);
5256 raid_bio->bi_next = (void*)rdev;
5257 bio_set_dev(align_bi, rdev->bdev);
5258 bio_clear_flag(align_bi, BIO_SEG_VALID);
5260 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5261 bio_sectors(align_bi),
5262 &first_bad, &bad_sectors)) {
5264 rdev_dec_pending(rdev, mddev);
5268 /* No reshape active, so we can trust rdev->data_offset */
5269 align_bi->bi_iter.bi_sector += rdev->data_offset;
5271 spin_lock_irq(&conf->device_lock);
5272 wait_event_lock_irq(conf->wait_for_quiescent,
5275 atomic_inc(&conf->active_aligned_reads);
5276 spin_unlock_irq(&conf->device_lock);
5279 trace_block_bio_remap(align_bi->bi_disk->queue,
5280 align_bi, disk_devt(mddev->gendisk),
5281 raid_bio->bi_iter.bi_sector);
5282 generic_make_request(align_bi);
5291 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5294 sector_t sector = raid_bio->bi_iter.bi_sector;
5295 unsigned chunk_sects = mddev->chunk_sectors;
5296 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5298 if (sectors < bio_sectors(raid_bio)) {
5299 struct r5conf *conf = mddev->private;
5300 split = bio_split(raid_bio, sectors, GFP_NOIO, conf->bio_split);
5301 bio_chain(split, raid_bio);
5302 generic_make_request(raid_bio);
5306 if (!raid5_read_one_chunk(mddev, raid_bio))
5312 /* __get_priority_stripe - get the next stripe to process
5314 * Full stripe writes are allowed to pass preread active stripes up until
5315 * the bypass_threshold is exceeded. In general the bypass_count
5316 * increments when the handle_list is handled before the hold_list; however, it
5317 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5318 * stripe with in flight i/o. The bypass_count will be reset when the
5319 * head of the hold_list has changed, i.e. the head was promoted to the
5322 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5324 struct stripe_head *sh, *tmp;
5325 struct list_head *handle_list = NULL;
5326 struct r5worker_group *wg;
5327 bool second_try = !r5c_is_writeback(conf->log) &&
5328 !r5l_log_disk_error(conf);
5329 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5330 r5l_log_disk_error(conf);
5335 if (conf->worker_cnt_per_group == 0) {
5336 handle_list = try_loprio ? &conf->loprio_list :
5338 } else if (group != ANY_GROUP) {
5339 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5340 &conf->worker_groups[group].handle_list;
5341 wg = &conf->worker_groups[group];
5344 for (i = 0; i < conf->group_cnt; i++) {
5345 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5346 &conf->worker_groups[i].handle_list;
5347 wg = &conf->worker_groups[i];
5348 if (!list_empty(handle_list))
5353 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5355 list_empty(handle_list) ? "empty" : "busy",
5356 list_empty(&conf->hold_list) ? "empty" : "busy",
5357 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5359 if (!list_empty(handle_list)) {
5360 sh = list_entry(handle_list->next, typeof(*sh), lru);
5362 if (list_empty(&conf->hold_list))
5363 conf->bypass_count = 0;
5364 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5365 if (conf->hold_list.next == conf->last_hold)
5366 conf->bypass_count++;
5368 conf->last_hold = conf->hold_list.next;
5369 conf->bypass_count -= conf->bypass_threshold;
5370 if (conf->bypass_count < 0)
5371 conf->bypass_count = 0;
5374 } else if (!list_empty(&conf->hold_list) &&
5375 ((conf->bypass_threshold &&
5376 conf->bypass_count > conf->bypass_threshold) ||
5377 atomic_read(&conf->pending_full_writes) == 0)) {
5379 list_for_each_entry(tmp, &conf->hold_list, lru) {
5380 if (conf->worker_cnt_per_group == 0 ||
5381 group == ANY_GROUP ||
5382 !cpu_online(tmp->cpu) ||
5383 cpu_to_group(tmp->cpu) == group) {
5390 conf->bypass_count -= conf->bypass_threshold;
5391 if (conf->bypass_count < 0)
5392 conf->bypass_count = 0;
5401 try_loprio = !try_loprio;
5409 list_del_init(&sh->lru);
5410 BUG_ON(atomic_inc_return(&sh->count) != 1);
5414 struct raid5_plug_cb {
5415 struct blk_plug_cb cb;
5416 struct list_head list;
5417 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5420 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5422 struct raid5_plug_cb *cb = container_of(
5423 blk_cb, struct raid5_plug_cb, cb);
5424 struct stripe_head *sh;
5425 struct mddev *mddev = cb->cb.data;
5426 struct r5conf *conf = mddev->private;
5430 if (cb->list.next && !list_empty(&cb->list)) {
5431 spin_lock_irq(&conf->device_lock);
5432 while (!list_empty(&cb->list)) {
5433 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5434 list_del_init(&sh->lru);
5436 * avoid race release_stripe_plug() sees
5437 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5438 * is still in our list
5440 smp_mb__before_atomic();
5441 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5443 * STRIPE_ON_RELEASE_LIST could be set here. In that
5444 * case, the count is always > 1 here
5446 hash = sh->hash_lock_index;
5447 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5450 spin_unlock_irq(&conf->device_lock);
5452 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5453 NR_STRIPE_HASH_LOCKS);
5455 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5459 static void release_stripe_plug(struct mddev *mddev,
5460 struct stripe_head *sh)
5462 struct blk_plug_cb *blk_cb = blk_check_plugged(
5463 raid5_unplug, mddev,
5464 sizeof(struct raid5_plug_cb));
5465 struct raid5_plug_cb *cb;
5468 raid5_release_stripe(sh);
5472 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5474 if (cb->list.next == NULL) {
5476 INIT_LIST_HEAD(&cb->list);
5477 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5478 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5481 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5482 list_add_tail(&sh->lru, &cb->list);
5484 raid5_release_stripe(sh);
5487 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5489 struct r5conf *conf = mddev->private;
5490 sector_t logical_sector, last_sector;
5491 struct stripe_head *sh;
5494 if (mddev->reshape_position != MaxSector)
5495 /* Skip discard while reshape is happening */
5498 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5499 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5503 stripe_sectors = conf->chunk_sectors *
5504 (conf->raid_disks - conf->max_degraded);
5505 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5507 sector_div(last_sector, stripe_sectors);
5509 logical_sector *= conf->chunk_sectors;
5510 last_sector *= conf->chunk_sectors;
5512 for (; logical_sector < last_sector;
5513 logical_sector += STRIPE_SECTORS) {
5517 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5518 prepare_to_wait(&conf->wait_for_overlap, &w,
5519 TASK_UNINTERRUPTIBLE);
5520 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5521 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5522 raid5_release_stripe(sh);
5526 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5527 spin_lock_irq(&sh->stripe_lock);
5528 for (d = 0; d < conf->raid_disks; d++) {
5529 if (d == sh->pd_idx || d == sh->qd_idx)
5531 if (sh->dev[d].towrite || sh->dev[d].toread) {
5532 set_bit(R5_Overlap, &sh->dev[d].flags);
5533 spin_unlock_irq(&sh->stripe_lock);
5534 raid5_release_stripe(sh);
5539 set_bit(STRIPE_DISCARD, &sh->state);
5540 finish_wait(&conf->wait_for_overlap, &w);
5541 sh->overwrite_disks = 0;
5542 for (d = 0; d < conf->raid_disks; d++) {
5543 if (d == sh->pd_idx || d == sh->qd_idx)
5545 sh->dev[d].towrite = bi;
5546 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5547 bio_inc_remaining(bi);
5548 md_write_inc(mddev, bi);
5549 sh->overwrite_disks++;
5551 spin_unlock_irq(&sh->stripe_lock);
5552 if (conf->mddev->bitmap) {
5554 d < conf->raid_disks - conf->max_degraded;
5556 bitmap_startwrite(mddev->bitmap,
5560 sh->bm_seq = conf->seq_flush + 1;
5561 set_bit(STRIPE_BIT_DELAY, &sh->state);
5564 set_bit(STRIPE_HANDLE, &sh->state);
5565 clear_bit(STRIPE_DELAYED, &sh->state);
5566 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5567 atomic_inc(&conf->preread_active_stripes);
5568 release_stripe_plug(mddev, sh);
5574 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5576 struct r5conf *conf = mddev->private;
5578 sector_t new_sector;
5579 sector_t logical_sector, last_sector;
5580 struct stripe_head *sh;
5581 const int rw = bio_data_dir(bi);
5584 bool do_flush = false;
5586 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5587 int ret = r5l_handle_flush_request(conf->log, bi);
5591 if (ret == -ENODEV) {
5592 md_flush_request(mddev, bi);
5595 /* ret == -EAGAIN, fallback */
5597 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5598 * we need to flush journal device
5600 do_flush = bi->bi_opf & REQ_PREFLUSH;
5603 if (!md_write_start(mddev, bi))
5606 * If array is degraded, better not do chunk aligned read because
5607 * later we might have to read it again in order to reconstruct
5608 * data on failed drives.
5610 if (rw == READ && mddev->degraded == 0 &&
5611 mddev->reshape_position == MaxSector) {
5612 bi = chunk_aligned_read(mddev, bi);
5617 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5618 make_discard_request(mddev, bi);
5619 md_write_end(mddev);
5623 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5624 last_sector = bio_end_sector(bi);
5627 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5628 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5634 seq = read_seqcount_begin(&conf->gen_lock);
5637 prepare_to_wait(&conf->wait_for_overlap, &w,
5638 TASK_UNINTERRUPTIBLE);
5639 if (unlikely(conf->reshape_progress != MaxSector)) {
5640 /* spinlock is needed as reshape_progress may be
5641 * 64bit on a 32bit platform, and so it might be
5642 * possible to see a half-updated value
5643 * Of course reshape_progress could change after
5644 * the lock is dropped, so once we get a reference
5645 * to the stripe that we think it is, we will have
5648 spin_lock_irq(&conf->device_lock);
5649 if (mddev->reshape_backwards
5650 ? logical_sector < conf->reshape_progress
5651 : logical_sector >= conf->reshape_progress) {
5654 if (mddev->reshape_backwards
5655 ? logical_sector < conf->reshape_safe
5656 : logical_sector >= conf->reshape_safe) {
5657 spin_unlock_irq(&conf->device_lock);
5663 spin_unlock_irq(&conf->device_lock);
5666 new_sector = raid5_compute_sector(conf, logical_sector,
5669 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5670 (unsigned long long)new_sector,
5671 (unsigned long long)logical_sector);
5673 sh = raid5_get_active_stripe(conf, new_sector, previous,
5674 (bi->bi_opf & REQ_RAHEAD), 0);
5676 if (unlikely(previous)) {
5677 /* expansion might have moved on while waiting for a
5678 * stripe, so we must do the range check again.
5679 * Expansion could still move past after this
5680 * test, but as we are holding a reference to
5681 * 'sh', we know that if that happens,
5682 * STRIPE_EXPANDING will get set and the expansion
5683 * won't proceed until we finish with the stripe.
5686 spin_lock_irq(&conf->device_lock);
5687 if (mddev->reshape_backwards
5688 ? logical_sector >= conf->reshape_progress
5689 : logical_sector < conf->reshape_progress)
5690 /* mismatch, need to try again */
5692 spin_unlock_irq(&conf->device_lock);
5694 raid5_release_stripe(sh);
5700 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5701 /* Might have got the wrong stripe_head
5704 raid5_release_stripe(sh);
5708 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5709 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5710 /* Stripe is busy expanding or
5711 * add failed due to overlap. Flush everything
5714 md_wakeup_thread(mddev->thread);
5715 raid5_release_stripe(sh);
5721 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5722 /* we only need flush for one stripe */
5726 if (!sh->batch_head || sh == sh->batch_head)
5727 set_bit(STRIPE_HANDLE, &sh->state);
5728 clear_bit(STRIPE_DELAYED, &sh->state);
5729 if ((!sh->batch_head || sh == sh->batch_head) &&
5730 (bi->bi_opf & REQ_SYNC) &&
5731 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5732 atomic_inc(&conf->preread_active_stripes);
5733 release_stripe_plug(mddev, sh);
5735 /* cannot get stripe for read-ahead, just give-up */
5736 bi->bi_status = BLK_STS_IOERR;
5740 finish_wait(&conf->wait_for_overlap, &w);
5743 md_write_end(mddev);
5748 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5750 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5752 /* reshaping is quite different to recovery/resync so it is
5753 * handled quite separately ... here.
5755 * On each call to sync_request, we gather one chunk worth of
5756 * destination stripes and flag them as expanding.
5757 * Then we find all the source stripes and request reads.
5758 * As the reads complete, handle_stripe will copy the data
5759 * into the destination stripe and release that stripe.
5761 struct r5conf *conf = mddev->private;
5762 struct stripe_head *sh;
5763 sector_t first_sector, last_sector;
5764 int raid_disks = conf->previous_raid_disks;
5765 int data_disks = raid_disks - conf->max_degraded;
5766 int new_data_disks = conf->raid_disks - conf->max_degraded;
5769 sector_t writepos, readpos, safepos;
5770 sector_t stripe_addr;
5771 int reshape_sectors;
5772 struct list_head stripes;
5775 if (sector_nr == 0) {
5776 /* If restarting in the middle, skip the initial sectors */
5777 if (mddev->reshape_backwards &&
5778 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5779 sector_nr = raid5_size(mddev, 0, 0)
5780 - conf->reshape_progress;
5781 } else if (mddev->reshape_backwards &&
5782 conf->reshape_progress == MaxSector) {
5783 /* shouldn't happen, but just in case, finish up.*/
5784 sector_nr = MaxSector;
5785 } else if (!mddev->reshape_backwards &&
5786 conf->reshape_progress > 0)
5787 sector_nr = conf->reshape_progress;
5788 sector_div(sector_nr, new_data_disks);
5790 mddev->curr_resync_completed = sector_nr;
5791 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5798 /* We need to process a full chunk at a time.
5799 * If old and new chunk sizes differ, we need to process the
5803 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5805 /* We update the metadata at least every 10 seconds, or when
5806 * the data about to be copied would over-write the source of
5807 * the data at the front of the range. i.e. one new_stripe
5808 * along from reshape_progress new_maps to after where
5809 * reshape_safe old_maps to
5811 writepos = conf->reshape_progress;
5812 sector_div(writepos, new_data_disks);
5813 readpos = conf->reshape_progress;
5814 sector_div(readpos, data_disks);
5815 safepos = conf->reshape_safe;
5816 sector_div(safepos, data_disks);
5817 if (mddev->reshape_backwards) {
5818 BUG_ON(writepos < reshape_sectors);
5819 writepos -= reshape_sectors;
5820 readpos += reshape_sectors;
5821 safepos += reshape_sectors;
5823 writepos += reshape_sectors;
5824 /* readpos and safepos are worst-case calculations.
5825 * A negative number is overly pessimistic, and causes
5826 * obvious problems for unsigned storage. So clip to 0.
5828 readpos -= min_t(sector_t, reshape_sectors, readpos);
5829 safepos -= min_t(sector_t, reshape_sectors, safepos);
5832 /* Having calculated the 'writepos' possibly use it
5833 * to set 'stripe_addr' which is where we will write to.
5835 if (mddev->reshape_backwards) {
5836 BUG_ON(conf->reshape_progress == 0);
5837 stripe_addr = writepos;
5838 BUG_ON((mddev->dev_sectors &
5839 ~((sector_t)reshape_sectors - 1))
5840 - reshape_sectors - stripe_addr
5843 BUG_ON(writepos != sector_nr + reshape_sectors);
5844 stripe_addr = sector_nr;
5847 /* 'writepos' is the most advanced device address we might write.
5848 * 'readpos' is the least advanced device address we might read.
5849 * 'safepos' is the least address recorded in the metadata as having
5851 * If there is a min_offset_diff, these are adjusted either by
5852 * increasing the safepos/readpos if diff is negative, or
5853 * increasing writepos if diff is positive.
5854 * If 'readpos' is then behind 'writepos', there is no way that we can
5855 * ensure safety in the face of a crash - that must be done by userspace
5856 * making a backup of the data. So in that case there is no particular
5857 * rush to update metadata.
5858 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5859 * update the metadata to advance 'safepos' to match 'readpos' so that
5860 * we can be safe in the event of a crash.
5861 * So we insist on updating metadata if safepos is behind writepos and
5862 * readpos is beyond writepos.
5863 * In any case, update the metadata every 10 seconds.
5864 * Maybe that number should be configurable, but I'm not sure it is
5865 * worth it.... maybe it could be a multiple of safemode_delay???
5867 if (conf->min_offset_diff < 0) {
5868 safepos += -conf->min_offset_diff;
5869 readpos += -conf->min_offset_diff;
5871 writepos += conf->min_offset_diff;
5873 if ((mddev->reshape_backwards
5874 ? (safepos > writepos && readpos < writepos)
5875 : (safepos < writepos && readpos > writepos)) ||
5876 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5877 /* Cannot proceed until we've updated the superblock... */
5878 wait_event(conf->wait_for_overlap,
5879 atomic_read(&conf->reshape_stripes)==0
5880 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5881 if (atomic_read(&conf->reshape_stripes) != 0)
5883 mddev->reshape_position = conf->reshape_progress;
5884 mddev->curr_resync_completed = sector_nr;
5885 conf->reshape_checkpoint = jiffies;
5886 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5887 md_wakeup_thread(mddev->thread);
5888 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
5889 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5890 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5892 spin_lock_irq(&conf->device_lock);
5893 conf->reshape_safe = mddev->reshape_position;
5894 spin_unlock_irq(&conf->device_lock);
5895 wake_up(&conf->wait_for_overlap);
5896 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5899 INIT_LIST_HEAD(&stripes);
5900 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5902 int skipped_disk = 0;
5903 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5904 set_bit(STRIPE_EXPANDING, &sh->state);
5905 atomic_inc(&conf->reshape_stripes);
5906 /* If any of this stripe is beyond the end of the old
5907 * array, then we need to zero those blocks
5909 for (j=sh->disks; j--;) {
5911 if (j == sh->pd_idx)
5913 if (conf->level == 6 &&
5916 s = raid5_compute_blocknr(sh, j, 0);
5917 if (s < raid5_size(mddev, 0, 0)) {
5921 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5922 set_bit(R5_Expanded, &sh->dev[j].flags);
5923 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5925 if (!skipped_disk) {
5926 set_bit(STRIPE_EXPAND_READY, &sh->state);
5927 set_bit(STRIPE_HANDLE, &sh->state);
5929 list_add(&sh->lru, &stripes);
5931 spin_lock_irq(&conf->device_lock);
5932 if (mddev->reshape_backwards)
5933 conf->reshape_progress -= reshape_sectors * new_data_disks;
5935 conf->reshape_progress += reshape_sectors * new_data_disks;
5936 spin_unlock_irq(&conf->device_lock);
5937 /* Ok, those stripe are ready. We can start scheduling
5938 * reads on the source stripes.
5939 * The source stripes are determined by mapping the first and last
5940 * block on the destination stripes.
5943 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5946 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5947 * new_data_disks - 1),
5949 if (last_sector >= mddev->dev_sectors)
5950 last_sector = mddev->dev_sectors - 1;
5951 while (first_sector <= last_sector) {
5952 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5953 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5954 set_bit(STRIPE_HANDLE, &sh->state);
5955 raid5_release_stripe(sh);
5956 first_sector += STRIPE_SECTORS;
5958 /* Now that the sources are clearly marked, we can release
5959 * the destination stripes
5961 while (!list_empty(&stripes)) {
5962 sh = list_entry(stripes.next, struct stripe_head, lru);
5963 list_del_init(&sh->lru);
5964 raid5_release_stripe(sh);
5966 /* If this takes us to the resync_max point where we have to pause,
5967 * then we need to write out the superblock.
5969 sector_nr += reshape_sectors;
5970 retn = reshape_sectors;
5972 if (mddev->curr_resync_completed > mddev->resync_max ||
5973 (sector_nr - mddev->curr_resync_completed) * 2
5974 >= mddev->resync_max - mddev->curr_resync_completed) {
5975 /* Cannot proceed until we've updated the superblock... */
5976 wait_event(conf->wait_for_overlap,
5977 atomic_read(&conf->reshape_stripes) == 0
5978 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5979 if (atomic_read(&conf->reshape_stripes) != 0)
5981 mddev->reshape_position = conf->reshape_progress;
5982 mddev->curr_resync_completed = sector_nr;
5983 conf->reshape_checkpoint = jiffies;
5984 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5985 md_wakeup_thread(mddev->thread);
5986 wait_event(mddev->sb_wait,
5987 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
5988 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5989 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5991 spin_lock_irq(&conf->device_lock);
5992 conf->reshape_safe = mddev->reshape_position;
5993 spin_unlock_irq(&conf->device_lock);
5994 wake_up(&conf->wait_for_overlap);
5995 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
6001 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6004 struct r5conf *conf = mddev->private;
6005 struct stripe_head *sh;
6006 sector_t max_sector = mddev->dev_sectors;
6007 sector_t sync_blocks;
6008 int still_degraded = 0;
6011 if (sector_nr >= max_sector) {
6012 /* just being told to finish up .. nothing much to do */
6014 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6019 if (mddev->curr_resync < max_sector) /* aborted */
6020 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6022 else /* completed sync */
6024 bitmap_close_sync(mddev->bitmap);
6029 /* Allow raid5_quiesce to complete */
6030 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6032 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6033 return reshape_request(mddev, sector_nr, skipped);
6035 /* No need to check resync_max as we never do more than one
6036 * stripe, and as resync_max will always be on a chunk boundary,
6037 * if the check in md_do_sync didn't fire, there is no chance
6038 * of overstepping resync_max here
6041 /* if there is too many failed drives and we are trying
6042 * to resync, then assert that we are finished, because there is
6043 * nothing we can do.
6045 if (mddev->degraded >= conf->max_degraded &&
6046 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6047 sector_t rv = mddev->dev_sectors - sector_nr;
6051 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6053 !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6054 sync_blocks >= STRIPE_SECTORS) {
6055 /* we can skip this block, and probably more */
6056 sync_blocks /= STRIPE_SECTORS;
6058 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
6061 bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6063 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6065 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6066 /* make sure we don't swamp the stripe cache if someone else
6067 * is trying to get access
6069 schedule_timeout_uninterruptible(1);
6071 /* Need to check if array will still be degraded after recovery/resync
6072 * Note in case of > 1 drive failures it's possible we're rebuilding
6073 * one drive while leaving another faulty drive in array.
6076 for (i = 0; i < conf->raid_disks; i++) {
6077 struct md_rdev *rdev = ACCESS_ONCE(conf->disks[i].rdev);
6079 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6084 bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6086 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6087 set_bit(STRIPE_HANDLE, &sh->state);
6089 raid5_release_stripe(sh);
6091 return STRIPE_SECTORS;
6094 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6095 unsigned int offset)
6097 /* We may not be able to submit a whole bio at once as there
6098 * may not be enough stripe_heads available.
6099 * We cannot pre-allocate enough stripe_heads as we may need
6100 * more than exist in the cache (if we allow ever large chunks).
6101 * So we do one stripe head at a time and record in
6102 * ->bi_hw_segments how many have been done.
6104 * We *know* that this entire raid_bio is in one chunk, so
6105 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6107 struct stripe_head *sh;
6109 sector_t sector, logical_sector, last_sector;
6113 logical_sector = raid_bio->bi_iter.bi_sector &
6114 ~((sector_t)STRIPE_SECTORS-1);
6115 sector = raid5_compute_sector(conf, logical_sector,
6117 last_sector = bio_end_sector(raid_bio);
6119 for (; logical_sector < last_sector;
6120 logical_sector += STRIPE_SECTORS,
6121 sector += STRIPE_SECTORS,
6125 /* already done this stripe */
6128 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6131 /* failed to get a stripe - must wait */
6132 conf->retry_read_aligned = raid_bio;
6133 conf->retry_read_offset = scnt;
6137 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6138 raid5_release_stripe(sh);
6139 conf->retry_read_aligned = raid_bio;
6140 conf->retry_read_offset = scnt;
6144 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6146 raid5_release_stripe(sh);
6150 bio_endio(raid_bio);
6152 if (atomic_dec_and_test(&conf->active_aligned_reads))
6153 wake_up(&conf->wait_for_quiescent);
6157 static int handle_active_stripes(struct r5conf *conf, int group,
6158 struct r5worker *worker,
6159 struct list_head *temp_inactive_list)
6161 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6162 int i, batch_size = 0, hash;
6163 bool release_inactive = false;
6165 while (batch_size < MAX_STRIPE_BATCH &&
6166 (sh = __get_priority_stripe(conf, group)) != NULL)
6167 batch[batch_size++] = sh;
6169 if (batch_size == 0) {
6170 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6171 if (!list_empty(temp_inactive_list + i))
6173 if (i == NR_STRIPE_HASH_LOCKS) {
6174 spin_unlock_irq(&conf->device_lock);
6175 r5l_flush_stripe_to_raid(conf->log);
6176 spin_lock_irq(&conf->device_lock);
6179 release_inactive = true;
6181 spin_unlock_irq(&conf->device_lock);
6183 release_inactive_stripe_list(conf, temp_inactive_list,
6184 NR_STRIPE_HASH_LOCKS);
6186 r5l_flush_stripe_to_raid(conf->log);
6187 if (release_inactive) {
6188 spin_lock_irq(&conf->device_lock);
6192 for (i = 0; i < batch_size; i++)
6193 handle_stripe(batch[i]);
6194 log_write_stripe_run(conf);
6198 spin_lock_irq(&conf->device_lock);
6199 for (i = 0; i < batch_size; i++) {
6200 hash = batch[i]->hash_lock_index;
6201 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6206 static void raid5_do_work(struct work_struct *work)
6208 struct r5worker *worker = container_of(work, struct r5worker, work);
6209 struct r5worker_group *group = worker->group;
6210 struct r5conf *conf = group->conf;
6211 struct mddev *mddev = conf->mddev;
6212 int group_id = group - conf->worker_groups;
6214 struct blk_plug plug;
6216 pr_debug("+++ raid5worker active\n");
6218 blk_start_plug(&plug);
6220 spin_lock_irq(&conf->device_lock);
6222 int batch_size, released;
6224 released = release_stripe_list(conf, worker->temp_inactive_list);
6226 batch_size = handle_active_stripes(conf, group_id, worker,
6227 worker->temp_inactive_list);
6228 worker->working = false;
6229 if (!batch_size && !released)
6231 handled += batch_size;
6232 wait_event_lock_irq(mddev->sb_wait,
6233 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6236 pr_debug("%d stripes handled\n", handled);
6238 spin_unlock_irq(&conf->device_lock);
6240 flush_deferred_bios(conf);
6242 r5l_flush_stripe_to_raid(conf->log);
6244 async_tx_issue_pending_all();
6245 blk_finish_plug(&plug);
6247 pr_debug("--- raid5worker inactive\n");
6251 * This is our raid5 kernel thread.
6253 * We scan the hash table for stripes which can be handled now.
6254 * During the scan, completed stripes are saved for us by the interrupt
6255 * handler, so that they will not have to wait for our next wakeup.
6257 static void raid5d(struct md_thread *thread)
6259 struct mddev *mddev = thread->mddev;
6260 struct r5conf *conf = mddev->private;
6262 struct blk_plug plug;
6264 pr_debug("+++ raid5d active\n");
6266 md_check_recovery(mddev);
6268 blk_start_plug(&plug);
6270 spin_lock_irq(&conf->device_lock);
6273 int batch_size, released;
6274 unsigned int offset;
6276 released = release_stripe_list(conf, conf->temp_inactive_list);
6278 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6281 !list_empty(&conf->bitmap_list)) {
6282 /* Now is a good time to flush some bitmap updates */
6284 spin_unlock_irq(&conf->device_lock);
6285 bitmap_unplug(mddev->bitmap);
6286 spin_lock_irq(&conf->device_lock);
6287 conf->seq_write = conf->seq_flush;
6288 activate_bit_delay(conf, conf->temp_inactive_list);
6290 raid5_activate_delayed(conf);
6292 while ((bio = remove_bio_from_retry(conf, &offset))) {
6294 spin_unlock_irq(&conf->device_lock);
6295 ok = retry_aligned_read(conf, bio, offset);
6296 spin_lock_irq(&conf->device_lock);
6302 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6303 conf->temp_inactive_list);
6304 if (!batch_size && !released)
6306 handled += batch_size;
6308 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6309 spin_unlock_irq(&conf->device_lock);
6310 md_check_recovery(mddev);
6311 spin_lock_irq(&conf->device_lock);
6314 * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6315 * seeing md_check_recovery() is needed to clear
6316 * the flag when using mdmon.
6321 wait_event_lock_irq(mddev->sb_wait,
6322 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6325 pr_debug("%d stripes handled\n", handled);
6327 spin_unlock_irq(&conf->device_lock);
6328 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6329 mutex_trylock(&conf->cache_size_mutex)) {
6330 grow_one_stripe(conf, __GFP_NOWARN);
6331 /* Set flag even if allocation failed. This helps
6332 * slow down allocation requests when mem is short
6334 set_bit(R5_DID_ALLOC, &conf->cache_state);
6335 mutex_unlock(&conf->cache_size_mutex);
6338 flush_deferred_bios(conf);
6340 r5l_flush_stripe_to_raid(conf->log);
6342 async_tx_issue_pending_all();
6343 blk_finish_plug(&plug);
6345 pr_debug("--- raid5d inactive\n");
6349 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6351 struct r5conf *conf;
6353 spin_lock(&mddev->lock);
6354 conf = mddev->private;
6356 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6357 spin_unlock(&mddev->lock);
6362 raid5_set_cache_size(struct mddev *mddev, int size)
6365 struct r5conf *conf = mddev->private;
6367 if (size <= 16 || size > 32768)
6370 conf->min_nr_stripes = size;
6371 mutex_lock(&conf->cache_size_mutex);
6372 while (size < conf->max_nr_stripes &&
6373 drop_one_stripe(conf))
6375 mutex_unlock(&conf->cache_size_mutex);
6377 md_allow_write(mddev);
6379 mutex_lock(&conf->cache_size_mutex);
6380 while (size > conf->max_nr_stripes)
6381 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6382 conf->min_nr_stripes = conf->max_nr_stripes;
6386 mutex_unlock(&conf->cache_size_mutex);
6390 EXPORT_SYMBOL(raid5_set_cache_size);
6393 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6395 struct r5conf *conf;
6399 if (len >= PAGE_SIZE)
6401 if (kstrtoul(page, 10, &new))
6403 err = mddev_lock(mddev);
6406 conf = mddev->private;
6410 err = raid5_set_cache_size(mddev, new);
6411 mddev_unlock(mddev);
6416 static struct md_sysfs_entry
6417 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6418 raid5_show_stripe_cache_size,
6419 raid5_store_stripe_cache_size);
6422 raid5_show_rmw_level(struct mddev *mddev, char *page)
6424 struct r5conf *conf = mddev->private;
6426 return sprintf(page, "%d\n", conf->rmw_level);
6432 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6434 struct r5conf *conf = mddev->private;
6440 if (len >= PAGE_SIZE)
6443 if (kstrtoul(page, 10, &new))
6446 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6449 if (new != PARITY_DISABLE_RMW &&
6450 new != PARITY_ENABLE_RMW &&
6451 new != PARITY_PREFER_RMW)
6454 conf->rmw_level = new;
6458 static struct md_sysfs_entry
6459 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6460 raid5_show_rmw_level,
6461 raid5_store_rmw_level);
6465 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6467 struct r5conf *conf;
6469 spin_lock(&mddev->lock);
6470 conf = mddev->private;
6472 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6473 spin_unlock(&mddev->lock);
6478 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6480 struct r5conf *conf;
6484 if (len >= PAGE_SIZE)
6486 if (kstrtoul(page, 10, &new))
6489 err = mddev_lock(mddev);
6492 conf = mddev->private;
6495 else if (new > conf->min_nr_stripes)
6498 conf->bypass_threshold = new;
6499 mddev_unlock(mddev);
6503 static struct md_sysfs_entry
6504 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6506 raid5_show_preread_threshold,
6507 raid5_store_preread_threshold);
6510 raid5_show_skip_copy(struct mddev *mddev, char *page)
6512 struct r5conf *conf;
6514 spin_lock(&mddev->lock);
6515 conf = mddev->private;
6517 ret = sprintf(page, "%d\n", conf->skip_copy);
6518 spin_unlock(&mddev->lock);
6523 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6525 struct r5conf *conf;
6529 if (len >= PAGE_SIZE)
6531 if (kstrtoul(page, 10, &new))
6535 err = mddev_lock(mddev);
6538 conf = mddev->private;
6541 else if (new != conf->skip_copy) {
6542 mddev_suspend(mddev);
6543 conf->skip_copy = new;
6545 mddev->queue->backing_dev_info->capabilities |=
6546 BDI_CAP_STABLE_WRITES;
6548 mddev->queue->backing_dev_info->capabilities &=
6549 ~BDI_CAP_STABLE_WRITES;
6550 mddev_resume(mddev);
6552 mddev_unlock(mddev);
6556 static struct md_sysfs_entry
6557 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6558 raid5_show_skip_copy,
6559 raid5_store_skip_copy);
6562 stripe_cache_active_show(struct mddev *mddev, char *page)
6564 struct r5conf *conf = mddev->private;
6566 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6571 static struct md_sysfs_entry
6572 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6575 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6577 struct r5conf *conf;
6579 spin_lock(&mddev->lock);
6580 conf = mddev->private;
6582 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6583 spin_unlock(&mddev->lock);
6587 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6589 int *worker_cnt_per_group,
6590 struct r5worker_group **worker_groups);
6592 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6594 struct r5conf *conf;
6597 struct r5worker_group *new_groups, *old_groups;
6598 int group_cnt, worker_cnt_per_group;
6600 if (len >= PAGE_SIZE)
6602 if (kstrtouint(page, 10, &new))
6604 /* 8192 should be big enough */
6608 err = mddev_lock(mddev);
6611 conf = mddev->private;
6614 else if (new != conf->worker_cnt_per_group) {
6615 mddev_suspend(mddev);
6617 old_groups = conf->worker_groups;
6619 flush_workqueue(raid5_wq);
6621 err = alloc_thread_groups(conf, new,
6622 &group_cnt, &worker_cnt_per_group,
6625 spin_lock_irq(&conf->device_lock);
6626 conf->group_cnt = group_cnt;
6627 conf->worker_cnt_per_group = worker_cnt_per_group;
6628 conf->worker_groups = new_groups;
6629 spin_unlock_irq(&conf->device_lock);
6632 kfree(old_groups[0].workers);
6635 mddev_resume(mddev);
6637 mddev_unlock(mddev);
6642 static struct md_sysfs_entry
6643 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6644 raid5_show_group_thread_cnt,
6645 raid5_store_group_thread_cnt);
6647 static struct attribute *raid5_attrs[] = {
6648 &raid5_stripecache_size.attr,
6649 &raid5_stripecache_active.attr,
6650 &raid5_preread_bypass_threshold.attr,
6651 &raid5_group_thread_cnt.attr,
6652 &raid5_skip_copy.attr,
6653 &raid5_rmw_level.attr,
6654 &r5c_journal_mode.attr,
6657 static struct attribute_group raid5_attrs_group = {
6659 .attrs = raid5_attrs,
6662 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6664 int *worker_cnt_per_group,
6665 struct r5worker_group **worker_groups)
6669 struct r5worker *workers;
6671 *worker_cnt_per_group = cnt;
6674 *worker_groups = NULL;
6677 *group_cnt = num_possible_nodes();
6678 size = sizeof(struct r5worker) * cnt;
6679 workers = kzalloc(size * *group_cnt, GFP_NOIO);
6680 *worker_groups = kzalloc(sizeof(struct r5worker_group) *
6681 *group_cnt, GFP_NOIO);
6682 if (!*worker_groups || !workers) {
6684 kfree(*worker_groups);
6688 for (i = 0; i < *group_cnt; i++) {
6689 struct r5worker_group *group;
6691 group = &(*worker_groups)[i];
6692 INIT_LIST_HEAD(&group->handle_list);
6693 INIT_LIST_HEAD(&group->loprio_list);
6695 group->workers = workers + i * cnt;
6697 for (j = 0; j < cnt; j++) {
6698 struct r5worker *worker = group->workers + j;
6699 worker->group = group;
6700 INIT_WORK(&worker->work, raid5_do_work);
6702 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6703 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6710 static void free_thread_groups(struct r5conf *conf)
6712 if (conf->worker_groups)
6713 kfree(conf->worker_groups[0].workers);
6714 kfree(conf->worker_groups);
6715 conf->worker_groups = NULL;
6719 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6721 struct r5conf *conf = mddev->private;
6724 sectors = mddev->dev_sectors;
6726 /* size is defined by the smallest of previous and new size */
6727 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6729 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6730 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6731 return sectors * (raid_disks - conf->max_degraded);
6734 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6736 safe_put_page(percpu->spare_page);
6737 if (percpu->scribble)
6738 flex_array_free(percpu->scribble);
6739 percpu->spare_page = NULL;
6740 percpu->scribble = NULL;
6743 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6745 if (conf->level == 6 && !percpu->spare_page)
6746 percpu->spare_page = alloc_page(GFP_KERNEL);
6747 if (!percpu->scribble)
6748 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6749 conf->previous_raid_disks),
6750 max(conf->chunk_sectors,
6751 conf->prev_chunk_sectors)
6755 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6756 free_scratch_buffer(conf, percpu);
6763 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
6765 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6767 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6771 static void raid5_free_percpu(struct r5conf *conf)
6776 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6777 free_percpu(conf->percpu);
6780 static void free_conf(struct r5conf *conf)
6786 if (conf->shrinker.nr_deferred)
6787 unregister_shrinker(&conf->shrinker);
6789 free_thread_groups(conf);
6790 shrink_stripes(conf);
6791 raid5_free_percpu(conf);
6792 for (i = 0; i < conf->pool_size; i++)
6793 if (conf->disks[i].extra_page)
6794 put_page(conf->disks[i].extra_page);
6796 if (conf->bio_split)
6797 bioset_free(conf->bio_split);
6798 kfree(conf->stripe_hashtbl);
6799 kfree(conf->pending_data);
6803 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
6805 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6806 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6808 if (alloc_scratch_buffer(conf, percpu)) {
6809 pr_warn("%s: failed memory allocation for cpu%u\n",
6816 static int raid5_alloc_percpu(struct r5conf *conf)
6820 conf->percpu = alloc_percpu(struct raid5_percpu);
6824 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6826 conf->scribble_disks = max(conf->raid_disks,
6827 conf->previous_raid_disks);
6828 conf->scribble_sectors = max(conf->chunk_sectors,
6829 conf->prev_chunk_sectors);
6834 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6835 struct shrink_control *sc)
6837 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6838 unsigned long ret = SHRINK_STOP;
6840 if (mutex_trylock(&conf->cache_size_mutex)) {
6842 while (ret < sc->nr_to_scan &&
6843 conf->max_nr_stripes > conf->min_nr_stripes) {
6844 if (drop_one_stripe(conf) == 0) {
6850 mutex_unlock(&conf->cache_size_mutex);
6855 static unsigned long raid5_cache_count(struct shrinker *shrink,
6856 struct shrink_control *sc)
6858 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6860 if (conf->max_nr_stripes < conf->min_nr_stripes)
6861 /* unlikely, but not impossible */
6863 return conf->max_nr_stripes - conf->min_nr_stripes;
6866 static struct r5conf *setup_conf(struct mddev *mddev)
6868 struct r5conf *conf;
6869 int raid_disk, memory, max_disks;
6870 struct md_rdev *rdev;
6871 struct disk_info *disk;
6874 int group_cnt, worker_cnt_per_group;
6875 struct r5worker_group *new_group;
6877 if (mddev->new_level != 5
6878 && mddev->new_level != 4
6879 && mddev->new_level != 6) {
6880 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6881 mdname(mddev), mddev->new_level);
6882 return ERR_PTR(-EIO);
6884 if ((mddev->new_level == 5
6885 && !algorithm_valid_raid5(mddev->new_layout)) ||
6886 (mddev->new_level == 6
6887 && !algorithm_valid_raid6(mddev->new_layout))) {
6888 pr_warn("md/raid:%s: layout %d not supported\n",
6889 mdname(mddev), mddev->new_layout);
6890 return ERR_PTR(-EIO);
6892 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6893 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6894 mdname(mddev), mddev->raid_disks);
6895 return ERR_PTR(-EINVAL);
6898 if (!mddev->new_chunk_sectors ||
6899 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6900 !is_power_of_2(mddev->new_chunk_sectors)) {
6901 pr_warn("md/raid:%s: invalid chunk size %d\n",
6902 mdname(mddev), mddev->new_chunk_sectors << 9);
6903 return ERR_PTR(-EINVAL);
6906 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6909 INIT_LIST_HEAD(&conf->free_list);
6910 INIT_LIST_HEAD(&conf->pending_list);
6911 conf->pending_data = kzalloc(sizeof(struct r5pending_data) *
6912 PENDING_IO_MAX, GFP_KERNEL);
6913 if (!conf->pending_data)
6915 for (i = 0; i < PENDING_IO_MAX; i++)
6916 list_add(&conf->pending_data[i].sibling, &conf->free_list);
6917 /* Don't enable multi-threading by default*/
6918 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6920 conf->group_cnt = group_cnt;
6921 conf->worker_cnt_per_group = worker_cnt_per_group;
6922 conf->worker_groups = new_group;
6925 spin_lock_init(&conf->device_lock);
6926 seqcount_init(&conf->gen_lock);
6927 mutex_init(&conf->cache_size_mutex);
6928 init_waitqueue_head(&conf->wait_for_quiescent);
6929 init_waitqueue_head(&conf->wait_for_stripe);
6930 init_waitqueue_head(&conf->wait_for_overlap);
6931 INIT_LIST_HEAD(&conf->handle_list);
6932 INIT_LIST_HEAD(&conf->loprio_list);
6933 INIT_LIST_HEAD(&conf->hold_list);
6934 INIT_LIST_HEAD(&conf->delayed_list);
6935 INIT_LIST_HEAD(&conf->bitmap_list);
6936 init_llist_head(&conf->released_stripes);
6937 atomic_set(&conf->active_stripes, 0);
6938 atomic_set(&conf->preread_active_stripes, 0);
6939 atomic_set(&conf->active_aligned_reads, 0);
6940 spin_lock_init(&conf->pending_bios_lock);
6941 conf->batch_bio_dispatch = true;
6942 rdev_for_each(rdev, mddev) {
6943 if (test_bit(Journal, &rdev->flags))
6945 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
6946 conf->batch_bio_dispatch = false;
6951 conf->bypass_threshold = BYPASS_THRESHOLD;
6952 conf->recovery_disabled = mddev->recovery_disabled - 1;
6954 conf->raid_disks = mddev->raid_disks;
6955 if (mddev->reshape_position == MaxSector)
6956 conf->previous_raid_disks = mddev->raid_disks;
6958 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6959 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6961 conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
6967 for (i = 0; i < max_disks; i++) {
6968 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
6969 if (!conf->disks[i].extra_page)
6973 conf->bio_split = bioset_create(BIO_POOL_SIZE, 0, 0);
6974 if (!conf->bio_split)
6976 conf->mddev = mddev;
6978 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
6981 /* We init hash_locks[0] separately to that it can be used
6982 * as the reference lock in the spin_lock_nest_lock() call
6983 * in lock_all_device_hash_locks_irq in order to convince
6984 * lockdep that we know what we are doing.
6986 spin_lock_init(conf->hash_locks);
6987 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
6988 spin_lock_init(conf->hash_locks + i);
6990 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6991 INIT_LIST_HEAD(conf->inactive_list + i);
6993 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6994 INIT_LIST_HEAD(conf->temp_inactive_list + i);
6996 atomic_set(&conf->r5c_cached_full_stripes, 0);
6997 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
6998 atomic_set(&conf->r5c_cached_partial_stripes, 0);
6999 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7000 atomic_set(&conf->r5c_flushing_full_stripes, 0);
7001 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7003 conf->level = mddev->new_level;
7004 conf->chunk_sectors = mddev->new_chunk_sectors;
7005 if (raid5_alloc_percpu(conf) != 0)
7008 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7010 rdev_for_each(rdev, mddev) {
7011 raid_disk = rdev->raid_disk;
7012 if (raid_disk >= max_disks
7013 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7015 disk = conf->disks + raid_disk;
7017 if (test_bit(Replacement, &rdev->flags)) {
7018 if (disk->replacement)
7020 disk->replacement = rdev;
7027 if (test_bit(In_sync, &rdev->flags)) {
7028 char b[BDEVNAME_SIZE];
7029 pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7030 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7031 } else if (rdev->saved_raid_disk != raid_disk)
7032 /* Cannot rely on bitmap to complete recovery */
7036 conf->level = mddev->new_level;
7037 if (conf->level == 6) {
7038 conf->max_degraded = 2;
7039 if (raid6_call.xor_syndrome)
7040 conf->rmw_level = PARITY_ENABLE_RMW;
7042 conf->rmw_level = PARITY_DISABLE_RMW;
7044 conf->max_degraded = 1;
7045 conf->rmw_level = PARITY_ENABLE_RMW;
7047 conf->algorithm = mddev->new_layout;
7048 conf->reshape_progress = mddev->reshape_position;
7049 if (conf->reshape_progress != MaxSector) {
7050 conf->prev_chunk_sectors = mddev->chunk_sectors;
7051 conf->prev_algo = mddev->layout;
7053 conf->prev_chunk_sectors = conf->chunk_sectors;
7054 conf->prev_algo = conf->algorithm;
7057 conf->min_nr_stripes = NR_STRIPES;
7058 if (mddev->reshape_position != MaxSector) {
7059 int stripes = max_t(int,
7060 ((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4,
7061 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4);
7062 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7063 if (conf->min_nr_stripes != NR_STRIPES)
7064 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7065 mdname(mddev), conf->min_nr_stripes);
7067 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7068 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7069 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7070 if (grow_stripes(conf, conf->min_nr_stripes)) {
7071 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7072 mdname(mddev), memory);
7075 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7077 * Losing a stripe head costs more than the time to refill it,
7078 * it reduces the queue depth and so can hurt throughput.
7079 * So set it rather large, scaled by number of devices.
7081 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7082 conf->shrinker.scan_objects = raid5_cache_scan;
7083 conf->shrinker.count_objects = raid5_cache_count;
7084 conf->shrinker.batch = 128;
7085 conf->shrinker.flags = 0;
7086 if (register_shrinker(&conf->shrinker)) {
7087 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7092 sprintf(pers_name, "raid%d", mddev->new_level);
7093 conf->thread = md_register_thread(raid5d, mddev, pers_name);
7094 if (!conf->thread) {
7095 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7105 return ERR_PTR(-EIO);
7107 return ERR_PTR(-ENOMEM);
7110 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7113 case ALGORITHM_PARITY_0:
7114 if (raid_disk < max_degraded)
7117 case ALGORITHM_PARITY_N:
7118 if (raid_disk >= raid_disks - max_degraded)
7121 case ALGORITHM_PARITY_0_6:
7122 if (raid_disk == 0 ||
7123 raid_disk == raid_disks - 1)
7126 case ALGORITHM_LEFT_ASYMMETRIC_6:
7127 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7128 case ALGORITHM_LEFT_SYMMETRIC_6:
7129 case ALGORITHM_RIGHT_SYMMETRIC_6:
7130 if (raid_disk == raid_disks - 1)
7136 static int raid5_run(struct mddev *mddev)
7138 struct r5conf *conf;
7139 int working_disks = 0;
7140 int dirty_parity_disks = 0;
7141 struct md_rdev *rdev;
7142 struct md_rdev *journal_dev = NULL;
7143 sector_t reshape_offset = 0;
7145 long long min_offset_diff = 0;
7148 if (mddev_init_writes_pending(mddev) < 0)
7151 if (mddev->recovery_cp != MaxSector)
7152 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7155 rdev_for_each(rdev, mddev) {
7158 if (test_bit(Journal, &rdev->flags)) {
7162 if (rdev->raid_disk < 0)
7164 diff = (rdev->new_data_offset - rdev->data_offset);
7166 min_offset_diff = diff;
7168 } else if (mddev->reshape_backwards &&
7169 diff < min_offset_diff)
7170 min_offset_diff = diff;
7171 else if (!mddev->reshape_backwards &&
7172 diff > min_offset_diff)
7173 min_offset_diff = diff;
7176 if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7177 (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7178 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7183 if (mddev->reshape_position != MaxSector) {
7184 /* Check that we can continue the reshape.
7185 * Difficulties arise if the stripe we would write to
7186 * next is at or after the stripe we would read from next.
7187 * For a reshape that changes the number of devices, this
7188 * is only possible for a very short time, and mdadm makes
7189 * sure that time appears to have past before assembling
7190 * the array. So we fail if that time hasn't passed.
7191 * For a reshape that keeps the number of devices the same
7192 * mdadm must be monitoring the reshape can keeping the
7193 * critical areas read-only and backed up. It will start
7194 * the array in read-only mode, so we check for that.
7196 sector_t here_new, here_old;
7198 int max_degraded = (mddev->level == 6 ? 2 : 1);
7203 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7208 if (mddev->new_level != mddev->level) {
7209 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7213 old_disks = mddev->raid_disks - mddev->delta_disks;
7214 /* reshape_position must be on a new-stripe boundary, and one
7215 * further up in new geometry must map after here in old
7217 * If the chunk sizes are different, then as we perform reshape
7218 * in units of the largest of the two, reshape_position needs
7219 * be a multiple of the largest chunk size times new data disks.
7221 here_new = mddev->reshape_position;
7222 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7223 new_data_disks = mddev->raid_disks - max_degraded;
7224 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7225 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7229 reshape_offset = here_new * chunk_sectors;
7230 /* here_new is the stripe we will write to */
7231 here_old = mddev->reshape_position;
7232 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7233 /* here_old is the first stripe that we might need to read
7235 if (mddev->delta_disks == 0) {
7236 /* We cannot be sure it is safe to start an in-place
7237 * reshape. It is only safe if user-space is monitoring
7238 * and taking constant backups.
7239 * mdadm always starts a situation like this in
7240 * readonly mode so it can take control before
7241 * allowing any writes. So just check for that.
7243 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7244 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7245 /* not really in-place - so OK */;
7246 else if (mddev->ro == 0) {
7247 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7251 } else if (mddev->reshape_backwards
7252 ? (here_new * chunk_sectors + min_offset_diff <=
7253 here_old * chunk_sectors)
7254 : (here_new * chunk_sectors >=
7255 here_old * chunk_sectors + (-min_offset_diff))) {
7256 /* Reading from the same stripe as writing to - bad */
7257 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7261 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7262 /* OK, we should be able to continue; */
7264 BUG_ON(mddev->level != mddev->new_level);
7265 BUG_ON(mddev->layout != mddev->new_layout);
7266 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7267 BUG_ON(mddev->delta_disks != 0);
7270 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7271 test_bit(MD_HAS_PPL, &mddev->flags)) {
7272 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7274 clear_bit(MD_HAS_PPL, &mddev->flags);
7275 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7278 if (mddev->private == NULL)
7279 conf = setup_conf(mddev);
7281 conf = mddev->private;
7284 return PTR_ERR(conf);
7286 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7288 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7291 set_disk_ro(mddev->gendisk, 1);
7292 } else if (mddev->recovery_cp == MaxSector)
7293 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7296 conf->min_offset_diff = min_offset_diff;
7297 mddev->thread = conf->thread;
7298 conf->thread = NULL;
7299 mddev->private = conf;
7301 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7303 rdev = conf->disks[i].rdev;
7304 if (!rdev && conf->disks[i].replacement) {
7305 /* The replacement is all we have yet */
7306 rdev = conf->disks[i].replacement;
7307 conf->disks[i].replacement = NULL;
7308 clear_bit(Replacement, &rdev->flags);
7309 conf->disks[i].rdev = rdev;
7313 if (conf->disks[i].replacement &&
7314 conf->reshape_progress != MaxSector) {
7315 /* replacements and reshape simply do not mix. */
7316 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7319 if (test_bit(In_sync, &rdev->flags)) {
7323 /* This disc is not fully in-sync. However if it
7324 * just stored parity (beyond the recovery_offset),
7325 * when we don't need to be concerned about the
7326 * array being dirty.
7327 * When reshape goes 'backwards', we never have
7328 * partially completed devices, so we only need
7329 * to worry about reshape going forwards.
7331 /* Hack because v0.91 doesn't store recovery_offset properly. */
7332 if (mddev->major_version == 0 &&
7333 mddev->minor_version > 90)
7334 rdev->recovery_offset = reshape_offset;
7336 if (rdev->recovery_offset < reshape_offset) {
7337 /* We need to check old and new layout */
7338 if (!only_parity(rdev->raid_disk,
7341 conf->max_degraded))
7344 if (!only_parity(rdev->raid_disk,
7346 conf->previous_raid_disks,
7347 conf->max_degraded))
7349 dirty_parity_disks++;
7353 * 0 for a fully functional array, 1 or 2 for a degraded array.
7355 mddev->degraded = raid5_calc_degraded(conf);
7357 if (has_failed(conf)) {
7358 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7359 mdname(mddev), mddev->degraded, conf->raid_disks);
7363 /* device size must be a multiple of chunk size */
7364 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7365 mddev->resync_max_sectors = mddev->dev_sectors;
7367 if (mddev->degraded > dirty_parity_disks &&
7368 mddev->recovery_cp != MaxSector) {
7369 if (test_bit(MD_HAS_PPL, &mddev->flags))
7370 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7372 else if (mddev->ok_start_degraded)
7373 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7376 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7382 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7383 mdname(mddev), conf->level,
7384 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7387 print_raid5_conf(conf);
7389 if (conf->reshape_progress != MaxSector) {
7390 conf->reshape_safe = conf->reshape_progress;
7391 atomic_set(&conf->reshape_stripes, 0);
7392 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7393 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7394 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7395 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7396 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7398 if (!mddev->sync_thread)
7402 /* Ok, everything is just fine now */
7403 if (mddev->to_remove == &raid5_attrs_group)
7404 mddev->to_remove = NULL;
7405 else if (mddev->kobj.sd &&
7406 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7407 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7409 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7413 /* read-ahead size must cover two whole stripes, which
7414 * is 2 * (datadisks) * chunksize where 'n' is the
7415 * number of raid devices
7417 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7418 int stripe = data_disks *
7419 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7420 if (mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
7421 mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
7423 chunk_size = mddev->chunk_sectors << 9;
7424 blk_queue_io_min(mddev->queue, chunk_size);
7425 blk_queue_io_opt(mddev->queue, chunk_size *
7426 (conf->raid_disks - conf->max_degraded));
7427 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7429 * We can only discard a whole stripe. It doesn't make sense to
7430 * discard data disk but write parity disk
7432 stripe = stripe * PAGE_SIZE;
7433 /* Round up to power of 2, as discard handling
7434 * currently assumes that */
7435 while ((stripe-1) & stripe)
7436 stripe = (stripe | (stripe-1)) + 1;
7437 mddev->queue->limits.discard_alignment = stripe;
7438 mddev->queue->limits.discard_granularity = stripe;
7440 blk_queue_max_write_same_sectors(mddev->queue, 0);
7441 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7443 rdev_for_each(rdev, mddev) {
7444 disk_stack_limits(mddev->gendisk, rdev->bdev,
7445 rdev->data_offset << 9);
7446 disk_stack_limits(mddev->gendisk, rdev->bdev,
7447 rdev->new_data_offset << 9);
7451 * zeroing is required, otherwise data
7452 * could be lost. Consider a scenario: discard a stripe
7453 * (the stripe could be inconsistent if
7454 * discard_zeroes_data is 0); write one disk of the
7455 * stripe (the stripe could be inconsistent again
7456 * depending on which disks are used to calculate
7457 * parity); the disk is broken; The stripe data of this
7460 * We only allow DISCARD if the sysadmin has confirmed that
7461 * only safe devices are in use by setting a module parameter.
7462 * A better idea might be to turn DISCARD into WRITE_ZEROES
7463 * requests, as that is required to be safe.
7465 if (devices_handle_discard_safely &&
7466 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7467 mddev->queue->limits.discard_granularity >= stripe)
7468 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
7471 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
7474 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7477 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7482 md_unregister_thread(&mddev->thread);
7483 print_raid5_conf(conf);
7485 mddev->private = NULL;
7486 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7490 static void raid5_free(struct mddev *mddev, void *priv)
7492 struct r5conf *conf = priv;
7495 mddev->to_remove = &raid5_attrs_group;
7498 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7500 struct r5conf *conf = mddev->private;
7503 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7504 conf->chunk_sectors / 2, mddev->layout);
7505 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7507 for (i = 0; i < conf->raid_disks; i++) {
7508 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7509 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7512 seq_printf (seq, "]");
7515 static void print_raid5_conf (struct r5conf *conf)
7518 struct disk_info *tmp;
7520 pr_debug("RAID conf printout:\n");
7522 pr_debug("(conf==NULL)\n");
7525 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7527 conf->raid_disks - conf->mddev->degraded);
7529 for (i = 0; i < conf->raid_disks; i++) {
7530 char b[BDEVNAME_SIZE];
7531 tmp = conf->disks + i;
7533 pr_debug(" disk %d, o:%d, dev:%s\n",
7534 i, !test_bit(Faulty, &tmp->rdev->flags),
7535 bdevname(tmp->rdev->bdev, b));
7539 static int raid5_spare_active(struct mddev *mddev)
7542 struct r5conf *conf = mddev->private;
7543 struct disk_info *tmp;
7545 unsigned long flags;
7547 for (i = 0; i < conf->raid_disks; i++) {
7548 tmp = conf->disks + i;
7549 if (tmp->replacement
7550 && tmp->replacement->recovery_offset == MaxSector
7551 && !test_bit(Faulty, &tmp->replacement->flags)
7552 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7553 /* Replacement has just become active. */
7555 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7558 /* Replaced device not technically faulty,
7559 * but we need to be sure it gets removed
7560 * and never re-added.
7562 set_bit(Faulty, &tmp->rdev->flags);
7563 sysfs_notify_dirent_safe(
7564 tmp->rdev->sysfs_state);
7566 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7567 } else if (tmp->rdev
7568 && tmp->rdev->recovery_offset == MaxSector
7569 && !test_bit(Faulty, &tmp->rdev->flags)
7570 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7572 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7575 spin_lock_irqsave(&conf->device_lock, flags);
7576 mddev->degraded = raid5_calc_degraded(conf);
7577 spin_unlock_irqrestore(&conf->device_lock, flags);
7578 print_raid5_conf(conf);
7582 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7584 struct r5conf *conf = mddev->private;
7586 int number = rdev->raid_disk;
7587 struct md_rdev **rdevp;
7588 struct disk_info *p = conf->disks + number;
7590 print_raid5_conf(conf);
7591 if (test_bit(Journal, &rdev->flags) && conf->log) {
7593 * we can't wait pending write here, as this is called in
7594 * raid5d, wait will deadlock.
7595 * neilb: there is no locking about new writes here,
7596 * so this cannot be safe.
7598 if (atomic_read(&conf->active_stripes) ||
7599 atomic_read(&conf->r5c_cached_full_stripes) ||
7600 atomic_read(&conf->r5c_cached_partial_stripes)) {
7606 if (rdev == p->rdev)
7608 else if (rdev == p->replacement)
7609 rdevp = &p->replacement;
7613 if (number >= conf->raid_disks &&
7614 conf->reshape_progress == MaxSector)
7615 clear_bit(In_sync, &rdev->flags);
7617 if (test_bit(In_sync, &rdev->flags) ||
7618 atomic_read(&rdev->nr_pending)) {
7622 /* Only remove non-faulty devices if recovery
7625 if (!test_bit(Faulty, &rdev->flags) &&
7626 mddev->recovery_disabled != conf->recovery_disabled &&
7627 !has_failed(conf) &&
7628 (!p->replacement || p->replacement == rdev) &&
7629 number < conf->raid_disks) {
7634 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7636 if (atomic_read(&rdev->nr_pending)) {
7637 /* lost the race, try later */
7643 err = log_modify(conf, rdev, false);
7647 if (p->replacement) {
7648 /* We must have just cleared 'rdev' */
7649 p->rdev = p->replacement;
7650 clear_bit(Replacement, &p->replacement->flags);
7651 smp_mb(); /* Make sure other CPUs may see both as identical
7652 * but will never see neither - if they are careful
7654 p->replacement = NULL;
7657 err = log_modify(conf, p->rdev, true);
7660 clear_bit(WantReplacement, &rdev->flags);
7663 print_raid5_conf(conf);
7667 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7669 struct r5conf *conf = mddev->private;
7672 struct disk_info *p;
7674 int last = conf->raid_disks - 1;
7676 if (test_bit(Journal, &rdev->flags)) {
7680 rdev->raid_disk = 0;
7682 * The array is in readonly mode if journal is missing, so no
7683 * write requests running. We should be safe
7685 log_init(conf, rdev, false);
7688 if (mddev->recovery_disabled == conf->recovery_disabled)
7691 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7692 /* no point adding a device */
7695 if (rdev->raid_disk >= 0)
7696 first = last = rdev->raid_disk;
7699 * find the disk ... but prefer rdev->saved_raid_disk
7702 if (rdev->saved_raid_disk >= 0 &&
7703 rdev->saved_raid_disk >= first &&
7704 rdev->saved_raid_disk <= last &&
7705 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7706 first = rdev->saved_raid_disk;
7708 for (disk = first; disk <= last; disk++) {
7709 p = conf->disks + disk;
7710 if (p->rdev == NULL) {
7711 clear_bit(In_sync, &rdev->flags);
7712 rdev->raid_disk = disk;
7713 if (rdev->saved_raid_disk != disk)
7715 rcu_assign_pointer(p->rdev, rdev);
7717 err = log_modify(conf, rdev, true);
7722 for (disk = first; disk <= last; disk++) {
7723 p = conf->disks + disk;
7724 if (test_bit(WantReplacement, &p->rdev->flags) &&
7725 p->replacement == NULL) {
7726 clear_bit(In_sync, &rdev->flags);
7727 set_bit(Replacement, &rdev->flags);
7728 rdev->raid_disk = disk;
7731 rcu_assign_pointer(p->replacement, rdev);
7736 print_raid5_conf(conf);
7740 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7742 /* no resync is happening, and there is enough space
7743 * on all devices, so we can resize.
7744 * We need to make sure resync covers any new space.
7745 * If the array is shrinking we should possibly wait until
7746 * any io in the removed space completes, but it hardly seems
7750 struct r5conf *conf = mddev->private;
7752 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7754 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7755 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7756 if (mddev->external_size &&
7757 mddev->array_sectors > newsize)
7759 if (mddev->bitmap) {
7760 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
7764 md_set_array_sectors(mddev, newsize);
7765 if (sectors > mddev->dev_sectors &&
7766 mddev->recovery_cp > mddev->dev_sectors) {
7767 mddev->recovery_cp = mddev->dev_sectors;
7768 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7770 mddev->dev_sectors = sectors;
7771 mddev->resync_max_sectors = sectors;
7775 static int check_stripe_cache(struct mddev *mddev)
7777 /* Can only proceed if there are plenty of stripe_heads.
7778 * We need a minimum of one full stripe,, and for sensible progress
7779 * it is best to have about 4 times that.
7780 * If we require 4 times, then the default 256 4K stripe_heads will
7781 * allow for chunk sizes up to 256K, which is probably OK.
7782 * If the chunk size is greater, user-space should request more
7783 * stripe_heads first.
7785 struct r5conf *conf = mddev->private;
7786 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7787 > conf->min_nr_stripes ||
7788 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7789 > conf->min_nr_stripes) {
7790 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7792 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7799 static int check_reshape(struct mddev *mddev)
7801 struct r5conf *conf = mddev->private;
7803 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7805 if (mddev->delta_disks == 0 &&
7806 mddev->new_layout == mddev->layout &&
7807 mddev->new_chunk_sectors == mddev->chunk_sectors)
7808 return 0; /* nothing to do */
7809 if (has_failed(conf))
7811 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7812 /* We might be able to shrink, but the devices must
7813 * be made bigger first.
7814 * For raid6, 4 is the minimum size.
7815 * Otherwise 2 is the minimum
7818 if (mddev->level == 6)
7820 if (mddev->raid_disks + mddev->delta_disks < min)
7824 if (!check_stripe_cache(mddev))
7827 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7828 mddev->delta_disks > 0)
7829 if (resize_chunks(conf,
7830 conf->previous_raid_disks
7831 + max(0, mddev->delta_disks),
7832 max(mddev->new_chunk_sectors,
7833 mddev->chunk_sectors)
7837 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
7838 return 0; /* never bother to shrink */
7839 return resize_stripes(conf, (conf->previous_raid_disks
7840 + mddev->delta_disks));
7843 static int raid5_start_reshape(struct mddev *mddev)
7845 struct r5conf *conf = mddev->private;
7846 struct md_rdev *rdev;
7848 unsigned long flags;
7850 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7853 if (!check_stripe_cache(mddev))
7856 if (has_failed(conf))
7859 rdev_for_each(rdev, mddev) {
7860 if (!test_bit(In_sync, &rdev->flags)
7861 && !test_bit(Faulty, &rdev->flags))
7865 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7866 /* Not enough devices even to make a degraded array
7871 /* Refuse to reduce size of the array. Any reductions in
7872 * array size must be through explicit setting of array_size
7875 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7876 < mddev->array_sectors) {
7877 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
7882 atomic_set(&conf->reshape_stripes, 0);
7883 spin_lock_irq(&conf->device_lock);
7884 write_seqcount_begin(&conf->gen_lock);
7885 conf->previous_raid_disks = conf->raid_disks;
7886 conf->raid_disks += mddev->delta_disks;
7887 conf->prev_chunk_sectors = conf->chunk_sectors;
7888 conf->chunk_sectors = mddev->new_chunk_sectors;
7889 conf->prev_algo = conf->algorithm;
7890 conf->algorithm = mddev->new_layout;
7892 /* Code that selects data_offset needs to see the generation update
7893 * if reshape_progress has been set - so a memory barrier needed.
7896 if (mddev->reshape_backwards)
7897 conf->reshape_progress = raid5_size(mddev, 0, 0);
7899 conf->reshape_progress = 0;
7900 conf->reshape_safe = conf->reshape_progress;
7901 write_seqcount_end(&conf->gen_lock);
7902 spin_unlock_irq(&conf->device_lock);
7904 /* Now make sure any requests that proceeded on the assumption
7905 * the reshape wasn't running - like Discard or Read - have
7908 mddev_suspend(mddev);
7909 mddev_resume(mddev);
7911 /* Add some new drives, as many as will fit.
7912 * We know there are enough to make the newly sized array work.
7913 * Don't add devices if we are reducing the number of
7914 * devices in the array. This is because it is not possible
7915 * to correctly record the "partially reconstructed" state of
7916 * such devices during the reshape and confusion could result.
7918 if (mddev->delta_disks >= 0) {
7919 rdev_for_each(rdev, mddev)
7920 if (rdev->raid_disk < 0 &&
7921 !test_bit(Faulty, &rdev->flags)) {
7922 if (raid5_add_disk(mddev, rdev) == 0) {
7924 >= conf->previous_raid_disks)
7925 set_bit(In_sync, &rdev->flags);
7927 rdev->recovery_offset = 0;
7929 if (sysfs_link_rdev(mddev, rdev))
7930 /* Failure here is OK */;
7932 } else if (rdev->raid_disk >= conf->previous_raid_disks
7933 && !test_bit(Faulty, &rdev->flags)) {
7934 /* This is a spare that was manually added */
7935 set_bit(In_sync, &rdev->flags);
7938 /* When a reshape changes the number of devices,
7939 * ->degraded is measured against the larger of the
7940 * pre and post number of devices.
7942 spin_lock_irqsave(&conf->device_lock, flags);
7943 mddev->degraded = raid5_calc_degraded(conf);
7944 spin_unlock_irqrestore(&conf->device_lock, flags);
7946 mddev->raid_disks = conf->raid_disks;
7947 mddev->reshape_position = conf->reshape_progress;
7948 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
7950 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7951 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7952 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7953 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7954 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7955 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7957 if (!mddev->sync_thread) {
7958 mddev->recovery = 0;
7959 spin_lock_irq(&conf->device_lock);
7960 write_seqcount_begin(&conf->gen_lock);
7961 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7962 mddev->new_chunk_sectors =
7963 conf->chunk_sectors = conf->prev_chunk_sectors;
7964 mddev->new_layout = conf->algorithm = conf->prev_algo;
7965 rdev_for_each(rdev, mddev)
7966 rdev->new_data_offset = rdev->data_offset;
7968 conf->generation --;
7969 conf->reshape_progress = MaxSector;
7970 mddev->reshape_position = MaxSector;
7971 write_seqcount_end(&conf->gen_lock);
7972 spin_unlock_irq(&conf->device_lock);
7975 conf->reshape_checkpoint = jiffies;
7976 md_wakeup_thread(mddev->sync_thread);
7977 md_new_event(mddev);
7981 /* This is called from the reshape thread and should make any
7982 * changes needed in 'conf'
7984 static void end_reshape(struct r5conf *conf)
7987 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
7989 spin_lock_irq(&conf->device_lock);
7990 conf->previous_raid_disks = conf->raid_disks;
7991 md_finish_reshape(conf->mddev);
7993 conf->reshape_progress = MaxSector;
7994 conf->mddev->reshape_position = MaxSector;
7995 spin_unlock_irq(&conf->device_lock);
7996 wake_up(&conf->wait_for_overlap);
7998 /* read-ahead size must cover two whole stripes, which is
7999 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
8001 if (conf->mddev->queue) {
8002 int data_disks = conf->raid_disks - conf->max_degraded;
8003 int stripe = data_disks * ((conf->chunk_sectors << 9)
8005 if (conf->mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
8006 conf->mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
8011 /* This is called from the raid5d thread with mddev_lock held.
8012 * It makes config changes to the device.
8014 static void raid5_finish_reshape(struct mddev *mddev)
8016 struct r5conf *conf = mddev->private;
8018 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8020 if (mddev->delta_disks <= 0) {
8022 spin_lock_irq(&conf->device_lock);
8023 mddev->degraded = raid5_calc_degraded(conf);
8024 spin_unlock_irq(&conf->device_lock);
8025 for (d = conf->raid_disks ;
8026 d < conf->raid_disks - mddev->delta_disks;
8028 struct md_rdev *rdev = conf->disks[d].rdev;
8030 clear_bit(In_sync, &rdev->flags);
8031 rdev = conf->disks[d].replacement;
8033 clear_bit(In_sync, &rdev->flags);
8036 mddev->layout = conf->algorithm;
8037 mddev->chunk_sectors = conf->chunk_sectors;
8038 mddev->reshape_position = MaxSector;
8039 mddev->delta_disks = 0;
8040 mddev->reshape_backwards = 0;
8044 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8046 struct r5conf *conf = mddev->private;
8049 /* stop all writes */
8050 lock_all_device_hash_locks_irq(conf);
8051 /* '2' tells resync/reshape to pause so that all
8052 * active stripes can drain
8054 r5c_flush_cache(conf, INT_MAX);
8056 wait_event_cmd(conf->wait_for_quiescent,
8057 atomic_read(&conf->active_stripes) == 0 &&
8058 atomic_read(&conf->active_aligned_reads) == 0,
8059 unlock_all_device_hash_locks_irq(conf),
8060 lock_all_device_hash_locks_irq(conf));
8062 unlock_all_device_hash_locks_irq(conf);
8063 /* allow reshape to continue */
8064 wake_up(&conf->wait_for_overlap);
8066 /* re-enable writes */
8067 lock_all_device_hash_locks_irq(conf);
8069 wake_up(&conf->wait_for_quiescent);
8070 wake_up(&conf->wait_for_overlap);
8071 unlock_all_device_hash_locks_irq(conf);
8073 r5l_quiesce(conf->log, quiesce);
8076 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8078 struct r0conf *raid0_conf = mddev->private;
8081 /* for raid0 takeover only one zone is supported */
8082 if (raid0_conf->nr_strip_zones > 1) {
8083 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8085 return ERR_PTR(-EINVAL);
8088 sectors = raid0_conf->strip_zone[0].zone_end;
8089 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8090 mddev->dev_sectors = sectors;
8091 mddev->new_level = level;
8092 mddev->new_layout = ALGORITHM_PARITY_N;
8093 mddev->new_chunk_sectors = mddev->chunk_sectors;
8094 mddev->raid_disks += 1;
8095 mddev->delta_disks = 1;
8096 /* make sure it will be not marked as dirty */
8097 mddev->recovery_cp = MaxSector;
8099 return setup_conf(mddev);
8102 static void *raid5_takeover_raid1(struct mddev *mddev)
8107 if (mddev->raid_disks != 2 ||
8108 mddev->degraded > 1)
8109 return ERR_PTR(-EINVAL);
8111 /* Should check if there are write-behind devices? */
8113 chunksect = 64*2; /* 64K by default */
8115 /* The array must be an exact multiple of chunksize */
8116 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8119 if ((chunksect<<9) < STRIPE_SIZE)
8120 /* array size does not allow a suitable chunk size */
8121 return ERR_PTR(-EINVAL);
8123 mddev->new_level = 5;
8124 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8125 mddev->new_chunk_sectors = chunksect;
8127 ret = setup_conf(mddev);
8129 mddev_clear_unsupported_flags(mddev,
8130 UNSUPPORTED_MDDEV_FLAGS);
8134 static void *raid5_takeover_raid6(struct mddev *mddev)
8138 switch (mddev->layout) {
8139 case ALGORITHM_LEFT_ASYMMETRIC_6:
8140 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8142 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8143 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8145 case ALGORITHM_LEFT_SYMMETRIC_6:
8146 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8148 case ALGORITHM_RIGHT_SYMMETRIC_6:
8149 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8151 case ALGORITHM_PARITY_0_6:
8152 new_layout = ALGORITHM_PARITY_0;
8154 case ALGORITHM_PARITY_N:
8155 new_layout = ALGORITHM_PARITY_N;
8158 return ERR_PTR(-EINVAL);
8160 mddev->new_level = 5;
8161 mddev->new_layout = new_layout;
8162 mddev->delta_disks = -1;
8163 mddev->raid_disks -= 1;
8164 return setup_conf(mddev);
8167 static int raid5_check_reshape(struct mddev *mddev)
8169 /* For a 2-drive array, the layout and chunk size can be changed
8170 * immediately as not restriping is needed.
8171 * For larger arrays we record the new value - after validation
8172 * to be used by a reshape pass.
8174 struct r5conf *conf = mddev->private;
8175 int new_chunk = mddev->new_chunk_sectors;
8177 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8179 if (new_chunk > 0) {
8180 if (!is_power_of_2(new_chunk))
8182 if (new_chunk < (PAGE_SIZE>>9))
8184 if (mddev->array_sectors & (new_chunk-1))
8185 /* not factor of array size */
8189 /* They look valid */
8191 if (mddev->raid_disks == 2) {
8192 /* can make the change immediately */
8193 if (mddev->new_layout >= 0) {
8194 conf->algorithm = mddev->new_layout;
8195 mddev->layout = mddev->new_layout;
8197 if (new_chunk > 0) {
8198 conf->chunk_sectors = new_chunk ;
8199 mddev->chunk_sectors = new_chunk;
8201 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8202 md_wakeup_thread(mddev->thread);
8204 return check_reshape(mddev);
8207 static int raid6_check_reshape(struct mddev *mddev)
8209 int new_chunk = mddev->new_chunk_sectors;
8211 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8213 if (new_chunk > 0) {
8214 if (!is_power_of_2(new_chunk))
8216 if (new_chunk < (PAGE_SIZE >> 9))
8218 if (mddev->array_sectors & (new_chunk-1))
8219 /* not factor of array size */
8223 /* They look valid */
8224 return check_reshape(mddev);
8227 static void *raid5_takeover(struct mddev *mddev)
8229 /* raid5 can take over:
8230 * raid0 - if there is only one strip zone - make it a raid4 layout
8231 * raid1 - if there are two drives. We need to know the chunk size
8232 * raid4 - trivial - just use a raid4 layout.
8233 * raid6 - Providing it is a *_6 layout
8235 if (mddev->level == 0)
8236 return raid45_takeover_raid0(mddev, 5);
8237 if (mddev->level == 1)
8238 return raid5_takeover_raid1(mddev);
8239 if (mddev->level == 4) {
8240 mddev->new_layout = ALGORITHM_PARITY_N;
8241 mddev->new_level = 5;
8242 return setup_conf(mddev);
8244 if (mddev->level == 6)
8245 return raid5_takeover_raid6(mddev);
8247 return ERR_PTR(-EINVAL);
8250 static void *raid4_takeover(struct mddev *mddev)
8252 /* raid4 can take over:
8253 * raid0 - if there is only one strip zone
8254 * raid5 - if layout is right
8256 if (mddev->level == 0)
8257 return raid45_takeover_raid0(mddev, 4);
8258 if (mddev->level == 5 &&
8259 mddev->layout == ALGORITHM_PARITY_N) {
8260 mddev->new_layout = 0;
8261 mddev->new_level = 4;
8262 return setup_conf(mddev);
8264 return ERR_PTR(-EINVAL);
8267 static struct md_personality raid5_personality;
8269 static void *raid6_takeover(struct mddev *mddev)
8271 /* Currently can only take over a raid5. We map the
8272 * personality to an equivalent raid6 personality
8273 * with the Q block at the end.
8277 if (mddev->pers != &raid5_personality)
8278 return ERR_PTR(-EINVAL);
8279 if (mddev->degraded > 1)
8280 return ERR_PTR(-EINVAL);
8281 if (mddev->raid_disks > 253)
8282 return ERR_PTR(-EINVAL);
8283 if (mddev->raid_disks < 3)
8284 return ERR_PTR(-EINVAL);
8286 switch (mddev->layout) {
8287 case ALGORITHM_LEFT_ASYMMETRIC:
8288 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8290 case ALGORITHM_RIGHT_ASYMMETRIC:
8291 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8293 case ALGORITHM_LEFT_SYMMETRIC:
8294 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8296 case ALGORITHM_RIGHT_SYMMETRIC:
8297 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8299 case ALGORITHM_PARITY_0:
8300 new_layout = ALGORITHM_PARITY_0_6;
8302 case ALGORITHM_PARITY_N:
8303 new_layout = ALGORITHM_PARITY_N;
8306 return ERR_PTR(-EINVAL);
8308 mddev->new_level = 6;
8309 mddev->new_layout = new_layout;
8310 mddev->delta_disks = 1;
8311 mddev->raid_disks += 1;
8312 return setup_conf(mddev);
8315 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8317 struct r5conf *conf;
8320 err = mddev_lock(mddev);
8323 conf = mddev->private;
8325 mddev_unlock(mddev);
8329 if (strncmp(buf, "ppl", 3) == 0) {
8330 /* ppl only works with RAID 5 */
8331 if (!raid5_has_ppl(conf) && conf->level == 5) {
8332 err = log_init(conf, NULL, true);
8334 err = resize_stripes(conf, conf->pool_size);
8340 } else if (strncmp(buf, "resync", 6) == 0) {
8341 if (raid5_has_ppl(conf)) {
8342 mddev_suspend(mddev);
8344 mddev_resume(mddev);
8345 err = resize_stripes(conf, conf->pool_size);
8346 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8347 r5l_log_disk_error(conf)) {
8348 bool journal_dev_exists = false;
8349 struct md_rdev *rdev;
8351 rdev_for_each(rdev, mddev)
8352 if (test_bit(Journal, &rdev->flags)) {
8353 journal_dev_exists = true;
8357 if (!journal_dev_exists) {
8358 mddev_suspend(mddev);
8359 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8360 mddev_resume(mddev);
8361 } else /* need remove journal device first */
8370 md_update_sb(mddev, 1);
8372 mddev_unlock(mddev);
8377 static struct md_personality raid6_personality =
8381 .owner = THIS_MODULE,
8382 .make_request = raid5_make_request,
8385 .status = raid5_status,
8386 .error_handler = raid5_error,
8387 .hot_add_disk = raid5_add_disk,
8388 .hot_remove_disk= raid5_remove_disk,
8389 .spare_active = raid5_spare_active,
8390 .sync_request = raid5_sync_request,
8391 .resize = raid5_resize,
8393 .check_reshape = raid6_check_reshape,
8394 .start_reshape = raid5_start_reshape,
8395 .finish_reshape = raid5_finish_reshape,
8396 .quiesce = raid5_quiesce,
8397 .takeover = raid6_takeover,
8398 .congested = raid5_congested,
8399 .change_consistency_policy = raid5_change_consistency_policy,
8401 static struct md_personality raid5_personality =
8405 .owner = THIS_MODULE,
8406 .make_request = raid5_make_request,
8409 .status = raid5_status,
8410 .error_handler = raid5_error,
8411 .hot_add_disk = raid5_add_disk,
8412 .hot_remove_disk= raid5_remove_disk,
8413 .spare_active = raid5_spare_active,
8414 .sync_request = raid5_sync_request,
8415 .resize = raid5_resize,
8417 .check_reshape = raid5_check_reshape,
8418 .start_reshape = raid5_start_reshape,
8419 .finish_reshape = raid5_finish_reshape,
8420 .quiesce = raid5_quiesce,
8421 .takeover = raid5_takeover,
8422 .congested = raid5_congested,
8423 .change_consistency_policy = raid5_change_consistency_policy,
8426 static struct md_personality raid4_personality =
8430 .owner = THIS_MODULE,
8431 .make_request = raid5_make_request,
8434 .status = raid5_status,
8435 .error_handler = raid5_error,
8436 .hot_add_disk = raid5_add_disk,
8437 .hot_remove_disk= raid5_remove_disk,
8438 .spare_active = raid5_spare_active,
8439 .sync_request = raid5_sync_request,
8440 .resize = raid5_resize,
8442 .check_reshape = raid5_check_reshape,
8443 .start_reshape = raid5_start_reshape,
8444 .finish_reshape = raid5_finish_reshape,
8445 .quiesce = raid5_quiesce,
8446 .takeover = raid4_takeover,
8447 .congested = raid5_congested,
8448 .change_consistency_policy = raid5_change_consistency_policy,
8451 static int __init raid5_init(void)
8455 raid5_wq = alloc_workqueue("raid5wq",
8456 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8460 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8462 raid456_cpu_up_prepare,
8465 destroy_workqueue(raid5_wq);
8468 register_md_personality(&raid6_personality);
8469 register_md_personality(&raid5_personality);
8470 register_md_personality(&raid4_personality);
8474 static void raid5_exit(void)
8476 unregister_md_personality(&raid6_personality);
8477 unregister_md_personality(&raid5_personality);
8478 unregister_md_personality(&raid4_personality);
8479 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8480 destroy_workqueue(raid5_wq);
8483 module_init(raid5_init);
8484 module_exit(raid5_exit);
8485 MODULE_LICENSE("GPL");
8486 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8487 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8488 MODULE_ALIAS("md-raid5");
8489 MODULE_ALIAS("md-raid4");
8490 MODULE_ALIAS("md-level-5");
8491 MODULE_ALIAS("md-level-4");
8492 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8493 MODULE_ALIAS("md-raid6");
8494 MODULE_ALIAS("md-level-6");
8496 /* This used to be two separate modules, they were: */
8497 MODULE_ALIAS("raid5");
8498 MODULE_ALIAS("raid6");