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>
60 #include <trace/events/block.h>
61 #include <linux/list_sort.h>
66 #include "md-bitmap.h"
67 #include "raid5-log.h"
69 #define UNSUPPORTED_MDDEV_FLAGS (1L << MD_FAILFAST_SUPPORTED)
71 #define cpu_to_group(cpu) cpu_to_node(cpu)
72 #define ANY_GROUP NUMA_NO_NODE
74 static bool devices_handle_discard_safely = false;
75 module_param(devices_handle_discard_safely, bool, 0644);
76 MODULE_PARM_DESC(devices_handle_discard_safely,
77 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
78 static struct workqueue_struct *raid5_wq;
80 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
82 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
83 return &conf->stripe_hashtbl[hash];
86 static inline int stripe_hash_locks_hash(sector_t sect)
88 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
91 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
93 spin_lock_irq(conf->hash_locks + hash);
94 spin_lock(&conf->device_lock);
97 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
99 spin_unlock(&conf->device_lock);
100 spin_unlock_irq(conf->hash_locks + hash);
103 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
106 spin_lock_irq(conf->hash_locks);
107 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
108 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
109 spin_lock(&conf->device_lock);
112 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
115 spin_unlock(&conf->device_lock);
116 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
117 spin_unlock(conf->hash_locks + i);
118 spin_unlock_irq(conf->hash_locks);
121 /* Find first data disk in a raid6 stripe */
122 static inline int raid6_d0(struct stripe_head *sh)
125 /* ddf always start from first device */
127 /* md starts just after Q block */
128 if (sh->qd_idx == sh->disks - 1)
131 return sh->qd_idx + 1;
133 static inline int raid6_next_disk(int disk, int raid_disks)
136 return (disk < raid_disks) ? disk : 0;
139 /* When walking through the disks in a raid5, starting at raid6_d0,
140 * We need to map each disk to a 'slot', where the data disks are slot
141 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
142 * is raid_disks-1. This help does that mapping.
144 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
145 int *count, int syndrome_disks)
151 if (idx == sh->pd_idx)
152 return syndrome_disks;
153 if (idx == sh->qd_idx)
154 return syndrome_disks + 1;
160 static void print_raid5_conf (struct r5conf *conf);
162 static int stripe_operations_active(struct stripe_head *sh)
164 return sh->check_state || sh->reconstruct_state ||
165 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
166 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
169 static bool stripe_is_lowprio(struct stripe_head *sh)
171 return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
172 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
173 !test_bit(STRIPE_R5C_CACHING, &sh->state);
176 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
178 struct r5conf *conf = sh->raid_conf;
179 struct r5worker_group *group;
181 int i, cpu = sh->cpu;
183 if (!cpu_online(cpu)) {
184 cpu = cpumask_any(cpu_online_mask);
188 if (list_empty(&sh->lru)) {
189 struct r5worker_group *group;
190 group = conf->worker_groups + cpu_to_group(cpu);
191 if (stripe_is_lowprio(sh))
192 list_add_tail(&sh->lru, &group->loprio_list);
194 list_add_tail(&sh->lru, &group->handle_list);
195 group->stripes_cnt++;
199 if (conf->worker_cnt_per_group == 0) {
200 md_wakeup_thread(conf->mddev->thread);
204 group = conf->worker_groups + cpu_to_group(sh->cpu);
206 group->workers[0].working = true;
207 /* at least one worker should run to avoid race */
208 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
210 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
211 /* wakeup more workers */
212 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
213 if (group->workers[i].working == false) {
214 group->workers[i].working = true;
215 queue_work_on(sh->cpu, raid5_wq,
216 &group->workers[i].work);
222 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
223 struct list_head *temp_inactive_list)
226 int injournal = 0; /* number of date pages with R5_InJournal */
228 BUG_ON(!list_empty(&sh->lru));
229 BUG_ON(atomic_read(&conf->active_stripes)==0);
231 if (r5c_is_writeback(conf->log))
232 for (i = sh->disks; i--; )
233 if (test_bit(R5_InJournal, &sh->dev[i].flags))
236 * In the following cases, the stripe cannot be released to cached
237 * lists. Therefore, we make the stripe write out and set
239 * 1. when quiesce in r5c write back;
240 * 2. when resync is requested fot the stripe.
242 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
243 (conf->quiesce && r5c_is_writeback(conf->log) &&
244 !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
245 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
246 r5c_make_stripe_write_out(sh);
247 set_bit(STRIPE_HANDLE, &sh->state);
250 if (test_bit(STRIPE_HANDLE, &sh->state)) {
251 if (test_bit(STRIPE_DELAYED, &sh->state) &&
252 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
253 list_add_tail(&sh->lru, &conf->delayed_list);
254 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
255 sh->bm_seq - conf->seq_write > 0)
256 list_add_tail(&sh->lru, &conf->bitmap_list);
258 clear_bit(STRIPE_DELAYED, &sh->state);
259 clear_bit(STRIPE_BIT_DELAY, &sh->state);
260 if (conf->worker_cnt_per_group == 0) {
261 if (stripe_is_lowprio(sh))
262 list_add_tail(&sh->lru,
265 list_add_tail(&sh->lru,
268 raid5_wakeup_stripe_thread(sh);
272 md_wakeup_thread(conf->mddev->thread);
274 BUG_ON(stripe_operations_active(sh));
275 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
276 if (atomic_dec_return(&conf->preread_active_stripes)
278 md_wakeup_thread(conf->mddev->thread);
279 atomic_dec(&conf->active_stripes);
280 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
281 if (!r5c_is_writeback(conf->log))
282 list_add_tail(&sh->lru, temp_inactive_list);
284 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
286 list_add_tail(&sh->lru, temp_inactive_list);
287 else if (injournal == conf->raid_disks - conf->max_degraded) {
289 if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
290 atomic_inc(&conf->r5c_cached_full_stripes);
291 if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
292 atomic_dec(&conf->r5c_cached_partial_stripes);
293 list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
294 r5c_check_cached_full_stripe(conf);
297 * STRIPE_R5C_PARTIAL_STRIPE is set in
298 * r5c_try_caching_write(). No need to
301 list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
307 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
308 struct list_head *temp_inactive_list)
310 if (atomic_dec_and_test(&sh->count))
311 do_release_stripe(conf, sh, temp_inactive_list);
315 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
317 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
318 * given time. Adding stripes only takes device lock, while deleting stripes
319 * only takes hash lock.
321 static void release_inactive_stripe_list(struct r5conf *conf,
322 struct list_head *temp_inactive_list,
326 bool do_wakeup = false;
329 if (hash == NR_STRIPE_HASH_LOCKS) {
330 size = NR_STRIPE_HASH_LOCKS;
331 hash = NR_STRIPE_HASH_LOCKS - 1;
335 struct list_head *list = &temp_inactive_list[size - 1];
338 * We don't hold any lock here yet, raid5_get_active_stripe() might
339 * remove stripes from the list
341 if (!list_empty_careful(list)) {
342 spin_lock_irqsave(conf->hash_locks + hash, flags);
343 if (list_empty(conf->inactive_list + hash) &&
345 atomic_dec(&conf->empty_inactive_list_nr);
346 list_splice_tail_init(list, conf->inactive_list + hash);
348 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
355 wake_up(&conf->wait_for_stripe);
356 if (atomic_read(&conf->active_stripes) == 0)
357 wake_up(&conf->wait_for_quiescent);
358 if (conf->retry_read_aligned)
359 md_wakeup_thread(conf->mddev->thread);
363 /* should hold conf->device_lock already */
364 static int release_stripe_list(struct r5conf *conf,
365 struct list_head *temp_inactive_list)
367 struct stripe_head *sh, *t;
369 struct llist_node *head;
371 head = llist_del_all(&conf->released_stripes);
372 head = llist_reverse_order(head);
373 llist_for_each_entry_safe(sh, t, head, release_list) {
376 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
378 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
380 * Don't worry the bit is set here, because if the bit is set
381 * again, the count is always > 1. This is true for
382 * STRIPE_ON_UNPLUG_LIST bit too.
384 hash = sh->hash_lock_index;
385 __release_stripe(conf, sh, &temp_inactive_list[hash]);
392 void raid5_release_stripe(struct stripe_head *sh)
394 struct r5conf *conf = sh->raid_conf;
396 struct list_head list;
400 /* Avoid release_list until the last reference.
402 if (atomic_add_unless(&sh->count, -1, 1))
405 if (unlikely(!conf->mddev->thread) ||
406 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
408 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
410 md_wakeup_thread(conf->mddev->thread);
413 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
414 if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
415 INIT_LIST_HEAD(&list);
416 hash = sh->hash_lock_index;
417 do_release_stripe(conf, sh, &list);
418 spin_unlock_irqrestore(&conf->device_lock, flags);
419 release_inactive_stripe_list(conf, &list, hash);
423 static inline void remove_hash(struct stripe_head *sh)
425 pr_debug("remove_hash(), stripe %llu\n",
426 (unsigned long long)sh->sector);
428 hlist_del_init(&sh->hash);
431 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
433 struct hlist_head *hp = stripe_hash(conf, sh->sector);
435 pr_debug("insert_hash(), stripe %llu\n",
436 (unsigned long long)sh->sector);
438 hlist_add_head(&sh->hash, hp);
441 /* find an idle stripe, make sure it is unhashed, and return it. */
442 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
444 struct stripe_head *sh = NULL;
445 struct list_head *first;
447 if (list_empty(conf->inactive_list + hash))
449 first = (conf->inactive_list + hash)->next;
450 sh = list_entry(first, struct stripe_head, lru);
451 list_del_init(first);
453 atomic_inc(&conf->active_stripes);
454 BUG_ON(hash != sh->hash_lock_index);
455 if (list_empty(conf->inactive_list + hash))
456 atomic_inc(&conf->empty_inactive_list_nr);
461 static void shrink_buffers(struct stripe_head *sh)
465 int num = sh->raid_conf->pool_size;
467 for (i = 0; i < num ; i++) {
468 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
472 sh->dev[i].page = NULL;
477 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
480 int num = sh->raid_conf->pool_size;
482 for (i = 0; i < num; i++) {
485 if (!(page = alloc_page(gfp))) {
488 sh->dev[i].page = page;
489 sh->dev[i].orig_page = page;
495 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
496 struct stripe_head *sh);
498 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
500 struct r5conf *conf = sh->raid_conf;
503 BUG_ON(atomic_read(&sh->count) != 0);
504 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
505 BUG_ON(stripe_operations_active(sh));
506 BUG_ON(sh->batch_head);
508 pr_debug("init_stripe called, stripe %llu\n",
509 (unsigned long long)sector);
511 seq = read_seqcount_begin(&conf->gen_lock);
512 sh->generation = conf->generation - previous;
513 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
515 stripe_set_idx(sector, conf, previous, sh);
518 for (i = sh->disks; i--; ) {
519 struct r5dev *dev = &sh->dev[i];
521 if (dev->toread || dev->read || dev->towrite || dev->written ||
522 test_bit(R5_LOCKED, &dev->flags)) {
523 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
524 (unsigned long long)sh->sector, i, dev->toread,
525 dev->read, dev->towrite, dev->written,
526 test_bit(R5_LOCKED, &dev->flags));
530 dev->sector = raid5_compute_blocknr(sh, i, previous);
532 if (read_seqcount_retry(&conf->gen_lock, seq))
534 sh->overwrite_disks = 0;
535 insert_hash(conf, sh);
536 sh->cpu = smp_processor_id();
537 set_bit(STRIPE_BATCH_READY, &sh->state);
540 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
543 struct stripe_head *sh;
545 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
546 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
547 if (sh->sector == sector && sh->generation == generation)
549 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
554 * Need to check if array has failed when deciding whether to:
556 * - remove non-faulty devices
559 * This determination is simple when no reshape is happening.
560 * However if there is a reshape, we need to carefully check
561 * both the before and after sections.
562 * This is because some failed devices may only affect one
563 * of the two sections, and some non-in_sync devices may
564 * be insync in the section most affected by failed devices.
566 int raid5_calc_degraded(struct r5conf *conf)
568 int degraded, degraded2;
573 for (i = 0; i < conf->previous_raid_disks; i++) {
574 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
575 if (rdev && test_bit(Faulty, &rdev->flags))
576 rdev = rcu_dereference(conf->disks[i].replacement);
577 if (!rdev || test_bit(Faulty, &rdev->flags))
579 else if (test_bit(In_sync, &rdev->flags))
582 /* not in-sync or faulty.
583 * If the reshape increases the number of devices,
584 * this is being recovered by the reshape, so
585 * this 'previous' section is not in_sync.
586 * If the number of devices is being reduced however,
587 * the device can only be part of the array if
588 * we are reverting a reshape, so this section will
591 if (conf->raid_disks >= conf->previous_raid_disks)
595 if (conf->raid_disks == conf->previous_raid_disks)
599 for (i = 0; i < conf->raid_disks; i++) {
600 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
601 if (rdev && test_bit(Faulty, &rdev->flags))
602 rdev = rcu_dereference(conf->disks[i].replacement);
603 if (!rdev || test_bit(Faulty, &rdev->flags))
605 else if (test_bit(In_sync, &rdev->flags))
608 /* not in-sync or faulty.
609 * If reshape increases the number of devices, this
610 * section has already been recovered, else it
611 * almost certainly hasn't.
613 if (conf->raid_disks <= conf->previous_raid_disks)
617 if (degraded2 > degraded)
622 static int has_failed(struct r5conf *conf)
626 if (conf->mddev->reshape_position == MaxSector)
627 return conf->mddev->degraded > conf->max_degraded;
629 degraded = raid5_calc_degraded(conf);
630 if (degraded > conf->max_degraded)
636 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
637 int previous, int noblock, int noquiesce)
639 struct stripe_head *sh;
640 int hash = stripe_hash_locks_hash(sector);
641 int inc_empty_inactive_list_flag;
643 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
645 spin_lock_irq(conf->hash_locks + hash);
648 wait_event_lock_irq(conf->wait_for_quiescent,
649 conf->quiesce == 0 || noquiesce,
650 *(conf->hash_locks + hash));
651 sh = __find_stripe(conf, sector, conf->generation - previous);
653 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
654 sh = get_free_stripe(conf, hash);
655 if (!sh && !test_bit(R5_DID_ALLOC,
657 set_bit(R5_ALLOC_MORE,
660 if (noblock && sh == NULL)
663 r5c_check_stripe_cache_usage(conf);
665 set_bit(R5_INACTIVE_BLOCKED,
667 r5l_wake_reclaim(conf->log, 0);
669 conf->wait_for_stripe,
670 !list_empty(conf->inactive_list + hash) &&
671 (atomic_read(&conf->active_stripes)
672 < (conf->max_nr_stripes * 3 / 4)
673 || !test_bit(R5_INACTIVE_BLOCKED,
674 &conf->cache_state)),
675 *(conf->hash_locks + hash));
676 clear_bit(R5_INACTIVE_BLOCKED,
679 init_stripe(sh, sector, previous);
680 atomic_inc(&sh->count);
682 } else if (!atomic_inc_not_zero(&sh->count)) {
683 spin_lock(&conf->device_lock);
684 if (!atomic_read(&sh->count)) {
685 if (!test_bit(STRIPE_HANDLE, &sh->state))
686 atomic_inc(&conf->active_stripes);
687 BUG_ON(list_empty(&sh->lru) &&
688 !test_bit(STRIPE_EXPANDING, &sh->state));
689 inc_empty_inactive_list_flag = 0;
690 if (!list_empty(conf->inactive_list + hash))
691 inc_empty_inactive_list_flag = 1;
692 list_del_init(&sh->lru);
693 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
694 atomic_inc(&conf->empty_inactive_list_nr);
696 sh->group->stripes_cnt--;
700 atomic_inc(&sh->count);
701 spin_unlock(&conf->device_lock);
703 } while (sh == NULL);
705 spin_unlock_irq(conf->hash_locks + hash);
709 static bool is_full_stripe_write(struct stripe_head *sh)
711 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
712 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
715 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
718 spin_lock_irq(&sh2->stripe_lock);
719 spin_lock_nested(&sh1->stripe_lock, 1);
721 spin_lock_irq(&sh1->stripe_lock);
722 spin_lock_nested(&sh2->stripe_lock, 1);
726 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
728 spin_unlock(&sh1->stripe_lock);
729 spin_unlock_irq(&sh2->stripe_lock);
732 /* Only freshly new full stripe normal write stripe can be added to a batch list */
733 static bool stripe_can_batch(struct stripe_head *sh)
735 struct r5conf *conf = sh->raid_conf;
737 if (raid5_has_log(conf) || raid5_has_ppl(conf))
739 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
740 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
741 is_full_stripe_write(sh);
744 /* we only do back search */
745 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
747 struct stripe_head *head;
748 sector_t head_sector, tmp_sec;
751 int inc_empty_inactive_list_flag;
753 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
754 tmp_sec = sh->sector;
755 if (!sector_div(tmp_sec, conf->chunk_sectors))
757 head_sector = sh->sector - STRIPE_SECTORS;
759 hash = stripe_hash_locks_hash(head_sector);
760 spin_lock_irq(conf->hash_locks + hash);
761 head = __find_stripe(conf, head_sector, conf->generation);
762 if (head && !atomic_inc_not_zero(&head->count)) {
763 spin_lock(&conf->device_lock);
764 if (!atomic_read(&head->count)) {
765 if (!test_bit(STRIPE_HANDLE, &head->state))
766 atomic_inc(&conf->active_stripes);
767 BUG_ON(list_empty(&head->lru) &&
768 !test_bit(STRIPE_EXPANDING, &head->state));
769 inc_empty_inactive_list_flag = 0;
770 if (!list_empty(conf->inactive_list + hash))
771 inc_empty_inactive_list_flag = 1;
772 list_del_init(&head->lru);
773 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
774 atomic_inc(&conf->empty_inactive_list_nr);
776 head->group->stripes_cnt--;
780 atomic_inc(&head->count);
781 spin_unlock(&conf->device_lock);
783 spin_unlock_irq(conf->hash_locks + hash);
787 if (!stripe_can_batch(head))
790 lock_two_stripes(head, sh);
791 /* clear_batch_ready clear the flag */
792 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
799 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
801 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
802 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
805 if (head->batch_head) {
806 spin_lock(&head->batch_head->batch_lock);
807 /* This batch list is already running */
808 if (!stripe_can_batch(head)) {
809 spin_unlock(&head->batch_head->batch_lock);
813 * We must assign batch_head of this stripe within the
814 * batch_lock, otherwise clear_batch_ready of batch head
815 * stripe could clear BATCH_READY bit of this stripe and
816 * this stripe->batch_head doesn't get assigned, which
817 * could confuse clear_batch_ready for this stripe
819 sh->batch_head = head->batch_head;
822 * at this point, head's BATCH_READY could be cleared, but we
823 * can still add the stripe to batch list
825 list_add(&sh->batch_list, &head->batch_list);
826 spin_unlock(&head->batch_head->batch_lock);
828 head->batch_head = head;
829 sh->batch_head = head->batch_head;
830 spin_lock(&head->batch_lock);
831 list_add_tail(&sh->batch_list, &head->batch_list);
832 spin_unlock(&head->batch_lock);
835 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
836 if (atomic_dec_return(&conf->preread_active_stripes)
838 md_wakeup_thread(conf->mddev->thread);
840 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
841 int seq = sh->bm_seq;
842 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
843 sh->batch_head->bm_seq > seq)
844 seq = sh->batch_head->bm_seq;
845 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
846 sh->batch_head->bm_seq = seq;
849 atomic_inc(&sh->count);
851 unlock_two_stripes(head, sh);
853 raid5_release_stripe(head);
856 /* Determine if 'data_offset' or 'new_data_offset' should be used
857 * in this stripe_head.
859 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
861 sector_t progress = conf->reshape_progress;
862 /* Need a memory barrier to make sure we see the value
863 * of conf->generation, or ->data_offset that was set before
864 * reshape_progress was updated.
867 if (progress == MaxSector)
869 if (sh->generation == conf->generation - 1)
871 /* We are in a reshape, and this is a new-generation stripe,
872 * so use new_data_offset.
877 static void dispatch_bio_list(struct bio_list *tmp)
881 while ((bio = bio_list_pop(tmp)))
882 generic_make_request(bio);
885 static int cmp_stripe(void *priv, struct list_head *a, struct list_head *b)
887 const struct r5pending_data *da = list_entry(a,
888 struct r5pending_data, sibling);
889 const struct r5pending_data *db = list_entry(b,
890 struct r5pending_data, sibling);
891 if (da->sector > db->sector)
893 if (da->sector < db->sector)
898 static void dispatch_defer_bios(struct r5conf *conf, int target,
899 struct bio_list *list)
901 struct r5pending_data *data;
902 struct list_head *first, *next = NULL;
905 if (conf->pending_data_cnt == 0)
908 list_sort(NULL, &conf->pending_list, cmp_stripe);
910 first = conf->pending_list.next;
912 /* temporarily move the head */
913 if (conf->next_pending_data)
914 list_move_tail(&conf->pending_list,
915 &conf->next_pending_data->sibling);
917 while (!list_empty(&conf->pending_list)) {
918 data = list_first_entry(&conf->pending_list,
919 struct r5pending_data, sibling);
920 if (&data->sibling == first)
921 first = data->sibling.next;
922 next = data->sibling.next;
924 bio_list_merge(list, &data->bios);
925 list_move(&data->sibling, &conf->free_list);
930 conf->pending_data_cnt -= cnt;
931 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
933 if (next != &conf->pending_list)
934 conf->next_pending_data = list_entry(next,
935 struct r5pending_data, sibling);
937 conf->next_pending_data = NULL;
938 /* list isn't empty */
939 if (first != &conf->pending_list)
940 list_move_tail(&conf->pending_list, first);
943 static void flush_deferred_bios(struct r5conf *conf)
945 struct bio_list tmp = BIO_EMPTY_LIST;
947 if (conf->pending_data_cnt == 0)
950 spin_lock(&conf->pending_bios_lock);
951 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
952 BUG_ON(conf->pending_data_cnt != 0);
953 spin_unlock(&conf->pending_bios_lock);
955 dispatch_bio_list(&tmp);
958 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
959 struct bio_list *bios)
961 struct bio_list tmp = BIO_EMPTY_LIST;
962 struct r5pending_data *ent;
964 spin_lock(&conf->pending_bios_lock);
965 ent = list_first_entry(&conf->free_list, struct r5pending_data,
967 list_move_tail(&ent->sibling, &conf->pending_list);
968 ent->sector = sector;
969 bio_list_init(&ent->bios);
970 bio_list_merge(&ent->bios, bios);
971 conf->pending_data_cnt++;
972 if (conf->pending_data_cnt >= PENDING_IO_MAX)
973 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
975 spin_unlock(&conf->pending_bios_lock);
977 dispatch_bio_list(&tmp);
981 raid5_end_read_request(struct bio *bi);
983 raid5_end_write_request(struct bio *bi);
985 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
987 struct r5conf *conf = sh->raid_conf;
988 int i, disks = sh->disks;
989 struct stripe_head *head_sh = sh;
990 struct bio_list pending_bios = BIO_EMPTY_LIST;
995 if (log_stripe(sh, s) == 0)
998 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1000 for (i = disks; i--; ) {
1001 int op, op_flags = 0;
1002 int replace_only = 0;
1003 struct bio *bi, *rbi;
1004 struct md_rdev *rdev, *rrdev = NULL;
1007 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1009 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1011 if (test_bit(R5_Discard, &sh->dev[i].flags))
1012 op = REQ_OP_DISCARD;
1013 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1015 else if (test_and_clear_bit(R5_WantReplace,
1016 &sh->dev[i].flags)) {
1021 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1022 op_flags |= REQ_SYNC;
1025 bi = &sh->dev[i].req;
1026 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1029 rrdev = rcu_dereference(conf->disks[i].replacement);
1030 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1031 rdev = rcu_dereference(conf->disks[i].rdev);
1036 if (op_is_write(op)) {
1040 /* We raced and saw duplicates */
1043 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1048 if (rdev && test_bit(Faulty, &rdev->flags))
1051 atomic_inc(&rdev->nr_pending);
1052 if (rrdev && test_bit(Faulty, &rrdev->flags))
1055 atomic_inc(&rrdev->nr_pending);
1058 /* We have already checked bad blocks for reads. Now
1059 * need to check for writes. We never accept write errors
1060 * on the replacement, so we don't to check rrdev.
1062 while (op_is_write(op) && rdev &&
1063 test_bit(WriteErrorSeen, &rdev->flags)) {
1066 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
1067 &first_bad, &bad_sectors);
1072 set_bit(BlockedBadBlocks, &rdev->flags);
1073 if (!conf->mddev->external &&
1074 conf->mddev->sb_flags) {
1075 /* It is very unlikely, but we might
1076 * still need to write out the
1077 * bad block log - better give it
1079 md_check_recovery(conf->mddev);
1082 * Because md_wait_for_blocked_rdev
1083 * will dec nr_pending, we must
1084 * increment it first.
1086 atomic_inc(&rdev->nr_pending);
1087 md_wait_for_blocked_rdev(rdev, conf->mddev);
1089 /* Acknowledged bad block - skip the write */
1090 rdev_dec_pending(rdev, conf->mddev);
1096 if (s->syncing || s->expanding || s->expanded
1098 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
1100 set_bit(STRIPE_IO_STARTED, &sh->state);
1102 bio_set_dev(bi, rdev->bdev);
1103 bio_set_op_attrs(bi, op, op_flags);
1104 bi->bi_end_io = op_is_write(op)
1105 ? raid5_end_write_request
1106 : raid5_end_read_request;
1107 bi->bi_private = sh;
1109 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1110 __func__, (unsigned long long)sh->sector,
1112 atomic_inc(&sh->count);
1114 atomic_inc(&head_sh->count);
1115 if (use_new_offset(conf, sh))
1116 bi->bi_iter.bi_sector = (sh->sector
1117 + rdev->new_data_offset);
1119 bi->bi_iter.bi_sector = (sh->sector
1120 + rdev->data_offset);
1121 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1122 bi->bi_opf |= REQ_NOMERGE;
1124 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1125 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1127 if (!op_is_write(op) &&
1128 test_bit(R5_InJournal, &sh->dev[i].flags))
1130 * issuing read for a page in journal, this
1131 * must be preparing for prexor in rmw; read
1132 * the data into orig_page
1134 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1136 sh->dev[i].vec.bv_page = sh->dev[i].page;
1138 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1139 bi->bi_io_vec[0].bv_offset = 0;
1140 bi->bi_iter.bi_size = STRIPE_SIZE;
1141 bi->bi_write_hint = sh->dev[i].write_hint;
1143 sh->dev[i].write_hint = RWF_WRITE_LIFE_NOT_SET;
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;
1195 rbi->bi_write_hint = sh->dev[i].write_hint;
1196 sh->dev[i].write_hint = RWF_WRITE_LIFE_NOT_SET;
1198 * If this is discard request, set bi_vcnt 0. We don't
1199 * want to confuse SCSI because SCSI will replace payload
1201 if (op == REQ_OP_DISCARD)
1203 if (conf->mddev->gendisk)
1204 trace_block_bio_remap(rbi->bi_disk->queue,
1205 rbi, disk_devt(conf->mddev->gendisk),
1207 if (should_defer && op_is_write(op))
1208 bio_list_add(&pending_bios, rbi);
1210 generic_make_request(rbi);
1212 if (!rdev && !rrdev) {
1213 if (op_is_write(op))
1214 set_bit(STRIPE_DEGRADED, &sh->state);
1215 pr_debug("skip op %d on disc %d for sector %llu\n",
1216 bi->bi_opf, i, (unsigned long long)sh->sector);
1217 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1218 set_bit(STRIPE_HANDLE, &sh->state);
1221 if (!head_sh->batch_head)
1223 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1229 if (should_defer && !bio_list_empty(&pending_bios))
1230 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1233 static struct dma_async_tx_descriptor *
1234 async_copy_data(int frombio, struct bio *bio, struct page **page,
1235 sector_t sector, struct dma_async_tx_descriptor *tx,
1236 struct stripe_head *sh, int no_skipcopy)
1239 struct bvec_iter iter;
1240 struct page *bio_page;
1242 struct async_submit_ctl submit;
1243 enum async_tx_flags flags = 0;
1245 if (bio->bi_iter.bi_sector >= sector)
1246 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1248 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1251 flags |= ASYNC_TX_FENCE;
1252 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1254 bio_for_each_segment(bvl, bio, iter) {
1255 int len = bvl.bv_len;
1259 if (page_offset < 0) {
1260 b_offset = -page_offset;
1261 page_offset += b_offset;
1265 if (len > 0 && page_offset + len > STRIPE_SIZE)
1266 clen = STRIPE_SIZE - page_offset;
1271 b_offset += bvl.bv_offset;
1272 bio_page = bvl.bv_page;
1274 if (sh->raid_conf->skip_copy &&
1275 b_offset == 0 && page_offset == 0 &&
1276 clen == STRIPE_SIZE &&
1280 tx = async_memcpy(*page, bio_page, page_offset,
1281 b_offset, clen, &submit);
1283 tx = async_memcpy(bio_page, *page, b_offset,
1284 page_offset, clen, &submit);
1286 /* chain the operations */
1287 submit.depend_tx = tx;
1289 if (clen < len) /* hit end of page */
1297 static void ops_complete_biofill(void *stripe_head_ref)
1299 struct stripe_head *sh = stripe_head_ref;
1302 pr_debug("%s: stripe %llu\n", __func__,
1303 (unsigned long long)sh->sector);
1305 /* clear completed biofills */
1306 for (i = sh->disks; i--; ) {
1307 struct r5dev *dev = &sh->dev[i];
1309 /* acknowledge completion of a biofill operation */
1310 /* and check if we need to reply to a read request,
1311 * new R5_Wantfill requests are held off until
1312 * !STRIPE_BIOFILL_RUN
1314 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1315 struct bio *rbi, *rbi2;
1320 while (rbi && rbi->bi_iter.bi_sector <
1321 dev->sector + STRIPE_SECTORS) {
1322 rbi2 = r5_next_bio(rbi, dev->sector);
1328 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1330 set_bit(STRIPE_HANDLE, &sh->state);
1331 raid5_release_stripe(sh);
1334 static void ops_run_biofill(struct stripe_head *sh)
1336 struct dma_async_tx_descriptor *tx = NULL;
1337 struct async_submit_ctl submit;
1340 BUG_ON(sh->batch_head);
1341 pr_debug("%s: stripe %llu\n", __func__,
1342 (unsigned long long)sh->sector);
1344 for (i = sh->disks; i--; ) {
1345 struct r5dev *dev = &sh->dev[i];
1346 if (test_bit(R5_Wantfill, &dev->flags)) {
1348 spin_lock_irq(&sh->stripe_lock);
1349 dev->read = rbi = dev->toread;
1351 spin_unlock_irq(&sh->stripe_lock);
1352 while (rbi && rbi->bi_iter.bi_sector <
1353 dev->sector + STRIPE_SECTORS) {
1354 tx = async_copy_data(0, rbi, &dev->page,
1355 dev->sector, tx, sh, 0);
1356 rbi = r5_next_bio(rbi, dev->sector);
1361 atomic_inc(&sh->count);
1362 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1363 async_trigger_callback(&submit);
1366 static void mark_target_uptodate(struct stripe_head *sh, int target)
1373 tgt = &sh->dev[target];
1374 set_bit(R5_UPTODATE, &tgt->flags);
1375 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1376 clear_bit(R5_Wantcompute, &tgt->flags);
1379 static void ops_complete_compute(void *stripe_head_ref)
1381 struct stripe_head *sh = stripe_head_ref;
1383 pr_debug("%s: stripe %llu\n", __func__,
1384 (unsigned long long)sh->sector);
1386 /* mark the computed target(s) as uptodate */
1387 mark_target_uptodate(sh, sh->ops.target);
1388 mark_target_uptodate(sh, sh->ops.target2);
1390 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1391 if (sh->check_state == check_state_compute_run)
1392 sh->check_state = check_state_compute_result;
1393 set_bit(STRIPE_HANDLE, &sh->state);
1394 raid5_release_stripe(sh);
1397 /* return a pointer to the address conversion region of the scribble buffer */
1398 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1399 struct raid5_percpu *percpu, int i)
1403 addr = flex_array_get(percpu->scribble, i);
1404 return addr + sizeof(struct page *) * (sh->disks + 2);
1407 /* return a pointer to the address conversion region of the scribble buffer */
1408 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1412 addr = flex_array_get(percpu->scribble, i);
1416 static struct dma_async_tx_descriptor *
1417 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1419 int disks = sh->disks;
1420 struct page **xor_srcs = to_addr_page(percpu, 0);
1421 int target = sh->ops.target;
1422 struct r5dev *tgt = &sh->dev[target];
1423 struct page *xor_dest = tgt->page;
1425 struct dma_async_tx_descriptor *tx;
1426 struct async_submit_ctl submit;
1429 BUG_ON(sh->batch_head);
1431 pr_debug("%s: stripe %llu block: %d\n",
1432 __func__, (unsigned long long)sh->sector, target);
1433 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1435 for (i = disks; i--; )
1437 xor_srcs[count++] = sh->dev[i].page;
1439 atomic_inc(&sh->count);
1441 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1442 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1443 if (unlikely(count == 1))
1444 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1446 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1451 /* set_syndrome_sources - populate source buffers for gen_syndrome
1452 * @srcs - (struct page *) array of size sh->disks
1453 * @sh - stripe_head to parse
1455 * Populates srcs in proper layout order for the stripe and returns the
1456 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1457 * destination buffer is recorded in srcs[count] and the Q destination
1458 * is recorded in srcs[count+1]].
1460 static int set_syndrome_sources(struct page **srcs,
1461 struct stripe_head *sh,
1464 int disks = sh->disks;
1465 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1466 int d0_idx = raid6_d0(sh);
1470 for (i = 0; i < disks; i++)
1476 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1477 struct r5dev *dev = &sh->dev[i];
1479 if (i == sh->qd_idx || i == sh->pd_idx ||
1480 (srctype == SYNDROME_SRC_ALL) ||
1481 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1482 (test_bit(R5_Wantdrain, &dev->flags) ||
1483 test_bit(R5_InJournal, &dev->flags))) ||
1484 (srctype == SYNDROME_SRC_WRITTEN &&
1486 test_bit(R5_InJournal, &dev->flags)))) {
1487 if (test_bit(R5_InJournal, &dev->flags))
1488 srcs[slot] = sh->dev[i].orig_page;
1490 srcs[slot] = sh->dev[i].page;
1492 i = raid6_next_disk(i, disks);
1493 } while (i != d0_idx);
1495 return syndrome_disks;
1498 static struct dma_async_tx_descriptor *
1499 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1501 int disks = sh->disks;
1502 struct page **blocks = to_addr_page(percpu, 0);
1504 int qd_idx = sh->qd_idx;
1505 struct dma_async_tx_descriptor *tx;
1506 struct async_submit_ctl submit;
1512 BUG_ON(sh->batch_head);
1513 if (sh->ops.target < 0)
1514 target = sh->ops.target2;
1515 else if (sh->ops.target2 < 0)
1516 target = sh->ops.target;
1518 /* we should only have one valid target */
1521 pr_debug("%s: stripe %llu block: %d\n",
1522 __func__, (unsigned long long)sh->sector, target);
1524 tgt = &sh->dev[target];
1525 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1528 atomic_inc(&sh->count);
1530 if (target == qd_idx) {
1531 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1532 blocks[count] = NULL; /* regenerating p is not necessary */
1533 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1534 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1535 ops_complete_compute, sh,
1536 to_addr_conv(sh, percpu, 0));
1537 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1539 /* Compute any data- or p-drive using XOR */
1541 for (i = disks; i-- ; ) {
1542 if (i == target || i == qd_idx)
1544 blocks[count++] = sh->dev[i].page;
1547 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1548 NULL, ops_complete_compute, sh,
1549 to_addr_conv(sh, percpu, 0));
1550 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1556 static struct dma_async_tx_descriptor *
1557 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1559 int i, count, disks = sh->disks;
1560 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1561 int d0_idx = raid6_d0(sh);
1562 int faila = -1, failb = -1;
1563 int target = sh->ops.target;
1564 int target2 = sh->ops.target2;
1565 struct r5dev *tgt = &sh->dev[target];
1566 struct r5dev *tgt2 = &sh->dev[target2];
1567 struct dma_async_tx_descriptor *tx;
1568 struct page **blocks = to_addr_page(percpu, 0);
1569 struct async_submit_ctl submit;
1571 BUG_ON(sh->batch_head);
1572 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1573 __func__, (unsigned long long)sh->sector, target, target2);
1574 BUG_ON(target < 0 || target2 < 0);
1575 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1576 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1578 /* we need to open-code set_syndrome_sources to handle the
1579 * slot number conversion for 'faila' and 'failb'
1581 for (i = 0; i < disks ; i++)
1586 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1588 blocks[slot] = sh->dev[i].page;
1594 i = raid6_next_disk(i, disks);
1595 } while (i != d0_idx);
1597 BUG_ON(faila == failb);
1600 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1601 __func__, (unsigned long long)sh->sector, faila, failb);
1603 atomic_inc(&sh->count);
1605 if (failb == syndrome_disks+1) {
1606 /* Q disk is one of the missing disks */
1607 if (faila == syndrome_disks) {
1608 /* Missing P+Q, just recompute */
1609 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1610 ops_complete_compute, sh,
1611 to_addr_conv(sh, percpu, 0));
1612 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1613 STRIPE_SIZE, &submit);
1617 int qd_idx = sh->qd_idx;
1619 /* Missing D+Q: recompute D from P, then recompute Q */
1620 if (target == qd_idx)
1621 data_target = target2;
1623 data_target = target;
1626 for (i = disks; i-- ; ) {
1627 if (i == data_target || i == qd_idx)
1629 blocks[count++] = sh->dev[i].page;
1631 dest = sh->dev[data_target].page;
1632 init_async_submit(&submit,
1633 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1635 to_addr_conv(sh, percpu, 0));
1636 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1639 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1640 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1641 ops_complete_compute, sh,
1642 to_addr_conv(sh, percpu, 0));
1643 return async_gen_syndrome(blocks, 0, count+2,
1644 STRIPE_SIZE, &submit);
1647 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1648 ops_complete_compute, sh,
1649 to_addr_conv(sh, percpu, 0));
1650 if (failb == syndrome_disks) {
1651 /* We're missing D+P. */
1652 return async_raid6_datap_recov(syndrome_disks+2,
1656 /* We're missing D+D. */
1657 return async_raid6_2data_recov(syndrome_disks+2,
1658 STRIPE_SIZE, faila, failb,
1664 static void ops_complete_prexor(void *stripe_head_ref)
1666 struct stripe_head *sh = stripe_head_ref;
1668 pr_debug("%s: stripe %llu\n", __func__,
1669 (unsigned long long)sh->sector);
1671 if (r5c_is_writeback(sh->raid_conf->log))
1673 * raid5-cache write back uses orig_page during prexor.
1674 * After prexor, it is time to free orig_page
1676 r5c_release_extra_page(sh);
1679 static struct dma_async_tx_descriptor *
1680 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1681 struct dma_async_tx_descriptor *tx)
1683 int disks = sh->disks;
1684 struct page **xor_srcs = to_addr_page(percpu, 0);
1685 int count = 0, pd_idx = sh->pd_idx, i;
1686 struct async_submit_ctl submit;
1688 /* existing parity data subtracted */
1689 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1691 BUG_ON(sh->batch_head);
1692 pr_debug("%s: stripe %llu\n", __func__,
1693 (unsigned long long)sh->sector);
1695 for (i = disks; i--; ) {
1696 struct r5dev *dev = &sh->dev[i];
1697 /* Only process blocks that are known to be uptodate */
1698 if (test_bit(R5_InJournal, &dev->flags))
1699 xor_srcs[count++] = dev->orig_page;
1700 else if (test_bit(R5_Wantdrain, &dev->flags))
1701 xor_srcs[count++] = dev->page;
1704 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1705 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1706 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1711 static struct dma_async_tx_descriptor *
1712 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1713 struct dma_async_tx_descriptor *tx)
1715 struct page **blocks = to_addr_page(percpu, 0);
1717 struct async_submit_ctl submit;
1719 pr_debug("%s: stripe %llu\n", __func__,
1720 (unsigned long long)sh->sector);
1722 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1724 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1725 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1726 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1731 static struct dma_async_tx_descriptor *
1732 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1734 struct r5conf *conf = sh->raid_conf;
1735 int disks = sh->disks;
1737 struct stripe_head *head_sh = sh;
1739 pr_debug("%s: stripe %llu\n", __func__,
1740 (unsigned long long)sh->sector);
1742 for (i = disks; i--; ) {
1747 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1753 * clear R5_InJournal, so when rewriting a page in
1754 * journal, it is not skipped by r5l_log_stripe()
1756 clear_bit(R5_InJournal, &dev->flags);
1757 spin_lock_irq(&sh->stripe_lock);
1758 chosen = dev->towrite;
1759 dev->towrite = NULL;
1760 sh->overwrite_disks = 0;
1761 BUG_ON(dev->written);
1762 wbi = dev->written = chosen;
1763 spin_unlock_irq(&sh->stripe_lock);
1764 WARN_ON(dev->page != dev->orig_page);
1766 while (wbi && wbi->bi_iter.bi_sector <
1767 dev->sector + STRIPE_SECTORS) {
1768 if (wbi->bi_opf & REQ_FUA)
1769 set_bit(R5_WantFUA, &dev->flags);
1770 if (wbi->bi_opf & REQ_SYNC)
1771 set_bit(R5_SyncIO, &dev->flags);
1772 if (bio_op(wbi) == REQ_OP_DISCARD)
1773 set_bit(R5_Discard, &dev->flags);
1775 tx = async_copy_data(1, wbi, &dev->page,
1776 dev->sector, tx, sh,
1777 r5c_is_writeback(conf->log));
1778 if (dev->page != dev->orig_page &&
1779 !r5c_is_writeback(conf->log)) {
1780 set_bit(R5_SkipCopy, &dev->flags);
1781 clear_bit(R5_UPTODATE, &dev->flags);
1782 clear_bit(R5_OVERWRITE, &dev->flags);
1785 wbi = r5_next_bio(wbi, dev->sector);
1788 if (head_sh->batch_head) {
1789 sh = list_first_entry(&sh->batch_list,
1802 static void ops_complete_reconstruct(void *stripe_head_ref)
1804 struct stripe_head *sh = stripe_head_ref;
1805 int disks = sh->disks;
1806 int pd_idx = sh->pd_idx;
1807 int qd_idx = sh->qd_idx;
1809 bool fua = false, sync = false, discard = false;
1811 pr_debug("%s: stripe %llu\n", __func__,
1812 (unsigned long long)sh->sector);
1814 for (i = disks; i--; ) {
1815 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1816 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1817 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1820 for (i = disks; i--; ) {
1821 struct r5dev *dev = &sh->dev[i];
1823 if (dev->written || i == pd_idx || i == qd_idx) {
1824 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1825 set_bit(R5_UPTODATE, &dev->flags);
1826 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1827 set_bit(R5_Expanded, &dev->flags);
1830 set_bit(R5_WantFUA, &dev->flags);
1832 set_bit(R5_SyncIO, &dev->flags);
1836 if (sh->reconstruct_state == reconstruct_state_drain_run)
1837 sh->reconstruct_state = reconstruct_state_drain_result;
1838 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1839 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1841 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1842 sh->reconstruct_state = reconstruct_state_result;
1845 set_bit(STRIPE_HANDLE, &sh->state);
1846 raid5_release_stripe(sh);
1850 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1851 struct dma_async_tx_descriptor *tx)
1853 int disks = sh->disks;
1854 struct page **xor_srcs;
1855 struct async_submit_ctl submit;
1856 int count, pd_idx = sh->pd_idx, i;
1857 struct page *xor_dest;
1859 unsigned long flags;
1861 struct stripe_head *head_sh = sh;
1864 pr_debug("%s: stripe %llu\n", __func__,
1865 (unsigned long long)sh->sector);
1867 for (i = 0; i < sh->disks; i++) {
1870 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1873 if (i >= sh->disks) {
1874 atomic_inc(&sh->count);
1875 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1876 ops_complete_reconstruct(sh);
1881 xor_srcs = to_addr_page(percpu, j);
1882 /* check if prexor is active which means only process blocks
1883 * that are part of a read-modify-write (written)
1885 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1887 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1888 for (i = disks; i--; ) {
1889 struct r5dev *dev = &sh->dev[i];
1890 if (head_sh->dev[i].written ||
1891 test_bit(R5_InJournal, &head_sh->dev[i].flags))
1892 xor_srcs[count++] = dev->page;
1895 xor_dest = sh->dev[pd_idx].page;
1896 for (i = disks; i--; ) {
1897 struct r5dev *dev = &sh->dev[i];
1899 xor_srcs[count++] = dev->page;
1903 /* 1/ if we prexor'd then the dest is reused as a source
1904 * 2/ if we did not prexor then we are redoing the parity
1905 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1906 * for the synchronous xor case
1908 last_stripe = !head_sh->batch_head ||
1909 list_first_entry(&sh->batch_list,
1910 struct stripe_head, batch_list) == head_sh;
1912 flags = ASYNC_TX_ACK |
1913 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1915 atomic_inc(&head_sh->count);
1916 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1917 to_addr_conv(sh, percpu, j));
1919 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1920 init_async_submit(&submit, flags, tx, NULL, NULL,
1921 to_addr_conv(sh, percpu, j));
1924 if (unlikely(count == 1))
1925 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1927 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1930 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1937 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1938 struct dma_async_tx_descriptor *tx)
1940 struct async_submit_ctl submit;
1941 struct page **blocks;
1942 int count, i, j = 0;
1943 struct stripe_head *head_sh = sh;
1946 unsigned long txflags;
1948 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1950 for (i = 0; i < sh->disks; i++) {
1951 if (sh->pd_idx == i || sh->qd_idx == i)
1953 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1956 if (i >= sh->disks) {
1957 atomic_inc(&sh->count);
1958 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1959 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1960 ops_complete_reconstruct(sh);
1965 blocks = to_addr_page(percpu, j);
1967 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1968 synflags = SYNDROME_SRC_WRITTEN;
1969 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1971 synflags = SYNDROME_SRC_ALL;
1972 txflags = ASYNC_TX_ACK;
1975 count = set_syndrome_sources(blocks, sh, synflags);
1976 last_stripe = !head_sh->batch_head ||
1977 list_first_entry(&sh->batch_list,
1978 struct stripe_head, batch_list) == head_sh;
1981 atomic_inc(&head_sh->count);
1982 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1983 head_sh, to_addr_conv(sh, percpu, j));
1985 init_async_submit(&submit, 0, tx, NULL, NULL,
1986 to_addr_conv(sh, percpu, j));
1987 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1990 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1996 static void ops_complete_check(void *stripe_head_ref)
1998 struct stripe_head *sh = stripe_head_ref;
2000 pr_debug("%s: stripe %llu\n", __func__,
2001 (unsigned long long)sh->sector);
2003 sh->check_state = check_state_check_result;
2004 set_bit(STRIPE_HANDLE, &sh->state);
2005 raid5_release_stripe(sh);
2008 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2010 int disks = sh->disks;
2011 int pd_idx = sh->pd_idx;
2012 int qd_idx = sh->qd_idx;
2013 struct page *xor_dest;
2014 struct page **xor_srcs = to_addr_page(percpu, 0);
2015 struct dma_async_tx_descriptor *tx;
2016 struct async_submit_ctl submit;
2020 pr_debug("%s: stripe %llu\n", __func__,
2021 (unsigned long long)sh->sector);
2023 BUG_ON(sh->batch_head);
2025 xor_dest = sh->dev[pd_idx].page;
2026 xor_srcs[count++] = xor_dest;
2027 for (i = disks; i--; ) {
2028 if (i == pd_idx || i == qd_idx)
2030 xor_srcs[count++] = sh->dev[i].page;
2033 init_async_submit(&submit, 0, NULL, NULL, NULL,
2034 to_addr_conv(sh, percpu, 0));
2035 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
2036 &sh->ops.zero_sum_result, &submit);
2038 atomic_inc(&sh->count);
2039 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2040 tx = async_trigger_callback(&submit);
2043 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2045 struct page **srcs = to_addr_page(percpu, 0);
2046 struct async_submit_ctl submit;
2049 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2050 (unsigned long long)sh->sector, checkp);
2052 BUG_ON(sh->batch_head);
2053 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
2057 atomic_inc(&sh->count);
2058 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2059 sh, to_addr_conv(sh, percpu, 0));
2060 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
2061 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
2064 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2066 int overlap_clear = 0, i, disks = sh->disks;
2067 struct dma_async_tx_descriptor *tx = NULL;
2068 struct r5conf *conf = sh->raid_conf;
2069 int level = conf->level;
2070 struct raid5_percpu *percpu;
2074 percpu = per_cpu_ptr(conf->percpu, cpu);
2075 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2076 ops_run_biofill(sh);
2080 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2082 tx = ops_run_compute5(sh, percpu);
2084 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2085 tx = ops_run_compute6_1(sh, percpu);
2087 tx = ops_run_compute6_2(sh, percpu);
2089 /* terminate the chain if reconstruct is not set to be run */
2090 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2094 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2096 tx = ops_run_prexor5(sh, percpu, tx);
2098 tx = ops_run_prexor6(sh, percpu, tx);
2101 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2102 tx = ops_run_partial_parity(sh, percpu, tx);
2104 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2105 tx = ops_run_biodrain(sh, tx);
2109 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2111 ops_run_reconstruct5(sh, percpu, tx);
2113 ops_run_reconstruct6(sh, percpu, tx);
2116 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2117 if (sh->check_state == check_state_run)
2118 ops_run_check_p(sh, percpu);
2119 else if (sh->check_state == check_state_run_q)
2120 ops_run_check_pq(sh, percpu, 0);
2121 else if (sh->check_state == check_state_run_pq)
2122 ops_run_check_pq(sh, percpu, 1);
2127 if (overlap_clear && !sh->batch_head)
2128 for (i = disks; i--; ) {
2129 struct r5dev *dev = &sh->dev[i];
2130 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2131 wake_up(&sh->raid_conf->wait_for_overlap);
2136 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2139 __free_page(sh->ppl_page);
2140 kmem_cache_free(sc, sh);
2143 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2144 int disks, struct r5conf *conf)
2146 struct stripe_head *sh;
2149 sh = kmem_cache_zalloc(sc, gfp);
2151 spin_lock_init(&sh->stripe_lock);
2152 spin_lock_init(&sh->batch_lock);
2153 INIT_LIST_HEAD(&sh->batch_list);
2154 INIT_LIST_HEAD(&sh->lru);
2155 INIT_LIST_HEAD(&sh->r5c);
2156 INIT_LIST_HEAD(&sh->log_list);
2157 atomic_set(&sh->count, 1);
2158 sh->raid_conf = conf;
2159 sh->log_start = MaxSector;
2160 for (i = 0; i < disks; i++) {
2161 struct r5dev *dev = &sh->dev[i];
2163 bio_init(&dev->req, &dev->vec, 1);
2164 bio_init(&dev->rreq, &dev->rvec, 1);
2167 if (raid5_has_ppl(conf)) {
2168 sh->ppl_page = alloc_page(gfp);
2169 if (!sh->ppl_page) {
2170 free_stripe(sc, sh);
2177 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2179 struct stripe_head *sh;
2181 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2185 if (grow_buffers(sh, gfp)) {
2187 free_stripe(conf->slab_cache, sh);
2190 sh->hash_lock_index =
2191 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2192 /* we just created an active stripe so... */
2193 atomic_inc(&conf->active_stripes);
2195 raid5_release_stripe(sh);
2196 conf->max_nr_stripes++;
2200 static int grow_stripes(struct r5conf *conf, int num)
2202 struct kmem_cache *sc;
2203 size_t namelen = sizeof(conf->cache_name[0]);
2204 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2206 if (conf->mddev->gendisk)
2207 snprintf(conf->cache_name[0], namelen,
2208 "raid%d-%s", conf->level, mdname(conf->mddev));
2210 snprintf(conf->cache_name[0], namelen,
2211 "raid%d-%p", conf->level, conf->mddev);
2212 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2214 conf->active_name = 0;
2215 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2216 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2220 conf->slab_cache = sc;
2221 conf->pool_size = devs;
2223 if (!grow_one_stripe(conf, GFP_KERNEL))
2230 * scribble_len - return the required size of the scribble region
2231 * @num - total number of disks in the array
2233 * The size must be enough to contain:
2234 * 1/ a struct page pointer for each device in the array +2
2235 * 2/ room to convert each entry in (1) to its corresponding dma
2236 * (dma_map_page()) or page (page_address()) address.
2238 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2239 * calculate over all devices (not just the data blocks), using zeros in place
2240 * of the P and Q blocks.
2242 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2244 struct flex_array *ret;
2247 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2248 ret = flex_array_alloc(len, cnt, flags);
2251 /* always prealloc all elements, so no locking is required */
2252 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2253 flex_array_free(ret);
2259 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2265 * Never shrink. And mddev_suspend() could deadlock if this is called
2266 * from raid5d. In that case, scribble_disks and scribble_sectors
2267 * should equal to new_disks and new_sectors
2269 if (conf->scribble_disks >= new_disks &&
2270 conf->scribble_sectors >= new_sectors)
2272 mddev_suspend(conf->mddev);
2274 for_each_present_cpu(cpu) {
2275 struct raid5_percpu *percpu;
2276 struct flex_array *scribble;
2278 percpu = per_cpu_ptr(conf->percpu, cpu);
2279 scribble = scribble_alloc(new_disks,
2280 new_sectors / STRIPE_SECTORS,
2284 flex_array_free(percpu->scribble);
2285 percpu->scribble = scribble;
2292 mddev_resume(conf->mddev);
2294 conf->scribble_disks = new_disks;
2295 conf->scribble_sectors = new_sectors;
2300 static int resize_stripes(struct r5conf *conf, int newsize)
2302 /* Make all the stripes able to hold 'newsize' devices.
2303 * New slots in each stripe get 'page' set to a new page.
2305 * This happens in stages:
2306 * 1/ create a new kmem_cache and allocate the required number of
2308 * 2/ gather all the old stripe_heads and transfer the pages across
2309 * to the new stripe_heads. This will have the side effect of
2310 * freezing the array as once all stripe_heads have been collected,
2311 * no IO will be possible. Old stripe heads are freed once their
2312 * pages have been transferred over, and the old kmem_cache is
2313 * freed when all stripes are done.
2314 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2315 * we simple return a failure status - no need to clean anything up.
2316 * 4/ allocate new pages for the new slots in the new stripe_heads.
2317 * If this fails, we don't bother trying the shrink the
2318 * stripe_heads down again, we just leave them as they are.
2319 * As each stripe_head is processed the new one is released into
2322 * Once step2 is started, we cannot afford to wait for a write,
2323 * so we use GFP_NOIO allocations.
2325 struct stripe_head *osh, *nsh;
2326 LIST_HEAD(newstripes);
2327 struct disk_info *ndisks;
2329 struct kmem_cache *sc;
2333 md_allow_write(conf->mddev);
2336 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2337 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2342 /* Need to ensure auto-resizing doesn't interfere */
2343 mutex_lock(&conf->cache_size_mutex);
2345 for (i = conf->max_nr_stripes; i; i--) {
2346 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2350 list_add(&nsh->lru, &newstripes);
2353 /* didn't get enough, give up */
2354 while (!list_empty(&newstripes)) {
2355 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2356 list_del(&nsh->lru);
2357 free_stripe(sc, nsh);
2359 kmem_cache_destroy(sc);
2360 mutex_unlock(&conf->cache_size_mutex);
2363 /* Step 2 - Must use GFP_NOIO now.
2364 * OK, we have enough stripes, start collecting inactive
2365 * stripes and copying them over
2369 list_for_each_entry(nsh, &newstripes, lru) {
2370 lock_device_hash_lock(conf, hash);
2371 wait_event_cmd(conf->wait_for_stripe,
2372 !list_empty(conf->inactive_list + hash),
2373 unlock_device_hash_lock(conf, hash),
2374 lock_device_hash_lock(conf, hash));
2375 osh = get_free_stripe(conf, hash);
2376 unlock_device_hash_lock(conf, hash);
2378 for(i=0; i<conf->pool_size; i++) {
2379 nsh->dev[i].page = osh->dev[i].page;
2380 nsh->dev[i].orig_page = osh->dev[i].page;
2382 nsh->hash_lock_index = hash;
2383 free_stripe(conf->slab_cache, osh);
2385 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2386 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2391 kmem_cache_destroy(conf->slab_cache);
2394 * At this point, we are holding all the stripes so the array
2395 * is completely stalled, so now is a good time to resize
2396 * conf->disks and the scribble region
2398 ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2400 for (i = 0; i < conf->pool_size; i++)
2401 ndisks[i] = conf->disks[i];
2403 for (i = conf->pool_size; i < newsize; i++) {
2404 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2405 if (!ndisks[i].extra_page)
2410 for (i = conf->pool_size; i < newsize; i++)
2411 if (ndisks[i].extra_page)
2412 put_page(ndisks[i].extra_page);
2416 conf->disks = ndisks;
2421 conf->slab_cache = sc;
2422 conf->active_name = 1-conf->active_name;
2424 /* Step 4, return new stripes to service */
2425 while(!list_empty(&newstripes)) {
2426 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2427 list_del_init(&nsh->lru);
2429 for (i=conf->raid_disks; i < newsize; i++)
2430 if (nsh->dev[i].page == NULL) {
2431 struct page *p = alloc_page(GFP_NOIO);
2432 nsh->dev[i].page = p;
2433 nsh->dev[i].orig_page = p;
2437 raid5_release_stripe(nsh);
2439 /* critical section pass, GFP_NOIO no longer needed */
2442 conf->pool_size = newsize;
2443 mutex_unlock(&conf->cache_size_mutex);
2448 static int drop_one_stripe(struct r5conf *conf)
2450 struct stripe_head *sh;
2451 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2453 spin_lock_irq(conf->hash_locks + hash);
2454 sh = get_free_stripe(conf, hash);
2455 spin_unlock_irq(conf->hash_locks + hash);
2458 BUG_ON(atomic_read(&sh->count));
2460 free_stripe(conf->slab_cache, sh);
2461 atomic_dec(&conf->active_stripes);
2462 conf->max_nr_stripes--;
2466 static void shrink_stripes(struct r5conf *conf)
2468 while (conf->max_nr_stripes &&
2469 drop_one_stripe(conf))
2472 kmem_cache_destroy(conf->slab_cache);
2473 conf->slab_cache = NULL;
2476 static void raid5_end_read_request(struct bio * bi)
2478 struct stripe_head *sh = bi->bi_private;
2479 struct r5conf *conf = sh->raid_conf;
2480 int disks = sh->disks, i;
2481 char b[BDEVNAME_SIZE];
2482 struct md_rdev *rdev = NULL;
2485 for (i=0 ; i<disks; i++)
2486 if (bi == &sh->dev[i].req)
2489 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2490 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2497 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2498 /* If replacement finished while this request was outstanding,
2499 * 'replacement' might be NULL already.
2500 * In that case it moved down to 'rdev'.
2501 * rdev is not removed until all requests are finished.
2503 rdev = conf->disks[i].replacement;
2505 rdev = conf->disks[i].rdev;
2507 if (use_new_offset(conf, sh))
2508 s = sh->sector + rdev->new_data_offset;
2510 s = sh->sector + rdev->data_offset;
2511 if (!bi->bi_status) {
2512 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2513 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2514 /* Note that this cannot happen on a
2515 * replacement device. We just fail those on
2518 pr_info_ratelimited(
2519 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2520 mdname(conf->mddev), STRIPE_SECTORS,
2521 (unsigned long long)s,
2522 bdevname(rdev->bdev, b));
2523 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2524 clear_bit(R5_ReadError, &sh->dev[i].flags);
2525 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2526 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2527 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2529 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2531 * end read for a page in journal, this
2532 * must be preparing for prexor in rmw
2534 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2536 if (atomic_read(&rdev->read_errors))
2537 atomic_set(&rdev->read_errors, 0);
2539 const char *bdn = bdevname(rdev->bdev, b);
2543 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2544 if (!(bi->bi_status == BLK_STS_PROTECTION))
2545 atomic_inc(&rdev->read_errors);
2546 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2547 pr_warn_ratelimited(
2548 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2549 mdname(conf->mddev),
2550 (unsigned long long)s,
2552 else if (conf->mddev->degraded >= conf->max_degraded) {
2554 pr_warn_ratelimited(
2555 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2556 mdname(conf->mddev),
2557 (unsigned long long)s,
2559 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2562 pr_warn_ratelimited(
2563 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2564 mdname(conf->mddev),
2565 (unsigned long long)s,
2567 } else if (atomic_read(&rdev->read_errors)
2568 > conf->max_nr_stripes)
2569 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2570 mdname(conf->mddev), bdn);
2573 if (set_bad && test_bit(In_sync, &rdev->flags)
2574 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2577 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2578 set_bit(R5_ReadError, &sh->dev[i].flags);
2579 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2580 set_bit(R5_ReadError, &sh->dev[i].flags);
2581 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2583 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2585 clear_bit(R5_ReadError, &sh->dev[i].flags);
2586 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2588 && test_bit(In_sync, &rdev->flags)
2589 && rdev_set_badblocks(
2590 rdev, sh->sector, STRIPE_SECTORS, 0)))
2591 md_error(conf->mddev, rdev);
2594 rdev_dec_pending(rdev, conf->mddev);
2596 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2597 set_bit(STRIPE_HANDLE, &sh->state);
2598 raid5_release_stripe(sh);
2601 static void raid5_end_write_request(struct bio *bi)
2603 struct stripe_head *sh = bi->bi_private;
2604 struct r5conf *conf = sh->raid_conf;
2605 int disks = sh->disks, i;
2606 struct md_rdev *rdev;
2609 int replacement = 0;
2611 for (i = 0 ; i < disks; i++) {
2612 if (bi == &sh->dev[i].req) {
2613 rdev = conf->disks[i].rdev;
2616 if (bi == &sh->dev[i].rreq) {
2617 rdev = conf->disks[i].replacement;
2621 /* rdev was removed and 'replacement'
2622 * replaced it. rdev is not removed
2623 * until all requests are finished.
2625 rdev = conf->disks[i].rdev;
2629 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2630 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2640 md_error(conf->mddev, rdev);
2641 else if (is_badblock(rdev, sh->sector,
2643 &first_bad, &bad_sectors))
2644 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2646 if (bi->bi_status) {
2647 set_bit(STRIPE_DEGRADED, &sh->state);
2648 set_bit(WriteErrorSeen, &rdev->flags);
2649 set_bit(R5_WriteError, &sh->dev[i].flags);
2650 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2651 set_bit(MD_RECOVERY_NEEDED,
2652 &rdev->mddev->recovery);
2653 } else if (is_badblock(rdev, sh->sector,
2655 &first_bad, &bad_sectors)) {
2656 set_bit(R5_MadeGood, &sh->dev[i].flags);
2657 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2658 /* That was a successful write so make
2659 * sure it looks like we already did
2662 set_bit(R5_ReWrite, &sh->dev[i].flags);
2665 rdev_dec_pending(rdev, conf->mddev);
2667 if (sh->batch_head && bi->bi_status && !replacement)
2668 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2671 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2672 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2673 set_bit(STRIPE_HANDLE, &sh->state);
2675 if (sh->batch_head && sh != sh->batch_head)
2676 raid5_release_stripe(sh->batch_head);
2677 raid5_release_stripe(sh);
2680 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2682 char b[BDEVNAME_SIZE];
2683 struct r5conf *conf = mddev->private;
2684 unsigned long flags;
2685 pr_debug("raid456: error called\n");
2687 spin_lock_irqsave(&conf->device_lock, flags);
2688 set_bit(Faulty, &rdev->flags);
2689 clear_bit(In_sync, &rdev->flags);
2690 mddev->degraded = raid5_calc_degraded(conf);
2691 spin_unlock_irqrestore(&conf->device_lock, flags);
2692 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2694 set_bit(Blocked, &rdev->flags);
2695 set_mask_bits(&mddev->sb_flags, 0,
2696 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2697 pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n"
2698 "md/raid:%s: Operation continuing on %d devices.\n",
2700 bdevname(rdev->bdev, b),
2702 conf->raid_disks - mddev->degraded);
2703 r5c_update_on_rdev_error(mddev, rdev);
2707 * Input: a 'big' sector number,
2708 * Output: index of the data and parity disk, and the sector # in them.
2710 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2711 int previous, int *dd_idx,
2712 struct stripe_head *sh)
2714 sector_t stripe, stripe2;
2715 sector_t chunk_number;
2716 unsigned int chunk_offset;
2719 sector_t new_sector;
2720 int algorithm = previous ? conf->prev_algo
2722 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2723 : conf->chunk_sectors;
2724 int raid_disks = previous ? conf->previous_raid_disks
2726 int data_disks = raid_disks - conf->max_degraded;
2728 /* First compute the information on this sector */
2731 * Compute the chunk number and the sector offset inside the chunk
2733 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2734 chunk_number = r_sector;
2737 * Compute the stripe number
2739 stripe = chunk_number;
2740 *dd_idx = sector_div(stripe, data_disks);
2743 * Select the parity disk based on the user selected algorithm.
2745 pd_idx = qd_idx = -1;
2746 switch(conf->level) {
2748 pd_idx = data_disks;
2751 switch (algorithm) {
2752 case ALGORITHM_LEFT_ASYMMETRIC:
2753 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2754 if (*dd_idx >= pd_idx)
2757 case ALGORITHM_RIGHT_ASYMMETRIC:
2758 pd_idx = sector_div(stripe2, raid_disks);
2759 if (*dd_idx >= pd_idx)
2762 case ALGORITHM_LEFT_SYMMETRIC:
2763 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2764 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2766 case ALGORITHM_RIGHT_SYMMETRIC:
2767 pd_idx = sector_div(stripe2, raid_disks);
2768 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2770 case ALGORITHM_PARITY_0:
2774 case ALGORITHM_PARITY_N:
2775 pd_idx = data_disks;
2783 switch (algorithm) {
2784 case ALGORITHM_LEFT_ASYMMETRIC:
2785 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2786 qd_idx = pd_idx + 1;
2787 if (pd_idx == raid_disks-1) {
2788 (*dd_idx)++; /* Q D D D P */
2790 } else if (*dd_idx >= pd_idx)
2791 (*dd_idx) += 2; /* D D P Q D */
2793 case ALGORITHM_RIGHT_ASYMMETRIC:
2794 pd_idx = sector_div(stripe2, raid_disks);
2795 qd_idx = pd_idx + 1;
2796 if (pd_idx == raid_disks-1) {
2797 (*dd_idx)++; /* Q D D D P */
2799 } else if (*dd_idx >= pd_idx)
2800 (*dd_idx) += 2; /* D D P Q D */
2802 case ALGORITHM_LEFT_SYMMETRIC:
2803 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2804 qd_idx = (pd_idx + 1) % raid_disks;
2805 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2807 case ALGORITHM_RIGHT_SYMMETRIC:
2808 pd_idx = sector_div(stripe2, raid_disks);
2809 qd_idx = (pd_idx + 1) % raid_disks;
2810 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2813 case ALGORITHM_PARITY_0:
2818 case ALGORITHM_PARITY_N:
2819 pd_idx = data_disks;
2820 qd_idx = data_disks + 1;
2823 case ALGORITHM_ROTATING_ZERO_RESTART:
2824 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2825 * of blocks for computing Q is different.
2827 pd_idx = sector_div(stripe2, raid_disks);
2828 qd_idx = pd_idx + 1;
2829 if (pd_idx == raid_disks-1) {
2830 (*dd_idx)++; /* Q D D D P */
2832 } else if (*dd_idx >= pd_idx)
2833 (*dd_idx) += 2; /* D D P Q D */
2837 case ALGORITHM_ROTATING_N_RESTART:
2838 /* Same a left_asymmetric, by first stripe is
2839 * D D D P Q rather than
2843 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2844 qd_idx = pd_idx + 1;
2845 if (pd_idx == raid_disks-1) {
2846 (*dd_idx)++; /* Q D D D P */
2848 } else if (*dd_idx >= pd_idx)
2849 (*dd_idx) += 2; /* D D P Q D */
2853 case ALGORITHM_ROTATING_N_CONTINUE:
2854 /* Same as left_symmetric but Q is before P */
2855 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2856 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2857 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2861 case ALGORITHM_LEFT_ASYMMETRIC_6:
2862 /* RAID5 left_asymmetric, with Q on last device */
2863 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2864 if (*dd_idx >= pd_idx)
2866 qd_idx = raid_disks - 1;
2869 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2870 pd_idx = sector_div(stripe2, raid_disks-1);
2871 if (*dd_idx >= pd_idx)
2873 qd_idx = raid_disks - 1;
2876 case ALGORITHM_LEFT_SYMMETRIC_6:
2877 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2878 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2879 qd_idx = raid_disks - 1;
2882 case ALGORITHM_RIGHT_SYMMETRIC_6:
2883 pd_idx = sector_div(stripe2, raid_disks-1);
2884 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2885 qd_idx = raid_disks - 1;
2888 case ALGORITHM_PARITY_0_6:
2891 qd_idx = raid_disks - 1;
2901 sh->pd_idx = pd_idx;
2902 sh->qd_idx = qd_idx;
2903 sh->ddf_layout = ddf_layout;
2906 * Finally, compute the new sector number
2908 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2912 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2914 struct r5conf *conf = sh->raid_conf;
2915 int raid_disks = sh->disks;
2916 int data_disks = raid_disks - conf->max_degraded;
2917 sector_t new_sector = sh->sector, check;
2918 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2919 : conf->chunk_sectors;
2920 int algorithm = previous ? conf->prev_algo
2924 sector_t chunk_number;
2925 int dummy1, dd_idx = i;
2927 struct stripe_head sh2;
2929 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2930 stripe = new_sector;
2932 if (i == sh->pd_idx)
2934 switch(conf->level) {
2937 switch (algorithm) {
2938 case ALGORITHM_LEFT_ASYMMETRIC:
2939 case ALGORITHM_RIGHT_ASYMMETRIC:
2943 case ALGORITHM_LEFT_SYMMETRIC:
2944 case ALGORITHM_RIGHT_SYMMETRIC:
2947 i -= (sh->pd_idx + 1);
2949 case ALGORITHM_PARITY_0:
2952 case ALGORITHM_PARITY_N:
2959 if (i == sh->qd_idx)
2960 return 0; /* It is the Q disk */
2961 switch (algorithm) {
2962 case ALGORITHM_LEFT_ASYMMETRIC:
2963 case ALGORITHM_RIGHT_ASYMMETRIC:
2964 case ALGORITHM_ROTATING_ZERO_RESTART:
2965 case ALGORITHM_ROTATING_N_RESTART:
2966 if (sh->pd_idx == raid_disks-1)
2967 i--; /* Q D D D P */
2968 else if (i > sh->pd_idx)
2969 i -= 2; /* D D P Q D */
2971 case ALGORITHM_LEFT_SYMMETRIC:
2972 case ALGORITHM_RIGHT_SYMMETRIC:
2973 if (sh->pd_idx == raid_disks-1)
2974 i--; /* Q D D D P */
2979 i -= (sh->pd_idx + 2);
2982 case ALGORITHM_PARITY_0:
2985 case ALGORITHM_PARITY_N:
2987 case ALGORITHM_ROTATING_N_CONTINUE:
2988 /* Like left_symmetric, but P is before Q */
2989 if (sh->pd_idx == 0)
2990 i--; /* P D D D Q */
2995 i -= (sh->pd_idx + 1);
2998 case ALGORITHM_LEFT_ASYMMETRIC_6:
2999 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3003 case ALGORITHM_LEFT_SYMMETRIC_6:
3004 case ALGORITHM_RIGHT_SYMMETRIC_6:
3006 i += data_disks + 1;
3007 i -= (sh->pd_idx + 1);
3009 case ALGORITHM_PARITY_0_6:
3018 chunk_number = stripe * data_disks + i;
3019 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3021 check = raid5_compute_sector(conf, r_sector,
3022 previous, &dummy1, &sh2);
3023 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3024 || sh2.qd_idx != sh->qd_idx) {
3025 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3026 mdname(conf->mddev));
3033 * There are cases where we want handle_stripe_dirtying() and
3034 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3036 * This function checks whether we want to delay the towrite. Specifically,
3037 * we delay the towrite when:
3039 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3040 * stripe has data in journal (for other devices).
3042 * In this case, when reading data for the non-overwrite dev, it is
3043 * necessary to handle complex rmw of write back cache (prexor with
3044 * orig_page, and xor with page). To keep read path simple, we would
3045 * like to flush data in journal to RAID disks first, so complex rmw
3046 * is handled in the write patch (handle_stripe_dirtying).
3048 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3050 * It is important to be able to flush all stripes in raid5-cache.
3051 * Therefore, we need reserve some space on the journal device for
3052 * these flushes. If flush operation includes pending writes to the
3053 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3054 * for the flush out. If we exclude these pending writes from flush
3055 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3056 * Therefore, excluding pending writes in these cases enables more
3057 * efficient use of the journal device.
3059 * Note: To make sure the stripe makes progress, we only delay
3060 * towrite for stripes with data already in journal (injournal > 0).
3061 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3062 * no_space_stripes list.
3064 * 3. during journal failure
3065 * In journal failure, we try to flush all cached data to raid disks
3066 * based on data in stripe cache. The array is read-only to upper
3067 * layers, so we would skip all pending writes.
3070 static inline bool delay_towrite(struct r5conf *conf,
3072 struct stripe_head_state *s)
3075 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3076 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3079 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3083 if (s->log_failed && s->injournal)
3089 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3090 int rcw, int expand)
3092 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3093 struct r5conf *conf = sh->raid_conf;
3094 int level = conf->level;
3098 * In some cases, handle_stripe_dirtying initially decided to
3099 * run rmw and allocates extra page for prexor. However, rcw is
3100 * cheaper later on. We need to free the extra page now,
3101 * because we won't be able to do that in ops_complete_prexor().
3103 r5c_release_extra_page(sh);
3105 for (i = disks; i--; ) {
3106 struct r5dev *dev = &sh->dev[i];
3108 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3109 set_bit(R5_LOCKED, &dev->flags);
3110 set_bit(R5_Wantdrain, &dev->flags);
3112 clear_bit(R5_UPTODATE, &dev->flags);
3114 } else if (test_bit(R5_InJournal, &dev->flags)) {
3115 set_bit(R5_LOCKED, &dev->flags);
3119 /* if we are not expanding this is a proper write request, and
3120 * there will be bios with new data to be drained into the
3125 /* False alarm, nothing to do */
3127 sh->reconstruct_state = reconstruct_state_drain_run;
3128 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3130 sh->reconstruct_state = reconstruct_state_run;
3132 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3134 if (s->locked + conf->max_degraded == disks)
3135 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3136 atomic_inc(&conf->pending_full_writes);
3138 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3139 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3140 BUG_ON(level == 6 &&
3141 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3142 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3144 for (i = disks; i--; ) {
3145 struct r5dev *dev = &sh->dev[i];
3146 if (i == pd_idx || i == qd_idx)
3150 (test_bit(R5_UPTODATE, &dev->flags) ||
3151 test_bit(R5_Wantcompute, &dev->flags))) {
3152 set_bit(R5_Wantdrain, &dev->flags);
3153 set_bit(R5_LOCKED, &dev->flags);
3154 clear_bit(R5_UPTODATE, &dev->flags);
3156 } else if (test_bit(R5_InJournal, &dev->flags)) {
3157 set_bit(R5_LOCKED, &dev->flags);
3162 /* False alarm - nothing to do */
3164 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3165 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3166 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3167 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3170 /* keep the parity disk(s) locked while asynchronous operations
3173 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3174 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3178 int qd_idx = sh->qd_idx;
3179 struct r5dev *dev = &sh->dev[qd_idx];
3181 set_bit(R5_LOCKED, &dev->flags);
3182 clear_bit(R5_UPTODATE, &dev->flags);
3186 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3187 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3188 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3189 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3190 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3192 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3193 __func__, (unsigned long long)sh->sector,
3194 s->locked, s->ops_request);
3198 * Each stripe/dev can have one or more bion attached.
3199 * toread/towrite point to the first in a chain.
3200 * The bi_next chain must be in order.
3202 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3203 int forwrite, int previous)
3206 struct r5conf *conf = sh->raid_conf;
3209 pr_debug("adding bi b#%llu to stripe s#%llu\n",
3210 (unsigned long long)bi->bi_iter.bi_sector,
3211 (unsigned long long)sh->sector);
3213 spin_lock_irq(&sh->stripe_lock);
3214 sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3215 /* Don't allow new IO added to stripes in batch list */
3219 bip = &sh->dev[dd_idx].towrite;
3223 bip = &sh->dev[dd_idx].toread;
3224 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3225 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3227 bip = & (*bip)->bi_next;
3229 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3232 if (forwrite && raid5_has_ppl(conf)) {
3234 * With PPL only writes to consecutive data chunks within a
3235 * stripe are allowed because for a single stripe_head we can
3236 * only have one PPL entry at a time, which describes one data
3237 * range. Not really an overlap, but wait_for_overlap can be
3238 * used to handle this.
3246 for (i = 0; i < sh->disks; i++) {
3247 if (i != sh->pd_idx &&
3248 (i == dd_idx || sh->dev[i].towrite)) {
3249 sector = sh->dev[i].sector;
3250 if (count == 0 || sector < first)
3258 if (first + conf->chunk_sectors * (count - 1) != last)
3262 if (!forwrite || previous)
3263 clear_bit(STRIPE_BATCH_READY, &sh->state);
3265 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3269 bio_inc_remaining(bi);
3270 md_write_inc(conf->mddev, bi);
3273 /* check if page is covered */
3274 sector_t sector = sh->dev[dd_idx].sector;
3275 for (bi=sh->dev[dd_idx].towrite;
3276 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3277 bi && bi->bi_iter.bi_sector <= sector;
3278 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3279 if (bio_end_sector(bi) >= sector)
3280 sector = bio_end_sector(bi);
3282 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3283 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3284 sh->overwrite_disks++;
3287 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3288 (unsigned long long)(*bip)->bi_iter.bi_sector,
3289 (unsigned long long)sh->sector, dd_idx);
3291 if (conf->mddev->bitmap && firstwrite) {
3292 /* Cannot hold spinlock over bitmap_startwrite,
3293 * but must ensure this isn't added to a batch until
3294 * we have added to the bitmap and set bm_seq.
3295 * So set STRIPE_BITMAP_PENDING to prevent
3297 * If multiple add_stripe_bio() calls race here they
3298 * much all set STRIPE_BITMAP_PENDING. So only the first one
3299 * to complete "bitmap_startwrite" gets to set
3300 * STRIPE_BIT_DELAY. This is important as once a stripe
3301 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3304 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3305 spin_unlock_irq(&sh->stripe_lock);
3306 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3308 spin_lock_irq(&sh->stripe_lock);
3309 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3310 if (!sh->batch_head) {
3311 sh->bm_seq = conf->seq_flush+1;
3312 set_bit(STRIPE_BIT_DELAY, &sh->state);
3315 spin_unlock_irq(&sh->stripe_lock);
3317 if (stripe_can_batch(sh))
3318 stripe_add_to_batch_list(conf, sh);
3322 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3323 spin_unlock_irq(&sh->stripe_lock);
3327 static void end_reshape(struct r5conf *conf);
3329 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3330 struct stripe_head *sh)
3332 int sectors_per_chunk =
3333 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3335 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3336 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3338 raid5_compute_sector(conf,
3339 stripe * (disks - conf->max_degraded)
3340 *sectors_per_chunk + chunk_offset,
3346 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3347 struct stripe_head_state *s, int disks)
3350 BUG_ON(sh->batch_head);
3351 for (i = disks; i--; ) {
3355 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3356 struct md_rdev *rdev;
3358 rdev = rcu_dereference(conf->disks[i].rdev);
3359 if (rdev && test_bit(In_sync, &rdev->flags) &&
3360 !test_bit(Faulty, &rdev->flags))
3361 atomic_inc(&rdev->nr_pending);
3366 if (!rdev_set_badblocks(
3370 md_error(conf->mddev, rdev);
3371 rdev_dec_pending(rdev, conf->mddev);
3374 spin_lock_irq(&sh->stripe_lock);
3375 /* fail all writes first */
3376 bi = sh->dev[i].towrite;
3377 sh->dev[i].towrite = NULL;
3378 sh->overwrite_disks = 0;
3379 spin_unlock_irq(&sh->stripe_lock);
3383 log_stripe_write_finished(sh);
3385 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3386 wake_up(&conf->wait_for_overlap);
3388 while (bi && bi->bi_iter.bi_sector <
3389 sh->dev[i].sector + STRIPE_SECTORS) {
3390 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3392 md_write_end(conf->mddev);
3397 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3398 STRIPE_SECTORS, 0, 0);
3400 /* and fail all 'written' */
3401 bi = sh->dev[i].written;
3402 sh->dev[i].written = NULL;
3403 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3404 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3405 sh->dev[i].page = sh->dev[i].orig_page;
3408 if (bi) bitmap_end = 1;
3409 while (bi && bi->bi_iter.bi_sector <
3410 sh->dev[i].sector + STRIPE_SECTORS) {
3411 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3413 md_write_end(conf->mddev);
3418 /* fail any reads if this device is non-operational and
3419 * the data has not reached the cache yet.
3421 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3422 s->failed > conf->max_degraded &&
3423 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3424 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3425 spin_lock_irq(&sh->stripe_lock);
3426 bi = sh->dev[i].toread;
3427 sh->dev[i].toread = NULL;
3428 spin_unlock_irq(&sh->stripe_lock);
3429 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3430 wake_up(&conf->wait_for_overlap);
3433 while (bi && bi->bi_iter.bi_sector <
3434 sh->dev[i].sector + STRIPE_SECTORS) {
3435 struct bio *nextbi =
3436 r5_next_bio(bi, sh->dev[i].sector);
3443 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3444 STRIPE_SECTORS, 0, 0);
3445 /* If we were in the middle of a write the parity block might
3446 * still be locked - so just clear all R5_LOCKED flags
3448 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3453 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3454 if (atomic_dec_and_test(&conf->pending_full_writes))
3455 md_wakeup_thread(conf->mddev->thread);
3459 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3460 struct stripe_head_state *s)
3465 BUG_ON(sh->batch_head);
3466 clear_bit(STRIPE_SYNCING, &sh->state);
3467 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3468 wake_up(&conf->wait_for_overlap);
3471 /* There is nothing more to do for sync/check/repair.
3472 * Don't even need to abort as that is handled elsewhere
3473 * if needed, and not always wanted e.g. if there is a known
3475 * For recover/replace we need to record a bad block on all
3476 * non-sync devices, or abort the recovery
3478 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3479 /* During recovery devices cannot be removed, so
3480 * locking and refcounting of rdevs is not needed
3483 for (i = 0; i < conf->raid_disks; i++) {
3484 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3486 && !test_bit(Faulty, &rdev->flags)
3487 && !test_bit(In_sync, &rdev->flags)
3488 && !rdev_set_badblocks(rdev, sh->sector,
3491 rdev = rcu_dereference(conf->disks[i].replacement);
3493 && !test_bit(Faulty, &rdev->flags)
3494 && !test_bit(In_sync, &rdev->flags)
3495 && !rdev_set_badblocks(rdev, sh->sector,
3501 conf->recovery_disabled =
3502 conf->mddev->recovery_disabled;
3504 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3507 static int want_replace(struct stripe_head *sh, int disk_idx)
3509 struct md_rdev *rdev;
3513 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3515 && !test_bit(Faulty, &rdev->flags)
3516 && !test_bit(In_sync, &rdev->flags)
3517 && (rdev->recovery_offset <= sh->sector
3518 || rdev->mddev->recovery_cp <= sh->sector))
3524 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3525 int disk_idx, int disks)
3527 struct r5dev *dev = &sh->dev[disk_idx];
3528 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3529 &sh->dev[s->failed_num[1]] };
3533 if (test_bit(R5_LOCKED, &dev->flags) ||
3534 test_bit(R5_UPTODATE, &dev->flags))
3535 /* No point reading this as we already have it or have
3536 * decided to get it.
3541 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3542 /* We need this block to directly satisfy a request */
3545 if (s->syncing || s->expanding ||
3546 (s->replacing && want_replace(sh, disk_idx)))
3547 /* When syncing, or expanding we read everything.
3548 * When replacing, we need the replaced block.
3552 if ((s->failed >= 1 && fdev[0]->toread) ||
3553 (s->failed >= 2 && fdev[1]->toread))
3554 /* If we want to read from a failed device, then
3555 * we need to actually read every other device.
3559 /* Sometimes neither read-modify-write nor reconstruct-write
3560 * cycles can work. In those cases we read every block we
3561 * can. Then the parity-update is certain to have enough to
3563 * This can only be a problem when we need to write something,
3564 * and some device has failed. If either of those tests
3565 * fail we need look no further.
3567 if (!s->failed || !s->to_write)
3570 if (test_bit(R5_Insync, &dev->flags) &&
3571 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3572 /* Pre-reads at not permitted until after short delay
3573 * to gather multiple requests. However if this
3574 * device is no Insync, the block could only be computed
3575 * and there is no need to delay that.
3579 for (i = 0; i < s->failed && i < 2; i++) {
3580 if (fdev[i]->towrite &&
3581 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3582 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3583 /* If we have a partial write to a failed
3584 * device, then we will need to reconstruct
3585 * the content of that device, so all other
3586 * devices must be read.
3591 /* If we are forced to do a reconstruct-write, either because
3592 * the current RAID6 implementation only supports that, or
3593 * because parity cannot be trusted and we are currently
3594 * recovering it, there is extra need to be careful.
3595 * If one of the devices that we would need to read, because
3596 * it is not being overwritten (and maybe not written at all)
3597 * is missing/faulty, then we need to read everything we can.
3599 if (sh->raid_conf->level != 6 &&
3600 sh->raid_conf->rmw_level != PARITY_DISABLE_RMW &&
3601 sh->sector < sh->raid_conf->mddev->recovery_cp)
3602 /* reconstruct-write isn't being forced */
3604 for (i = 0; i < s->failed && i < 2; i++) {
3605 if (s->failed_num[i] != sh->pd_idx &&
3606 s->failed_num[i] != sh->qd_idx &&
3607 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3608 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3615 /* fetch_block - checks the given member device to see if its data needs
3616 * to be read or computed to satisfy a request.
3618 * Returns 1 when no more member devices need to be checked, otherwise returns
3619 * 0 to tell the loop in handle_stripe_fill to continue
3621 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3622 int disk_idx, int disks)
3624 struct r5dev *dev = &sh->dev[disk_idx];
3626 /* is the data in this block needed, and can we get it? */
3627 if (need_this_block(sh, s, disk_idx, disks)) {
3628 /* we would like to get this block, possibly by computing it,
3629 * otherwise read it if the backing disk is insync
3631 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3632 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3633 BUG_ON(sh->batch_head);
3636 * In the raid6 case if the only non-uptodate disk is P
3637 * then we already trusted P to compute the other failed
3638 * drives. It is safe to compute rather than re-read P.
3639 * In other cases we only compute blocks from failed
3640 * devices, otherwise check/repair might fail to detect
3641 * a real inconsistency.
3644 if ((s->uptodate == disks - 1) &&
3645 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3646 (s->failed && (disk_idx == s->failed_num[0] ||
3647 disk_idx == s->failed_num[1])))) {
3648 /* have disk failed, and we're requested to fetch it;
3651 pr_debug("Computing stripe %llu block %d\n",
3652 (unsigned long long)sh->sector, disk_idx);
3653 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3654 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3655 set_bit(R5_Wantcompute, &dev->flags);
3656 sh->ops.target = disk_idx;
3657 sh->ops.target2 = -1; /* no 2nd target */
3659 /* Careful: from this point on 'uptodate' is in the eye
3660 * of raid_run_ops which services 'compute' operations
3661 * before writes. R5_Wantcompute flags a block that will
3662 * be R5_UPTODATE by the time it is needed for a
3663 * subsequent operation.
3667 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3668 /* Computing 2-failure is *very* expensive; only
3669 * do it if failed >= 2
3672 for (other = disks; other--; ) {
3673 if (other == disk_idx)
3675 if (!test_bit(R5_UPTODATE,
3676 &sh->dev[other].flags))
3680 pr_debug("Computing stripe %llu blocks %d,%d\n",
3681 (unsigned long long)sh->sector,
3683 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3684 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3685 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3686 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3687 sh->ops.target = disk_idx;
3688 sh->ops.target2 = other;
3692 } else if (test_bit(R5_Insync, &dev->flags)) {
3693 set_bit(R5_LOCKED, &dev->flags);
3694 set_bit(R5_Wantread, &dev->flags);
3696 pr_debug("Reading block %d (sync=%d)\n",
3697 disk_idx, s->syncing);
3705 * handle_stripe_fill - read or compute data to satisfy pending requests.
3707 static void handle_stripe_fill(struct stripe_head *sh,
3708 struct stripe_head_state *s,
3713 /* look for blocks to read/compute, skip this if a compute
3714 * is already in flight, or if the stripe contents are in the
3715 * midst of changing due to a write
3717 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3718 !sh->reconstruct_state) {
3721 * For degraded stripe with data in journal, do not handle
3722 * read requests yet, instead, flush the stripe to raid
3723 * disks first, this avoids handling complex rmw of write
3724 * back cache (prexor with orig_page, and then xor with
3725 * page) in the read path
3727 if (s->to_read && s->injournal && s->failed) {
3728 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3729 r5c_make_stripe_write_out(sh);
3733 for (i = disks; i--; )
3734 if (fetch_block(sh, s, i, disks))
3738 set_bit(STRIPE_HANDLE, &sh->state);
3741 static void break_stripe_batch_list(struct stripe_head *head_sh,
3742 unsigned long handle_flags);
3743 /* handle_stripe_clean_event
3744 * any written block on an uptodate or failed drive can be returned.
3745 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3746 * never LOCKED, so we don't need to test 'failed' directly.
3748 static void handle_stripe_clean_event(struct r5conf *conf,
3749 struct stripe_head *sh, int disks)
3753 int discard_pending = 0;
3754 struct stripe_head *head_sh = sh;
3755 bool do_endio = false;
3757 for (i = disks; i--; )
3758 if (sh->dev[i].written) {
3760 if (!test_bit(R5_LOCKED, &dev->flags) &&
3761 (test_bit(R5_UPTODATE, &dev->flags) ||
3762 test_bit(R5_Discard, &dev->flags) ||
3763 test_bit(R5_SkipCopy, &dev->flags))) {
3764 /* We can return any write requests */
3765 struct bio *wbi, *wbi2;
3766 pr_debug("Return write for disc %d\n", i);
3767 if (test_and_clear_bit(R5_Discard, &dev->flags))
3768 clear_bit(R5_UPTODATE, &dev->flags);
3769 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3770 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3775 dev->page = dev->orig_page;
3777 dev->written = NULL;
3778 while (wbi && wbi->bi_iter.bi_sector <
3779 dev->sector + STRIPE_SECTORS) {
3780 wbi2 = r5_next_bio(wbi, dev->sector);
3781 md_write_end(conf->mddev);
3785 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3787 !test_bit(STRIPE_DEGRADED, &sh->state),
3789 if (head_sh->batch_head) {
3790 sh = list_first_entry(&sh->batch_list,
3793 if (sh != head_sh) {
3800 } else if (test_bit(R5_Discard, &dev->flags))
3801 discard_pending = 1;
3804 log_stripe_write_finished(sh);
3806 if (!discard_pending &&
3807 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3809 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3810 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3811 if (sh->qd_idx >= 0) {
3812 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3813 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3815 /* now that discard is done we can proceed with any sync */
3816 clear_bit(STRIPE_DISCARD, &sh->state);
3818 * SCSI discard will change some bio fields and the stripe has
3819 * no updated data, so remove it from hash list and the stripe
3820 * will be reinitialized
3823 hash = sh->hash_lock_index;
3824 spin_lock_irq(conf->hash_locks + hash);
3826 spin_unlock_irq(conf->hash_locks + hash);
3827 if (head_sh->batch_head) {
3828 sh = list_first_entry(&sh->batch_list,
3829 struct stripe_head, batch_list);
3835 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3836 set_bit(STRIPE_HANDLE, &sh->state);
3840 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3841 if (atomic_dec_and_test(&conf->pending_full_writes))
3842 md_wakeup_thread(conf->mddev->thread);
3844 if (head_sh->batch_head && do_endio)
3845 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3849 * For RMW in write back cache, we need extra page in prexor to store the
3850 * old data. This page is stored in dev->orig_page.
3852 * This function checks whether we have data for prexor. The exact logic
3854 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
3856 static inline bool uptodate_for_rmw(struct r5dev *dev)
3858 return (test_bit(R5_UPTODATE, &dev->flags)) &&
3859 (!test_bit(R5_InJournal, &dev->flags) ||
3860 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
3863 static int handle_stripe_dirtying(struct r5conf *conf,
3864 struct stripe_head *sh,
3865 struct stripe_head_state *s,
3868 int rmw = 0, rcw = 0, i;
3869 sector_t recovery_cp = conf->mddev->recovery_cp;
3871 /* Check whether resync is now happening or should start.
3872 * If yes, then the array is dirty (after unclean shutdown or
3873 * initial creation), so parity in some stripes might be inconsistent.
3874 * In this case, we need to always do reconstruct-write, to ensure
3875 * that in case of drive failure or read-error correction, we
3876 * generate correct data from the parity.
3878 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3879 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3881 /* Calculate the real rcw later - for now make it
3882 * look like rcw is cheaper
3885 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3886 conf->rmw_level, (unsigned long long)recovery_cp,
3887 (unsigned long long)sh->sector);
3888 } else for (i = disks; i--; ) {
3889 /* would I have to read this buffer for read_modify_write */
3890 struct r5dev *dev = &sh->dev[i];
3891 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3892 i == sh->pd_idx || i == sh->qd_idx ||
3893 test_bit(R5_InJournal, &dev->flags)) &&
3894 !test_bit(R5_LOCKED, &dev->flags) &&
3895 !(uptodate_for_rmw(dev) ||
3896 test_bit(R5_Wantcompute, &dev->flags))) {
3897 if (test_bit(R5_Insync, &dev->flags))
3900 rmw += 2*disks; /* cannot read it */
3902 /* Would I have to read this buffer for reconstruct_write */
3903 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3904 i != sh->pd_idx && i != sh->qd_idx &&
3905 !test_bit(R5_LOCKED, &dev->flags) &&
3906 !(test_bit(R5_UPTODATE, &dev->flags) ||
3907 test_bit(R5_Wantcompute, &dev->flags))) {
3908 if (test_bit(R5_Insync, &dev->flags))
3915 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
3916 (unsigned long long)sh->sector, sh->state, rmw, rcw);
3917 set_bit(STRIPE_HANDLE, &sh->state);
3918 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
3919 /* prefer read-modify-write, but need to get some data */
3920 if (conf->mddev->queue)
3921 blk_add_trace_msg(conf->mddev->queue,
3922 "raid5 rmw %llu %d",
3923 (unsigned long long)sh->sector, rmw);
3924 for (i = disks; i--; ) {
3925 struct r5dev *dev = &sh->dev[i];
3926 if (test_bit(R5_InJournal, &dev->flags) &&
3927 dev->page == dev->orig_page &&
3928 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
3929 /* alloc page for prexor */
3930 struct page *p = alloc_page(GFP_NOIO);
3938 * alloc_page() failed, try use
3939 * disk_info->extra_page
3941 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
3942 &conf->cache_state)) {
3943 r5c_use_extra_page(sh);
3947 /* extra_page in use, add to delayed_list */
3948 set_bit(STRIPE_DELAYED, &sh->state);
3949 s->waiting_extra_page = 1;
3954 for (i = disks; i--; ) {
3955 struct r5dev *dev = &sh->dev[i];
3956 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3957 i == sh->pd_idx || i == sh->qd_idx ||
3958 test_bit(R5_InJournal, &dev->flags)) &&
3959 !test_bit(R5_LOCKED, &dev->flags) &&
3960 !(uptodate_for_rmw(dev) ||
3961 test_bit(R5_Wantcompute, &dev->flags)) &&
3962 test_bit(R5_Insync, &dev->flags)) {
3963 if (test_bit(STRIPE_PREREAD_ACTIVE,
3965 pr_debug("Read_old block %d for r-m-w\n",
3967 set_bit(R5_LOCKED, &dev->flags);
3968 set_bit(R5_Wantread, &dev->flags);
3971 set_bit(STRIPE_DELAYED, &sh->state);
3972 set_bit(STRIPE_HANDLE, &sh->state);
3977 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
3978 /* want reconstruct write, but need to get some data */
3981 for (i = disks; i--; ) {
3982 struct r5dev *dev = &sh->dev[i];
3983 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3984 i != sh->pd_idx && i != sh->qd_idx &&
3985 !test_bit(R5_LOCKED, &dev->flags) &&
3986 !(test_bit(R5_UPTODATE, &dev->flags) ||
3987 test_bit(R5_Wantcompute, &dev->flags))) {
3989 if (test_bit(R5_Insync, &dev->flags) &&
3990 test_bit(STRIPE_PREREAD_ACTIVE,
3992 pr_debug("Read_old block "
3993 "%d for Reconstruct\n", i);
3994 set_bit(R5_LOCKED, &dev->flags);
3995 set_bit(R5_Wantread, &dev->flags);
3999 set_bit(STRIPE_DELAYED, &sh->state);
4000 set_bit(STRIPE_HANDLE, &sh->state);
4004 if (rcw && conf->mddev->queue)
4005 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4006 (unsigned long long)sh->sector,
4007 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4010 if (rcw > disks && rmw > disks &&
4011 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4012 set_bit(STRIPE_DELAYED, &sh->state);
4014 /* now if nothing is locked, and if we have enough data,
4015 * we can start a write request
4017 /* since handle_stripe can be called at any time we need to handle the
4018 * case where a compute block operation has been submitted and then a
4019 * subsequent call wants to start a write request. raid_run_ops only
4020 * handles the case where compute block and reconstruct are requested
4021 * simultaneously. If this is not the case then new writes need to be
4022 * held off until the compute completes.
4024 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4025 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4026 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4027 schedule_reconstruction(sh, s, rcw == 0, 0);
4031 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4032 struct stripe_head_state *s, int disks)
4034 struct r5dev *dev = NULL;
4036 BUG_ON(sh->batch_head);
4037 set_bit(STRIPE_HANDLE, &sh->state);
4039 switch (sh->check_state) {
4040 case check_state_idle:
4041 /* start a new check operation if there are no failures */
4042 if (s->failed == 0) {
4043 BUG_ON(s->uptodate != disks);
4044 sh->check_state = check_state_run;
4045 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4046 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4050 dev = &sh->dev[s->failed_num[0]];
4052 case check_state_compute_result:
4053 sh->check_state = check_state_idle;
4055 dev = &sh->dev[sh->pd_idx];
4057 /* check that a write has not made the stripe insync */
4058 if (test_bit(STRIPE_INSYNC, &sh->state))
4061 /* either failed parity check, or recovery is happening */
4062 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4063 BUG_ON(s->uptodate != disks);
4065 set_bit(R5_LOCKED, &dev->flags);
4067 set_bit(R5_Wantwrite, &dev->flags);
4069 clear_bit(STRIPE_DEGRADED, &sh->state);
4070 set_bit(STRIPE_INSYNC, &sh->state);
4072 case check_state_run:
4073 break; /* we will be called again upon completion */
4074 case check_state_check_result:
4075 sh->check_state = check_state_idle;
4077 /* if a failure occurred during the check operation, leave
4078 * STRIPE_INSYNC not set and let the stripe be handled again
4083 /* handle a successful check operation, if parity is correct
4084 * we are done. Otherwise update the mismatch count and repair
4085 * parity if !MD_RECOVERY_CHECK
4087 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4088 /* parity is correct (on disc,
4089 * not in buffer any more)
4091 set_bit(STRIPE_INSYNC, &sh->state);
4093 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4094 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4095 /* don't try to repair!! */
4096 set_bit(STRIPE_INSYNC, &sh->state);
4097 pr_warn_ratelimited("%s: mismatch sector in range "
4098 "%llu-%llu\n", mdname(conf->mddev),
4099 (unsigned long long) sh->sector,
4100 (unsigned long long) sh->sector +
4103 sh->check_state = check_state_compute_run;
4104 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4105 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4106 set_bit(R5_Wantcompute,
4107 &sh->dev[sh->pd_idx].flags);
4108 sh->ops.target = sh->pd_idx;
4109 sh->ops.target2 = -1;
4114 case check_state_compute_run:
4117 pr_err("%s: unknown check_state: %d sector: %llu\n",
4118 __func__, sh->check_state,
4119 (unsigned long long) sh->sector);
4124 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4125 struct stripe_head_state *s,
4128 int pd_idx = sh->pd_idx;
4129 int qd_idx = sh->qd_idx;
4132 BUG_ON(sh->batch_head);
4133 set_bit(STRIPE_HANDLE, &sh->state);
4135 BUG_ON(s->failed > 2);
4137 /* Want to check and possibly repair P and Q.
4138 * However there could be one 'failed' device, in which
4139 * case we can only check one of them, possibly using the
4140 * other to generate missing data
4143 switch (sh->check_state) {
4144 case check_state_idle:
4145 /* start a new check operation if there are < 2 failures */
4146 if (s->failed == s->q_failed) {
4147 /* The only possible failed device holds Q, so it
4148 * makes sense to check P (If anything else were failed,
4149 * we would have used P to recreate it).
4151 sh->check_state = check_state_run;
4153 if (!s->q_failed && s->failed < 2) {
4154 /* Q is not failed, and we didn't use it to generate
4155 * anything, so it makes sense to check it
4157 if (sh->check_state == check_state_run)
4158 sh->check_state = check_state_run_pq;
4160 sh->check_state = check_state_run_q;
4163 /* discard potentially stale zero_sum_result */
4164 sh->ops.zero_sum_result = 0;
4166 if (sh->check_state == check_state_run) {
4167 /* async_xor_zero_sum destroys the contents of P */
4168 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4171 if (sh->check_state >= check_state_run &&
4172 sh->check_state <= check_state_run_pq) {
4173 /* async_syndrome_zero_sum preserves P and Q, so
4174 * no need to mark them !uptodate here
4176 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4180 /* we have 2-disk failure */
4181 BUG_ON(s->failed != 2);
4183 case check_state_compute_result:
4184 sh->check_state = check_state_idle;
4186 /* check that a write has not made the stripe insync */
4187 if (test_bit(STRIPE_INSYNC, &sh->state))
4190 /* now write out any block on a failed drive,
4191 * or P or Q if they were recomputed
4194 if (s->failed == 2) {
4195 dev = &sh->dev[s->failed_num[1]];
4197 set_bit(R5_LOCKED, &dev->flags);
4198 set_bit(R5_Wantwrite, &dev->flags);
4200 if (s->failed >= 1) {
4201 dev = &sh->dev[s->failed_num[0]];
4203 set_bit(R5_LOCKED, &dev->flags);
4204 set_bit(R5_Wantwrite, &dev->flags);
4206 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4207 dev = &sh->dev[pd_idx];
4209 set_bit(R5_LOCKED, &dev->flags);
4210 set_bit(R5_Wantwrite, &dev->flags);
4212 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4213 dev = &sh->dev[qd_idx];
4215 set_bit(R5_LOCKED, &dev->flags);
4216 set_bit(R5_Wantwrite, &dev->flags);
4218 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4219 "%s: disk%td not up to date\n",
4220 mdname(conf->mddev),
4221 dev - (struct r5dev *) &sh->dev)) {
4222 clear_bit(R5_LOCKED, &dev->flags);
4223 clear_bit(R5_Wantwrite, &dev->flags);
4226 clear_bit(STRIPE_DEGRADED, &sh->state);
4228 set_bit(STRIPE_INSYNC, &sh->state);
4230 case check_state_run:
4231 case check_state_run_q:
4232 case check_state_run_pq:
4233 break; /* we will be called again upon completion */
4234 case check_state_check_result:
4235 sh->check_state = check_state_idle;
4237 /* handle a successful check operation, if parity is correct
4238 * we are done. Otherwise update the mismatch count and repair
4239 * parity if !MD_RECOVERY_CHECK
4241 if (sh->ops.zero_sum_result == 0) {
4242 /* both parities are correct */
4244 set_bit(STRIPE_INSYNC, &sh->state);
4246 /* in contrast to the raid5 case we can validate
4247 * parity, but still have a failure to write
4250 sh->check_state = check_state_compute_result;
4251 /* Returning at this point means that we may go
4252 * off and bring p and/or q uptodate again so
4253 * we make sure to check zero_sum_result again
4254 * to verify if p or q need writeback
4258 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4259 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4260 /* don't try to repair!! */
4261 set_bit(STRIPE_INSYNC, &sh->state);
4262 pr_warn_ratelimited("%s: mismatch sector in range "
4263 "%llu-%llu\n", mdname(conf->mddev),
4264 (unsigned long long) sh->sector,
4265 (unsigned long long) sh->sector +
4268 int *target = &sh->ops.target;
4270 sh->ops.target = -1;
4271 sh->ops.target2 = -1;
4272 sh->check_state = check_state_compute_run;
4273 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4274 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4275 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4276 set_bit(R5_Wantcompute,
4277 &sh->dev[pd_idx].flags);
4279 target = &sh->ops.target2;
4282 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4283 set_bit(R5_Wantcompute,
4284 &sh->dev[qd_idx].flags);
4291 case check_state_compute_run:
4294 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4295 __func__, sh->check_state,
4296 (unsigned long long) sh->sector);
4301 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4305 /* We have read all the blocks in this stripe and now we need to
4306 * copy some of them into a target stripe for expand.
4308 struct dma_async_tx_descriptor *tx = NULL;
4309 BUG_ON(sh->batch_head);
4310 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4311 for (i = 0; i < sh->disks; i++)
4312 if (i != sh->pd_idx && i != sh->qd_idx) {
4314 struct stripe_head *sh2;
4315 struct async_submit_ctl submit;
4317 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4318 sector_t s = raid5_compute_sector(conf, bn, 0,
4320 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4322 /* so far only the early blocks of this stripe
4323 * have been requested. When later blocks
4324 * get requested, we will try again
4327 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4328 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4329 /* must have already done this block */
4330 raid5_release_stripe(sh2);
4334 /* place all the copies on one channel */
4335 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4336 tx = async_memcpy(sh2->dev[dd_idx].page,
4337 sh->dev[i].page, 0, 0, STRIPE_SIZE,
4340 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4341 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4342 for (j = 0; j < conf->raid_disks; j++)
4343 if (j != sh2->pd_idx &&
4345 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4347 if (j == conf->raid_disks) {
4348 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4349 set_bit(STRIPE_HANDLE, &sh2->state);
4351 raid5_release_stripe(sh2);
4354 /* done submitting copies, wait for them to complete */
4355 async_tx_quiesce(&tx);
4359 * handle_stripe - do things to a stripe.
4361 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4362 * state of various bits to see what needs to be done.
4364 * return some read requests which now have data
4365 * return some write requests which are safely on storage
4366 * schedule a read on some buffers
4367 * schedule a write of some buffers
4368 * return confirmation of parity correctness
4372 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4374 struct r5conf *conf = sh->raid_conf;
4375 int disks = sh->disks;
4378 int do_recovery = 0;
4380 memset(s, 0, sizeof(*s));
4382 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4383 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4384 s->failed_num[0] = -1;
4385 s->failed_num[1] = -1;
4386 s->log_failed = r5l_log_disk_error(conf);
4388 /* Now to look around and see what can be done */
4390 for (i=disks; i--; ) {
4391 struct md_rdev *rdev;
4398 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4400 dev->toread, dev->towrite, dev->written);
4401 /* maybe we can reply to a read
4403 * new wantfill requests are only permitted while
4404 * ops_complete_biofill is guaranteed to be inactive
4406 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4407 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4408 set_bit(R5_Wantfill, &dev->flags);
4410 /* now count some things */
4411 if (test_bit(R5_LOCKED, &dev->flags))
4413 if (test_bit(R5_UPTODATE, &dev->flags))
4415 if (test_bit(R5_Wantcompute, &dev->flags)) {
4417 BUG_ON(s->compute > 2);
4420 if (test_bit(R5_Wantfill, &dev->flags))
4422 else if (dev->toread)
4426 if (!test_bit(R5_OVERWRITE, &dev->flags))
4431 /* Prefer to use the replacement for reads, but only
4432 * if it is recovered enough and has no bad blocks.
4434 rdev = rcu_dereference(conf->disks[i].replacement);
4435 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4436 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4437 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4438 &first_bad, &bad_sectors))
4439 set_bit(R5_ReadRepl, &dev->flags);
4441 if (rdev && !test_bit(Faulty, &rdev->flags))
4442 set_bit(R5_NeedReplace, &dev->flags);
4444 clear_bit(R5_NeedReplace, &dev->flags);
4445 rdev = rcu_dereference(conf->disks[i].rdev);
4446 clear_bit(R5_ReadRepl, &dev->flags);
4448 if (rdev && test_bit(Faulty, &rdev->flags))
4451 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4452 &first_bad, &bad_sectors);
4453 if (s->blocked_rdev == NULL
4454 && (test_bit(Blocked, &rdev->flags)
4457 set_bit(BlockedBadBlocks,
4459 s->blocked_rdev = rdev;
4460 atomic_inc(&rdev->nr_pending);
4463 clear_bit(R5_Insync, &dev->flags);
4467 /* also not in-sync */
4468 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4469 test_bit(R5_UPTODATE, &dev->flags)) {
4470 /* treat as in-sync, but with a read error
4471 * which we can now try to correct
4473 set_bit(R5_Insync, &dev->flags);
4474 set_bit(R5_ReadError, &dev->flags);
4476 } else if (test_bit(In_sync, &rdev->flags))
4477 set_bit(R5_Insync, &dev->flags);
4478 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4479 /* in sync if before recovery_offset */
4480 set_bit(R5_Insync, &dev->flags);
4481 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4482 test_bit(R5_Expanded, &dev->flags))
4483 /* If we've reshaped into here, we assume it is Insync.
4484 * We will shortly update recovery_offset to make
4487 set_bit(R5_Insync, &dev->flags);
4489 if (test_bit(R5_WriteError, &dev->flags)) {
4490 /* This flag does not apply to '.replacement'
4491 * only to .rdev, so make sure to check that*/
4492 struct md_rdev *rdev2 = rcu_dereference(
4493 conf->disks[i].rdev);
4495 clear_bit(R5_Insync, &dev->flags);
4496 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4497 s->handle_bad_blocks = 1;
4498 atomic_inc(&rdev2->nr_pending);
4500 clear_bit(R5_WriteError, &dev->flags);
4502 if (test_bit(R5_MadeGood, &dev->flags)) {
4503 /* This flag does not apply to '.replacement'
4504 * only to .rdev, so make sure to check that*/
4505 struct md_rdev *rdev2 = rcu_dereference(
4506 conf->disks[i].rdev);
4507 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4508 s->handle_bad_blocks = 1;
4509 atomic_inc(&rdev2->nr_pending);
4511 clear_bit(R5_MadeGood, &dev->flags);
4513 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4514 struct md_rdev *rdev2 = rcu_dereference(
4515 conf->disks[i].replacement);
4516 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4517 s->handle_bad_blocks = 1;
4518 atomic_inc(&rdev2->nr_pending);
4520 clear_bit(R5_MadeGoodRepl, &dev->flags);
4522 if (!test_bit(R5_Insync, &dev->flags)) {
4523 /* The ReadError flag will just be confusing now */
4524 clear_bit(R5_ReadError, &dev->flags);
4525 clear_bit(R5_ReWrite, &dev->flags);
4527 if (test_bit(R5_ReadError, &dev->flags))
4528 clear_bit(R5_Insync, &dev->flags);
4529 if (!test_bit(R5_Insync, &dev->flags)) {
4531 s->failed_num[s->failed] = i;
4533 if (rdev && !test_bit(Faulty, &rdev->flags))
4536 rdev = rcu_dereference(
4537 conf->disks[i].replacement);
4538 if (rdev && !test_bit(Faulty, &rdev->flags))
4543 if (test_bit(R5_InJournal, &dev->flags))
4545 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4548 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4549 /* If there is a failed device being replaced,
4550 * we must be recovering.
4551 * else if we are after recovery_cp, we must be syncing
4552 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4553 * else we can only be replacing
4554 * sync and recovery both need to read all devices, and so
4555 * use the same flag.
4558 sh->sector >= conf->mddev->recovery_cp ||
4559 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4567 static int clear_batch_ready(struct stripe_head *sh)
4569 /* Return '1' if this is a member of batch, or
4570 * '0' if it is a lone stripe or a head which can now be
4573 struct stripe_head *tmp;
4574 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4575 return (sh->batch_head && sh->batch_head != sh);
4576 spin_lock(&sh->stripe_lock);
4577 if (!sh->batch_head) {
4578 spin_unlock(&sh->stripe_lock);
4583 * this stripe could be added to a batch list before we check
4584 * BATCH_READY, skips it
4586 if (sh->batch_head != sh) {
4587 spin_unlock(&sh->stripe_lock);
4590 spin_lock(&sh->batch_lock);
4591 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4592 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4593 spin_unlock(&sh->batch_lock);
4594 spin_unlock(&sh->stripe_lock);
4597 * BATCH_READY is cleared, no new stripes can be added.
4598 * batch_list can be accessed without lock
4603 static void break_stripe_batch_list(struct stripe_head *head_sh,
4604 unsigned long handle_flags)
4606 struct stripe_head *sh, *next;
4610 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4612 list_del_init(&sh->batch_list);
4614 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4615 (1 << STRIPE_SYNCING) |
4616 (1 << STRIPE_REPLACED) |
4617 (1 << STRIPE_DELAYED) |
4618 (1 << STRIPE_BIT_DELAY) |
4619 (1 << STRIPE_FULL_WRITE) |
4620 (1 << STRIPE_BIOFILL_RUN) |
4621 (1 << STRIPE_COMPUTE_RUN) |
4622 (1 << STRIPE_OPS_REQ_PENDING) |
4623 (1 << STRIPE_DISCARD) |
4624 (1 << STRIPE_BATCH_READY) |
4625 (1 << STRIPE_BATCH_ERR) |
4626 (1 << STRIPE_BITMAP_PENDING)),
4627 "stripe state: %lx\n", sh->state);
4628 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4629 (1 << STRIPE_REPLACED)),
4630 "head stripe state: %lx\n", head_sh->state);
4632 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4633 (1 << STRIPE_PREREAD_ACTIVE) |
4634 (1 << STRIPE_DEGRADED) |
4635 (1 << STRIPE_ON_UNPLUG_LIST)),
4636 head_sh->state & (1 << STRIPE_INSYNC));
4638 sh->check_state = head_sh->check_state;
4639 sh->reconstruct_state = head_sh->reconstruct_state;
4640 spin_lock_irq(&sh->stripe_lock);
4641 sh->batch_head = NULL;
4642 spin_unlock_irq(&sh->stripe_lock);
4643 for (i = 0; i < sh->disks; i++) {
4644 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4646 sh->dev[i].flags = head_sh->dev[i].flags &
4647 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4649 if (handle_flags == 0 ||
4650 sh->state & handle_flags)
4651 set_bit(STRIPE_HANDLE, &sh->state);
4652 raid5_release_stripe(sh);
4654 spin_lock_irq(&head_sh->stripe_lock);
4655 head_sh->batch_head = NULL;
4656 spin_unlock_irq(&head_sh->stripe_lock);
4657 for (i = 0; i < head_sh->disks; i++)
4658 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4660 if (head_sh->state & handle_flags)
4661 set_bit(STRIPE_HANDLE, &head_sh->state);
4664 wake_up(&head_sh->raid_conf->wait_for_overlap);
4667 static void handle_stripe(struct stripe_head *sh)
4669 struct stripe_head_state s;
4670 struct r5conf *conf = sh->raid_conf;
4673 int disks = sh->disks;
4674 struct r5dev *pdev, *qdev;
4676 clear_bit(STRIPE_HANDLE, &sh->state);
4677 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4678 /* already being handled, ensure it gets handled
4679 * again when current action finishes */
4680 set_bit(STRIPE_HANDLE, &sh->state);
4684 if (clear_batch_ready(sh) ) {
4685 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4689 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4690 break_stripe_batch_list(sh, 0);
4692 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4693 spin_lock(&sh->stripe_lock);
4695 * Cannot process 'sync' concurrently with 'discard'.
4696 * Flush data in r5cache before 'sync'.
4698 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4699 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4700 !test_bit(STRIPE_DISCARD, &sh->state) &&
4701 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4702 set_bit(STRIPE_SYNCING, &sh->state);
4703 clear_bit(STRIPE_INSYNC, &sh->state);
4704 clear_bit(STRIPE_REPLACED, &sh->state);
4706 spin_unlock(&sh->stripe_lock);
4708 clear_bit(STRIPE_DELAYED, &sh->state);
4710 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4711 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4712 (unsigned long long)sh->sector, sh->state,
4713 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4714 sh->check_state, sh->reconstruct_state);
4716 analyse_stripe(sh, &s);
4718 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4721 if (s.handle_bad_blocks ||
4722 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4723 set_bit(STRIPE_HANDLE, &sh->state);
4727 if (unlikely(s.blocked_rdev)) {
4728 if (s.syncing || s.expanding || s.expanded ||
4729 s.replacing || s.to_write || s.written) {
4730 set_bit(STRIPE_HANDLE, &sh->state);
4733 /* There is nothing for the blocked_rdev to block */
4734 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4735 s.blocked_rdev = NULL;
4738 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4739 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4740 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4743 pr_debug("locked=%d uptodate=%d to_read=%d"
4744 " to_write=%d failed=%d failed_num=%d,%d\n",
4745 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4746 s.failed_num[0], s.failed_num[1]);
4748 * check if the array has lost more than max_degraded devices and,
4749 * if so, some requests might need to be failed.
4751 * When journal device failed (log_failed), we will only process
4752 * the stripe if there is data need write to raid disks
4754 if (s.failed > conf->max_degraded ||
4755 (s.log_failed && s.injournal == 0)) {
4756 sh->check_state = 0;
4757 sh->reconstruct_state = 0;
4758 break_stripe_batch_list(sh, 0);
4759 if (s.to_read+s.to_write+s.written)
4760 handle_failed_stripe(conf, sh, &s, disks);
4761 if (s.syncing + s.replacing)
4762 handle_failed_sync(conf, sh, &s);
4765 /* Now we check to see if any write operations have recently
4769 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4771 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4772 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4773 sh->reconstruct_state = reconstruct_state_idle;
4775 /* All the 'written' buffers and the parity block are ready to
4776 * be written back to disk
4778 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4779 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4780 BUG_ON(sh->qd_idx >= 0 &&
4781 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4782 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4783 for (i = disks; i--; ) {
4784 struct r5dev *dev = &sh->dev[i];
4785 if (test_bit(R5_LOCKED, &dev->flags) &&
4786 (i == sh->pd_idx || i == sh->qd_idx ||
4787 dev->written || test_bit(R5_InJournal,
4789 pr_debug("Writing block %d\n", i);
4790 set_bit(R5_Wantwrite, &dev->flags);
4795 if (!test_bit(R5_Insync, &dev->flags) ||
4796 ((i == sh->pd_idx || i == sh->qd_idx) &&
4798 set_bit(STRIPE_INSYNC, &sh->state);
4801 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4802 s.dec_preread_active = 1;
4806 * might be able to return some write requests if the parity blocks
4807 * are safe, or on a failed drive
4809 pdev = &sh->dev[sh->pd_idx];
4810 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4811 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4812 qdev = &sh->dev[sh->qd_idx];
4813 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4814 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4818 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4819 && !test_bit(R5_LOCKED, &pdev->flags)
4820 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4821 test_bit(R5_Discard, &pdev->flags))))) &&
4822 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4823 && !test_bit(R5_LOCKED, &qdev->flags)
4824 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4825 test_bit(R5_Discard, &qdev->flags))))))
4826 handle_stripe_clean_event(conf, sh, disks);
4829 r5c_handle_cached_data_endio(conf, sh, disks);
4830 log_stripe_write_finished(sh);
4832 /* Now we might consider reading some blocks, either to check/generate
4833 * parity, or to satisfy requests
4834 * or to load a block that is being partially written.
4836 if (s.to_read || s.non_overwrite
4837 || (s.to_write && s.failed)
4838 || (s.syncing && (s.uptodate + s.compute < disks))
4841 handle_stripe_fill(sh, &s, disks);
4844 * When the stripe finishes full journal write cycle (write to journal
4845 * and raid disk), this is the clean up procedure so it is ready for
4848 r5c_finish_stripe_write_out(conf, sh, &s);
4851 * Now to consider new write requests, cache write back and what else,
4852 * if anything should be read. We do not handle new writes when:
4853 * 1/ A 'write' operation (copy+xor) is already in flight.
4854 * 2/ A 'check' operation is in flight, as it may clobber the parity
4856 * 3/ A r5c cache log write is in flight.
4859 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
4860 if (!r5c_is_writeback(conf->log)) {
4862 handle_stripe_dirtying(conf, sh, &s, disks);
4863 } else { /* write back cache */
4866 /* First, try handle writes in caching phase */
4868 ret = r5c_try_caching_write(conf, sh, &s,
4871 * If caching phase failed: ret == -EAGAIN
4873 * stripe under reclaim: !caching && injournal
4875 * fall back to handle_stripe_dirtying()
4877 if (ret == -EAGAIN ||
4878 /* stripe under reclaim: !caching && injournal */
4879 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
4881 ret = handle_stripe_dirtying(conf, sh, &s,
4889 /* maybe we need to check and possibly fix the parity for this stripe
4890 * Any reads will already have been scheduled, so we just see if enough
4891 * data is available. The parity check is held off while parity
4892 * dependent operations are in flight.
4894 if (sh->check_state ||
4895 (s.syncing && s.locked == 0 &&
4896 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4897 !test_bit(STRIPE_INSYNC, &sh->state))) {
4898 if (conf->level == 6)
4899 handle_parity_checks6(conf, sh, &s, disks);
4901 handle_parity_checks5(conf, sh, &s, disks);
4904 if ((s.replacing || s.syncing) && s.locked == 0
4905 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4906 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4907 /* Write out to replacement devices where possible */
4908 for (i = 0; i < conf->raid_disks; i++)
4909 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4910 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4911 set_bit(R5_WantReplace, &sh->dev[i].flags);
4912 set_bit(R5_LOCKED, &sh->dev[i].flags);
4916 set_bit(STRIPE_INSYNC, &sh->state);
4917 set_bit(STRIPE_REPLACED, &sh->state);
4919 if ((s.syncing || s.replacing) && s.locked == 0 &&
4920 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4921 test_bit(STRIPE_INSYNC, &sh->state)) {
4922 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4923 clear_bit(STRIPE_SYNCING, &sh->state);
4924 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4925 wake_up(&conf->wait_for_overlap);
4928 /* If the failed drives are just a ReadError, then we might need
4929 * to progress the repair/check process
4931 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4932 for (i = 0; i < s.failed; i++) {
4933 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4934 if (test_bit(R5_ReadError, &dev->flags)
4935 && !test_bit(R5_LOCKED, &dev->flags)
4936 && test_bit(R5_UPTODATE, &dev->flags)
4938 if (!test_bit(R5_ReWrite, &dev->flags)) {
4939 set_bit(R5_Wantwrite, &dev->flags);
4940 set_bit(R5_ReWrite, &dev->flags);
4941 set_bit(R5_LOCKED, &dev->flags);
4944 /* let's read it back */
4945 set_bit(R5_Wantread, &dev->flags);
4946 set_bit(R5_LOCKED, &dev->flags);
4952 /* Finish reconstruct operations initiated by the expansion process */
4953 if (sh->reconstruct_state == reconstruct_state_result) {
4954 struct stripe_head *sh_src
4955 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4956 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4957 /* sh cannot be written until sh_src has been read.
4958 * so arrange for sh to be delayed a little
4960 set_bit(STRIPE_DELAYED, &sh->state);
4961 set_bit(STRIPE_HANDLE, &sh->state);
4962 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4964 atomic_inc(&conf->preread_active_stripes);
4965 raid5_release_stripe(sh_src);
4969 raid5_release_stripe(sh_src);
4971 sh->reconstruct_state = reconstruct_state_idle;
4972 clear_bit(STRIPE_EXPANDING, &sh->state);
4973 for (i = conf->raid_disks; i--; ) {
4974 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4975 set_bit(R5_LOCKED, &sh->dev[i].flags);
4980 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4981 !sh->reconstruct_state) {
4982 /* Need to write out all blocks after computing parity */
4983 sh->disks = conf->raid_disks;
4984 stripe_set_idx(sh->sector, conf, 0, sh);
4985 schedule_reconstruction(sh, &s, 1, 1);
4986 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4987 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4988 atomic_dec(&conf->reshape_stripes);
4989 wake_up(&conf->wait_for_overlap);
4990 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4993 if (s.expanding && s.locked == 0 &&
4994 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4995 handle_stripe_expansion(conf, sh);
4998 /* wait for this device to become unblocked */
4999 if (unlikely(s.blocked_rdev)) {
5000 if (conf->mddev->external)
5001 md_wait_for_blocked_rdev(s.blocked_rdev,
5004 /* Internal metadata will immediately
5005 * be written by raid5d, so we don't
5006 * need to wait here.
5008 rdev_dec_pending(s.blocked_rdev,
5012 if (s.handle_bad_blocks)
5013 for (i = disks; i--; ) {
5014 struct md_rdev *rdev;
5015 struct r5dev *dev = &sh->dev[i];
5016 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5017 /* We own a safe reference to the rdev */
5018 rdev = conf->disks[i].rdev;
5019 if (!rdev_set_badblocks(rdev, sh->sector,
5021 md_error(conf->mddev, rdev);
5022 rdev_dec_pending(rdev, conf->mddev);
5024 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5025 rdev = conf->disks[i].rdev;
5026 rdev_clear_badblocks(rdev, sh->sector,
5028 rdev_dec_pending(rdev, conf->mddev);
5030 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5031 rdev = conf->disks[i].replacement;
5033 /* rdev have been moved down */
5034 rdev = conf->disks[i].rdev;
5035 rdev_clear_badblocks(rdev, sh->sector,
5037 rdev_dec_pending(rdev, conf->mddev);
5042 raid_run_ops(sh, s.ops_request);
5046 if (s.dec_preread_active) {
5047 /* We delay this until after ops_run_io so that if make_request
5048 * is waiting on a flush, it won't continue until the writes
5049 * have actually been submitted.
5051 atomic_dec(&conf->preread_active_stripes);
5052 if (atomic_read(&conf->preread_active_stripes) <
5054 md_wakeup_thread(conf->mddev->thread);
5057 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5060 static void raid5_activate_delayed(struct r5conf *conf)
5062 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5063 while (!list_empty(&conf->delayed_list)) {
5064 struct list_head *l = conf->delayed_list.next;
5065 struct stripe_head *sh;
5066 sh = list_entry(l, struct stripe_head, lru);
5068 clear_bit(STRIPE_DELAYED, &sh->state);
5069 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5070 atomic_inc(&conf->preread_active_stripes);
5071 list_add_tail(&sh->lru, &conf->hold_list);
5072 raid5_wakeup_stripe_thread(sh);
5077 static void activate_bit_delay(struct r5conf *conf,
5078 struct list_head *temp_inactive_list)
5080 /* device_lock is held */
5081 struct list_head head;
5082 list_add(&head, &conf->bitmap_list);
5083 list_del_init(&conf->bitmap_list);
5084 while (!list_empty(&head)) {
5085 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5087 list_del_init(&sh->lru);
5088 atomic_inc(&sh->count);
5089 hash = sh->hash_lock_index;
5090 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5094 static int raid5_congested(struct mddev *mddev, int bits)
5096 struct r5conf *conf = mddev->private;
5098 /* No difference between reads and writes. Just check
5099 * how busy the stripe_cache is
5102 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
5105 /* Also checks whether there is pressure on r5cache log space */
5106 if (test_bit(R5C_LOG_TIGHT, &conf->cache_state))
5110 if (atomic_read(&conf->empty_inactive_list_nr))
5116 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5118 struct r5conf *conf = mddev->private;
5119 sector_t sector = bio->bi_iter.bi_sector;
5120 unsigned int chunk_sectors;
5121 unsigned int bio_sectors = bio_sectors(bio);
5123 WARN_ON_ONCE(bio->bi_partno);
5125 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5126 return chunk_sectors >=
5127 ((sector & (chunk_sectors - 1)) + bio_sectors);
5131 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5132 * later sampled by raid5d.
5134 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5136 unsigned long flags;
5138 spin_lock_irqsave(&conf->device_lock, flags);
5140 bi->bi_next = conf->retry_read_aligned_list;
5141 conf->retry_read_aligned_list = bi;
5143 spin_unlock_irqrestore(&conf->device_lock, flags);
5144 md_wakeup_thread(conf->mddev->thread);
5147 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5148 unsigned int *offset)
5152 bi = conf->retry_read_aligned;
5154 *offset = conf->retry_read_offset;
5155 conf->retry_read_aligned = NULL;
5158 bi = conf->retry_read_aligned_list;
5160 conf->retry_read_aligned_list = bi->bi_next;
5169 * The "raid5_align_endio" should check if the read succeeded and if it
5170 * did, call bio_endio on the original bio (having bio_put the new bio
5172 * If the read failed..
5174 static void raid5_align_endio(struct bio *bi)
5176 struct bio* raid_bi = bi->bi_private;
5177 struct mddev *mddev;
5178 struct r5conf *conf;
5179 struct md_rdev *rdev;
5180 blk_status_t error = bi->bi_status;
5184 rdev = (void*)raid_bi->bi_next;
5185 raid_bi->bi_next = NULL;
5186 mddev = rdev->mddev;
5187 conf = mddev->private;
5189 rdev_dec_pending(rdev, conf->mddev);
5193 if (atomic_dec_and_test(&conf->active_aligned_reads))
5194 wake_up(&conf->wait_for_quiescent);
5198 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5200 add_bio_to_retry(raid_bi, conf);
5203 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5205 struct r5conf *conf = mddev->private;
5207 struct bio* align_bi;
5208 struct md_rdev *rdev;
5209 sector_t end_sector;
5211 if (!in_chunk_boundary(mddev, raid_bio)) {
5212 pr_debug("%s: non aligned\n", __func__);
5216 * use bio_clone_fast to make a copy of the bio
5218 align_bi = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5222 * set bi_end_io to a new function, and set bi_private to the
5225 align_bi->bi_end_io = raid5_align_endio;
5226 align_bi->bi_private = raid_bio;
5230 align_bi->bi_iter.bi_sector =
5231 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5234 end_sector = bio_end_sector(align_bi);
5236 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5237 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5238 rdev->recovery_offset < end_sector) {
5239 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5241 (test_bit(Faulty, &rdev->flags) ||
5242 !(test_bit(In_sync, &rdev->flags) ||
5243 rdev->recovery_offset >= end_sector)))
5247 if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5257 atomic_inc(&rdev->nr_pending);
5259 raid_bio->bi_next = (void*)rdev;
5260 bio_set_dev(align_bi, rdev->bdev);
5261 bio_clear_flag(align_bi, BIO_SEG_VALID);
5263 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5264 bio_sectors(align_bi),
5265 &first_bad, &bad_sectors)) {
5267 rdev_dec_pending(rdev, mddev);
5271 /* No reshape active, so we can trust rdev->data_offset */
5272 align_bi->bi_iter.bi_sector += rdev->data_offset;
5274 spin_lock_irq(&conf->device_lock);
5275 wait_event_lock_irq(conf->wait_for_quiescent,
5278 atomic_inc(&conf->active_aligned_reads);
5279 spin_unlock_irq(&conf->device_lock);
5282 trace_block_bio_remap(align_bi->bi_disk->queue,
5283 align_bi, disk_devt(mddev->gendisk),
5284 raid_bio->bi_iter.bi_sector);
5285 generic_make_request(align_bi);
5294 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5297 sector_t sector = raid_bio->bi_iter.bi_sector;
5298 unsigned chunk_sects = mddev->chunk_sectors;
5299 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5301 if (sectors < bio_sectors(raid_bio)) {
5302 struct r5conf *conf = mddev->private;
5303 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5304 bio_chain(split, raid_bio);
5305 generic_make_request(raid_bio);
5309 if (!raid5_read_one_chunk(mddev, raid_bio))
5315 /* __get_priority_stripe - get the next stripe to process
5317 * Full stripe writes are allowed to pass preread active stripes up until
5318 * the bypass_threshold is exceeded. In general the bypass_count
5319 * increments when the handle_list is handled before the hold_list; however, it
5320 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5321 * stripe with in flight i/o. The bypass_count will be reset when the
5322 * head of the hold_list has changed, i.e. the head was promoted to the
5325 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5327 struct stripe_head *sh, *tmp;
5328 struct list_head *handle_list = NULL;
5329 struct r5worker_group *wg;
5330 bool second_try = !r5c_is_writeback(conf->log) &&
5331 !r5l_log_disk_error(conf);
5332 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5333 r5l_log_disk_error(conf);
5338 if (conf->worker_cnt_per_group == 0) {
5339 handle_list = try_loprio ? &conf->loprio_list :
5341 } else if (group != ANY_GROUP) {
5342 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5343 &conf->worker_groups[group].handle_list;
5344 wg = &conf->worker_groups[group];
5347 for (i = 0; i < conf->group_cnt; i++) {
5348 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5349 &conf->worker_groups[i].handle_list;
5350 wg = &conf->worker_groups[i];
5351 if (!list_empty(handle_list))
5356 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5358 list_empty(handle_list) ? "empty" : "busy",
5359 list_empty(&conf->hold_list) ? "empty" : "busy",
5360 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5362 if (!list_empty(handle_list)) {
5363 sh = list_entry(handle_list->next, typeof(*sh), lru);
5365 if (list_empty(&conf->hold_list))
5366 conf->bypass_count = 0;
5367 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5368 if (conf->hold_list.next == conf->last_hold)
5369 conf->bypass_count++;
5371 conf->last_hold = conf->hold_list.next;
5372 conf->bypass_count -= conf->bypass_threshold;
5373 if (conf->bypass_count < 0)
5374 conf->bypass_count = 0;
5377 } else if (!list_empty(&conf->hold_list) &&
5378 ((conf->bypass_threshold &&
5379 conf->bypass_count > conf->bypass_threshold) ||
5380 atomic_read(&conf->pending_full_writes) == 0)) {
5382 list_for_each_entry(tmp, &conf->hold_list, lru) {
5383 if (conf->worker_cnt_per_group == 0 ||
5384 group == ANY_GROUP ||
5385 !cpu_online(tmp->cpu) ||
5386 cpu_to_group(tmp->cpu) == group) {
5393 conf->bypass_count -= conf->bypass_threshold;
5394 if (conf->bypass_count < 0)
5395 conf->bypass_count = 0;
5404 try_loprio = !try_loprio;
5412 list_del_init(&sh->lru);
5413 BUG_ON(atomic_inc_return(&sh->count) != 1);
5417 struct raid5_plug_cb {
5418 struct blk_plug_cb cb;
5419 struct list_head list;
5420 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5423 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5425 struct raid5_plug_cb *cb = container_of(
5426 blk_cb, struct raid5_plug_cb, cb);
5427 struct stripe_head *sh;
5428 struct mddev *mddev = cb->cb.data;
5429 struct r5conf *conf = mddev->private;
5433 if (cb->list.next && !list_empty(&cb->list)) {
5434 spin_lock_irq(&conf->device_lock);
5435 while (!list_empty(&cb->list)) {
5436 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5437 list_del_init(&sh->lru);
5439 * avoid race release_stripe_plug() sees
5440 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5441 * is still in our list
5443 smp_mb__before_atomic();
5444 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5446 * STRIPE_ON_RELEASE_LIST could be set here. In that
5447 * case, the count is always > 1 here
5449 hash = sh->hash_lock_index;
5450 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5453 spin_unlock_irq(&conf->device_lock);
5455 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5456 NR_STRIPE_HASH_LOCKS);
5458 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5462 static void release_stripe_plug(struct mddev *mddev,
5463 struct stripe_head *sh)
5465 struct blk_plug_cb *blk_cb = blk_check_plugged(
5466 raid5_unplug, mddev,
5467 sizeof(struct raid5_plug_cb));
5468 struct raid5_plug_cb *cb;
5471 raid5_release_stripe(sh);
5475 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5477 if (cb->list.next == NULL) {
5479 INIT_LIST_HEAD(&cb->list);
5480 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5481 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5484 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5485 list_add_tail(&sh->lru, &cb->list);
5487 raid5_release_stripe(sh);
5490 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5492 struct r5conf *conf = mddev->private;
5493 sector_t logical_sector, last_sector;
5494 struct stripe_head *sh;
5497 if (mddev->reshape_position != MaxSector)
5498 /* Skip discard while reshape is happening */
5501 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5502 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5506 stripe_sectors = conf->chunk_sectors *
5507 (conf->raid_disks - conf->max_degraded);
5508 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5510 sector_div(last_sector, stripe_sectors);
5512 logical_sector *= conf->chunk_sectors;
5513 last_sector *= conf->chunk_sectors;
5515 for (; logical_sector < last_sector;
5516 logical_sector += STRIPE_SECTORS) {
5520 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5521 prepare_to_wait(&conf->wait_for_overlap, &w,
5522 TASK_UNINTERRUPTIBLE);
5523 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5524 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5525 raid5_release_stripe(sh);
5529 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5530 spin_lock_irq(&sh->stripe_lock);
5531 for (d = 0; d < conf->raid_disks; d++) {
5532 if (d == sh->pd_idx || d == sh->qd_idx)
5534 if (sh->dev[d].towrite || sh->dev[d].toread) {
5535 set_bit(R5_Overlap, &sh->dev[d].flags);
5536 spin_unlock_irq(&sh->stripe_lock);
5537 raid5_release_stripe(sh);
5542 set_bit(STRIPE_DISCARD, &sh->state);
5543 finish_wait(&conf->wait_for_overlap, &w);
5544 sh->overwrite_disks = 0;
5545 for (d = 0; d < conf->raid_disks; d++) {
5546 if (d == sh->pd_idx || d == sh->qd_idx)
5548 sh->dev[d].towrite = bi;
5549 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5550 bio_inc_remaining(bi);
5551 md_write_inc(mddev, bi);
5552 sh->overwrite_disks++;
5554 spin_unlock_irq(&sh->stripe_lock);
5555 if (conf->mddev->bitmap) {
5557 d < conf->raid_disks - conf->max_degraded;
5559 md_bitmap_startwrite(mddev->bitmap,
5563 sh->bm_seq = conf->seq_flush + 1;
5564 set_bit(STRIPE_BIT_DELAY, &sh->state);
5567 set_bit(STRIPE_HANDLE, &sh->state);
5568 clear_bit(STRIPE_DELAYED, &sh->state);
5569 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5570 atomic_inc(&conf->preread_active_stripes);
5571 release_stripe_plug(mddev, sh);
5577 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5579 struct r5conf *conf = mddev->private;
5581 sector_t new_sector;
5582 sector_t logical_sector, last_sector;
5583 struct stripe_head *sh;
5584 const int rw = bio_data_dir(bi);
5587 bool do_flush = false;
5589 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5590 int ret = log_handle_flush_request(conf, bi);
5594 if (ret == -ENODEV) {
5595 if (md_flush_request(mddev, bi))
5598 /* ret == -EAGAIN, fallback */
5600 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5601 * we need to flush journal device
5603 do_flush = bi->bi_opf & REQ_PREFLUSH;
5606 if (!md_write_start(mddev, bi))
5609 * If array is degraded, better not do chunk aligned read because
5610 * later we might have to read it again in order to reconstruct
5611 * data on failed drives.
5613 if (rw == READ && mddev->degraded == 0 &&
5614 mddev->reshape_position == MaxSector) {
5615 bi = chunk_aligned_read(mddev, bi);
5620 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5621 make_discard_request(mddev, bi);
5622 md_write_end(mddev);
5626 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5627 last_sector = bio_end_sector(bi);
5630 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5631 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5637 seq = read_seqcount_begin(&conf->gen_lock);
5640 prepare_to_wait(&conf->wait_for_overlap, &w,
5641 TASK_UNINTERRUPTIBLE);
5642 if (unlikely(conf->reshape_progress != MaxSector)) {
5643 /* spinlock is needed as reshape_progress may be
5644 * 64bit on a 32bit platform, and so it might be
5645 * possible to see a half-updated value
5646 * Of course reshape_progress could change after
5647 * the lock is dropped, so once we get a reference
5648 * to the stripe that we think it is, we will have
5651 spin_lock_irq(&conf->device_lock);
5652 if (mddev->reshape_backwards
5653 ? logical_sector < conf->reshape_progress
5654 : logical_sector >= conf->reshape_progress) {
5657 if (mddev->reshape_backwards
5658 ? logical_sector < conf->reshape_safe
5659 : logical_sector >= conf->reshape_safe) {
5660 spin_unlock_irq(&conf->device_lock);
5666 spin_unlock_irq(&conf->device_lock);
5669 new_sector = raid5_compute_sector(conf, logical_sector,
5672 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5673 (unsigned long long)new_sector,
5674 (unsigned long long)logical_sector);
5676 sh = raid5_get_active_stripe(conf, new_sector, previous,
5677 (bi->bi_opf & REQ_RAHEAD), 0);
5679 if (unlikely(previous)) {
5680 /* expansion might have moved on while waiting for a
5681 * stripe, so we must do the range check again.
5682 * Expansion could still move past after this
5683 * test, but as we are holding a reference to
5684 * 'sh', we know that if that happens,
5685 * STRIPE_EXPANDING will get set and the expansion
5686 * won't proceed until we finish with the stripe.
5689 spin_lock_irq(&conf->device_lock);
5690 if (mddev->reshape_backwards
5691 ? logical_sector >= conf->reshape_progress
5692 : logical_sector < conf->reshape_progress)
5693 /* mismatch, need to try again */
5695 spin_unlock_irq(&conf->device_lock);
5697 raid5_release_stripe(sh);
5703 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5704 /* Might have got the wrong stripe_head
5707 raid5_release_stripe(sh);
5711 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5712 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5713 /* Stripe is busy expanding or
5714 * add failed due to overlap. Flush everything
5717 md_wakeup_thread(mddev->thread);
5718 raid5_release_stripe(sh);
5724 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5725 /* we only need flush for one stripe */
5729 if (!sh->batch_head || sh == sh->batch_head)
5730 set_bit(STRIPE_HANDLE, &sh->state);
5731 clear_bit(STRIPE_DELAYED, &sh->state);
5732 if ((!sh->batch_head || sh == sh->batch_head) &&
5733 (bi->bi_opf & REQ_SYNC) &&
5734 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5735 atomic_inc(&conf->preread_active_stripes);
5736 release_stripe_plug(mddev, sh);
5738 /* cannot get stripe for read-ahead, just give-up */
5739 bi->bi_status = BLK_STS_IOERR;
5743 finish_wait(&conf->wait_for_overlap, &w);
5746 md_write_end(mddev);
5751 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5753 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5755 /* reshaping is quite different to recovery/resync so it is
5756 * handled quite separately ... here.
5758 * On each call to sync_request, we gather one chunk worth of
5759 * destination stripes and flag them as expanding.
5760 * Then we find all the source stripes and request reads.
5761 * As the reads complete, handle_stripe will copy the data
5762 * into the destination stripe and release that stripe.
5764 struct r5conf *conf = mddev->private;
5765 struct stripe_head *sh;
5766 struct md_rdev *rdev;
5767 sector_t first_sector, last_sector;
5768 int raid_disks = conf->previous_raid_disks;
5769 int data_disks = raid_disks - conf->max_degraded;
5770 int new_data_disks = conf->raid_disks - conf->max_degraded;
5773 sector_t writepos, readpos, safepos;
5774 sector_t stripe_addr;
5775 int reshape_sectors;
5776 struct list_head stripes;
5779 if (sector_nr == 0) {
5780 /* If restarting in the middle, skip the initial sectors */
5781 if (mddev->reshape_backwards &&
5782 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5783 sector_nr = raid5_size(mddev, 0, 0)
5784 - conf->reshape_progress;
5785 } else if (mddev->reshape_backwards &&
5786 conf->reshape_progress == MaxSector) {
5787 /* shouldn't happen, but just in case, finish up.*/
5788 sector_nr = MaxSector;
5789 } else if (!mddev->reshape_backwards &&
5790 conf->reshape_progress > 0)
5791 sector_nr = conf->reshape_progress;
5792 sector_div(sector_nr, new_data_disks);
5794 mddev->curr_resync_completed = sector_nr;
5795 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5802 /* We need to process a full chunk at a time.
5803 * If old and new chunk sizes differ, we need to process the
5807 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5809 /* We update the metadata at least every 10 seconds, or when
5810 * the data about to be copied would over-write the source of
5811 * the data at the front of the range. i.e. one new_stripe
5812 * along from reshape_progress new_maps to after where
5813 * reshape_safe old_maps to
5815 writepos = conf->reshape_progress;
5816 sector_div(writepos, new_data_disks);
5817 readpos = conf->reshape_progress;
5818 sector_div(readpos, data_disks);
5819 safepos = conf->reshape_safe;
5820 sector_div(safepos, data_disks);
5821 if (mddev->reshape_backwards) {
5822 BUG_ON(writepos < reshape_sectors);
5823 writepos -= reshape_sectors;
5824 readpos += reshape_sectors;
5825 safepos += reshape_sectors;
5827 writepos += reshape_sectors;
5828 /* readpos and safepos are worst-case calculations.
5829 * A negative number is overly pessimistic, and causes
5830 * obvious problems for unsigned storage. So clip to 0.
5832 readpos -= min_t(sector_t, reshape_sectors, readpos);
5833 safepos -= min_t(sector_t, reshape_sectors, safepos);
5836 /* Having calculated the 'writepos' possibly use it
5837 * to set 'stripe_addr' which is where we will write to.
5839 if (mddev->reshape_backwards) {
5840 BUG_ON(conf->reshape_progress == 0);
5841 stripe_addr = writepos;
5842 BUG_ON((mddev->dev_sectors &
5843 ~((sector_t)reshape_sectors - 1))
5844 - reshape_sectors - stripe_addr
5847 BUG_ON(writepos != sector_nr + reshape_sectors);
5848 stripe_addr = sector_nr;
5851 /* 'writepos' is the most advanced device address we might write.
5852 * 'readpos' is the least advanced device address we might read.
5853 * 'safepos' is the least address recorded in the metadata as having
5855 * If there is a min_offset_diff, these are adjusted either by
5856 * increasing the safepos/readpos if diff is negative, or
5857 * increasing writepos if diff is positive.
5858 * If 'readpos' is then behind 'writepos', there is no way that we can
5859 * ensure safety in the face of a crash - that must be done by userspace
5860 * making a backup of the data. So in that case there is no particular
5861 * rush to update metadata.
5862 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5863 * update the metadata to advance 'safepos' to match 'readpos' so that
5864 * we can be safe in the event of a crash.
5865 * So we insist on updating metadata if safepos is behind writepos and
5866 * readpos is beyond writepos.
5867 * In any case, update the metadata every 10 seconds.
5868 * Maybe that number should be configurable, but I'm not sure it is
5869 * worth it.... maybe it could be a multiple of safemode_delay???
5871 if (conf->min_offset_diff < 0) {
5872 safepos += -conf->min_offset_diff;
5873 readpos += -conf->min_offset_diff;
5875 writepos += conf->min_offset_diff;
5877 if ((mddev->reshape_backwards
5878 ? (safepos > writepos && readpos < writepos)
5879 : (safepos < writepos && readpos > writepos)) ||
5880 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5881 /* Cannot proceed until we've updated the superblock... */
5882 wait_event(conf->wait_for_overlap,
5883 atomic_read(&conf->reshape_stripes)==0
5884 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5885 if (atomic_read(&conf->reshape_stripes) != 0)
5887 mddev->reshape_position = conf->reshape_progress;
5888 mddev->curr_resync_completed = sector_nr;
5889 if (!mddev->reshape_backwards)
5890 /* Can update recovery_offset */
5891 rdev_for_each(rdev, mddev)
5892 if (rdev->raid_disk >= 0 &&
5893 !test_bit(Journal, &rdev->flags) &&
5894 !test_bit(In_sync, &rdev->flags) &&
5895 rdev->recovery_offset < sector_nr)
5896 rdev->recovery_offset = sector_nr;
5898 conf->reshape_checkpoint = jiffies;
5899 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5900 md_wakeup_thread(mddev->thread);
5901 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
5902 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5903 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5905 spin_lock_irq(&conf->device_lock);
5906 conf->reshape_safe = mddev->reshape_position;
5907 spin_unlock_irq(&conf->device_lock);
5908 wake_up(&conf->wait_for_overlap);
5909 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5912 INIT_LIST_HEAD(&stripes);
5913 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5915 int skipped_disk = 0;
5916 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5917 set_bit(STRIPE_EXPANDING, &sh->state);
5918 atomic_inc(&conf->reshape_stripes);
5919 /* If any of this stripe is beyond the end of the old
5920 * array, then we need to zero those blocks
5922 for (j=sh->disks; j--;) {
5924 if (j == sh->pd_idx)
5926 if (conf->level == 6 &&
5929 s = raid5_compute_blocknr(sh, j, 0);
5930 if (s < raid5_size(mddev, 0, 0)) {
5934 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5935 set_bit(R5_Expanded, &sh->dev[j].flags);
5936 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5938 if (!skipped_disk) {
5939 set_bit(STRIPE_EXPAND_READY, &sh->state);
5940 set_bit(STRIPE_HANDLE, &sh->state);
5942 list_add(&sh->lru, &stripes);
5944 spin_lock_irq(&conf->device_lock);
5945 if (mddev->reshape_backwards)
5946 conf->reshape_progress -= reshape_sectors * new_data_disks;
5948 conf->reshape_progress += reshape_sectors * new_data_disks;
5949 spin_unlock_irq(&conf->device_lock);
5950 /* Ok, those stripe are ready. We can start scheduling
5951 * reads on the source stripes.
5952 * The source stripes are determined by mapping the first and last
5953 * block on the destination stripes.
5956 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5959 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5960 * new_data_disks - 1),
5962 if (last_sector >= mddev->dev_sectors)
5963 last_sector = mddev->dev_sectors - 1;
5964 while (first_sector <= last_sector) {
5965 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5966 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5967 set_bit(STRIPE_HANDLE, &sh->state);
5968 raid5_release_stripe(sh);
5969 first_sector += STRIPE_SECTORS;
5971 /* Now that the sources are clearly marked, we can release
5972 * the destination stripes
5974 while (!list_empty(&stripes)) {
5975 sh = list_entry(stripes.next, struct stripe_head, lru);
5976 list_del_init(&sh->lru);
5977 raid5_release_stripe(sh);
5979 /* If this takes us to the resync_max point where we have to pause,
5980 * then we need to write out the superblock.
5982 sector_nr += reshape_sectors;
5983 retn = reshape_sectors;
5985 if (mddev->curr_resync_completed > mddev->resync_max ||
5986 (sector_nr - mddev->curr_resync_completed) * 2
5987 >= mddev->resync_max - mddev->curr_resync_completed) {
5988 /* Cannot proceed until we've updated the superblock... */
5989 wait_event(conf->wait_for_overlap,
5990 atomic_read(&conf->reshape_stripes) == 0
5991 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5992 if (atomic_read(&conf->reshape_stripes) != 0)
5994 mddev->reshape_position = conf->reshape_progress;
5995 mddev->curr_resync_completed = sector_nr;
5996 if (!mddev->reshape_backwards)
5997 /* Can update recovery_offset */
5998 rdev_for_each(rdev, mddev)
5999 if (rdev->raid_disk >= 0 &&
6000 !test_bit(Journal, &rdev->flags) &&
6001 !test_bit(In_sync, &rdev->flags) &&
6002 rdev->recovery_offset < sector_nr)
6003 rdev->recovery_offset = sector_nr;
6004 conf->reshape_checkpoint = jiffies;
6005 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6006 md_wakeup_thread(mddev->thread);
6007 wait_event(mddev->sb_wait,
6008 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6009 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6010 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6012 spin_lock_irq(&conf->device_lock);
6013 conf->reshape_safe = mddev->reshape_position;
6014 spin_unlock_irq(&conf->device_lock);
6015 wake_up(&conf->wait_for_overlap);
6016 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
6022 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6025 struct r5conf *conf = mddev->private;
6026 struct stripe_head *sh;
6027 sector_t max_sector = mddev->dev_sectors;
6028 sector_t sync_blocks;
6029 int still_degraded = 0;
6032 if (sector_nr >= max_sector) {
6033 /* just being told to finish up .. nothing much to do */
6035 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6040 if (mddev->curr_resync < max_sector) /* aborted */
6041 md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6043 else /* completed sync */
6045 md_bitmap_close_sync(mddev->bitmap);
6050 /* Allow raid5_quiesce to complete */
6051 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6053 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6054 return reshape_request(mddev, sector_nr, skipped);
6056 /* No need to check resync_max as we never do more than one
6057 * stripe, and as resync_max will always be on a chunk boundary,
6058 * if the check in md_do_sync didn't fire, there is no chance
6059 * of overstepping resync_max here
6062 /* if there is too many failed drives and we are trying
6063 * to resync, then assert that we are finished, because there is
6064 * nothing we can do.
6066 if (mddev->degraded >= conf->max_degraded &&
6067 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6068 sector_t rv = mddev->dev_sectors - sector_nr;
6072 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6074 !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6075 sync_blocks >= STRIPE_SECTORS) {
6076 /* we can skip this block, and probably more */
6077 sync_blocks /= STRIPE_SECTORS;
6079 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
6082 md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6084 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6086 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6087 /* make sure we don't swamp the stripe cache if someone else
6088 * is trying to get access
6090 schedule_timeout_uninterruptible(1);
6092 /* Need to check if array will still be degraded after recovery/resync
6093 * Note in case of > 1 drive failures it's possible we're rebuilding
6094 * one drive while leaving another faulty drive in array.
6097 for (i = 0; i < conf->raid_disks; i++) {
6098 struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6100 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6105 md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6107 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6108 set_bit(STRIPE_HANDLE, &sh->state);
6110 raid5_release_stripe(sh);
6112 return STRIPE_SECTORS;
6115 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6116 unsigned int offset)
6118 /* We may not be able to submit a whole bio at once as there
6119 * may not be enough stripe_heads available.
6120 * We cannot pre-allocate enough stripe_heads as we may need
6121 * more than exist in the cache (if we allow ever large chunks).
6122 * So we do one stripe head at a time and record in
6123 * ->bi_hw_segments how many have been done.
6125 * We *know* that this entire raid_bio is in one chunk, so
6126 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6128 struct stripe_head *sh;
6130 sector_t sector, logical_sector, last_sector;
6134 logical_sector = raid_bio->bi_iter.bi_sector &
6135 ~((sector_t)STRIPE_SECTORS-1);
6136 sector = raid5_compute_sector(conf, logical_sector,
6138 last_sector = bio_end_sector(raid_bio);
6140 for (; logical_sector < last_sector;
6141 logical_sector += STRIPE_SECTORS,
6142 sector += STRIPE_SECTORS,
6146 /* already done this stripe */
6149 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6152 /* failed to get a stripe - must wait */
6153 conf->retry_read_aligned = raid_bio;
6154 conf->retry_read_offset = scnt;
6158 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6159 raid5_release_stripe(sh);
6160 conf->retry_read_aligned = raid_bio;
6161 conf->retry_read_offset = scnt;
6165 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6167 raid5_release_stripe(sh);
6171 bio_endio(raid_bio);
6173 if (atomic_dec_and_test(&conf->active_aligned_reads))
6174 wake_up(&conf->wait_for_quiescent);
6178 static int handle_active_stripes(struct r5conf *conf, int group,
6179 struct r5worker *worker,
6180 struct list_head *temp_inactive_list)
6182 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6183 int i, batch_size = 0, hash;
6184 bool release_inactive = false;
6186 while (batch_size < MAX_STRIPE_BATCH &&
6187 (sh = __get_priority_stripe(conf, group)) != NULL)
6188 batch[batch_size++] = sh;
6190 if (batch_size == 0) {
6191 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6192 if (!list_empty(temp_inactive_list + i))
6194 if (i == NR_STRIPE_HASH_LOCKS) {
6195 spin_unlock_irq(&conf->device_lock);
6196 log_flush_stripe_to_raid(conf);
6197 spin_lock_irq(&conf->device_lock);
6200 release_inactive = true;
6202 spin_unlock_irq(&conf->device_lock);
6204 release_inactive_stripe_list(conf, temp_inactive_list,
6205 NR_STRIPE_HASH_LOCKS);
6207 r5l_flush_stripe_to_raid(conf->log);
6208 if (release_inactive) {
6209 spin_lock_irq(&conf->device_lock);
6213 for (i = 0; i < batch_size; i++)
6214 handle_stripe(batch[i]);
6215 log_write_stripe_run(conf);
6219 spin_lock_irq(&conf->device_lock);
6220 for (i = 0; i < batch_size; i++) {
6221 hash = batch[i]->hash_lock_index;
6222 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6227 static void raid5_do_work(struct work_struct *work)
6229 struct r5worker *worker = container_of(work, struct r5worker, work);
6230 struct r5worker_group *group = worker->group;
6231 struct r5conf *conf = group->conf;
6232 struct mddev *mddev = conf->mddev;
6233 int group_id = group - conf->worker_groups;
6235 struct blk_plug plug;
6237 pr_debug("+++ raid5worker active\n");
6239 blk_start_plug(&plug);
6241 spin_lock_irq(&conf->device_lock);
6243 int batch_size, released;
6245 released = release_stripe_list(conf, worker->temp_inactive_list);
6247 batch_size = handle_active_stripes(conf, group_id, worker,
6248 worker->temp_inactive_list);
6249 worker->working = false;
6250 if (!batch_size && !released)
6252 handled += batch_size;
6253 wait_event_lock_irq(mddev->sb_wait,
6254 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6257 pr_debug("%d stripes handled\n", handled);
6259 spin_unlock_irq(&conf->device_lock);
6261 flush_deferred_bios(conf);
6263 r5l_flush_stripe_to_raid(conf->log);
6265 async_tx_issue_pending_all();
6266 blk_finish_plug(&plug);
6268 pr_debug("--- raid5worker inactive\n");
6272 * This is our raid5 kernel thread.
6274 * We scan the hash table for stripes which can be handled now.
6275 * During the scan, completed stripes are saved for us by the interrupt
6276 * handler, so that they will not have to wait for our next wakeup.
6278 static void raid5d(struct md_thread *thread)
6280 struct mddev *mddev = thread->mddev;
6281 struct r5conf *conf = mddev->private;
6283 struct blk_plug plug;
6285 pr_debug("+++ raid5d active\n");
6287 md_check_recovery(mddev);
6289 blk_start_plug(&plug);
6291 spin_lock_irq(&conf->device_lock);
6294 int batch_size, released;
6295 unsigned int offset;
6297 released = release_stripe_list(conf, conf->temp_inactive_list);
6299 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6302 !list_empty(&conf->bitmap_list)) {
6303 /* Now is a good time to flush some bitmap updates */
6305 spin_unlock_irq(&conf->device_lock);
6306 md_bitmap_unplug(mddev->bitmap);
6307 spin_lock_irq(&conf->device_lock);
6308 conf->seq_write = conf->seq_flush;
6309 activate_bit_delay(conf, conf->temp_inactive_list);
6311 raid5_activate_delayed(conf);
6313 while ((bio = remove_bio_from_retry(conf, &offset))) {
6315 spin_unlock_irq(&conf->device_lock);
6316 ok = retry_aligned_read(conf, bio, offset);
6317 spin_lock_irq(&conf->device_lock);
6323 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6324 conf->temp_inactive_list);
6325 if (!batch_size && !released)
6327 handled += batch_size;
6329 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6330 spin_unlock_irq(&conf->device_lock);
6331 md_check_recovery(mddev);
6332 spin_lock_irq(&conf->device_lock);
6335 * Waiting on MD_SB_CHANGE_PENDING below may deadlock
6336 * seeing md_check_recovery() is needed to clear
6337 * the flag when using mdmon.
6342 wait_event_lock_irq(mddev->sb_wait,
6343 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6346 pr_debug("%d stripes handled\n", handled);
6348 spin_unlock_irq(&conf->device_lock);
6349 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6350 mutex_trylock(&conf->cache_size_mutex)) {
6351 grow_one_stripe(conf, __GFP_NOWARN);
6352 /* Set flag even if allocation failed. This helps
6353 * slow down allocation requests when mem is short
6355 set_bit(R5_DID_ALLOC, &conf->cache_state);
6356 mutex_unlock(&conf->cache_size_mutex);
6359 flush_deferred_bios(conf);
6361 r5l_flush_stripe_to_raid(conf->log);
6363 async_tx_issue_pending_all();
6364 blk_finish_plug(&plug);
6366 pr_debug("--- raid5d inactive\n");
6370 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6372 struct r5conf *conf;
6374 spin_lock(&mddev->lock);
6375 conf = mddev->private;
6377 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6378 spin_unlock(&mddev->lock);
6383 raid5_set_cache_size(struct mddev *mddev, int size)
6386 struct r5conf *conf = mddev->private;
6388 if (size <= 16 || size > 32768)
6391 conf->min_nr_stripes = size;
6392 mutex_lock(&conf->cache_size_mutex);
6393 while (size < conf->max_nr_stripes &&
6394 drop_one_stripe(conf))
6396 mutex_unlock(&conf->cache_size_mutex);
6398 md_allow_write(mddev);
6400 mutex_lock(&conf->cache_size_mutex);
6401 while (size > conf->max_nr_stripes)
6402 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6403 conf->min_nr_stripes = conf->max_nr_stripes;
6407 mutex_unlock(&conf->cache_size_mutex);
6411 EXPORT_SYMBOL(raid5_set_cache_size);
6414 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6416 struct r5conf *conf;
6420 if (len >= PAGE_SIZE)
6422 if (kstrtoul(page, 10, &new))
6424 err = mddev_lock(mddev);
6427 conf = mddev->private;
6431 err = raid5_set_cache_size(mddev, new);
6432 mddev_unlock(mddev);
6437 static struct md_sysfs_entry
6438 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6439 raid5_show_stripe_cache_size,
6440 raid5_store_stripe_cache_size);
6443 raid5_show_rmw_level(struct mddev *mddev, char *page)
6445 struct r5conf *conf = mddev->private;
6447 return sprintf(page, "%d\n", conf->rmw_level);
6453 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6455 struct r5conf *conf = mddev->private;
6461 if (len >= PAGE_SIZE)
6464 if (kstrtoul(page, 10, &new))
6467 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6470 if (new != PARITY_DISABLE_RMW &&
6471 new != PARITY_ENABLE_RMW &&
6472 new != PARITY_PREFER_RMW)
6475 conf->rmw_level = new;
6479 static struct md_sysfs_entry
6480 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6481 raid5_show_rmw_level,
6482 raid5_store_rmw_level);
6486 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6488 struct r5conf *conf;
6490 spin_lock(&mddev->lock);
6491 conf = mddev->private;
6493 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6494 spin_unlock(&mddev->lock);
6499 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6501 struct r5conf *conf;
6505 if (len >= PAGE_SIZE)
6507 if (kstrtoul(page, 10, &new))
6510 err = mddev_lock(mddev);
6513 conf = mddev->private;
6516 else if (new > conf->min_nr_stripes)
6519 conf->bypass_threshold = new;
6520 mddev_unlock(mddev);
6524 static struct md_sysfs_entry
6525 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6527 raid5_show_preread_threshold,
6528 raid5_store_preread_threshold);
6531 raid5_show_skip_copy(struct mddev *mddev, char *page)
6533 struct r5conf *conf;
6535 spin_lock(&mddev->lock);
6536 conf = mddev->private;
6538 ret = sprintf(page, "%d\n", conf->skip_copy);
6539 spin_unlock(&mddev->lock);
6544 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6546 struct r5conf *conf;
6550 if (len >= PAGE_SIZE)
6552 if (kstrtoul(page, 10, &new))
6556 err = mddev_lock(mddev);
6559 conf = mddev->private;
6562 else if (new != conf->skip_copy) {
6563 mddev_suspend(mddev);
6564 conf->skip_copy = new;
6566 mddev->queue->backing_dev_info->capabilities |=
6567 BDI_CAP_STABLE_WRITES;
6569 mddev->queue->backing_dev_info->capabilities &=
6570 ~BDI_CAP_STABLE_WRITES;
6571 mddev_resume(mddev);
6573 mddev_unlock(mddev);
6577 static struct md_sysfs_entry
6578 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6579 raid5_show_skip_copy,
6580 raid5_store_skip_copy);
6583 stripe_cache_active_show(struct mddev *mddev, char *page)
6585 struct r5conf *conf = mddev->private;
6587 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6592 static struct md_sysfs_entry
6593 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6596 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6598 struct r5conf *conf;
6600 spin_lock(&mddev->lock);
6601 conf = mddev->private;
6603 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6604 spin_unlock(&mddev->lock);
6608 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6610 int *worker_cnt_per_group,
6611 struct r5worker_group **worker_groups);
6613 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6615 struct r5conf *conf;
6618 struct r5worker_group *new_groups, *old_groups;
6619 int group_cnt, worker_cnt_per_group;
6621 if (len >= PAGE_SIZE)
6623 if (kstrtouint(page, 10, &new))
6625 /* 8192 should be big enough */
6629 err = mddev_lock(mddev);
6632 conf = mddev->private;
6635 else if (new != conf->worker_cnt_per_group) {
6636 mddev_suspend(mddev);
6638 old_groups = conf->worker_groups;
6640 flush_workqueue(raid5_wq);
6642 err = alloc_thread_groups(conf, new,
6643 &group_cnt, &worker_cnt_per_group,
6646 spin_lock_irq(&conf->device_lock);
6647 conf->group_cnt = group_cnt;
6648 conf->worker_cnt_per_group = worker_cnt_per_group;
6649 conf->worker_groups = new_groups;
6650 spin_unlock_irq(&conf->device_lock);
6653 kfree(old_groups[0].workers);
6656 mddev_resume(mddev);
6658 mddev_unlock(mddev);
6663 static struct md_sysfs_entry
6664 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6665 raid5_show_group_thread_cnt,
6666 raid5_store_group_thread_cnt);
6668 static struct attribute *raid5_attrs[] = {
6669 &raid5_stripecache_size.attr,
6670 &raid5_stripecache_active.attr,
6671 &raid5_preread_bypass_threshold.attr,
6672 &raid5_group_thread_cnt.attr,
6673 &raid5_skip_copy.attr,
6674 &raid5_rmw_level.attr,
6675 &r5c_journal_mode.attr,
6678 static struct attribute_group raid5_attrs_group = {
6680 .attrs = raid5_attrs,
6683 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6685 int *worker_cnt_per_group,
6686 struct r5worker_group **worker_groups)
6690 struct r5worker *workers;
6692 *worker_cnt_per_group = cnt;
6695 *worker_groups = NULL;
6698 *group_cnt = num_possible_nodes();
6699 size = sizeof(struct r5worker) * cnt;
6700 workers = kcalloc(size, *group_cnt, GFP_NOIO);
6701 *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6703 if (!*worker_groups || !workers) {
6705 kfree(*worker_groups);
6709 for (i = 0; i < *group_cnt; i++) {
6710 struct r5worker_group *group;
6712 group = &(*worker_groups)[i];
6713 INIT_LIST_HEAD(&group->handle_list);
6714 INIT_LIST_HEAD(&group->loprio_list);
6716 group->workers = workers + i * cnt;
6718 for (j = 0; j < cnt; j++) {
6719 struct r5worker *worker = group->workers + j;
6720 worker->group = group;
6721 INIT_WORK(&worker->work, raid5_do_work);
6723 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6724 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6731 static void free_thread_groups(struct r5conf *conf)
6733 if (conf->worker_groups)
6734 kfree(conf->worker_groups[0].workers);
6735 kfree(conf->worker_groups);
6736 conf->worker_groups = NULL;
6740 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6742 struct r5conf *conf = mddev->private;
6745 sectors = mddev->dev_sectors;
6747 /* size is defined by the smallest of previous and new size */
6748 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6750 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6751 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6752 return sectors * (raid_disks - conf->max_degraded);
6755 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6757 safe_put_page(percpu->spare_page);
6758 if (percpu->scribble)
6759 flex_array_free(percpu->scribble);
6760 percpu->spare_page = NULL;
6761 percpu->scribble = NULL;
6764 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6766 if (conf->level == 6 && !percpu->spare_page)
6767 percpu->spare_page = alloc_page(GFP_KERNEL);
6768 if (!percpu->scribble)
6769 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6770 conf->previous_raid_disks),
6771 max(conf->chunk_sectors,
6772 conf->prev_chunk_sectors)
6776 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6777 free_scratch_buffer(conf, percpu);
6784 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
6786 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6788 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6792 static void raid5_free_percpu(struct r5conf *conf)
6797 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6798 free_percpu(conf->percpu);
6801 static void free_conf(struct r5conf *conf)
6807 unregister_shrinker(&conf->shrinker);
6808 free_thread_groups(conf);
6809 shrink_stripes(conf);
6810 raid5_free_percpu(conf);
6811 for (i = 0; i < conf->pool_size; i++)
6812 if (conf->disks[i].extra_page)
6813 put_page(conf->disks[i].extra_page);
6815 bioset_exit(&conf->bio_split);
6816 kfree(conf->stripe_hashtbl);
6817 kfree(conf->pending_data);
6821 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
6823 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6824 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6826 if (alloc_scratch_buffer(conf, percpu)) {
6827 pr_warn("%s: failed memory allocation for cpu%u\n",
6834 static int raid5_alloc_percpu(struct r5conf *conf)
6838 conf->percpu = alloc_percpu(struct raid5_percpu);
6842 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6844 conf->scribble_disks = max(conf->raid_disks,
6845 conf->previous_raid_disks);
6846 conf->scribble_sectors = max(conf->chunk_sectors,
6847 conf->prev_chunk_sectors);
6852 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6853 struct shrink_control *sc)
6855 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6856 unsigned long ret = SHRINK_STOP;
6858 if (mutex_trylock(&conf->cache_size_mutex)) {
6860 while (ret < sc->nr_to_scan &&
6861 conf->max_nr_stripes > conf->min_nr_stripes) {
6862 if (drop_one_stripe(conf) == 0) {
6868 mutex_unlock(&conf->cache_size_mutex);
6873 static unsigned long raid5_cache_count(struct shrinker *shrink,
6874 struct shrink_control *sc)
6876 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6878 if (conf->max_nr_stripes < conf->min_nr_stripes)
6879 /* unlikely, but not impossible */
6881 return conf->max_nr_stripes - conf->min_nr_stripes;
6884 static struct r5conf *setup_conf(struct mddev *mddev)
6886 struct r5conf *conf;
6887 int raid_disk, memory, max_disks;
6888 struct md_rdev *rdev;
6889 struct disk_info *disk;
6892 int group_cnt, worker_cnt_per_group;
6893 struct r5worker_group *new_group;
6896 if (mddev->new_level != 5
6897 && mddev->new_level != 4
6898 && mddev->new_level != 6) {
6899 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6900 mdname(mddev), mddev->new_level);
6901 return ERR_PTR(-EIO);
6903 if ((mddev->new_level == 5
6904 && !algorithm_valid_raid5(mddev->new_layout)) ||
6905 (mddev->new_level == 6
6906 && !algorithm_valid_raid6(mddev->new_layout))) {
6907 pr_warn("md/raid:%s: layout %d not supported\n",
6908 mdname(mddev), mddev->new_layout);
6909 return ERR_PTR(-EIO);
6911 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6912 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6913 mdname(mddev), mddev->raid_disks);
6914 return ERR_PTR(-EINVAL);
6917 if (!mddev->new_chunk_sectors ||
6918 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6919 !is_power_of_2(mddev->new_chunk_sectors)) {
6920 pr_warn("md/raid:%s: invalid chunk size %d\n",
6921 mdname(mddev), mddev->new_chunk_sectors << 9);
6922 return ERR_PTR(-EINVAL);
6925 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6928 INIT_LIST_HEAD(&conf->free_list);
6929 INIT_LIST_HEAD(&conf->pending_list);
6930 conf->pending_data = kcalloc(PENDING_IO_MAX,
6931 sizeof(struct r5pending_data),
6933 if (!conf->pending_data)
6935 for (i = 0; i < PENDING_IO_MAX; i++)
6936 list_add(&conf->pending_data[i].sibling, &conf->free_list);
6937 /* Don't enable multi-threading by default*/
6938 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6940 conf->group_cnt = group_cnt;
6941 conf->worker_cnt_per_group = worker_cnt_per_group;
6942 conf->worker_groups = new_group;
6945 spin_lock_init(&conf->device_lock);
6946 seqcount_init(&conf->gen_lock);
6947 mutex_init(&conf->cache_size_mutex);
6948 init_waitqueue_head(&conf->wait_for_quiescent);
6949 init_waitqueue_head(&conf->wait_for_stripe);
6950 init_waitqueue_head(&conf->wait_for_overlap);
6951 INIT_LIST_HEAD(&conf->handle_list);
6952 INIT_LIST_HEAD(&conf->loprio_list);
6953 INIT_LIST_HEAD(&conf->hold_list);
6954 INIT_LIST_HEAD(&conf->delayed_list);
6955 INIT_LIST_HEAD(&conf->bitmap_list);
6956 init_llist_head(&conf->released_stripes);
6957 atomic_set(&conf->active_stripes, 0);
6958 atomic_set(&conf->preread_active_stripes, 0);
6959 atomic_set(&conf->active_aligned_reads, 0);
6960 spin_lock_init(&conf->pending_bios_lock);
6961 conf->batch_bio_dispatch = true;
6962 rdev_for_each(rdev, mddev) {
6963 if (test_bit(Journal, &rdev->flags))
6965 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
6966 conf->batch_bio_dispatch = false;
6971 conf->bypass_threshold = BYPASS_THRESHOLD;
6972 conf->recovery_disabled = mddev->recovery_disabled - 1;
6974 conf->raid_disks = mddev->raid_disks;
6975 if (mddev->reshape_position == MaxSector)
6976 conf->previous_raid_disks = mddev->raid_disks;
6978 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6979 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6981 conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
6987 for (i = 0; i < max_disks; i++) {
6988 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
6989 if (!conf->disks[i].extra_page)
6993 ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
6996 conf->mddev = mddev;
6998 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7001 /* We init hash_locks[0] separately to that it can be used
7002 * as the reference lock in the spin_lock_nest_lock() call
7003 * in lock_all_device_hash_locks_irq in order to convince
7004 * lockdep that we know what we are doing.
7006 spin_lock_init(conf->hash_locks);
7007 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7008 spin_lock_init(conf->hash_locks + i);
7010 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7011 INIT_LIST_HEAD(conf->inactive_list + i);
7013 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7014 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7016 atomic_set(&conf->r5c_cached_full_stripes, 0);
7017 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7018 atomic_set(&conf->r5c_cached_partial_stripes, 0);
7019 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7020 atomic_set(&conf->r5c_flushing_full_stripes, 0);
7021 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7023 conf->level = mddev->new_level;
7024 conf->chunk_sectors = mddev->new_chunk_sectors;
7025 if (raid5_alloc_percpu(conf) != 0)
7028 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7030 rdev_for_each(rdev, mddev) {
7031 raid_disk = rdev->raid_disk;
7032 if (raid_disk >= max_disks
7033 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7035 disk = conf->disks + raid_disk;
7037 if (test_bit(Replacement, &rdev->flags)) {
7038 if (disk->replacement)
7040 disk->replacement = rdev;
7047 if (test_bit(In_sync, &rdev->flags)) {
7048 char b[BDEVNAME_SIZE];
7049 pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7050 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7051 } else if (rdev->saved_raid_disk != raid_disk)
7052 /* Cannot rely on bitmap to complete recovery */
7056 conf->level = mddev->new_level;
7057 if (conf->level == 6) {
7058 conf->max_degraded = 2;
7059 if (raid6_call.xor_syndrome)
7060 conf->rmw_level = PARITY_ENABLE_RMW;
7062 conf->rmw_level = PARITY_DISABLE_RMW;
7064 conf->max_degraded = 1;
7065 conf->rmw_level = PARITY_ENABLE_RMW;
7067 conf->algorithm = mddev->new_layout;
7068 conf->reshape_progress = mddev->reshape_position;
7069 if (conf->reshape_progress != MaxSector) {
7070 conf->prev_chunk_sectors = mddev->chunk_sectors;
7071 conf->prev_algo = mddev->layout;
7073 conf->prev_chunk_sectors = conf->chunk_sectors;
7074 conf->prev_algo = conf->algorithm;
7077 conf->min_nr_stripes = NR_STRIPES;
7078 if (mddev->reshape_position != MaxSector) {
7079 int stripes = max_t(int,
7080 ((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4,
7081 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4);
7082 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7083 if (conf->min_nr_stripes != NR_STRIPES)
7084 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7085 mdname(mddev), conf->min_nr_stripes);
7087 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7088 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7089 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7090 if (grow_stripes(conf, conf->min_nr_stripes)) {
7091 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7092 mdname(mddev), memory);
7095 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7097 * Losing a stripe head costs more than the time to refill it,
7098 * it reduces the queue depth and so can hurt throughput.
7099 * So set it rather large, scaled by number of devices.
7101 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7102 conf->shrinker.scan_objects = raid5_cache_scan;
7103 conf->shrinker.count_objects = raid5_cache_count;
7104 conf->shrinker.batch = 128;
7105 conf->shrinker.flags = 0;
7106 if (register_shrinker(&conf->shrinker)) {
7107 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7112 sprintf(pers_name, "raid%d", mddev->new_level);
7113 conf->thread = md_register_thread(raid5d, mddev, pers_name);
7114 if (!conf->thread) {
7115 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7125 return ERR_PTR(-EIO);
7127 return ERR_PTR(-ENOMEM);
7130 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7133 case ALGORITHM_PARITY_0:
7134 if (raid_disk < max_degraded)
7137 case ALGORITHM_PARITY_N:
7138 if (raid_disk >= raid_disks - max_degraded)
7141 case ALGORITHM_PARITY_0_6:
7142 if (raid_disk == 0 ||
7143 raid_disk == raid_disks - 1)
7146 case ALGORITHM_LEFT_ASYMMETRIC_6:
7147 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7148 case ALGORITHM_LEFT_SYMMETRIC_6:
7149 case ALGORITHM_RIGHT_SYMMETRIC_6:
7150 if (raid_disk == raid_disks - 1)
7156 static void raid5_set_io_opt(struct r5conf *conf)
7158 blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7159 (conf->raid_disks - conf->max_degraded));
7162 static int raid5_run(struct mddev *mddev)
7164 struct r5conf *conf;
7165 int working_disks = 0;
7166 int dirty_parity_disks = 0;
7167 struct md_rdev *rdev;
7168 struct md_rdev *journal_dev = NULL;
7169 sector_t reshape_offset = 0;
7171 long long min_offset_diff = 0;
7174 if (mddev_init_writes_pending(mddev) < 0)
7177 if (mddev->recovery_cp != MaxSector)
7178 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7181 rdev_for_each(rdev, mddev) {
7184 if (test_bit(Journal, &rdev->flags)) {
7188 if (rdev->raid_disk < 0)
7190 diff = (rdev->new_data_offset - rdev->data_offset);
7192 min_offset_diff = diff;
7194 } else if (mddev->reshape_backwards &&
7195 diff < min_offset_diff)
7196 min_offset_diff = diff;
7197 else if (!mddev->reshape_backwards &&
7198 diff > min_offset_diff)
7199 min_offset_diff = diff;
7202 if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7203 (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7204 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7209 if (mddev->reshape_position != MaxSector) {
7210 /* Check that we can continue the reshape.
7211 * Difficulties arise if the stripe we would write to
7212 * next is at or after the stripe we would read from next.
7213 * For a reshape that changes the number of devices, this
7214 * is only possible for a very short time, and mdadm makes
7215 * sure that time appears to have past before assembling
7216 * the array. So we fail if that time hasn't passed.
7217 * For a reshape that keeps the number of devices the same
7218 * mdadm must be monitoring the reshape can keeping the
7219 * critical areas read-only and backed up. It will start
7220 * the array in read-only mode, so we check for that.
7222 sector_t here_new, here_old;
7224 int max_degraded = (mddev->level == 6 ? 2 : 1);
7229 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7234 if (mddev->new_level != mddev->level) {
7235 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7239 old_disks = mddev->raid_disks - mddev->delta_disks;
7240 /* reshape_position must be on a new-stripe boundary, and one
7241 * further up in new geometry must map after here in old
7243 * If the chunk sizes are different, then as we perform reshape
7244 * in units of the largest of the two, reshape_position needs
7245 * be a multiple of the largest chunk size times new data disks.
7247 here_new = mddev->reshape_position;
7248 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7249 new_data_disks = mddev->raid_disks - max_degraded;
7250 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7251 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7255 reshape_offset = here_new * chunk_sectors;
7256 /* here_new is the stripe we will write to */
7257 here_old = mddev->reshape_position;
7258 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7259 /* here_old is the first stripe that we might need to read
7261 if (mddev->delta_disks == 0) {
7262 /* We cannot be sure it is safe to start an in-place
7263 * reshape. It is only safe if user-space is monitoring
7264 * and taking constant backups.
7265 * mdadm always starts a situation like this in
7266 * readonly mode so it can take control before
7267 * allowing any writes. So just check for that.
7269 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7270 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7271 /* not really in-place - so OK */;
7272 else if (mddev->ro == 0) {
7273 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7277 } else if (mddev->reshape_backwards
7278 ? (here_new * chunk_sectors + min_offset_diff <=
7279 here_old * chunk_sectors)
7280 : (here_new * chunk_sectors >=
7281 here_old * chunk_sectors + (-min_offset_diff))) {
7282 /* Reading from the same stripe as writing to - bad */
7283 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7287 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7288 /* OK, we should be able to continue; */
7290 BUG_ON(mddev->level != mddev->new_level);
7291 BUG_ON(mddev->layout != mddev->new_layout);
7292 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7293 BUG_ON(mddev->delta_disks != 0);
7296 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7297 test_bit(MD_HAS_PPL, &mddev->flags)) {
7298 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7300 clear_bit(MD_HAS_PPL, &mddev->flags);
7301 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7304 if (mddev->private == NULL)
7305 conf = setup_conf(mddev);
7307 conf = mddev->private;
7310 return PTR_ERR(conf);
7312 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7314 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7317 set_disk_ro(mddev->gendisk, 1);
7318 } else if (mddev->recovery_cp == MaxSector)
7319 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7322 conf->min_offset_diff = min_offset_diff;
7323 mddev->thread = conf->thread;
7324 conf->thread = NULL;
7325 mddev->private = conf;
7327 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7329 rdev = conf->disks[i].rdev;
7330 if (!rdev && conf->disks[i].replacement) {
7331 /* The replacement is all we have yet */
7332 rdev = conf->disks[i].replacement;
7333 conf->disks[i].replacement = NULL;
7334 clear_bit(Replacement, &rdev->flags);
7335 conf->disks[i].rdev = rdev;
7339 if (conf->disks[i].replacement &&
7340 conf->reshape_progress != MaxSector) {
7341 /* replacements and reshape simply do not mix. */
7342 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7345 if (test_bit(In_sync, &rdev->flags)) {
7349 /* This disc is not fully in-sync. However if it
7350 * just stored parity (beyond the recovery_offset),
7351 * when we don't need to be concerned about the
7352 * array being dirty.
7353 * When reshape goes 'backwards', we never have
7354 * partially completed devices, so we only need
7355 * to worry about reshape going forwards.
7357 /* Hack because v0.91 doesn't store recovery_offset properly. */
7358 if (mddev->major_version == 0 &&
7359 mddev->minor_version > 90)
7360 rdev->recovery_offset = reshape_offset;
7362 if (rdev->recovery_offset < reshape_offset) {
7363 /* We need to check old and new layout */
7364 if (!only_parity(rdev->raid_disk,
7367 conf->max_degraded))
7370 if (!only_parity(rdev->raid_disk,
7372 conf->previous_raid_disks,
7373 conf->max_degraded))
7375 dirty_parity_disks++;
7379 * 0 for a fully functional array, 1 or 2 for a degraded array.
7381 mddev->degraded = raid5_calc_degraded(conf);
7383 if (has_failed(conf)) {
7384 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7385 mdname(mddev), mddev->degraded, conf->raid_disks);
7389 /* device size must be a multiple of chunk size */
7390 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7391 mddev->resync_max_sectors = mddev->dev_sectors;
7393 if (mddev->degraded > dirty_parity_disks &&
7394 mddev->recovery_cp != MaxSector) {
7395 if (test_bit(MD_HAS_PPL, &mddev->flags))
7396 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7398 else if (mddev->ok_start_degraded)
7399 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7402 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7408 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7409 mdname(mddev), conf->level,
7410 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7413 print_raid5_conf(conf);
7415 if (conf->reshape_progress != MaxSector) {
7416 conf->reshape_safe = conf->reshape_progress;
7417 atomic_set(&conf->reshape_stripes, 0);
7418 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7419 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7420 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7421 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7422 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7424 if (!mddev->sync_thread)
7428 /* Ok, everything is just fine now */
7429 if (mddev->to_remove == &raid5_attrs_group)
7430 mddev->to_remove = NULL;
7431 else if (mddev->kobj.sd &&
7432 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7433 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7435 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7439 /* read-ahead size must cover two whole stripes, which
7440 * is 2 * (datadisks) * chunksize where 'n' is the
7441 * number of raid devices
7443 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7444 int stripe = data_disks *
7445 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7446 if (mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
7447 mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
7449 chunk_size = mddev->chunk_sectors << 9;
7450 blk_queue_io_min(mddev->queue, chunk_size);
7451 raid5_set_io_opt(conf);
7452 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7454 * We can only discard a whole stripe. It doesn't make sense to
7455 * discard data disk but write parity disk
7457 stripe = stripe * PAGE_SIZE;
7458 /* Round up to power of 2, as discard handling
7459 * currently assumes that */
7460 while ((stripe-1) & stripe)
7461 stripe = (stripe | (stripe-1)) + 1;
7462 mddev->queue->limits.discard_alignment = stripe;
7463 mddev->queue->limits.discard_granularity = stripe;
7465 blk_queue_max_write_same_sectors(mddev->queue, 0);
7466 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7468 rdev_for_each(rdev, mddev) {
7469 disk_stack_limits(mddev->gendisk, rdev->bdev,
7470 rdev->data_offset << 9);
7471 disk_stack_limits(mddev->gendisk, rdev->bdev,
7472 rdev->new_data_offset << 9);
7476 * zeroing is required, otherwise data
7477 * could be lost. Consider a scenario: discard a stripe
7478 * (the stripe could be inconsistent if
7479 * discard_zeroes_data is 0); write one disk of the
7480 * stripe (the stripe could be inconsistent again
7481 * depending on which disks are used to calculate
7482 * parity); the disk is broken; The stripe data of this
7485 * We only allow DISCARD if the sysadmin has confirmed that
7486 * only safe devices are in use by setting a module parameter.
7487 * A better idea might be to turn DISCARD into WRITE_ZEROES
7488 * requests, as that is required to be safe.
7490 if (devices_handle_discard_safely &&
7491 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7492 mddev->queue->limits.discard_granularity >= stripe)
7493 blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7496 blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7499 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7502 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7507 md_unregister_thread(&mddev->thread);
7508 print_raid5_conf(conf);
7510 mddev->private = NULL;
7511 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7515 static void raid5_free(struct mddev *mddev, void *priv)
7517 struct r5conf *conf = priv;
7520 mddev->to_remove = &raid5_attrs_group;
7523 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7525 struct r5conf *conf = mddev->private;
7528 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7529 conf->chunk_sectors / 2, mddev->layout);
7530 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7532 for (i = 0; i < conf->raid_disks; i++) {
7533 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7534 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7537 seq_printf (seq, "]");
7540 static void print_raid5_conf (struct r5conf *conf)
7543 struct disk_info *tmp;
7545 pr_debug("RAID conf printout:\n");
7547 pr_debug("(conf==NULL)\n");
7550 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7552 conf->raid_disks - conf->mddev->degraded);
7554 for (i = 0; i < conf->raid_disks; i++) {
7555 char b[BDEVNAME_SIZE];
7556 tmp = conf->disks + i;
7558 pr_debug(" disk %d, o:%d, dev:%s\n",
7559 i, !test_bit(Faulty, &tmp->rdev->flags),
7560 bdevname(tmp->rdev->bdev, b));
7564 static int raid5_spare_active(struct mddev *mddev)
7567 struct r5conf *conf = mddev->private;
7568 struct disk_info *tmp;
7570 unsigned long flags;
7572 for (i = 0; i < conf->raid_disks; i++) {
7573 tmp = conf->disks + i;
7574 if (tmp->replacement
7575 && tmp->replacement->recovery_offset == MaxSector
7576 && !test_bit(Faulty, &tmp->replacement->flags)
7577 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7578 /* Replacement has just become active. */
7580 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7583 /* Replaced device not technically faulty,
7584 * but we need to be sure it gets removed
7585 * and never re-added.
7587 set_bit(Faulty, &tmp->rdev->flags);
7588 sysfs_notify_dirent_safe(
7589 tmp->rdev->sysfs_state);
7591 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7592 } else if (tmp->rdev
7593 && tmp->rdev->recovery_offset == MaxSector
7594 && !test_bit(Faulty, &tmp->rdev->flags)
7595 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7597 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7600 spin_lock_irqsave(&conf->device_lock, flags);
7601 mddev->degraded = raid5_calc_degraded(conf);
7602 spin_unlock_irqrestore(&conf->device_lock, flags);
7603 print_raid5_conf(conf);
7607 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7609 struct r5conf *conf = mddev->private;
7611 int number = rdev->raid_disk;
7612 struct md_rdev **rdevp;
7613 struct disk_info *p = conf->disks + number;
7615 print_raid5_conf(conf);
7616 if (test_bit(Journal, &rdev->flags) && conf->log) {
7618 * we can't wait pending write here, as this is called in
7619 * raid5d, wait will deadlock.
7620 * neilb: there is no locking about new writes here,
7621 * so this cannot be safe.
7623 if (atomic_read(&conf->active_stripes) ||
7624 atomic_read(&conf->r5c_cached_full_stripes) ||
7625 atomic_read(&conf->r5c_cached_partial_stripes)) {
7631 if (rdev == p->rdev)
7633 else if (rdev == p->replacement)
7634 rdevp = &p->replacement;
7638 if (number >= conf->raid_disks &&
7639 conf->reshape_progress == MaxSector)
7640 clear_bit(In_sync, &rdev->flags);
7642 if (test_bit(In_sync, &rdev->flags) ||
7643 atomic_read(&rdev->nr_pending)) {
7647 /* Only remove non-faulty devices if recovery
7650 if (!test_bit(Faulty, &rdev->flags) &&
7651 mddev->recovery_disabled != conf->recovery_disabled &&
7652 !has_failed(conf) &&
7653 (!p->replacement || p->replacement == rdev) &&
7654 number < conf->raid_disks) {
7659 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7661 if (atomic_read(&rdev->nr_pending)) {
7662 /* lost the race, try later */
7668 err = log_modify(conf, rdev, false);
7672 if (p->replacement) {
7673 /* We must have just cleared 'rdev' */
7674 p->rdev = p->replacement;
7675 clear_bit(Replacement, &p->replacement->flags);
7676 smp_mb(); /* Make sure other CPUs may see both as identical
7677 * but will never see neither - if they are careful
7679 p->replacement = NULL;
7682 err = log_modify(conf, p->rdev, true);
7685 clear_bit(WantReplacement, &rdev->flags);
7688 print_raid5_conf(conf);
7692 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7694 struct r5conf *conf = mddev->private;
7695 int ret, err = -EEXIST;
7697 struct disk_info *p;
7699 int last = conf->raid_disks - 1;
7701 if (test_bit(Journal, &rdev->flags)) {
7705 rdev->raid_disk = 0;
7707 * The array is in readonly mode if journal is missing, so no
7708 * write requests running. We should be safe
7710 ret = log_init(conf, rdev, false);
7714 ret = r5l_start(conf->log);
7720 if (mddev->recovery_disabled == conf->recovery_disabled)
7723 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7724 /* no point adding a device */
7727 if (rdev->raid_disk >= 0)
7728 first = last = rdev->raid_disk;
7731 * find the disk ... but prefer rdev->saved_raid_disk
7734 if (rdev->saved_raid_disk >= 0 &&
7735 rdev->saved_raid_disk >= first &&
7736 rdev->saved_raid_disk <= last &&
7737 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7738 first = rdev->saved_raid_disk;
7740 for (disk = first; disk <= last; disk++) {
7741 p = conf->disks + disk;
7742 if (p->rdev == NULL) {
7743 clear_bit(In_sync, &rdev->flags);
7744 rdev->raid_disk = disk;
7745 if (rdev->saved_raid_disk != disk)
7747 rcu_assign_pointer(p->rdev, rdev);
7749 err = log_modify(conf, rdev, true);
7754 for (disk = first; disk <= last; disk++) {
7755 p = conf->disks + disk;
7756 if (test_bit(WantReplacement, &p->rdev->flags) &&
7757 p->replacement == NULL) {
7758 clear_bit(In_sync, &rdev->flags);
7759 set_bit(Replacement, &rdev->flags);
7760 rdev->raid_disk = disk;
7763 rcu_assign_pointer(p->replacement, rdev);
7768 print_raid5_conf(conf);
7772 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7774 /* no resync is happening, and there is enough space
7775 * on all devices, so we can resize.
7776 * We need to make sure resync covers any new space.
7777 * If the array is shrinking we should possibly wait until
7778 * any io in the removed space completes, but it hardly seems
7782 struct r5conf *conf = mddev->private;
7784 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7786 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7787 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7788 if (mddev->external_size &&
7789 mddev->array_sectors > newsize)
7791 if (mddev->bitmap) {
7792 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
7796 md_set_array_sectors(mddev, newsize);
7797 if (sectors > mddev->dev_sectors &&
7798 mddev->recovery_cp > mddev->dev_sectors) {
7799 mddev->recovery_cp = mddev->dev_sectors;
7800 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7802 mddev->dev_sectors = sectors;
7803 mddev->resync_max_sectors = sectors;
7807 static int check_stripe_cache(struct mddev *mddev)
7809 /* Can only proceed if there are plenty of stripe_heads.
7810 * We need a minimum of one full stripe,, and for sensible progress
7811 * it is best to have about 4 times that.
7812 * If we require 4 times, then the default 256 4K stripe_heads will
7813 * allow for chunk sizes up to 256K, which is probably OK.
7814 * If the chunk size is greater, user-space should request more
7815 * stripe_heads first.
7817 struct r5conf *conf = mddev->private;
7818 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7819 > conf->min_nr_stripes ||
7820 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7821 > conf->min_nr_stripes) {
7822 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7824 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7831 static int check_reshape(struct mddev *mddev)
7833 struct r5conf *conf = mddev->private;
7835 if (raid5_has_log(conf) || raid5_has_ppl(conf))
7837 if (mddev->delta_disks == 0 &&
7838 mddev->new_layout == mddev->layout &&
7839 mddev->new_chunk_sectors == mddev->chunk_sectors)
7840 return 0; /* nothing to do */
7841 if (has_failed(conf))
7843 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7844 /* We might be able to shrink, but the devices must
7845 * be made bigger first.
7846 * For raid6, 4 is the minimum size.
7847 * Otherwise 2 is the minimum
7850 if (mddev->level == 6)
7852 if (mddev->raid_disks + mddev->delta_disks < min)
7856 if (!check_stripe_cache(mddev))
7859 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7860 mddev->delta_disks > 0)
7861 if (resize_chunks(conf,
7862 conf->previous_raid_disks
7863 + max(0, mddev->delta_disks),
7864 max(mddev->new_chunk_sectors,
7865 mddev->chunk_sectors)
7869 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
7870 return 0; /* never bother to shrink */
7871 return resize_stripes(conf, (conf->previous_raid_disks
7872 + mddev->delta_disks));
7875 static int raid5_start_reshape(struct mddev *mddev)
7877 struct r5conf *conf = mddev->private;
7878 struct md_rdev *rdev;
7880 unsigned long flags;
7882 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7885 if (!check_stripe_cache(mddev))
7888 if (has_failed(conf))
7891 rdev_for_each(rdev, mddev) {
7892 if (!test_bit(In_sync, &rdev->flags)
7893 && !test_bit(Faulty, &rdev->flags))
7897 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7898 /* Not enough devices even to make a degraded array
7903 /* Refuse to reduce size of the array. Any reductions in
7904 * array size must be through explicit setting of array_size
7907 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7908 < mddev->array_sectors) {
7909 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
7914 atomic_set(&conf->reshape_stripes, 0);
7915 spin_lock_irq(&conf->device_lock);
7916 write_seqcount_begin(&conf->gen_lock);
7917 conf->previous_raid_disks = conf->raid_disks;
7918 conf->raid_disks += mddev->delta_disks;
7919 conf->prev_chunk_sectors = conf->chunk_sectors;
7920 conf->chunk_sectors = mddev->new_chunk_sectors;
7921 conf->prev_algo = conf->algorithm;
7922 conf->algorithm = mddev->new_layout;
7924 /* Code that selects data_offset needs to see the generation update
7925 * if reshape_progress has been set - so a memory barrier needed.
7928 if (mddev->reshape_backwards)
7929 conf->reshape_progress = raid5_size(mddev, 0, 0);
7931 conf->reshape_progress = 0;
7932 conf->reshape_safe = conf->reshape_progress;
7933 write_seqcount_end(&conf->gen_lock);
7934 spin_unlock_irq(&conf->device_lock);
7936 /* Now make sure any requests that proceeded on the assumption
7937 * the reshape wasn't running - like Discard or Read - have
7940 mddev_suspend(mddev);
7941 mddev_resume(mddev);
7943 /* Add some new drives, as many as will fit.
7944 * We know there are enough to make the newly sized array work.
7945 * Don't add devices if we are reducing the number of
7946 * devices in the array. This is because it is not possible
7947 * to correctly record the "partially reconstructed" state of
7948 * such devices during the reshape and confusion could result.
7950 if (mddev->delta_disks >= 0) {
7951 rdev_for_each(rdev, mddev)
7952 if (rdev->raid_disk < 0 &&
7953 !test_bit(Faulty, &rdev->flags)) {
7954 if (raid5_add_disk(mddev, rdev) == 0) {
7956 >= conf->previous_raid_disks)
7957 set_bit(In_sync, &rdev->flags);
7959 rdev->recovery_offset = 0;
7961 if (sysfs_link_rdev(mddev, rdev))
7962 /* Failure here is OK */;
7964 } else if (rdev->raid_disk >= conf->previous_raid_disks
7965 && !test_bit(Faulty, &rdev->flags)) {
7966 /* This is a spare that was manually added */
7967 set_bit(In_sync, &rdev->flags);
7970 /* When a reshape changes the number of devices,
7971 * ->degraded is measured against the larger of the
7972 * pre and post number of devices.
7974 spin_lock_irqsave(&conf->device_lock, flags);
7975 mddev->degraded = raid5_calc_degraded(conf);
7976 spin_unlock_irqrestore(&conf->device_lock, flags);
7978 mddev->raid_disks = conf->raid_disks;
7979 mddev->reshape_position = conf->reshape_progress;
7980 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
7982 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7983 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7984 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7985 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7986 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7987 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7989 if (!mddev->sync_thread) {
7990 mddev->recovery = 0;
7991 spin_lock_irq(&conf->device_lock);
7992 write_seqcount_begin(&conf->gen_lock);
7993 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7994 mddev->new_chunk_sectors =
7995 conf->chunk_sectors = conf->prev_chunk_sectors;
7996 mddev->new_layout = conf->algorithm = conf->prev_algo;
7997 rdev_for_each(rdev, mddev)
7998 rdev->new_data_offset = rdev->data_offset;
8000 conf->generation --;
8001 conf->reshape_progress = MaxSector;
8002 mddev->reshape_position = MaxSector;
8003 write_seqcount_end(&conf->gen_lock);
8004 spin_unlock_irq(&conf->device_lock);
8007 conf->reshape_checkpoint = jiffies;
8008 md_wakeup_thread(mddev->sync_thread);
8009 md_new_event(mddev);
8013 /* This is called from the reshape thread and should make any
8014 * changes needed in 'conf'
8016 static void end_reshape(struct r5conf *conf)
8019 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8020 struct md_rdev *rdev;
8022 spin_lock_irq(&conf->device_lock);
8023 conf->previous_raid_disks = conf->raid_disks;
8024 md_finish_reshape(conf->mddev);
8026 conf->reshape_progress = MaxSector;
8027 conf->mddev->reshape_position = MaxSector;
8028 rdev_for_each(rdev, conf->mddev)
8029 if (rdev->raid_disk >= 0 &&
8030 !test_bit(Journal, &rdev->flags) &&
8031 !test_bit(In_sync, &rdev->flags))
8032 rdev->recovery_offset = MaxSector;
8033 spin_unlock_irq(&conf->device_lock);
8034 wake_up(&conf->wait_for_overlap);
8036 /* read-ahead size must cover two whole stripes, which is
8037 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
8039 if (conf->mddev->queue) {
8040 int data_disks = conf->raid_disks - conf->max_degraded;
8041 int stripe = data_disks * ((conf->chunk_sectors << 9)
8043 if (conf->mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
8044 conf->mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
8045 raid5_set_io_opt(conf);
8050 /* This is called from the raid5d thread with mddev_lock held.
8051 * It makes config changes to the device.
8053 static void raid5_finish_reshape(struct mddev *mddev)
8055 struct r5conf *conf = mddev->private;
8057 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8059 if (mddev->delta_disks <= 0) {
8061 spin_lock_irq(&conf->device_lock);
8062 mddev->degraded = raid5_calc_degraded(conf);
8063 spin_unlock_irq(&conf->device_lock);
8064 for (d = conf->raid_disks ;
8065 d < conf->raid_disks - mddev->delta_disks;
8067 struct md_rdev *rdev = conf->disks[d].rdev;
8069 clear_bit(In_sync, &rdev->flags);
8070 rdev = conf->disks[d].replacement;
8072 clear_bit(In_sync, &rdev->flags);
8075 mddev->layout = conf->algorithm;
8076 mddev->chunk_sectors = conf->chunk_sectors;
8077 mddev->reshape_position = MaxSector;
8078 mddev->delta_disks = 0;
8079 mddev->reshape_backwards = 0;
8083 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8085 struct r5conf *conf = mddev->private;
8088 /* stop all writes */
8089 lock_all_device_hash_locks_irq(conf);
8090 /* '2' tells resync/reshape to pause so that all
8091 * active stripes can drain
8093 r5c_flush_cache(conf, INT_MAX);
8095 wait_event_cmd(conf->wait_for_quiescent,
8096 atomic_read(&conf->active_stripes) == 0 &&
8097 atomic_read(&conf->active_aligned_reads) == 0,
8098 unlock_all_device_hash_locks_irq(conf),
8099 lock_all_device_hash_locks_irq(conf));
8101 unlock_all_device_hash_locks_irq(conf);
8102 /* allow reshape to continue */
8103 wake_up(&conf->wait_for_overlap);
8105 /* re-enable writes */
8106 lock_all_device_hash_locks_irq(conf);
8108 wake_up(&conf->wait_for_quiescent);
8109 wake_up(&conf->wait_for_overlap);
8110 unlock_all_device_hash_locks_irq(conf);
8112 log_quiesce(conf, quiesce);
8115 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8117 struct r0conf *raid0_conf = mddev->private;
8120 /* for raid0 takeover only one zone is supported */
8121 if (raid0_conf->nr_strip_zones > 1) {
8122 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8124 return ERR_PTR(-EINVAL);
8127 sectors = raid0_conf->strip_zone[0].zone_end;
8128 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8129 mddev->dev_sectors = sectors;
8130 mddev->new_level = level;
8131 mddev->new_layout = ALGORITHM_PARITY_N;
8132 mddev->new_chunk_sectors = mddev->chunk_sectors;
8133 mddev->raid_disks += 1;
8134 mddev->delta_disks = 1;
8135 /* make sure it will be not marked as dirty */
8136 mddev->recovery_cp = MaxSector;
8138 return setup_conf(mddev);
8141 static void *raid5_takeover_raid1(struct mddev *mddev)
8146 if (mddev->raid_disks != 2 ||
8147 mddev->degraded > 1)
8148 return ERR_PTR(-EINVAL);
8150 /* Should check if there are write-behind devices? */
8152 chunksect = 64*2; /* 64K by default */
8154 /* The array must be an exact multiple of chunksize */
8155 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8158 if ((chunksect<<9) < STRIPE_SIZE)
8159 /* array size does not allow a suitable chunk size */
8160 return ERR_PTR(-EINVAL);
8162 mddev->new_level = 5;
8163 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8164 mddev->new_chunk_sectors = chunksect;
8166 ret = setup_conf(mddev);
8168 mddev_clear_unsupported_flags(mddev,
8169 UNSUPPORTED_MDDEV_FLAGS);
8173 static void *raid5_takeover_raid6(struct mddev *mddev)
8177 switch (mddev->layout) {
8178 case ALGORITHM_LEFT_ASYMMETRIC_6:
8179 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8181 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8182 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8184 case ALGORITHM_LEFT_SYMMETRIC_6:
8185 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8187 case ALGORITHM_RIGHT_SYMMETRIC_6:
8188 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8190 case ALGORITHM_PARITY_0_6:
8191 new_layout = ALGORITHM_PARITY_0;
8193 case ALGORITHM_PARITY_N:
8194 new_layout = ALGORITHM_PARITY_N;
8197 return ERR_PTR(-EINVAL);
8199 mddev->new_level = 5;
8200 mddev->new_layout = new_layout;
8201 mddev->delta_disks = -1;
8202 mddev->raid_disks -= 1;
8203 return setup_conf(mddev);
8206 static int raid5_check_reshape(struct mddev *mddev)
8208 /* For a 2-drive array, the layout and chunk size can be changed
8209 * immediately as not restriping is needed.
8210 * For larger arrays we record the new value - after validation
8211 * to be used by a reshape pass.
8213 struct r5conf *conf = mddev->private;
8214 int new_chunk = mddev->new_chunk_sectors;
8216 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8218 if (new_chunk > 0) {
8219 if (!is_power_of_2(new_chunk))
8221 if (new_chunk < (PAGE_SIZE>>9))
8223 if (mddev->array_sectors & (new_chunk-1))
8224 /* not factor of array size */
8228 /* They look valid */
8230 if (mddev->raid_disks == 2) {
8231 /* can make the change immediately */
8232 if (mddev->new_layout >= 0) {
8233 conf->algorithm = mddev->new_layout;
8234 mddev->layout = mddev->new_layout;
8236 if (new_chunk > 0) {
8237 conf->chunk_sectors = new_chunk ;
8238 mddev->chunk_sectors = new_chunk;
8240 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8241 md_wakeup_thread(mddev->thread);
8243 return check_reshape(mddev);
8246 static int raid6_check_reshape(struct mddev *mddev)
8248 int new_chunk = mddev->new_chunk_sectors;
8250 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8252 if (new_chunk > 0) {
8253 if (!is_power_of_2(new_chunk))
8255 if (new_chunk < (PAGE_SIZE >> 9))
8257 if (mddev->array_sectors & (new_chunk-1))
8258 /* not factor of array size */
8262 /* They look valid */
8263 return check_reshape(mddev);
8266 static void *raid5_takeover(struct mddev *mddev)
8268 /* raid5 can take over:
8269 * raid0 - if there is only one strip zone - make it a raid4 layout
8270 * raid1 - if there are two drives. We need to know the chunk size
8271 * raid4 - trivial - just use a raid4 layout.
8272 * raid6 - Providing it is a *_6 layout
8274 if (mddev->level == 0)
8275 return raid45_takeover_raid0(mddev, 5);
8276 if (mddev->level == 1)
8277 return raid5_takeover_raid1(mddev);
8278 if (mddev->level == 4) {
8279 mddev->new_layout = ALGORITHM_PARITY_N;
8280 mddev->new_level = 5;
8281 return setup_conf(mddev);
8283 if (mddev->level == 6)
8284 return raid5_takeover_raid6(mddev);
8286 return ERR_PTR(-EINVAL);
8289 static void *raid4_takeover(struct mddev *mddev)
8291 /* raid4 can take over:
8292 * raid0 - if there is only one strip zone
8293 * raid5 - if layout is right
8295 if (mddev->level == 0)
8296 return raid45_takeover_raid0(mddev, 4);
8297 if (mddev->level == 5 &&
8298 mddev->layout == ALGORITHM_PARITY_N) {
8299 mddev->new_layout = 0;
8300 mddev->new_level = 4;
8301 return setup_conf(mddev);
8303 return ERR_PTR(-EINVAL);
8306 static struct md_personality raid5_personality;
8308 static void *raid6_takeover(struct mddev *mddev)
8310 /* Currently can only take over a raid5. We map the
8311 * personality to an equivalent raid6 personality
8312 * with the Q block at the end.
8316 if (mddev->pers != &raid5_personality)
8317 return ERR_PTR(-EINVAL);
8318 if (mddev->degraded > 1)
8319 return ERR_PTR(-EINVAL);
8320 if (mddev->raid_disks > 253)
8321 return ERR_PTR(-EINVAL);
8322 if (mddev->raid_disks < 3)
8323 return ERR_PTR(-EINVAL);
8325 switch (mddev->layout) {
8326 case ALGORITHM_LEFT_ASYMMETRIC:
8327 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8329 case ALGORITHM_RIGHT_ASYMMETRIC:
8330 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8332 case ALGORITHM_LEFT_SYMMETRIC:
8333 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8335 case ALGORITHM_RIGHT_SYMMETRIC:
8336 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8338 case ALGORITHM_PARITY_0:
8339 new_layout = ALGORITHM_PARITY_0_6;
8341 case ALGORITHM_PARITY_N:
8342 new_layout = ALGORITHM_PARITY_N;
8345 return ERR_PTR(-EINVAL);
8347 mddev->new_level = 6;
8348 mddev->new_layout = new_layout;
8349 mddev->delta_disks = 1;
8350 mddev->raid_disks += 1;
8351 return setup_conf(mddev);
8354 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8356 struct r5conf *conf;
8359 err = mddev_lock(mddev);
8362 conf = mddev->private;
8364 mddev_unlock(mddev);
8368 if (strncmp(buf, "ppl", 3) == 0) {
8369 /* ppl only works with RAID 5 */
8370 if (!raid5_has_ppl(conf) && conf->level == 5) {
8371 err = log_init(conf, NULL, true);
8373 err = resize_stripes(conf, conf->pool_size);
8379 } else if (strncmp(buf, "resync", 6) == 0) {
8380 if (raid5_has_ppl(conf)) {
8381 mddev_suspend(mddev);
8383 mddev_resume(mddev);
8384 err = resize_stripes(conf, conf->pool_size);
8385 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8386 r5l_log_disk_error(conf)) {
8387 bool journal_dev_exists = false;
8388 struct md_rdev *rdev;
8390 rdev_for_each(rdev, mddev)
8391 if (test_bit(Journal, &rdev->flags)) {
8392 journal_dev_exists = true;
8396 if (!journal_dev_exists) {
8397 mddev_suspend(mddev);
8398 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8399 mddev_resume(mddev);
8400 } else /* need remove journal device first */
8409 md_update_sb(mddev, 1);
8411 mddev_unlock(mddev);
8416 static int raid5_start(struct mddev *mddev)
8418 struct r5conf *conf = mddev->private;
8420 return r5l_start(conf->log);
8423 static struct md_personality raid6_personality =
8427 .owner = THIS_MODULE,
8428 .make_request = raid5_make_request,
8430 .start = raid5_start,
8432 .status = raid5_status,
8433 .error_handler = raid5_error,
8434 .hot_add_disk = raid5_add_disk,
8435 .hot_remove_disk= raid5_remove_disk,
8436 .spare_active = raid5_spare_active,
8437 .sync_request = raid5_sync_request,
8438 .resize = raid5_resize,
8440 .check_reshape = raid6_check_reshape,
8441 .start_reshape = raid5_start_reshape,
8442 .finish_reshape = raid5_finish_reshape,
8443 .quiesce = raid5_quiesce,
8444 .takeover = raid6_takeover,
8445 .congested = raid5_congested,
8446 .change_consistency_policy = raid5_change_consistency_policy,
8448 static struct md_personality raid5_personality =
8452 .owner = THIS_MODULE,
8453 .make_request = raid5_make_request,
8455 .start = raid5_start,
8457 .status = raid5_status,
8458 .error_handler = raid5_error,
8459 .hot_add_disk = raid5_add_disk,
8460 .hot_remove_disk= raid5_remove_disk,
8461 .spare_active = raid5_spare_active,
8462 .sync_request = raid5_sync_request,
8463 .resize = raid5_resize,
8465 .check_reshape = raid5_check_reshape,
8466 .start_reshape = raid5_start_reshape,
8467 .finish_reshape = raid5_finish_reshape,
8468 .quiesce = raid5_quiesce,
8469 .takeover = raid5_takeover,
8470 .congested = raid5_congested,
8471 .change_consistency_policy = raid5_change_consistency_policy,
8474 static struct md_personality raid4_personality =
8478 .owner = THIS_MODULE,
8479 .make_request = raid5_make_request,
8481 .start = raid5_start,
8483 .status = raid5_status,
8484 .error_handler = raid5_error,
8485 .hot_add_disk = raid5_add_disk,
8486 .hot_remove_disk= raid5_remove_disk,
8487 .spare_active = raid5_spare_active,
8488 .sync_request = raid5_sync_request,
8489 .resize = raid5_resize,
8491 .check_reshape = raid5_check_reshape,
8492 .start_reshape = raid5_start_reshape,
8493 .finish_reshape = raid5_finish_reshape,
8494 .quiesce = raid5_quiesce,
8495 .takeover = raid4_takeover,
8496 .congested = raid5_congested,
8497 .change_consistency_policy = raid5_change_consistency_policy,
8500 static int __init raid5_init(void)
8504 raid5_wq = alloc_workqueue("raid5wq",
8505 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8509 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8511 raid456_cpu_up_prepare,
8514 destroy_workqueue(raid5_wq);
8517 register_md_personality(&raid6_personality);
8518 register_md_personality(&raid5_personality);
8519 register_md_personality(&raid4_personality);
8523 static void raid5_exit(void)
8525 unregister_md_personality(&raid6_personality);
8526 unregister_md_personality(&raid5_personality);
8527 unregister_md_personality(&raid4_personality);
8528 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8529 destroy_workqueue(raid5_wq);
8532 module_init(raid5_init);
8533 module_exit(raid5_exit);
8534 MODULE_LICENSE("GPL");
8535 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8536 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8537 MODULE_ALIAS("md-raid5");
8538 MODULE_ALIAS("md-raid4");
8539 MODULE_ALIAS("md-level-5");
8540 MODULE_ALIAS("md-level-4");
8541 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8542 MODULE_ALIAS("md-raid6");
8543 MODULE_ALIAS("md-level-6");
8545 /* This used to be two separate modules, they were: */
8546 MODULE_ALIAS("raid5");
8547 MODULE_ALIAS("raid6");