2 * raid5.c : Multiple Devices driver for Linux
3 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4 * Copyright (C) 1999, 2000 Ingo Molnar
5 * Copyright (C) 2002, 2003 H. Peter Anvin
7 * RAID-4/5/6 management functions.
8 * Thanks to Penguin Computing for making the RAID-6 development possible
9 * by donating a test server!
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2, or (at your option)
16 * You should have received a copy of the GNU General Public License
17 * (for example /usr/src/linux/COPYING); if not, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 * The sequencing for updating the bitmap reliably is a little
25 * subtle (and I got it wrong the first time) so it deserves some
28 * We group bitmap updates into batches. Each batch has a number.
29 * We may write out several batches at once, but that isn't very important.
30 * conf->seq_write is the number of the last batch successfully written.
31 * conf->seq_flush is the number of the last batch that was closed to
33 * When we discover that we will need to write to any block in a stripe
34 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35 * the number of the batch it will be in. This is seq_flush+1.
36 * When we are ready to do a write, if that batch hasn't been written yet,
37 * we plug the array and queue the stripe for later.
38 * When an unplug happens, we increment bm_flush, thus closing the current
40 * When we notice that bm_flush > bm_write, we write out all pending updates
41 * to the bitmap, and advance bm_write to where bm_flush was.
42 * This may occasionally write a bit out twice, but is sure never to
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <linux/nodemask.h>
57 #include <linux/flex_array.h>
58 #include <linux/sched/signal.h>
60 #include <trace/events/block.h>
61 #include <linux/list_sort.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 local_irq_save(flags);
414 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
415 if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
416 INIT_LIST_HEAD(&list);
417 hash = sh->hash_lock_index;
418 do_release_stripe(conf, sh, &list);
419 spin_unlock(&conf->device_lock);
420 release_inactive_stripe_list(conf, &list, hash);
422 local_irq_restore(flags);
425 static inline void remove_hash(struct stripe_head *sh)
427 pr_debug("remove_hash(), stripe %llu\n",
428 (unsigned long long)sh->sector);
430 hlist_del_init(&sh->hash);
433 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
435 struct hlist_head *hp = stripe_hash(conf, sh->sector);
437 pr_debug("insert_hash(), stripe %llu\n",
438 (unsigned long long)sh->sector);
440 hlist_add_head(&sh->hash, hp);
443 /* find an idle stripe, make sure it is unhashed, and return it. */
444 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
446 struct stripe_head *sh = NULL;
447 struct list_head *first;
449 if (list_empty(conf->inactive_list + hash))
451 first = (conf->inactive_list + hash)->next;
452 sh = list_entry(first, struct stripe_head, lru);
453 list_del_init(first);
455 atomic_inc(&conf->active_stripes);
456 BUG_ON(hash != sh->hash_lock_index);
457 if (list_empty(conf->inactive_list + hash))
458 atomic_inc(&conf->empty_inactive_list_nr);
463 static void shrink_buffers(struct stripe_head *sh)
467 int num = sh->raid_conf->pool_size;
469 for (i = 0; i < num ; i++) {
470 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
474 sh->dev[i].page = NULL;
479 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
482 int num = sh->raid_conf->pool_size;
484 for (i = 0; i < num; i++) {
487 if (!(page = alloc_page(gfp))) {
490 sh->dev[i].page = page;
491 sh->dev[i].orig_page = page;
497 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
498 struct stripe_head *sh);
500 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
502 struct r5conf *conf = sh->raid_conf;
505 BUG_ON(atomic_read(&sh->count) != 0);
506 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
507 BUG_ON(stripe_operations_active(sh));
508 BUG_ON(sh->batch_head);
510 pr_debug("init_stripe called, stripe %llu\n",
511 (unsigned long long)sector);
513 seq = read_seqcount_begin(&conf->gen_lock);
514 sh->generation = conf->generation - previous;
515 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
517 stripe_set_idx(sector, conf, previous, sh);
520 for (i = sh->disks; i--; ) {
521 struct r5dev *dev = &sh->dev[i];
523 if (dev->toread || dev->read || dev->towrite || dev->written ||
524 test_bit(R5_LOCKED, &dev->flags)) {
525 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
526 (unsigned long long)sh->sector, i, dev->toread,
527 dev->read, dev->towrite, dev->written,
528 test_bit(R5_LOCKED, &dev->flags));
532 dev->sector = raid5_compute_blocknr(sh, i, previous);
534 if (read_seqcount_retry(&conf->gen_lock, seq))
536 sh->overwrite_disks = 0;
537 insert_hash(conf, sh);
538 sh->cpu = smp_processor_id();
539 set_bit(STRIPE_BATCH_READY, &sh->state);
542 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
545 struct stripe_head *sh;
547 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
548 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
549 if (sh->sector == sector && sh->generation == generation)
551 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
556 * Need to check if array has failed when deciding whether to:
558 * - remove non-faulty devices
561 * This determination is simple when no reshape is happening.
562 * However if there is a reshape, we need to carefully check
563 * both the before and after sections.
564 * This is because some failed devices may only affect one
565 * of the two sections, and some non-in_sync devices may
566 * be insync in the section most affected by failed devices.
568 int raid5_calc_degraded(struct r5conf *conf)
570 int degraded, degraded2;
575 for (i = 0; i < conf->previous_raid_disks; i++) {
576 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
577 if (rdev && test_bit(Faulty, &rdev->flags))
578 rdev = rcu_dereference(conf->disks[i].replacement);
579 if (!rdev || test_bit(Faulty, &rdev->flags))
581 else if (test_bit(In_sync, &rdev->flags))
584 /* not in-sync or faulty.
585 * If the reshape increases the number of devices,
586 * this is being recovered by the reshape, so
587 * this 'previous' section is not in_sync.
588 * If the number of devices is being reduced however,
589 * the device can only be part of the array if
590 * we are reverting a reshape, so this section will
593 if (conf->raid_disks >= conf->previous_raid_disks)
597 if (conf->raid_disks == conf->previous_raid_disks)
601 for (i = 0; i < conf->raid_disks; i++) {
602 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
603 if (rdev && test_bit(Faulty, &rdev->flags))
604 rdev = rcu_dereference(conf->disks[i].replacement);
605 if (!rdev || test_bit(Faulty, &rdev->flags))
607 else if (test_bit(In_sync, &rdev->flags))
610 /* not in-sync or faulty.
611 * If reshape increases the number of devices, this
612 * section has already been recovered, else it
613 * almost certainly hasn't.
615 if (conf->raid_disks <= conf->previous_raid_disks)
619 if (degraded2 > degraded)
624 static int has_failed(struct r5conf *conf)
628 if (conf->mddev->reshape_position == MaxSector)
629 return conf->mddev->degraded > conf->max_degraded;
631 degraded = raid5_calc_degraded(conf);
632 if (degraded > conf->max_degraded)
638 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
639 int previous, int noblock, int noquiesce)
641 struct stripe_head *sh;
642 int hash = stripe_hash_locks_hash(sector);
643 int inc_empty_inactive_list_flag;
645 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
647 spin_lock_irq(conf->hash_locks + hash);
650 wait_event_lock_irq(conf->wait_for_quiescent,
651 conf->quiesce == 0 || noquiesce,
652 *(conf->hash_locks + hash));
653 sh = __find_stripe(conf, sector, conf->generation - previous);
655 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
656 sh = get_free_stripe(conf, hash);
657 if (!sh && !test_bit(R5_DID_ALLOC,
659 set_bit(R5_ALLOC_MORE,
662 if (noblock && sh == NULL)
665 r5c_check_stripe_cache_usage(conf);
667 set_bit(R5_INACTIVE_BLOCKED,
669 r5l_wake_reclaim(conf->log, 0);
671 conf->wait_for_stripe,
672 !list_empty(conf->inactive_list + hash) &&
673 (atomic_read(&conf->active_stripes)
674 < (conf->max_nr_stripes * 3 / 4)
675 || !test_bit(R5_INACTIVE_BLOCKED,
676 &conf->cache_state)),
677 *(conf->hash_locks + hash));
678 clear_bit(R5_INACTIVE_BLOCKED,
681 init_stripe(sh, sector, previous);
682 atomic_inc(&sh->count);
684 } else if (!atomic_inc_not_zero(&sh->count)) {
685 spin_lock(&conf->device_lock);
686 if (!atomic_read(&sh->count)) {
687 if (!test_bit(STRIPE_HANDLE, &sh->state))
688 atomic_inc(&conf->active_stripes);
689 BUG_ON(list_empty(&sh->lru) &&
690 !test_bit(STRIPE_EXPANDING, &sh->state));
691 inc_empty_inactive_list_flag = 0;
692 if (!list_empty(conf->inactive_list + hash))
693 inc_empty_inactive_list_flag = 1;
694 list_del_init(&sh->lru);
695 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
696 atomic_inc(&conf->empty_inactive_list_nr);
698 sh->group->stripes_cnt--;
702 atomic_inc(&sh->count);
703 spin_unlock(&conf->device_lock);
705 } while (sh == NULL);
707 spin_unlock_irq(conf->hash_locks + hash);
711 static bool is_full_stripe_write(struct stripe_head *sh)
713 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
714 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
717 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
720 spin_lock_irq(&sh2->stripe_lock);
721 spin_lock_nested(&sh1->stripe_lock, 1);
723 spin_lock_irq(&sh1->stripe_lock);
724 spin_lock_nested(&sh2->stripe_lock, 1);
728 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
730 spin_unlock(&sh1->stripe_lock);
731 spin_unlock_irq(&sh2->stripe_lock);
734 /* Only freshly new full stripe normal write stripe can be added to a batch list */
735 static bool stripe_can_batch(struct stripe_head *sh)
737 struct r5conf *conf = sh->raid_conf;
739 if (conf->log || raid5_has_ppl(conf))
741 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
742 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
743 is_full_stripe_write(sh);
746 /* we only do back search */
747 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
749 struct stripe_head *head;
750 sector_t head_sector, tmp_sec;
753 int inc_empty_inactive_list_flag;
755 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
756 tmp_sec = sh->sector;
757 if (!sector_div(tmp_sec, conf->chunk_sectors))
759 head_sector = sh->sector - STRIPE_SECTORS;
761 hash = stripe_hash_locks_hash(head_sector);
762 spin_lock_irq(conf->hash_locks + hash);
763 head = __find_stripe(conf, head_sector, conf->generation);
764 if (head && !atomic_inc_not_zero(&head->count)) {
765 spin_lock(&conf->device_lock);
766 if (!atomic_read(&head->count)) {
767 if (!test_bit(STRIPE_HANDLE, &head->state))
768 atomic_inc(&conf->active_stripes);
769 BUG_ON(list_empty(&head->lru) &&
770 !test_bit(STRIPE_EXPANDING, &head->state));
771 inc_empty_inactive_list_flag = 0;
772 if (!list_empty(conf->inactive_list + hash))
773 inc_empty_inactive_list_flag = 1;
774 list_del_init(&head->lru);
775 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
776 atomic_inc(&conf->empty_inactive_list_nr);
778 head->group->stripes_cnt--;
782 atomic_inc(&head->count);
783 spin_unlock(&conf->device_lock);
785 spin_unlock_irq(conf->hash_locks + hash);
789 if (!stripe_can_batch(head))
792 lock_two_stripes(head, sh);
793 /* clear_batch_ready clear the flag */
794 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
801 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
803 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
804 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
807 if (head->batch_head) {
808 spin_lock(&head->batch_head->batch_lock);
809 /* This batch list is already running */
810 if (!stripe_can_batch(head)) {
811 spin_unlock(&head->batch_head->batch_lock);
816 * at this point, head's BATCH_READY could be cleared, but we
817 * can still add the stripe to batch list
819 list_add(&sh->batch_list, &head->batch_list);
820 spin_unlock(&head->batch_head->batch_lock);
822 sh->batch_head = head->batch_head;
824 head->batch_head = head;
825 sh->batch_head = head->batch_head;
826 spin_lock(&head->batch_lock);
827 list_add_tail(&sh->batch_list, &head->batch_list);
828 spin_unlock(&head->batch_lock);
831 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
832 if (atomic_dec_return(&conf->preread_active_stripes)
834 md_wakeup_thread(conf->mddev->thread);
836 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
837 int seq = sh->bm_seq;
838 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
839 sh->batch_head->bm_seq > seq)
840 seq = sh->batch_head->bm_seq;
841 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
842 sh->batch_head->bm_seq = seq;
845 atomic_inc(&sh->count);
847 unlock_two_stripes(head, sh);
849 raid5_release_stripe(head);
852 /* Determine if 'data_offset' or 'new_data_offset' should be used
853 * in this stripe_head.
855 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
857 sector_t progress = conf->reshape_progress;
858 /* Need a memory barrier to make sure we see the value
859 * of conf->generation, or ->data_offset that was set before
860 * reshape_progress was updated.
863 if (progress == MaxSector)
865 if (sh->generation == conf->generation - 1)
867 /* We are in a reshape, and this is a new-generation stripe,
868 * so use new_data_offset.
873 static void dispatch_bio_list(struct bio_list *tmp)
877 while ((bio = bio_list_pop(tmp)))
878 generic_make_request(bio);
881 static int cmp_stripe(void *priv, struct list_head *a, struct list_head *b)
883 const struct r5pending_data *da = list_entry(a,
884 struct r5pending_data, sibling);
885 const struct r5pending_data *db = list_entry(b,
886 struct r5pending_data, sibling);
887 if (da->sector > db->sector)
889 if (da->sector < db->sector)
894 static void dispatch_defer_bios(struct r5conf *conf, int target,
895 struct bio_list *list)
897 struct r5pending_data *data;
898 struct list_head *first, *next = NULL;
901 if (conf->pending_data_cnt == 0)
904 list_sort(NULL, &conf->pending_list, cmp_stripe);
906 first = conf->pending_list.next;
908 /* temporarily move the head */
909 if (conf->next_pending_data)
910 list_move_tail(&conf->pending_list,
911 &conf->next_pending_data->sibling);
913 while (!list_empty(&conf->pending_list)) {
914 data = list_first_entry(&conf->pending_list,
915 struct r5pending_data, sibling);
916 if (&data->sibling == first)
917 first = data->sibling.next;
918 next = data->sibling.next;
920 bio_list_merge(list, &data->bios);
921 list_move(&data->sibling, &conf->free_list);
926 conf->pending_data_cnt -= cnt;
927 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
929 if (next != &conf->pending_list)
930 conf->next_pending_data = list_entry(next,
931 struct r5pending_data, sibling);
933 conf->next_pending_data = NULL;
934 /* list isn't empty */
935 if (first != &conf->pending_list)
936 list_move_tail(&conf->pending_list, first);
939 static void flush_deferred_bios(struct r5conf *conf)
941 struct bio_list tmp = BIO_EMPTY_LIST;
943 if (conf->pending_data_cnt == 0)
946 spin_lock(&conf->pending_bios_lock);
947 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
948 BUG_ON(conf->pending_data_cnt != 0);
949 spin_unlock(&conf->pending_bios_lock);
951 dispatch_bio_list(&tmp);
954 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
955 struct bio_list *bios)
957 struct bio_list tmp = BIO_EMPTY_LIST;
958 struct r5pending_data *ent;
960 spin_lock(&conf->pending_bios_lock);
961 ent = list_first_entry(&conf->free_list, struct r5pending_data,
963 list_move_tail(&ent->sibling, &conf->pending_list);
964 ent->sector = sector;
965 bio_list_init(&ent->bios);
966 bio_list_merge(&ent->bios, bios);
967 conf->pending_data_cnt++;
968 if (conf->pending_data_cnt >= PENDING_IO_MAX)
969 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
971 spin_unlock(&conf->pending_bios_lock);
973 dispatch_bio_list(&tmp);
977 raid5_end_read_request(struct bio *bi);
979 raid5_end_write_request(struct bio *bi);
981 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
983 struct r5conf *conf = sh->raid_conf;
984 int i, disks = sh->disks;
985 struct stripe_head *head_sh = sh;
986 struct bio_list pending_bios = BIO_EMPTY_LIST;
991 if (log_stripe(sh, s) == 0)
994 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
996 for (i = disks; i--; ) {
997 int op, op_flags = 0;
998 int replace_only = 0;
999 struct bio *bi, *rbi;
1000 struct md_rdev *rdev, *rrdev = NULL;
1003 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1005 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1007 if (test_bit(R5_Discard, &sh->dev[i].flags))
1008 op = REQ_OP_DISCARD;
1009 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1011 else if (test_and_clear_bit(R5_WantReplace,
1012 &sh->dev[i].flags)) {
1017 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1018 op_flags |= REQ_SYNC;
1021 bi = &sh->dev[i].req;
1022 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1025 rrdev = rcu_dereference(conf->disks[i].replacement);
1026 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1027 rdev = rcu_dereference(conf->disks[i].rdev);
1032 if (op_is_write(op)) {
1036 /* We raced and saw duplicates */
1039 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1044 if (rdev && test_bit(Faulty, &rdev->flags))
1047 atomic_inc(&rdev->nr_pending);
1048 if (rrdev && test_bit(Faulty, &rrdev->flags))
1051 atomic_inc(&rrdev->nr_pending);
1054 /* We have already checked bad blocks for reads. Now
1055 * need to check for writes. We never accept write errors
1056 * on the replacement, so we don't to check rrdev.
1058 while (op_is_write(op) && rdev &&
1059 test_bit(WriteErrorSeen, &rdev->flags)) {
1062 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
1063 &first_bad, &bad_sectors);
1068 set_bit(BlockedBadBlocks, &rdev->flags);
1069 if (!conf->mddev->external &&
1070 conf->mddev->sb_flags) {
1071 /* It is very unlikely, but we might
1072 * still need to write out the
1073 * bad block log - better give it
1075 md_check_recovery(conf->mddev);
1078 * Because md_wait_for_blocked_rdev
1079 * will dec nr_pending, we must
1080 * increment it first.
1082 atomic_inc(&rdev->nr_pending);
1083 md_wait_for_blocked_rdev(rdev, conf->mddev);
1085 /* Acknowledged bad block - skip the write */
1086 rdev_dec_pending(rdev, conf->mddev);
1092 if (s->syncing || s->expanding || s->expanded
1094 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
1096 set_bit(STRIPE_IO_STARTED, &sh->state);
1098 bi->bi_bdev = rdev->bdev;
1099 bio_set_op_attrs(bi, op, op_flags);
1100 bi->bi_end_io = op_is_write(op)
1101 ? raid5_end_write_request
1102 : raid5_end_read_request;
1103 bi->bi_private = sh;
1105 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1106 __func__, (unsigned long long)sh->sector,
1108 atomic_inc(&sh->count);
1110 atomic_inc(&head_sh->count);
1111 if (use_new_offset(conf, sh))
1112 bi->bi_iter.bi_sector = (sh->sector
1113 + rdev->new_data_offset);
1115 bi->bi_iter.bi_sector = (sh->sector
1116 + rdev->data_offset);
1117 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1118 bi->bi_opf |= REQ_NOMERGE;
1120 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1121 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1123 if (!op_is_write(op) &&
1124 test_bit(R5_InJournal, &sh->dev[i].flags))
1126 * issuing read for a page in journal, this
1127 * must be preparing for prexor in rmw; read
1128 * the data into orig_page
1130 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1132 sh->dev[i].vec.bv_page = sh->dev[i].page;
1134 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1135 bi->bi_io_vec[0].bv_offset = 0;
1136 bi->bi_iter.bi_size = STRIPE_SIZE;
1138 * If this is discard request, set bi_vcnt 0. We don't
1139 * want to confuse SCSI because SCSI will replace payload
1141 if (op == REQ_OP_DISCARD)
1144 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1146 if (conf->mddev->gendisk)
1147 trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
1148 bi, disk_devt(conf->mddev->gendisk),
1150 if (should_defer && op_is_write(op))
1151 bio_list_add(&pending_bios, bi);
1153 generic_make_request(bi);
1156 if (s->syncing || s->expanding || s->expanded
1158 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1160 set_bit(STRIPE_IO_STARTED, &sh->state);
1162 rbi->bi_bdev = rrdev->bdev;
1163 bio_set_op_attrs(rbi, op, op_flags);
1164 BUG_ON(!op_is_write(op));
1165 rbi->bi_end_io = raid5_end_write_request;
1166 rbi->bi_private = sh;
1168 pr_debug("%s: for %llu schedule op %d on "
1169 "replacement disc %d\n",
1170 __func__, (unsigned long long)sh->sector,
1172 atomic_inc(&sh->count);
1174 atomic_inc(&head_sh->count);
1175 if (use_new_offset(conf, sh))
1176 rbi->bi_iter.bi_sector = (sh->sector
1177 + rrdev->new_data_offset);
1179 rbi->bi_iter.bi_sector = (sh->sector
1180 + rrdev->data_offset);
1181 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1182 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1183 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1185 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1186 rbi->bi_io_vec[0].bv_offset = 0;
1187 rbi->bi_iter.bi_size = STRIPE_SIZE;
1189 * If this is discard request, set bi_vcnt 0. We don't
1190 * want to confuse SCSI because SCSI will replace payload
1192 if (op == REQ_OP_DISCARD)
1194 if (conf->mddev->gendisk)
1195 trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
1196 rbi, disk_devt(conf->mddev->gendisk),
1198 if (should_defer && op_is_write(op))
1199 bio_list_add(&pending_bios, rbi);
1201 generic_make_request(rbi);
1203 if (!rdev && !rrdev) {
1204 if (op_is_write(op))
1205 set_bit(STRIPE_DEGRADED, &sh->state);
1206 pr_debug("skip op %d on disc %d for sector %llu\n",
1207 bi->bi_opf, i, (unsigned long long)sh->sector);
1208 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1209 set_bit(STRIPE_HANDLE, &sh->state);
1212 if (!head_sh->batch_head)
1214 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1220 if (should_defer && !bio_list_empty(&pending_bios))
1221 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1224 static struct dma_async_tx_descriptor *
1225 async_copy_data(int frombio, struct bio *bio, struct page **page,
1226 sector_t sector, struct dma_async_tx_descriptor *tx,
1227 struct stripe_head *sh, int no_skipcopy)
1230 struct bvec_iter iter;
1231 struct page *bio_page;
1233 struct async_submit_ctl submit;
1234 enum async_tx_flags flags = 0;
1236 if (bio->bi_iter.bi_sector >= sector)
1237 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1239 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1242 flags |= ASYNC_TX_FENCE;
1243 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1245 bio_for_each_segment(bvl, bio, iter) {
1246 int len = bvl.bv_len;
1250 if (page_offset < 0) {
1251 b_offset = -page_offset;
1252 page_offset += b_offset;
1256 if (len > 0 && page_offset + len > STRIPE_SIZE)
1257 clen = STRIPE_SIZE - page_offset;
1262 b_offset += bvl.bv_offset;
1263 bio_page = bvl.bv_page;
1265 if (sh->raid_conf->skip_copy &&
1266 b_offset == 0 && page_offset == 0 &&
1267 clen == STRIPE_SIZE &&
1271 tx = async_memcpy(*page, bio_page, page_offset,
1272 b_offset, clen, &submit);
1274 tx = async_memcpy(bio_page, *page, b_offset,
1275 page_offset, clen, &submit);
1277 /* chain the operations */
1278 submit.depend_tx = tx;
1280 if (clen < len) /* hit end of page */
1288 static void ops_complete_biofill(void *stripe_head_ref)
1290 struct stripe_head *sh = stripe_head_ref;
1293 pr_debug("%s: stripe %llu\n", __func__,
1294 (unsigned long long)sh->sector);
1296 /* clear completed biofills */
1297 for (i = sh->disks; i--; ) {
1298 struct r5dev *dev = &sh->dev[i];
1300 /* acknowledge completion of a biofill operation */
1301 /* and check if we need to reply to a read request,
1302 * new R5_Wantfill requests are held off until
1303 * !STRIPE_BIOFILL_RUN
1305 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1306 struct bio *rbi, *rbi2;
1311 while (rbi && rbi->bi_iter.bi_sector <
1312 dev->sector + STRIPE_SECTORS) {
1313 rbi2 = r5_next_bio(rbi, dev->sector);
1319 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1321 set_bit(STRIPE_HANDLE, &sh->state);
1322 raid5_release_stripe(sh);
1325 static void ops_run_biofill(struct stripe_head *sh)
1327 struct dma_async_tx_descriptor *tx = NULL;
1328 struct async_submit_ctl submit;
1331 BUG_ON(sh->batch_head);
1332 pr_debug("%s: stripe %llu\n", __func__,
1333 (unsigned long long)sh->sector);
1335 for (i = sh->disks; i--; ) {
1336 struct r5dev *dev = &sh->dev[i];
1337 if (test_bit(R5_Wantfill, &dev->flags)) {
1339 spin_lock_irq(&sh->stripe_lock);
1340 dev->read = rbi = dev->toread;
1342 spin_unlock_irq(&sh->stripe_lock);
1343 while (rbi && rbi->bi_iter.bi_sector <
1344 dev->sector + STRIPE_SECTORS) {
1345 tx = async_copy_data(0, rbi, &dev->page,
1346 dev->sector, tx, sh, 0);
1347 rbi = r5_next_bio(rbi, dev->sector);
1352 atomic_inc(&sh->count);
1353 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1354 async_trigger_callback(&submit);
1357 static void mark_target_uptodate(struct stripe_head *sh, int target)
1364 tgt = &sh->dev[target];
1365 set_bit(R5_UPTODATE, &tgt->flags);
1366 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1367 clear_bit(R5_Wantcompute, &tgt->flags);
1370 static void ops_complete_compute(void *stripe_head_ref)
1372 struct stripe_head *sh = stripe_head_ref;
1374 pr_debug("%s: stripe %llu\n", __func__,
1375 (unsigned long long)sh->sector);
1377 /* mark the computed target(s) as uptodate */
1378 mark_target_uptodate(sh, sh->ops.target);
1379 mark_target_uptodate(sh, sh->ops.target2);
1381 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1382 if (sh->check_state == check_state_compute_run)
1383 sh->check_state = check_state_compute_result;
1384 set_bit(STRIPE_HANDLE, &sh->state);
1385 raid5_release_stripe(sh);
1388 /* return a pointer to the address conversion region of the scribble buffer */
1389 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1390 struct raid5_percpu *percpu, int i)
1394 addr = flex_array_get(percpu->scribble, i);
1395 return addr + sizeof(struct page *) * (sh->disks + 2);
1398 /* return a pointer to the address conversion region of the scribble buffer */
1399 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1403 addr = flex_array_get(percpu->scribble, i);
1407 static struct dma_async_tx_descriptor *
1408 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1410 int disks = sh->disks;
1411 struct page **xor_srcs = to_addr_page(percpu, 0);
1412 int target = sh->ops.target;
1413 struct r5dev *tgt = &sh->dev[target];
1414 struct page *xor_dest = tgt->page;
1416 struct dma_async_tx_descriptor *tx;
1417 struct async_submit_ctl submit;
1420 BUG_ON(sh->batch_head);
1422 pr_debug("%s: stripe %llu block: %d\n",
1423 __func__, (unsigned long long)sh->sector, target);
1424 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1426 for (i = disks; i--; )
1428 xor_srcs[count++] = sh->dev[i].page;
1430 atomic_inc(&sh->count);
1432 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1433 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1434 if (unlikely(count == 1))
1435 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1437 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1442 /* set_syndrome_sources - populate source buffers for gen_syndrome
1443 * @srcs - (struct page *) array of size sh->disks
1444 * @sh - stripe_head to parse
1446 * Populates srcs in proper layout order for the stripe and returns the
1447 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1448 * destination buffer is recorded in srcs[count] and the Q destination
1449 * is recorded in srcs[count+1]].
1451 static int set_syndrome_sources(struct page **srcs,
1452 struct stripe_head *sh,
1455 int disks = sh->disks;
1456 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1457 int d0_idx = raid6_d0(sh);
1461 for (i = 0; i < disks; i++)
1467 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1468 struct r5dev *dev = &sh->dev[i];
1470 if (i == sh->qd_idx || i == sh->pd_idx ||
1471 (srctype == SYNDROME_SRC_ALL) ||
1472 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1473 (test_bit(R5_Wantdrain, &dev->flags) ||
1474 test_bit(R5_InJournal, &dev->flags))) ||
1475 (srctype == SYNDROME_SRC_WRITTEN &&
1477 test_bit(R5_InJournal, &dev->flags)))) {
1478 if (test_bit(R5_InJournal, &dev->flags))
1479 srcs[slot] = sh->dev[i].orig_page;
1481 srcs[slot] = sh->dev[i].page;
1483 i = raid6_next_disk(i, disks);
1484 } while (i != d0_idx);
1486 return syndrome_disks;
1489 static struct dma_async_tx_descriptor *
1490 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1492 int disks = sh->disks;
1493 struct page **blocks = to_addr_page(percpu, 0);
1495 int qd_idx = sh->qd_idx;
1496 struct dma_async_tx_descriptor *tx;
1497 struct async_submit_ctl submit;
1503 BUG_ON(sh->batch_head);
1504 if (sh->ops.target < 0)
1505 target = sh->ops.target2;
1506 else if (sh->ops.target2 < 0)
1507 target = sh->ops.target;
1509 /* we should only have one valid target */
1512 pr_debug("%s: stripe %llu block: %d\n",
1513 __func__, (unsigned long long)sh->sector, target);
1515 tgt = &sh->dev[target];
1516 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1519 atomic_inc(&sh->count);
1521 if (target == qd_idx) {
1522 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1523 blocks[count] = NULL; /* regenerating p is not necessary */
1524 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1525 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1526 ops_complete_compute, sh,
1527 to_addr_conv(sh, percpu, 0));
1528 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1530 /* Compute any data- or p-drive using XOR */
1532 for (i = disks; i-- ; ) {
1533 if (i == target || i == qd_idx)
1535 blocks[count++] = sh->dev[i].page;
1538 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1539 NULL, ops_complete_compute, sh,
1540 to_addr_conv(sh, percpu, 0));
1541 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1547 static struct dma_async_tx_descriptor *
1548 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1550 int i, count, disks = sh->disks;
1551 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1552 int d0_idx = raid6_d0(sh);
1553 int faila = -1, failb = -1;
1554 int target = sh->ops.target;
1555 int target2 = sh->ops.target2;
1556 struct r5dev *tgt = &sh->dev[target];
1557 struct r5dev *tgt2 = &sh->dev[target2];
1558 struct dma_async_tx_descriptor *tx;
1559 struct page **blocks = to_addr_page(percpu, 0);
1560 struct async_submit_ctl submit;
1562 BUG_ON(sh->batch_head);
1563 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1564 __func__, (unsigned long long)sh->sector, target, target2);
1565 BUG_ON(target < 0 || target2 < 0);
1566 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1567 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1569 /* we need to open-code set_syndrome_sources to handle the
1570 * slot number conversion for 'faila' and 'failb'
1572 for (i = 0; i < disks ; i++)
1577 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1579 blocks[slot] = sh->dev[i].page;
1585 i = raid6_next_disk(i, disks);
1586 } while (i != d0_idx);
1588 BUG_ON(faila == failb);
1591 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1592 __func__, (unsigned long long)sh->sector, faila, failb);
1594 atomic_inc(&sh->count);
1596 if (failb == syndrome_disks+1) {
1597 /* Q disk is one of the missing disks */
1598 if (faila == syndrome_disks) {
1599 /* Missing P+Q, just recompute */
1600 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1601 ops_complete_compute, sh,
1602 to_addr_conv(sh, percpu, 0));
1603 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1604 STRIPE_SIZE, &submit);
1608 int qd_idx = sh->qd_idx;
1610 /* Missing D+Q: recompute D from P, then recompute Q */
1611 if (target == qd_idx)
1612 data_target = target2;
1614 data_target = target;
1617 for (i = disks; i-- ; ) {
1618 if (i == data_target || i == qd_idx)
1620 blocks[count++] = sh->dev[i].page;
1622 dest = sh->dev[data_target].page;
1623 init_async_submit(&submit,
1624 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1626 to_addr_conv(sh, percpu, 0));
1627 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1630 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1631 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1632 ops_complete_compute, sh,
1633 to_addr_conv(sh, percpu, 0));
1634 return async_gen_syndrome(blocks, 0, count+2,
1635 STRIPE_SIZE, &submit);
1638 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1639 ops_complete_compute, sh,
1640 to_addr_conv(sh, percpu, 0));
1641 if (failb == syndrome_disks) {
1642 /* We're missing D+P. */
1643 return async_raid6_datap_recov(syndrome_disks+2,
1647 /* We're missing D+D. */
1648 return async_raid6_2data_recov(syndrome_disks+2,
1649 STRIPE_SIZE, faila, failb,
1655 static void ops_complete_prexor(void *stripe_head_ref)
1657 struct stripe_head *sh = stripe_head_ref;
1659 pr_debug("%s: stripe %llu\n", __func__,
1660 (unsigned long long)sh->sector);
1662 if (r5c_is_writeback(sh->raid_conf->log))
1664 * raid5-cache write back uses orig_page during prexor.
1665 * After prexor, it is time to free orig_page
1667 r5c_release_extra_page(sh);
1670 static struct dma_async_tx_descriptor *
1671 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1672 struct dma_async_tx_descriptor *tx)
1674 int disks = sh->disks;
1675 struct page **xor_srcs = to_addr_page(percpu, 0);
1676 int count = 0, pd_idx = sh->pd_idx, i;
1677 struct async_submit_ctl submit;
1679 /* existing parity data subtracted */
1680 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1682 BUG_ON(sh->batch_head);
1683 pr_debug("%s: stripe %llu\n", __func__,
1684 (unsigned long long)sh->sector);
1686 for (i = disks; i--; ) {
1687 struct r5dev *dev = &sh->dev[i];
1688 /* Only process blocks that are known to be uptodate */
1689 if (test_bit(R5_InJournal, &dev->flags))
1690 xor_srcs[count++] = dev->orig_page;
1691 else if (test_bit(R5_Wantdrain, &dev->flags))
1692 xor_srcs[count++] = dev->page;
1695 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1696 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1697 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1702 static struct dma_async_tx_descriptor *
1703 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1704 struct dma_async_tx_descriptor *tx)
1706 struct page **blocks = to_addr_page(percpu, 0);
1708 struct async_submit_ctl submit;
1710 pr_debug("%s: stripe %llu\n", __func__,
1711 (unsigned long long)sh->sector);
1713 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1715 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1716 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1717 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1722 static struct dma_async_tx_descriptor *
1723 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1725 struct r5conf *conf = sh->raid_conf;
1726 int disks = sh->disks;
1728 struct stripe_head *head_sh = sh;
1730 pr_debug("%s: stripe %llu\n", __func__,
1731 (unsigned long long)sh->sector);
1733 for (i = disks; i--; ) {
1738 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1744 * clear R5_InJournal, so when rewriting a page in
1745 * journal, it is not skipped by r5l_log_stripe()
1747 clear_bit(R5_InJournal, &dev->flags);
1748 spin_lock_irq(&sh->stripe_lock);
1749 chosen = dev->towrite;
1750 dev->towrite = NULL;
1751 sh->overwrite_disks = 0;
1752 BUG_ON(dev->written);
1753 wbi = dev->written = chosen;
1754 spin_unlock_irq(&sh->stripe_lock);
1755 WARN_ON(dev->page != dev->orig_page);
1757 while (wbi && wbi->bi_iter.bi_sector <
1758 dev->sector + STRIPE_SECTORS) {
1759 if (wbi->bi_opf & REQ_FUA)
1760 set_bit(R5_WantFUA, &dev->flags);
1761 if (wbi->bi_opf & REQ_SYNC)
1762 set_bit(R5_SyncIO, &dev->flags);
1763 if (bio_op(wbi) == REQ_OP_DISCARD)
1764 set_bit(R5_Discard, &dev->flags);
1766 tx = async_copy_data(1, wbi, &dev->page,
1767 dev->sector, tx, sh,
1768 r5c_is_writeback(conf->log));
1769 if (dev->page != dev->orig_page &&
1770 !r5c_is_writeback(conf->log)) {
1771 set_bit(R5_SkipCopy, &dev->flags);
1772 clear_bit(R5_UPTODATE, &dev->flags);
1773 clear_bit(R5_OVERWRITE, &dev->flags);
1776 wbi = r5_next_bio(wbi, dev->sector);
1779 if (head_sh->batch_head) {
1780 sh = list_first_entry(&sh->batch_list,
1793 static void ops_complete_reconstruct(void *stripe_head_ref)
1795 struct stripe_head *sh = stripe_head_ref;
1796 int disks = sh->disks;
1797 int pd_idx = sh->pd_idx;
1798 int qd_idx = sh->qd_idx;
1800 bool fua = false, sync = false, discard = false;
1802 pr_debug("%s: stripe %llu\n", __func__,
1803 (unsigned long long)sh->sector);
1805 for (i = disks; i--; ) {
1806 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1807 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1808 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1811 for (i = disks; i--; ) {
1812 struct r5dev *dev = &sh->dev[i];
1814 if (dev->written || i == pd_idx || i == qd_idx) {
1815 if (!discard && !test_bit(R5_SkipCopy, &dev->flags))
1816 set_bit(R5_UPTODATE, &dev->flags);
1818 set_bit(R5_WantFUA, &dev->flags);
1820 set_bit(R5_SyncIO, &dev->flags);
1824 if (sh->reconstruct_state == reconstruct_state_drain_run)
1825 sh->reconstruct_state = reconstruct_state_drain_result;
1826 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1827 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1829 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1830 sh->reconstruct_state = reconstruct_state_result;
1833 set_bit(STRIPE_HANDLE, &sh->state);
1834 raid5_release_stripe(sh);
1838 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1839 struct dma_async_tx_descriptor *tx)
1841 int disks = sh->disks;
1842 struct page **xor_srcs;
1843 struct async_submit_ctl submit;
1844 int count, pd_idx = sh->pd_idx, i;
1845 struct page *xor_dest;
1847 unsigned long flags;
1849 struct stripe_head *head_sh = sh;
1852 pr_debug("%s: stripe %llu\n", __func__,
1853 (unsigned long long)sh->sector);
1855 for (i = 0; i < sh->disks; i++) {
1858 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1861 if (i >= sh->disks) {
1862 atomic_inc(&sh->count);
1863 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1864 ops_complete_reconstruct(sh);
1869 xor_srcs = to_addr_page(percpu, j);
1870 /* check if prexor is active which means only process blocks
1871 * that are part of a read-modify-write (written)
1873 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1875 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1876 for (i = disks; i--; ) {
1877 struct r5dev *dev = &sh->dev[i];
1878 if (head_sh->dev[i].written ||
1879 test_bit(R5_InJournal, &head_sh->dev[i].flags))
1880 xor_srcs[count++] = dev->page;
1883 xor_dest = sh->dev[pd_idx].page;
1884 for (i = disks; i--; ) {
1885 struct r5dev *dev = &sh->dev[i];
1887 xor_srcs[count++] = dev->page;
1891 /* 1/ if we prexor'd then the dest is reused as a source
1892 * 2/ if we did not prexor then we are redoing the parity
1893 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1894 * for the synchronous xor case
1896 last_stripe = !head_sh->batch_head ||
1897 list_first_entry(&sh->batch_list,
1898 struct stripe_head, batch_list) == head_sh;
1900 flags = ASYNC_TX_ACK |
1901 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1903 atomic_inc(&head_sh->count);
1904 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1905 to_addr_conv(sh, percpu, j));
1907 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1908 init_async_submit(&submit, flags, tx, NULL, NULL,
1909 to_addr_conv(sh, percpu, j));
1912 if (unlikely(count == 1))
1913 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1915 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1918 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1925 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1926 struct dma_async_tx_descriptor *tx)
1928 struct async_submit_ctl submit;
1929 struct page **blocks;
1930 int count, i, j = 0;
1931 struct stripe_head *head_sh = sh;
1934 unsigned long txflags;
1936 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1938 for (i = 0; i < sh->disks; i++) {
1939 if (sh->pd_idx == i || sh->qd_idx == i)
1941 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1944 if (i >= sh->disks) {
1945 atomic_inc(&sh->count);
1946 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1947 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1948 ops_complete_reconstruct(sh);
1953 blocks = to_addr_page(percpu, j);
1955 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1956 synflags = SYNDROME_SRC_WRITTEN;
1957 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1959 synflags = SYNDROME_SRC_ALL;
1960 txflags = ASYNC_TX_ACK;
1963 count = set_syndrome_sources(blocks, sh, synflags);
1964 last_stripe = !head_sh->batch_head ||
1965 list_first_entry(&sh->batch_list,
1966 struct stripe_head, batch_list) == head_sh;
1969 atomic_inc(&head_sh->count);
1970 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1971 head_sh, to_addr_conv(sh, percpu, j));
1973 init_async_submit(&submit, 0, tx, NULL, NULL,
1974 to_addr_conv(sh, percpu, j));
1975 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1978 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1984 static void ops_complete_check(void *stripe_head_ref)
1986 struct stripe_head *sh = stripe_head_ref;
1988 pr_debug("%s: stripe %llu\n", __func__,
1989 (unsigned long long)sh->sector);
1991 sh->check_state = check_state_check_result;
1992 set_bit(STRIPE_HANDLE, &sh->state);
1993 raid5_release_stripe(sh);
1996 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1998 int disks = sh->disks;
1999 int pd_idx = sh->pd_idx;
2000 int qd_idx = sh->qd_idx;
2001 struct page *xor_dest;
2002 struct page **xor_srcs = to_addr_page(percpu, 0);
2003 struct dma_async_tx_descriptor *tx;
2004 struct async_submit_ctl submit;
2008 pr_debug("%s: stripe %llu\n", __func__,
2009 (unsigned long long)sh->sector);
2011 BUG_ON(sh->batch_head);
2013 xor_dest = sh->dev[pd_idx].page;
2014 xor_srcs[count++] = xor_dest;
2015 for (i = disks; i--; ) {
2016 if (i == pd_idx || i == qd_idx)
2018 xor_srcs[count++] = sh->dev[i].page;
2021 init_async_submit(&submit, 0, NULL, NULL, NULL,
2022 to_addr_conv(sh, percpu, 0));
2023 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
2024 &sh->ops.zero_sum_result, &submit);
2026 atomic_inc(&sh->count);
2027 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2028 tx = async_trigger_callback(&submit);
2031 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2033 struct page **srcs = to_addr_page(percpu, 0);
2034 struct async_submit_ctl submit;
2037 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2038 (unsigned long long)sh->sector, checkp);
2040 BUG_ON(sh->batch_head);
2041 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
2045 atomic_inc(&sh->count);
2046 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2047 sh, to_addr_conv(sh, percpu, 0));
2048 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
2049 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
2052 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2054 int overlap_clear = 0, i, disks = sh->disks;
2055 struct dma_async_tx_descriptor *tx = NULL;
2056 struct r5conf *conf = sh->raid_conf;
2057 int level = conf->level;
2058 struct raid5_percpu *percpu;
2062 percpu = per_cpu_ptr(conf->percpu, cpu);
2063 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2064 ops_run_biofill(sh);
2068 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2070 tx = ops_run_compute5(sh, percpu);
2072 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2073 tx = ops_run_compute6_1(sh, percpu);
2075 tx = ops_run_compute6_2(sh, percpu);
2077 /* terminate the chain if reconstruct is not set to be run */
2078 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2082 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2084 tx = ops_run_prexor5(sh, percpu, tx);
2086 tx = ops_run_prexor6(sh, percpu, tx);
2089 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2090 tx = ops_run_partial_parity(sh, percpu, tx);
2092 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2093 tx = ops_run_biodrain(sh, tx);
2097 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2099 ops_run_reconstruct5(sh, percpu, tx);
2101 ops_run_reconstruct6(sh, percpu, tx);
2104 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2105 if (sh->check_state == check_state_run)
2106 ops_run_check_p(sh, percpu);
2107 else if (sh->check_state == check_state_run_q)
2108 ops_run_check_pq(sh, percpu, 0);
2109 else if (sh->check_state == check_state_run_pq)
2110 ops_run_check_pq(sh, percpu, 1);
2115 if (overlap_clear && !sh->batch_head)
2116 for (i = disks; i--; ) {
2117 struct r5dev *dev = &sh->dev[i];
2118 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2119 wake_up(&sh->raid_conf->wait_for_overlap);
2124 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2127 __free_page(sh->ppl_page);
2128 kmem_cache_free(sc, sh);
2131 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2132 int disks, struct r5conf *conf)
2134 struct stripe_head *sh;
2137 sh = kmem_cache_zalloc(sc, gfp);
2139 spin_lock_init(&sh->stripe_lock);
2140 spin_lock_init(&sh->batch_lock);
2141 INIT_LIST_HEAD(&sh->batch_list);
2142 INIT_LIST_HEAD(&sh->lru);
2143 INIT_LIST_HEAD(&sh->r5c);
2144 INIT_LIST_HEAD(&sh->log_list);
2145 atomic_set(&sh->count, 1);
2146 sh->raid_conf = conf;
2147 sh->log_start = MaxSector;
2148 for (i = 0; i < disks; i++) {
2149 struct r5dev *dev = &sh->dev[i];
2151 bio_init(&dev->req, &dev->vec, 1);
2152 bio_init(&dev->rreq, &dev->rvec, 1);
2155 if (raid5_has_ppl(conf)) {
2156 sh->ppl_page = alloc_page(gfp);
2157 if (!sh->ppl_page) {
2158 free_stripe(sc, sh);
2165 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2167 struct stripe_head *sh;
2169 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2173 if (grow_buffers(sh, gfp)) {
2175 free_stripe(conf->slab_cache, sh);
2178 sh->hash_lock_index =
2179 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2180 /* we just created an active stripe so... */
2181 atomic_inc(&conf->active_stripes);
2183 raid5_release_stripe(sh);
2184 conf->max_nr_stripes++;
2188 static int grow_stripes(struct r5conf *conf, int num)
2190 struct kmem_cache *sc;
2191 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2193 if (conf->mddev->gendisk)
2194 sprintf(conf->cache_name[0],
2195 "raid%d-%s", conf->level, mdname(conf->mddev));
2197 sprintf(conf->cache_name[0],
2198 "raid%d-%p", conf->level, conf->mddev);
2199 sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
2201 conf->active_name = 0;
2202 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2203 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2207 conf->slab_cache = sc;
2208 conf->pool_size = devs;
2210 if (!grow_one_stripe(conf, GFP_KERNEL))
2217 * scribble_len - return the required size of the scribble region
2218 * @num - total number of disks in the array
2220 * The size must be enough to contain:
2221 * 1/ a struct page pointer for each device in the array +2
2222 * 2/ room to convert each entry in (1) to its corresponding dma
2223 * (dma_map_page()) or page (page_address()) address.
2225 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2226 * calculate over all devices (not just the data blocks), using zeros in place
2227 * of the P and Q blocks.
2229 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2231 struct flex_array *ret;
2234 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2235 ret = flex_array_alloc(len, cnt, flags);
2238 /* always prealloc all elements, so no locking is required */
2239 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2240 flex_array_free(ret);
2246 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2252 * Never shrink. And mddev_suspend() could deadlock if this is called
2253 * from raid5d. In that case, scribble_disks and scribble_sectors
2254 * should equal to new_disks and new_sectors
2256 if (conf->scribble_disks >= new_disks &&
2257 conf->scribble_sectors >= new_sectors)
2259 mddev_suspend(conf->mddev);
2261 for_each_present_cpu(cpu) {
2262 struct raid5_percpu *percpu;
2263 struct flex_array *scribble;
2265 percpu = per_cpu_ptr(conf->percpu, cpu);
2266 scribble = scribble_alloc(new_disks,
2267 new_sectors / STRIPE_SECTORS,
2271 flex_array_free(percpu->scribble);
2272 percpu->scribble = scribble;
2279 mddev_resume(conf->mddev);
2281 conf->scribble_disks = new_disks;
2282 conf->scribble_sectors = new_sectors;
2287 static int resize_stripes(struct r5conf *conf, int newsize)
2289 /* Make all the stripes able to hold 'newsize' devices.
2290 * New slots in each stripe get 'page' set to a new page.
2292 * This happens in stages:
2293 * 1/ create a new kmem_cache and allocate the required number of
2295 * 2/ gather all the old stripe_heads and transfer the pages across
2296 * to the new stripe_heads. This will have the side effect of
2297 * freezing the array as once all stripe_heads have been collected,
2298 * no IO will be possible. Old stripe heads are freed once their
2299 * pages have been transferred over, and the old kmem_cache is
2300 * freed when all stripes are done.
2301 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2302 * we simple return a failure status - no need to clean anything up.
2303 * 4/ allocate new pages for the new slots in the new stripe_heads.
2304 * If this fails, we don't bother trying the shrink the
2305 * stripe_heads down again, we just leave them as they are.
2306 * As each stripe_head is processed the new one is released into
2309 * Once step2 is started, we cannot afford to wait for a write,
2310 * so we use GFP_NOIO allocations.
2312 struct stripe_head *osh, *nsh;
2313 LIST_HEAD(newstripes);
2314 struct disk_info *ndisks;
2316 struct kmem_cache *sc;
2320 md_allow_write(conf->mddev);
2323 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2324 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2329 /* Need to ensure auto-resizing doesn't interfere */
2330 mutex_lock(&conf->cache_size_mutex);
2332 for (i = conf->max_nr_stripes; i; i--) {
2333 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2337 list_add(&nsh->lru, &newstripes);
2340 /* didn't get enough, give up */
2341 while (!list_empty(&newstripes)) {
2342 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2343 list_del(&nsh->lru);
2344 free_stripe(sc, nsh);
2346 kmem_cache_destroy(sc);
2347 mutex_unlock(&conf->cache_size_mutex);
2350 /* Step 2 - Must use GFP_NOIO now.
2351 * OK, we have enough stripes, start collecting inactive
2352 * stripes and copying them over
2356 list_for_each_entry(nsh, &newstripes, lru) {
2357 lock_device_hash_lock(conf, hash);
2358 wait_event_cmd(conf->wait_for_stripe,
2359 !list_empty(conf->inactive_list + hash),
2360 unlock_device_hash_lock(conf, hash),
2361 lock_device_hash_lock(conf, hash));
2362 osh = get_free_stripe(conf, hash);
2363 unlock_device_hash_lock(conf, hash);
2365 for(i=0; i<conf->pool_size; i++) {
2366 nsh->dev[i].page = osh->dev[i].page;
2367 nsh->dev[i].orig_page = osh->dev[i].page;
2369 nsh->hash_lock_index = hash;
2370 free_stripe(conf->slab_cache, osh);
2372 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2373 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2378 kmem_cache_destroy(conf->slab_cache);
2381 * At this point, we are holding all the stripes so the array
2382 * is completely stalled, so now is a good time to resize
2383 * conf->disks and the scribble region
2385 ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2387 for (i = 0; i < conf->pool_size; i++)
2388 ndisks[i] = conf->disks[i];
2390 for (i = conf->pool_size; i < newsize; i++) {
2391 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2392 if (!ndisks[i].extra_page)
2397 for (i = conf->pool_size; i < newsize; i++)
2398 if (ndisks[i].extra_page)
2399 put_page(ndisks[i].extra_page);
2403 conf->disks = ndisks;
2408 mutex_unlock(&conf->cache_size_mutex);
2410 conf->slab_cache = sc;
2411 conf->active_name = 1-conf->active_name;
2413 /* Step 4, return new stripes to service */
2414 while(!list_empty(&newstripes)) {
2415 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2416 list_del_init(&nsh->lru);
2418 for (i=conf->raid_disks; i < newsize; i++)
2419 if (nsh->dev[i].page == NULL) {
2420 struct page *p = alloc_page(GFP_NOIO);
2421 nsh->dev[i].page = p;
2422 nsh->dev[i].orig_page = p;
2426 raid5_release_stripe(nsh);
2428 /* critical section pass, GFP_NOIO no longer needed */
2431 conf->pool_size = newsize;
2435 static int drop_one_stripe(struct r5conf *conf)
2437 struct stripe_head *sh;
2438 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2440 spin_lock_irq(conf->hash_locks + hash);
2441 sh = get_free_stripe(conf, hash);
2442 spin_unlock_irq(conf->hash_locks + hash);
2445 BUG_ON(atomic_read(&sh->count));
2447 free_stripe(conf->slab_cache, sh);
2448 atomic_dec(&conf->active_stripes);
2449 conf->max_nr_stripes--;
2453 static void shrink_stripes(struct r5conf *conf)
2455 while (conf->max_nr_stripes &&
2456 drop_one_stripe(conf))
2459 kmem_cache_destroy(conf->slab_cache);
2460 conf->slab_cache = NULL;
2463 static void raid5_end_read_request(struct bio * bi)
2465 struct stripe_head *sh = bi->bi_private;
2466 struct r5conf *conf = sh->raid_conf;
2467 int disks = sh->disks, i;
2468 char b[BDEVNAME_SIZE];
2469 struct md_rdev *rdev = NULL;
2472 for (i=0 ; i<disks; i++)
2473 if (bi == &sh->dev[i].req)
2476 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2477 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2484 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2485 /* If replacement finished while this request was outstanding,
2486 * 'replacement' might be NULL already.
2487 * In that case it moved down to 'rdev'.
2488 * rdev is not removed until all requests are finished.
2490 rdev = conf->disks[i].replacement;
2492 rdev = conf->disks[i].rdev;
2494 if (use_new_offset(conf, sh))
2495 s = sh->sector + rdev->new_data_offset;
2497 s = sh->sector + rdev->data_offset;
2498 if (!bi->bi_status) {
2499 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2500 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2501 /* Note that this cannot happen on a
2502 * replacement device. We just fail those on
2505 pr_info_ratelimited(
2506 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2507 mdname(conf->mddev), STRIPE_SECTORS,
2508 (unsigned long long)s,
2509 bdevname(rdev->bdev, b));
2510 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2511 clear_bit(R5_ReadError, &sh->dev[i].flags);
2512 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2513 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2514 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2516 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2518 * end read for a page in journal, this
2519 * must be preparing for prexor in rmw
2521 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2523 if (atomic_read(&rdev->read_errors))
2524 atomic_set(&rdev->read_errors, 0);
2526 const char *bdn = bdevname(rdev->bdev, b);
2530 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2531 atomic_inc(&rdev->read_errors);
2532 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2533 pr_warn_ratelimited(
2534 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2535 mdname(conf->mddev),
2536 (unsigned long long)s,
2538 else if (conf->mddev->degraded >= conf->max_degraded) {
2540 pr_warn_ratelimited(
2541 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2542 mdname(conf->mddev),
2543 (unsigned long long)s,
2545 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2548 pr_warn_ratelimited(
2549 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2550 mdname(conf->mddev),
2551 (unsigned long long)s,
2553 } else if (atomic_read(&rdev->read_errors)
2554 > conf->max_nr_stripes)
2555 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2556 mdname(conf->mddev), bdn);
2559 if (set_bad && test_bit(In_sync, &rdev->flags)
2560 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2563 if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2564 set_bit(R5_ReadError, &sh->dev[i].flags);
2565 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2567 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2569 clear_bit(R5_ReadError, &sh->dev[i].flags);
2570 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2572 && test_bit(In_sync, &rdev->flags)
2573 && rdev_set_badblocks(
2574 rdev, sh->sector, STRIPE_SECTORS, 0)))
2575 md_error(conf->mddev, rdev);
2578 rdev_dec_pending(rdev, conf->mddev);
2580 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2581 set_bit(STRIPE_HANDLE, &sh->state);
2582 raid5_release_stripe(sh);
2585 static void raid5_end_write_request(struct bio *bi)
2587 struct stripe_head *sh = bi->bi_private;
2588 struct r5conf *conf = sh->raid_conf;
2589 int disks = sh->disks, i;
2590 struct md_rdev *uninitialized_var(rdev);
2593 int replacement = 0;
2595 for (i = 0 ; i < disks; i++) {
2596 if (bi == &sh->dev[i].req) {
2597 rdev = conf->disks[i].rdev;
2600 if (bi == &sh->dev[i].rreq) {
2601 rdev = conf->disks[i].replacement;
2605 /* rdev was removed and 'replacement'
2606 * replaced it. rdev is not removed
2607 * until all requests are finished.
2609 rdev = conf->disks[i].rdev;
2613 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2614 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2624 md_error(conf->mddev, rdev);
2625 else if (is_badblock(rdev, sh->sector,
2627 &first_bad, &bad_sectors))
2628 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2630 if (bi->bi_status) {
2631 set_bit(STRIPE_DEGRADED, &sh->state);
2632 set_bit(WriteErrorSeen, &rdev->flags);
2633 set_bit(R5_WriteError, &sh->dev[i].flags);
2634 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2635 set_bit(MD_RECOVERY_NEEDED,
2636 &rdev->mddev->recovery);
2637 } else if (is_badblock(rdev, sh->sector,
2639 &first_bad, &bad_sectors)) {
2640 set_bit(R5_MadeGood, &sh->dev[i].flags);
2641 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2642 /* That was a successful write so make
2643 * sure it looks like we already did
2646 set_bit(R5_ReWrite, &sh->dev[i].flags);
2649 rdev_dec_pending(rdev, conf->mddev);
2651 if (sh->batch_head && bi->bi_status && !replacement)
2652 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2655 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2656 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2657 set_bit(STRIPE_HANDLE, &sh->state);
2658 raid5_release_stripe(sh);
2660 if (sh->batch_head && sh != sh->batch_head)
2661 raid5_release_stripe(sh->batch_head);
2664 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2666 char b[BDEVNAME_SIZE];
2667 struct r5conf *conf = mddev->private;
2668 unsigned long flags;
2669 pr_debug("raid456: error called\n");
2671 spin_lock_irqsave(&conf->device_lock, flags);
2672 clear_bit(In_sync, &rdev->flags);
2673 mddev->degraded = raid5_calc_degraded(conf);
2674 spin_unlock_irqrestore(&conf->device_lock, flags);
2675 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2677 set_bit(Blocked, &rdev->flags);
2678 set_bit(Faulty, &rdev->flags);
2679 set_mask_bits(&mddev->sb_flags, 0,
2680 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2681 pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n"
2682 "md/raid:%s: Operation continuing on %d devices.\n",
2684 bdevname(rdev->bdev, b),
2686 conf->raid_disks - mddev->degraded);
2687 r5c_update_on_rdev_error(mddev, rdev);
2691 * Input: a 'big' sector number,
2692 * Output: index of the data and parity disk, and the sector # in them.
2694 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2695 int previous, int *dd_idx,
2696 struct stripe_head *sh)
2698 sector_t stripe, stripe2;
2699 sector_t chunk_number;
2700 unsigned int chunk_offset;
2703 sector_t new_sector;
2704 int algorithm = previous ? conf->prev_algo
2706 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2707 : conf->chunk_sectors;
2708 int raid_disks = previous ? conf->previous_raid_disks
2710 int data_disks = raid_disks - conf->max_degraded;
2712 /* First compute the information on this sector */
2715 * Compute the chunk number and the sector offset inside the chunk
2717 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2718 chunk_number = r_sector;
2721 * Compute the stripe number
2723 stripe = chunk_number;
2724 *dd_idx = sector_div(stripe, data_disks);
2727 * Select the parity disk based on the user selected algorithm.
2729 pd_idx = qd_idx = -1;
2730 switch(conf->level) {
2732 pd_idx = data_disks;
2735 switch (algorithm) {
2736 case ALGORITHM_LEFT_ASYMMETRIC:
2737 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2738 if (*dd_idx >= pd_idx)
2741 case ALGORITHM_RIGHT_ASYMMETRIC:
2742 pd_idx = sector_div(stripe2, raid_disks);
2743 if (*dd_idx >= pd_idx)
2746 case ALGORITHM_LEFT_SYMMETRIC:
2747 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2748 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2750 case ALGORITHM_RIGHT_SYMMETRIC:
2751 pd_idx = sector_div(stripe2, raid_disks);
2752 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2754 case ALGORITHM_PARITY_0:
2758 case ALGORITHM_PARITY_N:
2759 pd_idx = data_disks;
2767 switch (algorithm) {
2768 case ALGORITHM_LEFT_ASYMMETRIC:
2769 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2770 qd_idx = pd_idx + 1;
2771 if (pd_idx == raid_disks-1) {
2772 (*dd_idx)++; /* Q D D D P */
2774 } else if (*dd_idx >= pd_idx)
2775 (*dd_idx) += 2; /* D D P Q D */
2777 case ALGORITHM_RIGHT_ASYMMETRIC:
2778 pd_idx = sector_div(stripe2, raid_disks);
2779 qd_idx = pd_idx + 1;
2780 if (pd_idx == raid_disks-1) {
2781 (*dd_idx)++; /* Q D D D P */
2783 } else if (*dd_idx >= pd_idx)
2784 (*dd_idx) += 2; /* D D P Q D */
2786 case ALGORITHM_LEFT_SYMMETRIC:
2787 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2788 qd_idx = (pd_idx + 1) % raid_disks;
2789 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2791 case ALGORITHM_RIGHT_SYMMETRIC:
2792 pd_idx = sector_div(stripe2, raid_disks);
2793 qd_idx = (pd_idx + 1) % raid_disks;
2794 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2797 case ALGORITHM_PARITY_0:
2802 case ALGORITHM_PARITY_N:
2803 pd_idx = data_disks;
2804 qd_idx = data_disks + 1;
2807 case ALGORITHM_ROTATING_ZERO_RESTART:
2808 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2809 * of blocks for computing Q is different.
2811 pd_idx = sector_div(stripe2, raid_disks);
2812 qd_idx = pd_idx + 1;
2813 if (pd_idx == raid_disks-1) {
2814 (*dd_idx)++; /* Q D D D P */
2816 } else if (*dd_idx >= pd_idx)
2817 (*dd_idx) += 2; /* D D P Q D */
2821 case ALGORITHM_ROTATING_N_RESTART:
2822 /* Same a left_asymmetric, by first stripe is
2823 * D D D P Q rather than
2827 pd_idx = raid_disks - 1 - 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_CONTINUE:
2838 /* Same as left_symmetric but Q is before P */
2839 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2840 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2841 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2845 case ALGORITHM_LEFT_ASYMMETRIC_6:
2846 /* RAID5 left_asymmetric, with Q on last device */
2847 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2848 if (*dd_idx >= pd_idx)
2850 qd_idx = raid_disks - 1;
2853 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2854 pd_idx = sector_div(stripe2, raid_disks-1);
2855 if (*dd_idx >= pd_idx)
2857 qd_idx = raid_disks - 1;
2860 case ALGORITHM_LEFT_SYMMETRIC_6:
2861 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2862 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2863 qd_idx = raid_disks - 1;
2866 case ALGORITHM_RIGHT_SYMMETRIC_6:
2867 pd_idx = sector_div(stripe2, raid_disks-1);
2868 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2869 qd_idx = raid_disks - 1;
2872 case ALGORITHM_PARITY_0_6:
2875 qd_idx = raid_disks - 1;
2885 sh->pd_idx = pd_idx;
2886 sh->qd_idx = qd_idx;
2887 sh->ddf_layout = ddf_layout;
2890 * Finally, compute the new sector number
2892 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2896 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2898 struct r5conf *conf = sh->raid_conf;
2899 int raid_disks = sh->disks;
2900 int data_disks = raid_disks - conf->max_degraded;
2901 sector_t new_sector = sh->sector, check;
2902 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2903 : conf->chunk_sectors;
2904 int algorithm = previous ? conf->prev_algo
2908 sector_t chunk_number;
2909 int dummy1, dd_idx = i;
2911 struct stripe_head sh2;
2913 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2914 stripe = new_sector;
2916 if (i == sh->pd_idx)
2918 switch(conf->level) {
2921 switch (algorithm) {
2922 case ALGORITHM_LEFT_ASYMMETRIC:
2923 case ALGORITHM_RIGHT_ASYMMETRIC:
2927 case ALGORITHM_LEFT_SYMMETRIC:
2928 case ALGORITHM_RIGHT_SYMMETRIC:
2931 i -= (sh->pd_idx + 1);
2933 case ALGORITHM_PARITY_0:
2936 case ALGORITHM_PARITY_N:
2943 if (i == sh->qd_idx)
2944 return 0; /* It is the Q disk */
2945 switch (algorithm) {
2946 case ALGORITHM_LEFT_ASYMMETRIC:
2947 case ALGORITHM_RIGHT_ASYMMETRIC:
2948 case ALGORITHM_ROTATING_ZERO_RESTART:
2949 case ALGORITHM_ROTATING_N_RESTART:
2950 if (sh->pd_idx == raid_disks-1)
2951 i--; /* Q D D D P */
2952 else if (i > sh->pd_idx)
2953 i -= 2; /* D D P Q D */
2955 case ALGORITHM_LEFT_SYMMETRIC:
2956 case ALGORITHM_RIGHT_SYMMETRIC:
2957 if (sh->pd_idx == raid_disks-1)
2958 i--; /* Q D D D P */
2963 i -= (sh->pd_idx + 2);
2966 case ALGORITHM_PARITY_0:
2969 case ALGORITHM_PARITY_N:
2971 case ALGORITHM_ROTATING_N_CONTINUE:
2972 /* Like left_symmetric, but P is before Q */
2973 if (sh->pd_idx == 0)
2974 i--; /* P D D D Q */
2979 i -= (sh->pd_idx + 1);
2982 case ALGORITHM_LEFT_ASYMMETRIC_6:
2983 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2987 case ALGORITHM_LEFT_SYMMETRIC_6:
2988 case ALGORITHM_RIGHT_SYMMETRIC_6:
2990 i += data_disks + 1;
2991 i -= (sh->pd_idx + 1);
2993 case ALGORITHM_PARITY_0_6:
3002 chunk_number = stripe * data_disks + i;
3003 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3005 check = raid5_compute_sector(conf, r_sector,
3006 previous, &dummy1, &sh2);
3007 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3008 || sh2.qd_idx != sh->qd_idx) {
3009 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3010 mdname(conf->mddev));
3017 * There are cases where we want handle_stripe_dirtying() and
3018 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3020 * This function checks whether we want to delay the towrite. Specifically,
3021 * we delay the towrite when:
3023 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3024 * stripe has data in journal (for other devices).
3026 * In this case, when reading data for the non-overwrite dev, it is
3027 * necessary to handle complex rmw of write back cache (prexor with
3028 * orig_page, and xor with page). To keep read path simple, we would
3029 * like to flush data in journal to RAID disks first, so complex rmw
3030 * is handled in the write patch (handle_stripe_dirtying).
3032 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3034 * It is important to be able to flush all stripes in raid5-cache.
3035 * Therefore, we need reserve some space on the journal device for
3036 * these flushes. If flush operation includes pending writes to the
3037 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3038 * for the flush out. If we exclude these pending writes from flush
3039 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3040 * Therefore, excluding pending writes in these cases enables more
3041 * efficient use of the journal device.
3043 * Note: To make sure the stripe makes progress, we only delay
3044 * towrite for stripes with data already in journal (injournal > 0).
3045 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3046 * no_space_stripes list.
3048 * 3. during journal failure
3049 * In journal failure, we try to flush all cached data to raid disks
3050 * based on data in stripe cache. The array is read-only to upper
3051 * layers, so we would skip all pending writes.
3054 static inline bool delay_towrite(struct r5conf *conf,
3056 struct stripe_head_state *s)
3059 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3060 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3063 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3067 if (s->log_failed && s->injournal)
3073 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3074 int rcw, int expand)
3076 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3077 struct r5conf *conf = sh->raid_conf;
3078 int level = conf->level;
3082 * In some cases, handle_stripe_dirtying initially decided to
3083 * run rmw and allocates extra page for prexor. However, rcw is
3084 * cheaper later on. We need to free the extra page now,
3085 * because we won't be able to do that in ops_complete_prexor().
3087 r5c_release_extra_page(sh);
3089 for (i = disks; i--; ) {
3090 struct r5dev *dev = &sh->dev[i];
3092 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3093 set_bit(R5_LOCKED, &dev->flags);
3094 set_bit(R5_Wantdrain, &dev->flags);
3096 clear_bit(R5_UPTODATE, &dev->flags);
3098 } else if (test_bit(R5_InJournal, &dev->flags)) {
3099 set_bit(R5_LOCKED, &dev->flags);
3103 /* if we are not expanding this is a proper write request, and
3104 * there will be bios with new data to be drained into the
3109 /* False alarm, nothing to do */
3111 sh->reconstruct_state = reconstruct_state_drain_run;
3112 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3114 sh->reconstruct_state = reconstruct_state_run;
3116 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3118 if (s->locked + conf->max_degraded == disks)
3119 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3120 atomic_inc(&conf->pending_full_writes);
3122 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3123 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3124 BUG_ON(level == 6 &&
3125 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3126 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3128 for (i = disks; i--; ) {
3129 struct r5dev *dev = &sh->dev[i];
3130 if (i == pd_idx || i == qd_idx)
3134 (test_bit(R5_UPTODATE, &dev->flags) ||
3135 test_bit(R5_Wantcompute, &dev->flags))) {
3136 set_bit(R5_Wantdrain, &dev->flags);
3137 set_bit(R5_LOCKED, &dev->flags);
3138 clear_bit(R5_UPTODATE, &dev->flags);
3140 } else if (test_bit(R5_InJournal, &dev->flags)) {
3141 set_bit(R5_LOCKED, &dev->flags);
3146 /* False alarm - nothing to do */
3148 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3149 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3150 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3151 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3154 /* keep the parity disk(s) locked while asynchronous operations
3157 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3158 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3162 int qd_idx = sh->qd_idx;
3163 struct r5dev *dev = &sh->dev[qd_idx];
3165 set_bit(R5_LOCKED, &dev->flags);
3166 clear_bit(R5_UPTODATE, &dev->flags);
3170 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3171 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3172 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3173 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3174 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3176 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3177 __func__, (unsigned long long)sh->sector,
3178 s->locked, s->ops_request);
3182 * Each stripe/dev can have one or more bion attached.
3183 * toread/towrite point to the first in a chain.
3184 * The bi_next chain must be in order.
3186 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3187 int forwrite, int previous)
3190 struct r5conf *conf = sh->raid_conf;
3193 pr_debug("adding bi b#%llu to stripe s#%llu\n",
3194 (unsigned long long)bi->bi_iter.bi_sector,
3195 (unsigned long long)sh->sector);
3197 spin_lock_irq(&sh->stripe_lock);
3198 /* Don't allow new IO added to stripes in batch list */
3202 bip = &sh->dev[dd_idx].towrite;
3206 bip = &sh->dev[dd_idx].toread;
3207 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3208 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3210 bip = & (*bip)->bi_next;
3212 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3215 if (forwrite && raid5_has_ppl(conf)) {
3217 * With PPL only writes to consecutive data chunks within a
3218 * stripe are allowed because for a single stripe_head we can
3219 * only have one PPL entry at a time, which describes one data
3220 * range. Not really an overlap, but wait_for_overlap can be
3221 * used to handle this.
3229 for (i = 0; i < sh->disks; i++) {
3230 if (i != sh->pd_idx &&
3231 (i == dd_idx || sh->dev[i].towrite)) {
3232 sector = sh->dev[i].sector;
3233 if (count == 0 || sector < first)
3241 if (first + conf->chunk_sectors * (count - 1) != last)
3245 if (!forwrite || previous)
3246 clear_bit(STRIPE_BATCH_READY, &sh->state);
3248 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3252 bio_inc_remaining(bi);
3253 md_write_inc(conf->mddev, bi);
3256 /* check if page is covered */
3257 sector_t sector = sh->dev[dd_idx].sector;
3258 for (bi=sh->dev[dd_idx].towrite;
3259 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3260 bi && bi->bi_iter.bi_sector <= sector;
3261 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3262 if (bio_end_sector(bi) >= sector)
3263 sector = bio_end_sector(bi);
3265 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3266 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3267 sh->overwrite_disks++;
3270 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3271 (unsigned long long)(*bip)->bi_iter.bi_sector,
3272 (unsigned long long)sh->sector, dd_idx);
3274 if (conf->mddev->bitmap && firstwrite) {
3275 /* Cannot hold spinlock over bitmap_startwrite,
3276 * but must ensure this isn't added to a batch until
3277 * we have added to the bitmap and set bm_seq.
3278 * So set STRIPE_BITMAP_PENDING to prevent
3280 * If multiple add_stripe_bio() calls race here they
3281 * much all set STRIPE_BITMAP_PENDING. So only the first one
3282 * to complete "bitmap_startwrite" gets to set
3283 * STRIPE_BIT_DELAY. This is important as once a stripe
3284 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3287 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3288 spin_unlock_irq(&sh->stripe_lock);
3289 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3291 spin_lock_irq(&sh->stripe_lock);
3292 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3293 if (!sh->batch_head) {
3294 sh->bm_seq = conf->seq_flush+1;
3295 set_bit(STRIPE_BIT_DELAY, &sh->state);
3298 spin_unlock_irq(&sh->stripe_lock);
3300 if (stripe_can_batch(sh))
3301 stripe_add_to_batch_list(conf, sh);
3305 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3306 spin_unlock_irq(&sh->stripe_lock);
3310 static void end_reshape(struct r5conf *conf);
3312 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3313 struct stripe_head *sh)
3315 int sectors_per_chunk =
3316 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3318 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3319 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3321 raid5_compute_sector(conf,
3322 stripe * (disks - conf->max_degraded)
3323 *sectors_per_chunk + chunk_offset,
3329 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3330 struct stripe_head_state *s, int disks)
3333 BUG_ON(sh->batch_head);
3334 for (i = disks; i--; ) {
3338 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3339 struct md_rdev *rdev;
3341 rdev = rcu_dereference(conf->disks[i].rdev);
3342 if (rdev && test_bit(In_sync, &rdev->flags) &&
3343 !test_bit(Faulty, &rdev->flags))
3344 atomic_inc(&rdev->nr_pending);
3349 if (!rdev_set_badblocks(
3353 md_error(conf->mddev, rdev);
3354 rdev_dec_pending(rdev, conf->mddev);
3357 spin_lock_irq(&sh->stripe_lock);
3358 /* fail all writes first */
3359 bi = sh->dev[i].towrite;
3360 sh->dev[i].towrite = NULL;
3361 sh->overwrite_disks = 0;
3362 spin_unlock_irq(&sh->stripe_lock);
3366 log_stripe_write_finished(sh);
3368 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3369 wake_up(&conf->wait_for_overlap);
3371 while (bi && bi->bi_iter.bi_sector <
3372 sh->dev[i].sector + STRIPE_SECTORS) {
3373 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3375 md_write_end(conf->mddev);
3380 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3381 STRIPE_SECTORS, 0, 0);
3383 /* and fail all 'written' */
3384 bi = sh->dev[i].written;
3385 sh->dev[i].written = NULL;
3386 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3387 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3388 sh->dev[i].page = sh->dev[i].orig_page;
3391 if (bi) bitmap_end = 1;
3392 while (bi && bi->bi_iter.bi_sector <
3393 sh->dev[i].sector + STRIPE_SECTORS) {
3394 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3396 md_write_end(conf->mddev);
3401 /* fail any reads if this device is non-operational and
3402 * the data has not reached the cache yet.
3404 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3405 s->failed > conf->max_degraded &&
3406 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3407 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3408 spin_lock_irq(&sh->stripe_lock);
3409 bi = sh->dev[i].toread;
3410 sh->dev[i].toread = NULL;
3411 spin_unlock_irq(&sh->stripe_lock);
3412 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3413 wake_up(&conf->wait_for_overlap);
3416 while (bi && bi->bi_iter.bi_sector <
3417 sh->dev[i].sector + STRIPE_SECTORS) {
3418 struct bio *nextbi =
3419 r5_next_bio(bi, sh->dev[i].sector);
3426 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3427 STRIPE_SECTORS, 0, 0);
3428 /* If we were in the middle of a write the parity block might
3429 * still be locked - so just clear all R5_LOCKED flags
3431 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3436 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3437 if (atomic_dec_and_test(&conf->pending_full_writes))
3438 md_wakeup_thread(conf->mddev->thread);
3442 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3443 struct stripe_head_state *s)
3448 BUG_ON(sh->batch_head);
3449 clear_bit(STRIPE_SYNCING, &sh->state);
3450 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3451 wake_up(&conf->wait_for_overlap);
3454 /* There is nothing more to do for sync/check/repair.
3455 * Don't even need to abort as that is handled elsewhere
3456 * if needed, and not always wanted e.g. if there is a known
3458 * For recover/replace we need to record a bad block on all
3459 * non-sync devices, or abort the recovery
3461 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3462 /* During recovery devices cannot be removed, so
3463 * locking and refcounting of rdevs is not needed
3466 for (i = 0; i < conf->raid_disks; i++) {
3467 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3469 && !test_bit(Faulty, &rdev->flags)
3470 && !test_bit(In_sync, &rdev->flags)
3471 && !rdev_set_badblocks(rdev, sh->sector,
3474 rdev = rcu_dereference(conf->disks[i].replacement);
3476 && !test_bit(Faulty, &rdev->flags)
3477 && !test_bit(In_sync, &rdev->flags)
3478 && !rdev_set_badblocks(rdev, sh->sector,
3484 conf->recovery_disabled =
3485 conf->mddev->recovery_disabled;
3487 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3490 static int want_replace(struct stripe_head *sh, int disk_idx)
3492 struct md_rdev *rdev;
3496 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3498 && !test_bit(Faulty, &rdev->flags)
3499 && !test_bit(In_sync, &rdev->flags)
3500 && (rdev->recovery_offset <= sh->sector
3501 || rdev->mddev->recovery_cp <= sh->sector))
3507 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3508 int disk_idx, int disks)
3510 struct r5dev *dev = &sh->dev[disk_idx];
3511 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3512 &sh->dev[s->failed_num[1]] };
3516 if (test_bit(R5_LOCKED, &dev->flags) ||
3517 test_bit(R5_UPTODATE, &dev->flags))
3518 /* No point reading this as we already have it or have
3519 * decided to get it.
3524 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3525 /* We need this block to directly satisfy a request */
3528 if (s->syncing || s->expanding ||
3529 (s->replacing && want_replace(sh, disk_idx)))
3530 /* When syncing, or expanding we read everything.
3531 * When replacing, we need the replaced block.
3535 if ((s->failed >= 1 && fdev[0]->toread) ||
3536 (s->failed >= 2 && fdev[1]->toread))
3537 /* If we want to read from a failed device, then
3538 * we need to actually read every other device.
3542 /* Sometimes neither read-modify-write nor reconstruct-write
3543 * cycles can work. In those cases we read every block we
3544 * can. Then the parity-update is certain to have enough to
3546 * This can only be a problem when we need to write something,
3547 * and some device has failed. If either of those tests
3548 * fail we need look no further.
3550 if (!s->failed || !s->to_write)
3553 if (test_bit(R5_Insync, &dev->flags) &&
3554 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3555 /* Pre-reads at not permitted until after short delay
3556 * to gather multiple requests. However if this
3557 * device is no Insync, the block could only be computed
3558 * and there is no need to delay that.
3562 for (i = 0; i < s->failed && i < 2; i++) {
3563 if (fdev[i]->towrite &&
3564 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3565 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3566 /* If we have a partial write to a failed
3567 * device, then we will need to reconstruct
3568 * the content of that device, so all other
3569 * devices must be read.
3574 /* If we are forced to do a reconstruct-write, either because
3575 * the current RAID6 implementation only supports that, or
3576 * because parity cannot be trusted and we are currently
3577 * recovering it, there is extra need to be careful.
3578 * If one of the devices that we would need to read, because
3579 * it is not being overwritten (and maybe not written at all)
3580 * is missing/faulty, then we need to read everything we can.
3582 if (sh->raid_conf->level != 6 &&
3583 sh->sector < sh->raid_conf->mddev->recovery_cp)
3584 /* reconstruct-write isn't being forced */
3586 for (i = 0; i < s->failed && i < 2; i++) {
3587 if (s->failed_num[i] != sh->pd_idx &&
3588 s->failed_num[i] != sh->qd_idx &&
3589 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3590 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3597 /* fetch_block - checks the given member device to see if its data needs
3598 * to be read or computed to satisfy a request.
3600 * Returns 1 when no more member devices need to be checked, otherwise returns
3601 * 0 to tell the loop in handle_stripe_fill to continue
3603 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3604 int disk_idx, int disks)
3606 struct r5dev *dev = &sh->dev[disk_idx];
3608 /* is the data in this block needed, and can we get it? */
3609 if (need_this_block(sh, s, disk_idx, disks)) {
3610 /* we would like to get this block, possibly by computing it,
3611 * otherwise read it if the backing disk is insync
3613 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3614 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3615 BUG_ON(sh->batch_head);
3618 * In the raid6 case if the only non-uptodate disk is P
3619 * then we already trusted P to compute the other failed
3620 * drives. It is safe to compute rather than re-read P.
3621 * In other cases we only compute blocks from failed
3622 * devices, otherwise check/repair might fail to detect
3623 * a real inconsistency.
3626 if ((s->uptodate == disks - 1) &&
3627 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3628 (s->failed && (disk_idx == s->failed_num[0] ||
3629 disk_idx == s->failed_num[1])))) {
3630 /* have disk failed, and we're requested to fetch it;
3633 pr_debug("Computing stripe %llu block %d\n",
3634 (unsigned long long)sh->sector, disk_idx);
3635 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3636 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3637 set_bit(R5_Wantcompute, &dev->flags);
3638 sh->ops.target = disk_idx;
3639 sh->ops.target2 = -1; /* no 2nd target */
3641 /* Careful: from this point on 'uptodate' is in the eye
3642 * of raid_run_ops which services 'compute' operations
3643 * before writes. R5_Wantcompute flags a block that will
3644 * be R5_UPTODATE by the time it is needed for a
3645 * subsequent operation.
3649 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3650 /* Computing 2-failure is *very* expensive; only
3651 * do it if failed >= 2
3654 for (other = disks; other--; ) {
3655 if (other == disk_idx)
3657 if (!test_bit(R5_UPTODATE,
3658 &sh->dev[other].flags))
3662 pr_debug("Computing stripe %llu blocks %d,%d\n",
3663 (unsigned long long)sh->sector,
3665 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3666 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3667 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3668 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3669 sh->ops.target = disk_idx;
3670 sh->ops.target2 = other;
3674 } else if (test_bit(R5_Insync, &dev->flags)) {
3675 set_bit(R5_LOCKED, &dev->flags);
3676 set_bit(R5_Wantread, &dev->flags);
3678 pr_debug("Reading block %d (sync=%d)\n",
3679 disk_idx, s->syncing);
3687 * handle_stripe_fill - read or compute data to satisfy pending requests.
3689 static void handle_stripe_fill(struct stripe_head *sh,
3690 struct stripe_head_state *s,
3695 /* look for blocks to read/compute, skip this if a compute
3696 * is already in flight, or if the stripe contents are in the
3697 * midst of changing due to a write
3699 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3700 !sh->reconstruct_state) {
3703 * For degraded stripe with data in journal, do not handle
3704 * read requests yet, instead, flush the stripe to raid
3705 * disks first, this avoids handling complex rmw of write
3706 * back cache (prexor with orig_page, and then xor with
3707 * page) in the read path
3709 if (s->injournal && s->failed) {
3710 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3711 r5c_make_stripe_write_out(sh);
3715 for (i = disks; i--; )
3716 if (fetch_block(sh, s, i, disks))
3720 set_bit(STRIPE_HANDLE, &sh->state);
3723 static void break_stripe_batch_list(struct stripe_head *head_sh,
3724 unsigned long handle_flags);
3725 /* handle_stripe_clean_event
3726 * any written block on an uptodate or failed drive can be returned.
3727 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3728 * never LOCKED, so we don't need to test 'failed' directly.
3730 static void handle_stripe_clean_event(struct r5conf *conf,
3731 struct stripe_head *sh, int disks)
3735 int discard_pending = 0;
3736 struct stripe_head *head_sh = sh;
3737 bool do_endio = false;
3739 for (i = disks; i--; )
3740 if (sh->dev[i].written) {
3742 if (!test_bit(R5_LOCKED, &dev->flags) &&
3743 (test_bit(R5_UPTODATE, &dev->flags) ||
3744 test_bit(R5_Discard, &dev->flags) ||
3745 test_bit(R5_SkipCopy, &dev->flags))) {
3746 /* We can return any write requests */
3747 struct bio *wbi, *wbi2;
3748 pr_debug("Return write for disc %d\n", i);
3749 if (test_and_clear_bit(R5_Discard, &dev->flags))
3750 clear_bit(R5_UPTODATE, &dev->flags);
3751 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3752 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3757 dev->page = dev->orig_page;
3759 dev->written = NULL;
3760 while (wbi && wbi->bi_iter.bi_sector <
3761 dev->sector + STRIPE_SECTORS) {
3762 wbi2 = r5_next_bio(wbi, dev->sector);
3763 md_write_end(conf->mddev);
3767 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3769 !test_bit(STRIPE_DEGRADED, &sh->state),
3771 if (head_sh->batch_head) {
3772 sh = list_first_entry(&sh->batch_list,
3775 if (sh != head_sh) {
3782 } else if (test_bit(R5_Discard, &dev->flags))
3783 discard_pending = 1;
3786 log_stripe_write_finished(sh);
3788 if (!discard_pending &&
3789 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3791 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3792 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3793 if (sh->qd_idx >= 0) {
3794 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3795 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3797 /* now that discard is done we can proceed with any sync */
3798 clear_bit(STRIPE_DISCARD, &sh->state);
3800 * SCSI discard will change some bio fields and the stripe has
3801 * no updated data, so remove it from hash list and the stripe
3802 * will be reinitialized
3805 hash = sh->hash_lock_index;
3806 spin_lock_irq(conf->hash_locks + hash);
3808 spin_unlock_irq(conf->hash_locks + hash);
3809 if (head_sh->batch_head) {
3810 sh = list_first_entry(&sh->batch_list,
3811 struct stripe_head, batch_list);
3817 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3818 set_bit(STRIPE_HANDLE, &sh->state);
3822 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3823 if (atomic_dec_and_test(&conf->pending_full_writes))
3824 md_wakeup_thread(conf->mddev->thread);
3826 if (head_sh->batch_head && do_endio)
3827 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3831 * For RMW in write back cache, we need extra page in prexor to store the
3832 * old data. This page is stored in dev->orig_page.
3834 * This function checks whether we have data for prexor. The exact logic
3836 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
3838 static inline bool uptodate_for_rmw(struct r5dev *dev)
3840 return (test_bit(R5_UPTODATE, &dev->flags)) &&
3841 (!test_bit(R5_InJournal, &dev->flags) ||
3842 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
3845 static int handle_stripe_dirtying(struct r5conf *conf,
3846 struct stripe_head *sh,
3847 struct stripe_head_state *s,
3850 int rmw = 0, rcw = 0, i;
3851 sector_t recovery_cp = conf->mddev->recovery_cp;
3853 /* Check whether resync is now happening or should start.
3854 * If yes, then the array is dirty (after unclean shutdown or
3855 * initial creation), so parity in some stripes might be inconsistent.
3856 * In this case, we need to always do reconstruct-write, to ensure
3857 * that in case of drive failure or read-error correction, we
3858 * generate correct data from the parity.
3860 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3861 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3863 /* Calculate the real rcw later - for now make it
3864 * look like rcw is cheaper
3867 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3868 conf->rmw_level, (unsigned long long)recovery_cp,
3869 (unsigned long long)sh->sector);
3870 } else for (i = disks; i--; ) {
3871 /* would I have to read this buffer for read_modify_write */
3872 struct r5dev *dev = &sh->dev[i];
3873 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3874 i == sh->pd_idx || i == sh->qd_idx ||
3875 test_bit(R5_InJournal, &dev->flags)) &&
3876 !test_bit(R5_LOCKED, &dev->flags) &&
3877 !(uptodate_for_rmw(dev) ||
3878 test_bit(R5_Wantcompute, &dev->flags))) {
3879 if (test_bit(R5_Insync, &dev->flags))
3882 rmw += 2*disks; /* cannot read it */
3884 /* Would I have to read this buffer for reconstruct_write */
3885 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3886 i != sh->pd_idx && i != sh->qd_idx &&
3887 !test_bit(R5_LOCKED, &dev->flags) &&
3888 !(test_bit(R5_UPTODATE, &dev->flags) ||
3889 test_bit(R5_Wantcompute, &dev->flags))) {
3890 if (test_bit(R5_Insync, &dev->flags))
3897 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
3898 (unsigned long long)sh->sector, sh->state, rmw, rcw);
3899 set_bit(STRIPE_HANDLE, &sh->state);
3900 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
3901 /* prefer read-modify-write, but need to get some data */
3902 if (conf->mddev->queue)
3903 blk_add_trace_msg(conf->mddev->queue,
3904 "raid5 rmw %llu %d",
3905 (unsigned long long)sh->sector, rmw);
3906 for (i = disks; i--; ) {
3907 struct r5dev *dev = &sh->dev[i];
3908 if (test_bit(R5_InJournal, &dev->flags) &&
3909 dev->page == dev->orig_page &&
3910 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
3911 /* alloc page for prexor */
3912 struct page *p = alloc_page(GFP_NOIO);
3920 * alloc_page() failed, try use
3921 * disk_info->extra_page
3923 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
3924 &conf->cache_state)) {
3925 r5c_use_extra_page(sh);
3929 /* extra_page in use, add to delayed_list */
3930 set_bit(STRIPE_DELAYED, &sh->state);
3931 s->waiting_extra_page = 1;
3936 for (i = disks; i--; ) {
3937 struct r5dev *dev = &sh->dev[i];
3938 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
3939 i == sh->pd_idx || i == sh->qd_idx ||
3940 test_bit(R5_InJournal, &dev->flags)) &&
3941 !test_bit(R5_LOCKED, &dev->flags) &&
3942 !(uptodate_for_rmw(dev) ||
3943 test_bit(R5_Wantcompute, &dev->flags)) &&
3944 test_bit(R5_Insync, &dev->flags)) {
3945 if (test_bit(STRIPE_PREREAD_ACTIVE,
3947 pr_debug("Read_old block %d for r-m-w\n",
3949 set_bit(R5_LOCKED, &dev->flags);
3950 set_bit(R5_Wantread, &dev->flags);
3953 set_bit(STRIPE_DELAYED, &sh->state);
3954 set_bit(STRIPE_HANDLE, &sh->state);
3959 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
3960 /* want reconstruct write, but need to get some data */
3963 for (i = disks; i--; ) {
3964 struct r5dev *dev = &sh->dev[i];
3965 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3966 i != sh->pd_idx && i != sh->qd_idx &&
3967 !test_bit(R5_LOCKED, &dev->flags) &&
3968 !(test_bit(R5_UPTODATE, &dev->flags) ||
3969 test_bit(R5_Wantcompute, &dev->flags))) {
3971 if (test_bit(R5_Insync, &dev->flags) &&
3972 test_bit(STRIPE_PREREAD_ACTIVE,
3974 pr_debug("Read_old block "
3975 "%d for Reconstruct\n", i);
3976 set_bit(R5_LOCKED, &dev->flags);
3977 set_bit(R5_Wantread, &dev->flags);
3981 set_bit(STRIPE_DELAYED, &sh->state);
3982 set_bit(STRIPE_HANDLE, &sh->state);
3986 if (rcw && conf->mddev->queue)
3987 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
3988 (unsigned long long)sh->sector,
3989 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
3992 if (rcw > disks && rmw > disks &&
3993 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3994 set_bit(STRIPE_DELAYED, &sh->state);
3996 /* now if nothing is locked, and if we have enough data,
3997 * we can start a write request
3999 /* since handle_stripe can be called at any time we need to handle the
4000 * case where a compute block operation has been submitted and then a
4001 * subsequent call wants to start a write request. raid_run_ops only
4002 * handles the case where compute block and reconstruct are requested
4003 * simultaneously. If this is not the case then new writes need to be
4004 * held off until the compute completes.
4006 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4007 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4008 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4009 schedule_reconstruction(sh, s, rcw == 0, 0);
4013 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4014 struct stripe_head_state *s, int disks)
4016 struct r5dev *dev = NULL;
4018 BUG_ON(sh->batch_head);
4019 set_bit(STRIPE_HANDLE, &sh->state);
4021 switch (sh->check_state) {
4022 case check_state_idle:
4023 /* start a new check operation if there are no failures */
4024 if (s->failed == 0) {
4025 BUG_ON(s->uptodate != disks);
4026 sh->check_state = check_state_run;
4027 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4028 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4032 dev = &sh->dev[s->failed_num[0]];
4034 case check_state_compute_result:
4035 sh->check_state = check_state_idle;
4037 dev = &sh->dev[sh->pd_idx];
4039 /* check that a write has not made the stripe insync */
4040 if (test_bit(STRIPE_INSYNC, &sh->state))
4043 /* either failed parity check, or recovery is happening */
4044 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4045 BUG_ON(s->uptodate != disks);
4047 set_bit(R5_LOCKED, &dev->flags);
4049 set_bit(R5_Wantwrite, &dev->flags);
4051 clear_bit(STRIPE_DEGRADED, &sh->state);
4052 set_bit(STRIPE_INSYNC, &sh->state);
4054 case check_state_run:
4055 break; /* we will be called again upon completion */
4056 case check_state_check_result:
4057 sh->check_state = check_state_idle;
4059 /* if a failure occurred during the check operation, leave
4060 * STRIPE_INSYNC not set and let the stripe be handled again
4065 /* handle a successful check operation, if parity is correct
4066 * we are done. Otherwise update the mismatch count and repair
4067 * parity if !MD_RECOVERY_CHECK
4069 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4070 /* parity is correct (on disc,
4071 * not in buffer any more)
4073 set_bit(STRIPE_INSYNC, &sh->state);
4075 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4076 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4077 /* don't try to repair!! */
4078 set_bit(STRIPE_INSYNC, &sh->state);
4079 pr_warn_ratelimited("%s: mismatch sector in range "
4080 "%llu-%llu\n", mdname(conf->mddev),
4081 (unsigned long long) sh->sector,
4082 (unsigned long long) sh->sector +
4085 sh->check_state = check_state_compute_run;
4086 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4087 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4088 set_bit(R5_Wantcompute,
4089 &sh->dev[sh->pd_idx].flags);
4090 sh->ops.target = sh->pd_idx;
4091 sh->ops.target2 = -1;
4096 case check_state_compute_run:
4099 pr_err("%s: unknown check_state: %d sector: %llu\n",
4100 __func__, sh->check_state,
4101 (unsigned long long) sh->sector);
4106 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4107 struct stripe_head_state *s,
4110 int pd_idx = sh->pd_idx;
4111 int qd_idx = sh->qd_idx;
4114 BUG_ON(sh->batch_head);
4115 set_bit(STRIPE_HANDLE, &sh->state);
4117 BUG_ON(s->failed > 2);
4119 /* Want to check and possibly repair P and Q.
4120 * However there could be one 'failed' device, in which
4121 * case we can only check one of them, possibly using the
4122 * other to generate missing data
4125 switch (sh->check_state) {
4126 case check_state_idle:
4127 /* start a new check operation if there are < 2 failures */
4128 if (s->failed == s->q_failed) {
4129 /* The only possible failed device holds Q, so it
4130 * makes sense to check P (If anything else were failed,
4131 * we would have used P to recreate it).
4133 sh->check_state = check_state_run;
4135 if (!s->q_failed && s->failed < 2) {
4136 /* Q is not failed, and we didn't use it to generate
4137 * anything, so it makes sense to check it
4139 if (sh->check_state == check_state_run)
4140 sh->check_state = check_state_run_pq;
4142 sh->check_state = check_state_run_q;
4145 /* discard potentially stale zero_sum_result */
4146 sh->ops.zero_sum_result = 0;
4148 if (sh->check_state == check_state_run) {
4149 /* async_xor_zero_sum destroys the contents of P */
4150 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4153 if (sh->check_state >= check_state_run &&
4154 sh->check_state <= check_state_run_pq) {
4155 /* async_syndrome_zero_sum preserves P and Q, so
4156 * no need to mark them !uptodate here
4158 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4162 /* we have 2-disk failure */
4163 BUG_ON(s->failed != 2);
4165 case check_state_compute_result:
4166 sh->check_state = check_state_idle;
4168 /* check that a write has not made the stripe insync */
4169 if (test_bit(STRIPE_INSYNC, &sh->state))
4172 /* now write out any block on a failed drive,
4173 * or P or Q if they were recomputed
4175 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
4176 if (s->failed == 2) {
4177 dev = &sh->dev[s->failed_num[1]];
4179 set_bit(R5_LOCKED, &dev->flags);
4180 set_bit(R5_Wantwrite, &dev->flags);
4182 if (s->failed >= 1) {
4183 dev = &sh->dev[s->failed_num[0]];
4185 set_bit(R5_LOCKED, &dev->flags);
4186 set_bit(R5_Wantwrite, &dev->flags);
4188 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4189 dev = &sh->dev[pd_idx];
4191 set_bit(R5_LOCKED, &dev->flags);
4192 set_bit(R5_Wantwrite, &dev->flags);
4194 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4195 dev = &sh->dev[qd_idx];
4197 set_bit(R5_LOCKED, &dev->flags);
4198 set_bit(R5_Wantwrite, &dev->flags);
4200 clear_bit(STRIPE_DEGRADED, &sh->state);
4202 set_bit(STRIPE_INSYNC, &sh->state);
4204 case check_state_run:
4205 case check_state_run_q:
4206 case check_state_run_pq:
4207 break; /* we will be called again upon completion */
4208 case check_state_check_result:
4209 sh->check_state = check_state_idle;
4211 /* handle a successful check operation, if parity is correct
4212 * we are done. Otherwise update the mismatch count and repair
4213 * parity if !MD_RECOVERY_CHECK
4215 if (sh->ops.zero_sum_result == 0) {
4216 /* both parities are correct */
4218 set_bit(STRIPE_INSYNC, &sh->state);
4220 /* in contrast to the raid5 case we can validate
4221 * parity, but still have a failure to write
4224 sh->check_state = check_state_compute_result;
4225 /* Returning at this point means that we may go
4226 * off and bring p and/or q uptodate again so
4227 * we make sure to check zero_sum_result again
4228 * to verify if p or q need writeback
4232 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
4233 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4234 /* don't try to repair!! */
4235 set_bit(STRIPE_INSYNC, &sh->state);
4236 pr_warn_ratelimited("%s: mismatch sector in range "
4237 "%llu-%llu\n", mdname(conf->mddev),
4238 (unsigned long long) sh->sector,
4239 (unsigned long long) sh->sector +
4242 int *target = &sh->ops.target;
4244 sh->ops.target = -1;
4245 sh->ops.target2 = -1;
4246 sh->check_state = check_state_compute_run;
4247 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4248 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4249 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4250 set_bit(R5_Wantcompute,
4251 &sh->dev[pd_idx].flags);
4253 target = &sh->ops.target2;
4256 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4257 set_bit(R5_Wantcompute,
4258 &sh->dev[qd_idx].flags);
4265 case check_state_compute_run:
4268 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4269 __func__, sh->check_state,
4270 (unsigned long long) sh->sector);
4275 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4279 /* We have read all the blocks in this stripe and now we need to
4280 * copy some of them into a target stripe for expand.
4282 struct dma_async_tx_descriptor *tx = NULL;
4283 BUG_ON(sh->batch_head);
4284 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4285 for (i = 0; i < sh->disks; i++)
4286 if (i != sh->pd_idx && i != sh->qd_idx) {
4288 struct stripe_head *sh2;
4289 struct async_submit_ctl submit;
4291 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4292 sector_t s = raid5_compute_sector(conf, bn, 0,
4294 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4296 /* so far only the early blocks of this stripe
4297 * have been requested. When later blocks
4298 * get requested, we will try again
4301 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4302 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4303 /* must have already done this block */
4304 raid5_release_stripe(sh2);
4308 /* place all the copies on one channel */
4309 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4310 tx = async_memcpy(sh2->dev[dd_idx].page,
4311 sh->dev[i].page, 0, 0, STRIPE_SIZE,
4314 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4315 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4316 for (j = 0; j < conf->raid_disks; j++)
4317 if (j != sh2->pd_idx &&
4319 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4321 if (j == conf->raid_disks) {
4322 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4323 set_bit(STRIPE_HANDLE, &sh2->state);
4325 raid5_release_stripe(sh2);
4328 /* done submitting copies, wait for them to complete */
4329 async_tx_quiesce(&tx);
4333 * handle_stripe - do things to a stripe.
4335 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4336 * state of various bits to see what needs to be done.
4338 * return some read requests which now have data
4339 * return some write requests which are safely on storage
4340 * schedule a read on some buffers
4341 * schedule a write of some buffers
4342 * return confirmation of parity correctness
4346 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4348 struct r5conf *conf = sh->raid_conf;
4349 int disks = sh->disks;
4352 int do_recovery = 0;
4354 memset(s, 0, sizeof(*s));
4356 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4357 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4358 s->failed_num[0] = -1;
4359 s->failed_num[1] = -1;
4360 s->log_failed = r5l_log_disk_error(conf);
4362 /* Now to look around and see what can be done */
4364 for (i=disks; i--; ) {
4365 struct md_rdev *rdev;
4372 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4374 dev->toread, dev->towrite, dev->written);
4375 /* maybe we can reply to a read
4377 * new wantfill requests are only permitted while
4378 * ops_complete_biofill is guaranteed to be inactive
4380 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4381 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4382 set_bit(R5_Wantfill, &dev->flags);
4384 /* now count some things */
4385 if (test_bit(R5_LOCKED, &dev->flags))
4387 if (test_bit(R5_UPTODATE, &dev->flags))
4389 if (test_bit(R5_Wantcompute, &dev->flags)) {
4391 BUG_ON(s->compute > 2);
4394 if (test_bit(R5_Wantfill, &dev->flags))
4396 else if (dev->toread)
4400 if (!test_bit(R5_OVERWRITE, &dev->flags))
4405 /* Prefer to use the replacement for reads, but only
4406 * if it is recovered enough and has no bad blocks.
4408 rdev = rcu_dereference(conf->disks[i].replacement);
4409 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4410 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4411 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4412 &first_bad, &bad_sectors))
4413 set_bit(R5_ReadRepl, &dev->flags);
4415 if (rdev && !test_bit(Faulty, &rdev->flags))
4416 set_bit(R5_NeedReplace, &dev->flags);
4418 clear_bit(R5_NeedReplace, &dev->flags);
4419 rdev = rcu_dereference(conf->disks[i].rdev);
4420 clear_bit(R5_ReadRepl, &dev->flags);
4422 if (rdev && test_bit(Faulty, &rdev->flags))
4425 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4426 &first_bad, &bad_sectors);
4427 if (s->blocked_rdev == NULL
4428 && (test_bit(Blocked, &rdev->flags)
4431 set_bit(BlockedBadBlocks,
4433 s->blocked_rdev = rdev;
4434 atomic_inc(&rdev->nr_pending);
4437 clear_bit(R5_Insync, &dev->flags);
4441 /* also not in-sync */
4442 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4443 test_bit(R5_UPTODATE, &dev->flags)) {
4444 /* treat as in-sync, but with a read error
4445 * which we can now try to correct
4447 set_bit(R5_Insync, &dev->flags);
4448 set_bit(R5_ReadError, &dev->flags);
4450 } else if (test_bit(In_sync, &rdev->flags))
4451 set_bit(R5_Insync, &dev->flags);
4452 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4453 /* in sync if before recovery_offset */
4454 set_bit(R5_Insync, &dev->flags);
4455 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4456 test_bit(R5_Expanded, &dev->flags))
4457 /* If we've reshaped into here, we assume it is Insync.
4458 * We will shortly update recovery_offset to make
4461 set_bit(R5_Insync, &dev->flags);
4463 if (test_bit(R5_WriteError, &dev->flags)) {
4464 /* This flag does not apply to '.replacement'
4465 * only to .rdev, so make sure to check that*/
4466 struct md_rdev *rdev2 = rcu_dereference(
4467 conf->disks[i].rdev);
4469 clear_bit(R5_Insync, &dev->flags);
4470 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4471 s->handle_bad_blocks = 1;
4472 atomic_inc(&rdev2->nr_pending);
4474 clear_bit(R5_WriteError, &dev->flags);
4476 if (test_bit(R5_MadeGood, &dev->flags)) {
4477 /* This flag does not apply to '.replacement'
4478 * only to .rdev, so make sure to check that*/
4479 struct md_rdev *rdev2 = rcu_dereference(
4480 conf->disks[i].rdev);
4481 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4482 s->handle_bad_blocks = 1;
4483 atomic_inc(&rdev2->nr_pending);
4485 clear_bit(R5_MadeGood, &dev->flags);
4487 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4488 struct md_rdev *rdev2 = rcu_dereference(
4489 conf->disks[i].replacement);
4490 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4491 s->handle_bad_blocks = 1;
4492 atomic_inc(&rdev2->nr_pending);
4494 clear_bit(R5_MadeGoodRepl, &dev->flags);
4496 if (!test_bit(R5_Insync, &dev->flags)) {
4497 /* The ReadError flag will just be confusing now */
4498 clear_bit(R5_ReadError, &dev->flags);
4499 clear_bit(R5_ReWrite, &dev->flags);
4501 if (test_bit(R5_ReadError, &dev->flags))
4502 clear_bit(R5_Insync, &dev->flags);
4503 if (!test_bit(R5_Insync, &dev->flags)) {
4505 s->failed_num[s->failed] = i;
4507 if (rdev && !test_bit(Faulty, &rdev->flags))
4511 if (test_bit(R5_InJournal, &dev->flags))
4513 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4516 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4517 /* If there is a failed device being replaced,
4518 * we must be recovering.
4519 * else if we are after recovery_cp, we must be syncing
4520 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4521 * else we can only be replacing
4522 * sync and recovery both need to read all devices, and so
4523 * use the same flag.
4526 sh->sector >= conf->mddev->recovery_cp ||
4527 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4535 static int clear_batch_ready(struct stripe_head *sh)
4537 /* Return '1' if this is a member of batch, or
4538 * '0' if it is a lone stripe or a head which can now be
4541 struct stripe_head *tmp;
4542 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4543 return (sh->batch_head && sh->batch_head != sh);
4544 spin_lock(&sh->stripe_lock);
4545 if (!sh->batch_head) {
4546 spin_unlock(&sh->stripe_lock);
4551 * this stripe could be added to a batch list before we check
4552 * BATCH_READY, skips it
4554 if (sh->batch_head != sh) {
4555 spin_unlock(&sh->stripe_lock);
4558 spin_lock(&sh->batch_lock);
4559 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4560 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4561 spin_unlock(&sh->batch_lock);
4562 spin_unlock(&sh->stripe_lock);
4565 * BATCH_READY is cleared, no new stripes can be added.
4566 * batch_list can be accessed without lock
4571 static void break_stripe_batch_list(struct stripe_head *head_sh,
4572 unsigned long handle_flags)
4574 struct stripe_head *sh, *next;
4578 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4580 list_del_init(&sh->batch_list);
4582 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4583 (1 << STRIPE_SYNCING) |
4584 (1 << STRIPE_REPLACED) |
4585 (1 << STRIPE_DELAYED) |
4586 (1 << STRIPE_BIT_DELAY) |
4587 (1 << STRIPE_FULL_WRITE) |
4588 (1 << STRIPE_BIOFILL_RUN) |
4589 (1 << STRIPE_COMPUTE_RUN) |
4590 (1 << STRIPE_OPS_REQ_PENDING) |
4591 (1 << STRIPE_DISCARD) |
4592 (1 << STRIPE_BATCH_READY) |
4593 (1 << STRIPE_BATCH_ERR) |
4594 (1 << STRIPE_BITMAP_PENDING)),
4595 "stripe state: %lx\n", sh->state);
4596 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4597 (1 << STRIPE_REPLACED)),
4598 "head stripe state: %lx\n", head_sh->state);
4600 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4601 (1 << STRIPE_PREREAD_ACTIVE) |
4602 (1 << STRIPE_DEGRADED)),
4603 head_sh->state & (1 << STRIPE_INSYNC));
4605 sh->check_state = head_sh->check_state;
4606 sh->reconstruct_state = head_sh->reconstruct_state;
4607 for (i = 0; i < sh->disks; i++) {
4608 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4610 sh->dev[i].flags = head_sh->dev[i].flags &
4611 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4613 spin_lock_irq(&sh->stripe_lock);
4614 sh->batch_head = NULL;
4615 spin_unlock_irq(&sh->stripe_lock);
4616 if (handle_flags == 0 ||
4617 sh->state & handle_flags)
4618 set_bit(STRIPE_HANDLE, &sh->state);
4619 raid5_release_stripe(sh);
4621 spin_lock_irq(&head_sh->stripe_lock);
4622 head_sh->batch_head = NULL;
4623 spin_unlock_irq(&head_sh->stripe_lock);
4624 for (i = 0; i < head_sh->disks; i++)
4625 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4627 if (head_sh->state & handle_flags)
4628 set_bit(STRIPE_HANDLE, &head_sh->state);
4631 wake_up(&head_sh->raid_conf->wait_for_overlap);
4634 static void handle_stripe(struct stripe_head *sh)
4636 struct stripe_head_state s;
4637 struct r5conf *conf = sh->raid_conf;
4640 int disks = sh->disks;
4641 struct r5dev *pdev, *qdev;
4643 clear_bit(STRIPE_HANDLE, &sh->state);
4644 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4645 /* already being handled, ensure it gets handled
4646 * again when current action finishes */
4647 set_bit(STRIPE_HANDLE, &sh->state);
4651 if (clear_batch_ready(sh) ) {
4652 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4656 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4657 break_stripe_batch_list(sh, 0);
4659 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4660 spin_lock(&sh->stripe_lock);
4662 * Cannot process 'sync' concurrently with 'discard'.
4663 * Flush data in r5cache before 'sync'.
4665 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4666 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4667 !test_bit(STRIPE_DISCARD, &sh->state) &&
4668 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4669 set_bit(STRIPE_SYNCING, &sh->state);
4670 clear_bit(STRIPE_INSYNC, &sh->state);
4671 clear_bit(STRIPE_REPLACED, &sh->state);
4673 spin_unlock(&sh->stripe_lock);
4675 clear_bit(STRIPE_DELAYED, &sh->state);
4677 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4678 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4679 (unsigned long long)sh->sector, sh->state,
4680 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4681 sh->check_state, sh->reconstruct_state);
4683 analyse_stripe(sh, &s);
4685 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4688 if (s.handle_bad_blocks ||
4689 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4690 set_bit(STRIPE_HANDLE, &sh->state);
4694 if (unlikely(s.blocked_rdev)) {
4695 if (s.syncing || s.expanding || s.expanded ||
4696 s.replacing || s.to_write || s.written) {
4697 set_bit(STRIPE_HANDLE, &sh->state);
4700 /* There is nothing for the blocked_rdev to block */
4701 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4702 s.blocked_rdev = NULL;
4705 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4706 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4707 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4710 pr_debug("locked=%d uptodate=%d to_read=%d"
4711 " to_write=%d failed=%d failed_num=%d,%d\n",
4712 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4713 s.failed_num[0], s.failed_num[1]);
4715 * check if the array has lost more than max_degraded devices and,
4716 * if so, some requests might need to be failed.
4718 * When journal device failed (log_failed), we will only process
4719 * the stripe if there is data need write to raid disks
4721 if (s.failed > conf->max_degraded ||
4722 (s.log_failed && s.injournal == 0)) {
4723 sh->check_state = 0;
4724 sh->reconstruct_state = 0;
4725 break_stripe_batch_list(sh, 0);
4726 if (s.to_read+s.to_write+s.written)
4727 handle_failed_stripe(conf, sh, &s, disks);
4728 if (s.syncing + s.replacing)
4729 handle_failed_sync(conf, sh, &s);
4732 /* Now we check to see if any write operations have recently
4736 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4738 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4739 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4740 sh->reconstruct_state = reconstruct_state_idle;
4742 /* All the 'written' buffers and the parity block are ready to
4743 * be written back to disk
4745 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4746 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4747 BUG_ON(sh->qd_idx >= 0 &&
4748 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4749 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4750 for (i = disks; i--; ) {
4751 struct r5dev *dev = &sh->dev[i];
4752 if (test_bit(R5_LOCKED, &dev->flags) &&
4753 (i == sh->pd_idx || i == sh->qd_idx ||
4754 dev->written || test_bit(R5_InJournal,
4756 pr_debug("Writing block %d\n", i);
4757 set_bit(R5_Wantwrite, &dev->flags);
4762 if (!test_bit(R5_Insync, &dev->flags) ||
4763 ((i == sh->pd_idx || i == sh->qd_idx) &&
4765 set_bit(STRIPE_INSYNC, &sh->state);
4768 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4769 s.dec_preread_active = 1;
4773 * might be able to return some write requests if the parity blocks
4774 * are safe, or on a failed drive
4776 pdev = &sh->dev[sh->pd_idx];
4777 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4778 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4779 qdev = &sh->dev[sh->qd_idx];
4780 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4781 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4785 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4786 && !test_bit(R5_LOCKED, &pdev->flags)
4787 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4788 test_bit(R5_Discard, &pdev->flags))))) &&
4789 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4790 && !test_bit(R5_LOCKED, &qdev->flags)
4791 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4792 test_bit(R5_Discard, &qdev->flags))))))
4793 handle_stripe_clean_event(conf, sh, disks);
4796 r5c_handle_cached_data_endio(conf, sh, disks);
4797 log_stripe_write_finished(sh);
4799 /* Now we might consider reading some blocks, either to check/generate
4800 * parity, or to satisfy requests
4801 * or to load a block that is being partially written.
4803 if (s.to_read || s.non_overwrite
4804 || (conf->level == 6 && s.to_write && s.failed)
4805 || (s.syncing && (s.uptodate + s.compute < disks))
4808 handle_stripe_fill(sh, &s, disks);
4811 * When the stripe finishes full journal write cycle (write to journal
4812 * and raid disk), this is the clean up procedure so it is ready for
4815 r5c_finish_stripe_write_out(conf, sh, &s);
4818 * Now to consider new write requests, cache write back and what else,
4819 * if anything should be read. We do not handle new writes when:
4820 * 1/ A 'write' operation (copy+xor) is already in flight.
4821 * 2/ A 'check' operation is in flight, as it may clobber the parity
4823 * 3/ A r5c cache log write is in flight.
4826 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
4827 if (!r5c_is_writeback(conf->log)) {
4829 handle_stripe_dirtying(conf, sh, &s, disks);
4830 } else { /* write back cache */
4833 /* First, try handle writes in caching phase */
4835 ret = r5c_try_caching_write(conf, sh, &s,
4838 * If caching phase failed: ret == -EAGAIN
4840 * stripe under reclaim: !caching && injournal
4842 * fall back to handle_stripe_dirtying()
4844 if (ret == -EAGAIN ||
4845 /* stripe under reclaim: !caching && injournal */
4846 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
4848 ret = handle_stripe_dirtying(conf, sh, &s,
4856 /* maybe we need to check and possibly fix the parity for this stripe
4857 * Any reads will already have been scheduled, so we just see if enough
4858 * data is available. The parity check is held off while parity
4859 * dependent operations are in flight.
4861 if (sh->check_state ||
4862 (s.syncing && s.locked == 0 &&
4863 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4864 !test_bit(STRIPE_INSYNC, &sh->state))) {
4865 if (conf->level == 6)
4866 handle_parity_checks6(conf, sh, &s, disks);
4868 handle_parity_checks5(conf, sh, &s, disks);
4871 if ((s.replacing || s.syncing) && s.locked == 0
4872 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4873 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4874 /* Write out to replacement devices where possible */
4875 for (i = 0; i < conf->raid_disks; i++)
4876 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4877 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4878 set_bit(R5_WantReplace, &sh->dev[i].flags);
4879 set_bit(R5_LOCKED, &sh->dev[i].flags);
4883 set_bit(STRIPE_INSYNC, &sh->state);
4884 set_bit(STRIPE_REPLACED, &sh->state);
4886 if ((s.syncing || s.replacing) && s.locked == 0 &&
4887 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4888 test_bit(STRIPE_INSYNC, &sh->state)) {
4889 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4890 clear_bit(STRIPE_SYNCING, &sh->state);
4891 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4892 wake_up(&conf->wait_for_overlap);
4895 /* If the failed drives are just a ReadError, then we might need
4896 * to progress the repair/check process
4898 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4899 for (i = 0; i < s.failed; i++) {
4900 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4901 if (test_bit(R5_ReadError, &dev->flags)
4902 && !test_bit(R5_LOCKED, &dev->flags)
4903 && test_bit(R5_UPTODATE, &dev->flags)
4905 if (!test_bit(R5_ReWrite, &dev->flags)) {
4906 set_bit(R5_Wantwrite, &dev->flags);
4907 set_bit(R5_ReWrite, &dev->flags);
4908 set_bit(R5_LOCKED, &dev->flags);
4911 /* let's read it back */
4912 set_bit(R5_Wantread, &dev->flags);
4913 set_bit(R5_LOCKED, &dev->flags);
4919 /* Finish reconstruct operations initiated by the expansion process */
4920 if (sh->reconstruct_state == reconstruct_state_result) {
4921 struct stripe_head *sh_src
4922 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4923 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4924 /* sh cannot be written until sh_src has been read.
4925 * so arrange for sh to be delayed a little
4927 set_bit(STRIPE_DELAYED, &sh->state);
4928 set_bit(STRIPE_HANDLE, &sh->state);
4929 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4931 atomic_inc(&conf->preread_active_stripes);
4932 raid5_release_stripe(sh_src);
4936 raid5_release_stripe(sh_src);
4938 sh->reconstruct_state = reconstruct_state_idle;
4939 clear_bit(STRIPE_EXPANDING, &sh->state);
4940 for (i = conf->raid_disks; i--; ) {
4941 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4942 set_bit(R5_LOCKED, &sh->dev[i].flags);
4947 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4948 !sh->reconstruct_state) {
4949 /* Need to write out all blocks after computing parity */
4950 sh->disks = conf->raid_disks;
4951 stripe_set_idx(sh->sector, conf, 0, sh);
4952 schedule_reconstruction(sh, &s, 1, 1);
4953 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4954 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4955 atomic_dec(&conf->reshape_stripes);
4956 wake_up(&conf->wait_for_overlap);
4957 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4960 if (s.expanding && s.locked == 0 &&
4961 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4962 handle_stripe_expansion(conf, sh);
4965 /* wait for this device to become unblocked */
4966 if (unlikely(s.blocked_rdev)) {
4967 if (conf->mddev->external)
4968 md_wait_for_blocked_rdev(s.blocked_rdev,
4971 /* Internal metadata will immediately
4972 * be written by raid5d, so we don't
4973 * need to wait here.
4975 rdev_dec_pending(s.blocked_rdev,
4979 if (s.handle_bad_blocks)
4980 for (i = disks; i--; ) {
4981 struct md_rdev *rdev;
4982 struct r5dev *dev = &sh->dev[i];
4983 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
4984 /* We own a safe reference to the rdev */
4985 rdev = conf->disks[i].rdev;
4986 if (!rdev_set_badblocks(rdev, sh->sector,
4988 md_error(conf->mddev, rdev);
4989 rdev_dec_pending(rdev, conf->mddev);
4991 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
4992 rdev = conf->disks[i].rdev;
4993 rdev_clear_badblocks(rdev, sh->sector,
4995 rdev_dec_pending(rdev, conf->mddev);
4997 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
4998 rdev = conf->disks[i].replacement;
5000 /* rdev have been moved down */
5001 rdev = conf->disks[i].rdev;
5002 rdev_clear_badblocks(rdev, sh->sector,
5004 rdev_dec_pending(rdev, conf->mddev);
5009 raid_run_ops(sh, s.ops_request);
5013 if (s.dec_preread_active) {
5014 /* We delay this until after ops_run_io so that if make_request
5015 * is waiting on a flush, it won't continue until the writes
5016 * have actually been submitted.
5018 atomic_dec(&conf->preread_active_stripes);
5019 if (atomic_read(&conf->preread_active_stripes) <
5021 md_wakeup_thread(conf->mddev->thread);
5024 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5027 static void raid5_activate_delayed(struct r5conf *conf)
5029 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5030 while (!list_empty(&conf->delayed_list)) {
5031 struct list_head *l = conf->delayed_list.next;
5032 struct stripe_head *sh;
5033 sh = list_entry(l, struct stripe_head, lru);
5035 clear_bit(STRIPE_DELAYED, &sh->state);
5036 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5037 atomic_inc(&conf->preread_active_stripes);
5038 list_add_tail(&sh->lru, &conf->hold_list);
5039 raid5_wakeup_stripe_thread(sh);
5044 static void activate_bit_delay(struct r5conf *conf,
5045 struct list_head *temp_inactive_list)
5047 /* device_lock is held */
5048 struct list_head head;
5049 list_add(&head, &conf->bitmap_list);
5050 list_del_init(&conf->bitmap_list);
5051 while (!list_empty(&head)) {
5052 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5054 list_del_init(&sh->lru);
5055 atomic_inc(&sh->count);
5056 hash = sh->hash_lock_index;
5057 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5061 static int raid5_congested(struct mddev *mddev, int bits)
5063 struct r5conf *conf = mddev->private;
5065 /* No difference between reads and writes. Just check
5066 * how busy the stripe_cache is
5069 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
5072 /* Also checks whether there is pressure on r5cache log space */
5073 if (test_bit(R5C_LOG_TIGHT, &conf->cache_state))
5077 if (atomic_read(&conf->empty_inactive_list_nr))
5083 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5085 struct r5conf *conf = mddev->private;
5086 sector_t sector = bio->bi_iter.bi_sector + get_start_sect(bio->bi_bdev);
5087 unsigned int chunk_sectors;
5088 unsigned int bio_sectors = bio_sectors(bio);
5090 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5091 return chunk_sectors >=
5092 ((sector & (chunk_sectors - 1)) + bio_sectors);
5096 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5097 * later sampled by raid5d.
5099 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5101 unsigned long flags;
5103 spin_lock_irqsave(&conf->device_lock, flags);
5105 bi->bi_next = conf->retry_read_aligned_list;
5106 conf->retry_read_aligned_list = bi;
5108 spin_unlock_irqrestore(&conf->device_lock, flags);
5109 md_wakeup_thread(conf->mddev->thread);
5112 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5113 unsigned int *offset)
5117 bi = conf->retry_read_aligned;
5119 *offset = conf->retry_read_offset;
5120 conf->retry_read_aligned = NULL;
5123 bi = conf->retry_read_aligned_list;
5125 conf->retry_read_aligned_list = bi->bi_next;
5134 * The "raid5_align_endio" should check if the read succeeded and if it
5135 * did, call bio_endio on the original bio (having bio_put the new bio
5137 * If the read failed..
5139 static void raid5_align_endio(struct bio *bi)
5141 struct bio* raid_bi = bi->bi_private;
5142 struct mddev *mddev;
5143 struct r5conf *conf;
5144 struct md_rdev *rdev;
5145 blk_status_t error = bi->bi_status;
5149 rdev = (void*)raid_bi->bi_next;
5150 raid_bi->bi_next = NULL;
5151 mddev = rdev->mddev;
5152 conf = mddev->private;
5154 rdev_dec_pending(rdev, conf->mddev);
5158 if (atomic_dec_and_test(&conf->active_aligned_reads))
5159 wake_up(&conf->wait_for_quiescent);
5163 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5165 add_bio_to_retry(raid_bi, conf);
5168 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5170 struct r5conf *conf = mddev->private;
5172 struct bio* align_bi;
5173 struct md_rdev *rdev;
5174 sector_t end_sector;
5176 if (!in_chunk_boundary(mddev, raid_bio)) {
5177 pr_debug("%s: non aligned\n", __func__);
5181 * use bio_clone_fast to make a copy of the bio
5183 align_bi = bio_clone_fast(raid_bio, GFP_NOIO, mddev->bio_set);
5187 * set bi_end_io to a new function, and set bi_private to the
5190 align_bi->bi_end_io = raid5_align_endio;
5191 align_bi->bi_private = raid_bio;
5195 align_bi->bi_iter.bi_sector =
5196 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5199 end_sector = bio_end_sector(align_bi);
5201 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5202 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5203 rdev->recovery_offset < end_sector) {
5204 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5206 (test_bit(Faulty, &rdev->flags) ||
5207 !(test_bit(In_sync, &rdev->flags) ||
5208 rdev->recovery_offset >= end_sector)))
5212 if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5222 atomic_inc(&rdev->nr_pending);
5224 raid_bio->bi_next = (void*)rdev;
5225 align_bi->bi_bdev = rdev->bdev;
5226 bio_clear_flag(align_bi, BIO_SEG_VALID);
5228 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5229 bio_sectors(align_bi),
5230 &first_bad, &bad_sectors)) {
5232 rdev_dec_pending(rdev, mddev);
5236 /* No reshape active, so we can trust rdev->data_offset */
5237 align_bi->bi_iter.bi_sector += rdev->data_offset;
5239 spin_lock_irq(&conf->device_lock);
5240 wait_event_lock_irq(conf->wait_for_quiescent,
5243 atomic_inc(&conf->active_aligned_reads);
5244 spin_unlock_irq(&conf->device_lock);
5247 trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
5248 align_bi, disk_devt(mddev->gendisk),
5249 raid_bio->bi_iter.bi_sector);
5250 generic_make_request(align_bi);
5259 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5262 sector_t sector = raid_bio->bi_iter.bi_sector;
5263 unsigned chunk_sects = mddev->chunk_sectors;
5264 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5266 if (sectors < bio_sectors(raid_bio)) {
5267 struct r5conf *conf = mddev->private;
5268 split = bio_split(raid_bio, sectors, GFP_NOIO, conf->bio_split);
5269 bio_chain(split, raid_bio);
5270 generic_make_request(raid_bio);
5274 if (!raid5_read_one_chunk(mddev, raid_bio))
5280 /* __get_priority_stripe - get the next stripe to process
5282 * Full stripe writes are allowed to pass preread active stripes up until
5283 * the bypass_threshold is exceeded. In general the bypass_count
5284 * increments when the handle_list is handled before the hold_list; however, it
5285 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5286 * stripe with in flight i/o. The bypass_count will be reset when the
5287 * head of the hold_list has changed, i.e. the head was promoted to the
5290 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5292 struct stripe_head *sh, *tmp;
5293 struct list_head *handle_list = NULL;
5294 struct r5worker_group *wg;
5295 bool second_try = !r5c_is_writeback(conf->log) &&
5296 !r5l_log_disk_error(conf);
5297 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5298 r5l_log_disk_error(conf);
5303 if (conf->worker_cnt_per_group == 0) {
5304 handle_list = try_loprio ? &conf->loprio_list :
5306 } else if (group != ANY_GROUP) {
5307 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5308 &conf->worker_groups[group].handle_list;
5309 wg = &conf->worker_groups[group];
5312 for (i = 0; i < conf->group_cnt; i++) {
5313 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5314 &conf->worker_groups[i].handle_list;
5315 wg = &conf->worker_groups[i];
5316 if (!list_empty(handle_list))
5321 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5323 list_empty(handle_list) ? "empty" : "busy",
5324 list_empty(&conf->hold_list) ? "empty" : "busy",
5325 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5327 if (!list_empty(handle_list)) {
5328 sh = list_entry(handle_list->next, typeof(*sh), lru);
5330 if (list_empty(&conf->hold_list))
5331 conf->bypass_count = 0;
5332 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5333 if (conf->hold_list.next == conf->last_hold)
5334 conf->bypass_count++;
5336 conf->last_hold = conf->hold_list.next;
5337 conf->bypass_count -= conf->bypass_threshold;
5338 if (conf->bypass_count < 0)
5339 conf->bypass_count = 0;
5342 } else if (!list_empty(&conf->hold_list) &&
5343 ((conf->bypass_threshold &&
5344 conf->bypass_count > conf->bypass_threshold) ||
5345 atomic_read(&conf->pending_full_writes) == 0)) {
5347 list_for_each_entry(tmp, &conf->hold_list, lru) {
5348 if (conf->worker_cnt_per_group == 0 ||
5349 group == ANY_GROUP ||
5350 !cpu_online(tmp->cpu) ||
5351 cpu_to_group(tmp->cpu) == group) {
5358 conf->bypass_count -= conf->bypass_threshold;
5359 if (conf->bypass_count < 0)
5360 conf->bypass_count = 0;
5369 try_loprio = !try_loprio;
5377 list_del_init(&sh->lru);
5378 BUG_ON(atomic_inc_return(&sh->count) != 1);
5382 struct raid5_plug_cb {
5383 struct blk_plug_cb cb;
5384 struct list_head list;
5385 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5388 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5390 struct raid5_plug_cb *cb = container_of(
5391 blk_cb, struct raid5_plug_cb, cb);
5392 struct stripe_head *sh;
5393 struct mddev *mddev = cb->cb.data;
5394 struct r5conf *conf = mddev->private;
5398 if (cb->list.next && !list_empty(&cb->list)) {
5399 spin_lock_irq(&conf->device_lock);
5400 while (!list_empty(&cb->list)) {
5401 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5402 list_del_init(&sh->lru);
5404 * avoid race release_stripe_plug() sees
5405 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5406 * is still in our list
5408 smp_mb__before_atomic();
5409 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5411 * STRIPE_ON_RELEASE_LIST could be set here. In that
5412 * case, the count is always > 1 here
5414 hash = sh->hash_lock_index;
5415 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5418 spin_unlock_irq(&conf->device_lock);
5420 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5421 NR_STRIPE_HASH_LOCKS);
5423 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5427 static void release_stripe_plug(struct mddev *mddev,
5428 struct stripe_head *sh)
5430 struct blk_plug_cb *blk_cb = blk_check_plugged(
5431 raid5_unplug, mddev,
5432 sizeof(struct raid5_plug_cb));
5433 struct raid5_plug_cb *cb;
5436 raid5_release_stripe(sh);
5440 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5442 if (cb->list.next == NULL) {
5444 INIT_LIST_HEAD(&cb->list);
5445 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5446 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5449 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5450 list_add_tail(&sh->lru, &cb->list);
5452 raid5_release_stripe(sh);
5455 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5457 struct r5conf *conf = mddev->private;
5458 sector_t logical_sector, last_sector;
5459 struct stripe_head *sh;
5462 if (mddev->reshape_position != MaxSector)
5463 /* Skip discard while reshape is happening */
5466 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5467 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5471 stripe_sectors = conf->chunk_sectors *
5472 (conf->raid_disks - conf->max_degraded);
5473 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5475 sector_div(last_sector, stripe_sectors);
5477 logical_sector *= conf->chunk_sectors;
5478 last_sector *= conf->chunk_sectors;
5480 for (; logical_sector < last_sector;
5481 logical_sector += STRIPE_SECTORS) {
5485 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5486 prepare_to_wait(&conf->wait_for_overlap, &w,
5487 TASK_UNINTERRUPTIBLE);
5488 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5489 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5490 raid5_release_stripe(sh);
5494 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5495 spin_lock_irq(&sh->stripe_lock);
5496 for (d = 0; d < conf->raid_disks; d++) {
5497 if (d == sh->pd_idx || d == sh->qd_idx)
5499 if (sh->dev[d].towrite || sh->dev[d].toread) {
5500 set_bit(R5_Overlap, &sh->dev[d].flags);
5501 spin_unlock_irq(&sh->stripe_lock);
5502 raid5_release_stripe(sh);
5507 set_bit(STRIPE_DISCARD, &sh->state);
5508 finish_wait(&conf->wait_for_overlap, &w);
5509 sh->overwrite_disks = 0;
5510 for (d = 0; d < conf->raid_disks; d++) {
5511 if (d == sh->pd_idx || d == sh->qd_idx)
5513 sh->dev[d].towrite = bi;
5514 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5515 bio_inc_remaining(bi);
5516 md_write_inc(mddev, bi);
5517 sh->overwrite_disks++;
5519 spin_unlock_irq(&sh->stripe_lock);
5520 if (conf->mddev->bitmap) {
5522 d < conf->raid_disks - conf->max_degraded;
5524 bitmap_startwrite(mddev->bitmap,
5528 sh->bm_seq = conf->seq_flush + 1;
5529 set_bit(STRIPE_BIT_DELAY, &sh->state);
5532 set_bit(STRIPE_HANDLE, &sh->state);
5533 clear_bit(STRIPE_DELAYED, &sh->state);
5534 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5535 atomic_inc(&conf->preread_active_stripes);
5536 release_stripe_plug(mddev, sh);
5542 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5544 struct r5conf *conf = mddev->private;
5546 sector_t new_sector;
5547 sector_t logical_sector, last_sector;
5548 struct stripe_head *sh;
5549 const int rw = bio_data_dir(bi);
5552 bool do_flush = false;
5554 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5555 int ret = r5l_handle_flush_request(conf->log, bi);
5559 if (ret == -ENODEV) {
5560 md_flush_request(mddev, bi);
5563 /* ret == -EAGAIN, fallback */
5565 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5566 * we need to flush journal device
5568 do_flush = bi->bi_opf & REQ_PREFLUSH;
5571 if (!md_write_start(mddev, bi))
5574 * If array is degraded, better not do chunk aligned read because
5575 * later we might have to read it again in order to reconstruct
5576 * data on failed drives.
5578 if (rw == READ && mddev->degraded == 0 &&
5579 mddev->reshape_position == MaxSector) {
5580 bi = chunk_aligned_read(mddev, bi);
5585 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5586 make_discard_request(mddev, bi);
5587 md_write_end(mddev);
5591 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5592 last_sector = bio_end_sector(bi);
5595 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5596 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5602 seq = read_seqcount_begin(&conf->gen_lock);
5605 prepare_to_wait(&conf->wait_for_overlap, &w,
5606 TASK_UNINTERRUPTIBLE);
5607 if (unlikely(conf->reshape_progress != MaxSector)) {
5608 /* spinlock is needed as reshape_progress may be
5609 * 64bit on a 32bit platform, and so it might be
5610 * possible to see a half-updated value
5611 * Of course reshape_progress could change after
5612 * the lock is dropped, so once we get a reference
5613 * to the stripe that we think it is, we will have
5616 spin_lock_irq(&conf->device_lock);
5617 if (mddev->reshape_backwards
5618 ? logical_sector < conf->reshape_progress
5619 : logical_sector >= conf->reshape_progress) {
5622 if (mddev->reshape_backwards
5623 ? logical_sector < conf->reshape_safe
5624 : logical_sector >= conf->reshape_safe) {
5625 spin_unlock_irq(&conf->device_lock);
5631 spin_unlock_irq(&conf->device_lock);
5634 new_sector = raid5_compute_sector(conf, logical_sector,
5637 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5638 (unsigned long long)new_sector,
5639 (unsigned long long)logical_sector);
5641 sh = raid5_get_active_stripe(conf, new_sector, previous,
5642 (bi->bi_opf & REQ_RAHEAD), 0);
5644 if (unlikely(previous)) {
5645 /* expansion might have moved on while waiting for a
5646 * stripe, so we must do the range check again.
5647 * Expansion could still move past after this
5648 * test, but as we are holding a reference to
5649 * 'sh', we know that if that happens,
5650 * STRIPE_EXPANDING will get set and the expansion
5651 * won't proceed until we finish with the stripe.
5654 spin_lock_irq(&conf->device_lock);
5655 if (mddev->reshape_backwards
5656 ? logical_sector >= conf->reshape_progress
5657 : logical_sector < conf->reshape_progress)
5658 /* mismatch, need to try again */
5660 spin_unlock_irq(&conf->device_lock);
5662 raid5_release_stripe(sh);
5668 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5669 /* Might have got the wrong stripe_head
5672 raid5_release_stripe(sh);
5677 logical_sector >= mddev->suspend_lo &&
5678 logical_sector < mddev->suspend_hi) {
5679 raid5_release_stripe(sh);
5680 /* As the suspend_* range is controlled by
5681 * userspace, we want an interruptible
5684 prepare_to_wait(&conf->wait_for_overlap,
5685 &w, TASK_INTERRUPTIBLE);
5686 if (logical_sector >= mddev->suspend_lo &&
5687 logical_sector < mddev->suspend_hi) {
5690 sigprocmask(SIG_BLOCK, &full, &old);
5692 sigprocmask(SIG_SETMASK, &old, NULL);
5698 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5699 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5700 /* Stripe is busy expanding or
5701 * add failed due to overlap. Flush everything
5704 md_wakeup_thread(mddev->thread);
5705 raid5_release_stripe(sh);
5711 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5712 /* we only need flush for one stripe */
5716 set_bit(STRIPE_HANDLE, &sh->state);
5717 clear_bit(STRIPE_DELAYED, &sh->state);
5718 if ((!sh->batch_head || sh == sh->batch_head) &&
5719 (bi->bi_opf & REQ_SYNC) &&
5720 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5721 atomic_inc(&conf->preread_active_stripes);
5722 release_stripe_plug(mddev, sh);
5724 /* cannot get stripe for read-ahead, just give-up */
5725 bi->bi_status = BLK_STS_IOERR;
5729 finish_wait(&conf->wait_for_overlap, &w);
5732 md_write_end(mddev);
5737 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5739 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5741 /* reshaping is quite different to recovery/resync so it is
5742 * handled quite separately ... here.
5744 * On each call to sync_request, we gather one chunk worth of
5745 * destination stripes and flag them as expanding.
5746 * Then we find all the source stripes and request reads.
5747 * As the reads complete, handle_stripe will copy the data
5748 * into the destination stripe and release that stripe.
5750 struct r5conf *conf = mddev->private;
5751 struct stripe_head *sh;
5752 sector_t first_sector, last_sector;
5753 int raid_disks = conf->previous_raid_disks;
5754 int data_disks = raid_disks - conf->max_degraded;
5755 int new_data_disks = conf->raid_disks - conf->max_degraded;
5758 sector_t writepos, readpos, safepos;
5759 sector_t stripe_addr;
5760 int reshape_sectors;
5761 struct list_head stripes;
5764 if (sector_nr == 0) {
5765 /* If restarting in the middle, skip the initial sectors */
5766 if (mddev->reshape_backwards &&
5767 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5768 sector_nr = raid5_size(mddev, 0, 0)
5769 - conf->reshape_progress;
5770 } else if (mddev->reshape_backwards &&
5771 conf->reshape_progress == MaxSector) {
5772 /* shouldn't happen, but just in case, finish up.*/
5773 sector_nr = MaxSector;
5774 } else if (!mddev->reshape_backwards &&
5775 conf->reshape_progress > 0)
5776 sector_nr = conf->reshape_progress;
5777 sector_div(sector_nr, new_data_disks);
5779 mddev->curr_resync_completed = sector_nr;
5780 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5787 /* We need to process a full chunk at a time.
5788 * If old and new chunk sizes differ, we need to process the
5792 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5794 /* We update the metadata at least every 10 seconds, or when
5795 * the data about to be copied would over-write the source of
5796 * the data at the front of the range. i.e. one new_stripe
5797 * along from reshape_progress new_maps to after where
5798 * reshape_safe old_maps to
5800 writepos = conf->reshape_progress;
5801 sector_div(writepos, new_data_disks);
5802 readpos = conf->reshape_progress;
5803 sector_div(readpos, data_disks);
5804 safepos = conf->reshape_safe;
5805 sector_div(safepos, data_disks);
5806 if (mddev->reshape_backwards) {
5807 BUG_ON(writepos < reshape_sectors);
5808 writepos -= reshape_sectors;
5809 readpos += reshape_sectors;
5810 safepos += reshape_sectors;
5812 writepos += reshape_sectors;
5813 /* readpos and safepos are worst-case calculations.
5814 * A negative number is overly pessimistic, and causes
5815 * obvious problems for unsigned storage. So clip to 0.
5817 readpos -= min_t(sector_t, reshape_sectors, readpos);
5818 safepos -= min_t(sector_t, reshape_sectors, safepos);
5821 /* Having calculated the 'writepos' possibly use it
5822 * to set 'stripe_addr' which is where we will write to.
5824 if (mddev->reshape_backwards) {
5825 BUG_ON(conf->reshape_progress == 0);
5826 stripe_addr = writepos;
5827 BUG_ON((mddev->dev_sectors &
5828 ~((sector_t)reshape_sectors - 1))
5829 - reshape_sectors - stripe_addr
5832 BUG_ON(writepos != sector_nr + reshape_sectors);
5833 stripe_addr = sector_nr;
5836 /* 'writepos' is the most advanced device address we might write.
5837 * 'readpos' is the least advanced device address we might read.
5838 * 'safepos' is the least address recorded in the metadata as having
5840 * If there is a min_offset_diff, these are adjusted either by
5841 * increasing the safepos/readpos if diff is negative, or
5842 * increasing writepos if diff is positive.
5843 * If 'readpos' is then behind 'writepos', there is no way that we can
5844 * ensure safety in the face of a crash - that must be done by userspace
5845 * making a backup of the data. So in that case there is no particular
5846 * rush to update metadata.
5847 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5848 * update the metadata to advance 'safepos' to match 'readpos' so that
5849 * we can be safe in the event of a crash.
5850 * So we insist on updating metadata if safepos is behind writepos and
5851 * readpos is beyond writepos.
5852 * In any case, update the metadata every 10 seconds.
5853 * Maybe that number should be configurable, but I'm not sure it is
5854 * worth it.... maybe it could be a multiple of safemode_delay???
5856 if (conf->min_offset_diff < 0) {
5857 safepos += -conf->min_offset_diff;
5858 readpos += -conf->min_offset_diff;
5860 writepos += conf->min_offset_diff;
5862 if ((mddev->reshape_backwards
5863 ? (safepos > writepos && readpos < writepos)
5864 : (safepos < writepos && readpos > writepos)) ||
5865 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5866 /* Cannot proceed until we've updated the superblock... */
5867 wait_event(conf->wait_for_overlap,
5868 atomic_read(&conf->reshape_stripes)==0
5869 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5870 if (atomic_read(&conf->reshape_stripes) != 0)
5872 mddev->reshape_position = conf->reshape_progress;
5873 mddev->curr_resync_completed = sector_nr;
5874 conf->reshape_checkpoint = jiffies;
5875 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5876 md_wakeup_thread(mddev->thread);
5877 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
5878 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5879 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5881 spin_lock_irq(&conf->device_lock);
5882 conf->reshape_safe = mddev->reshape_position;
5883 spin_unlock_irq(&conf->device_lock);
5884 wake_up(&conf->wait_for_overlap);
5885 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5888 INIT_LIST_HEAD(&stripes);
5889 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5891 int skipped_disk = 0;
5892 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5893 set_bit(STRIPE_EXPANDING, &sh->state);
5894 atomic_inc(&conf->reshape_stripes);
5895 /* If any of this stripe is beyond the end of the old
5896 * array, then we need to zero those blocks
5898 for (j=sh->disks; j--;) {
5900 if (j == sh->pd_idx)
5902 if (conf->level == 6 &&
5905 s = raid5_compute_blocknr(sh, j, 0);
5906 if (s < raid5_size(mddev, 0, 0)) {
5910 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5911 set_bit(R5_Expanded, &sh->dev[j].flags);
5912 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5914 if (!skipped_disk) {
5915 set_bit(STRIPE_EXPAND_READY, &sh->state);
5916 set_bit(STRIPE_HANDLE, &sh->state);
5918 list_add(&sh->lru, &stripes);
5920 spin_lock_irq(&conf->device_lock);
5921 if (mddev->reshape_backwards)
5922 conf->reshape_progress -= reshape_sectors * new_data_disks;
5924 conf->reshape_progress += reshape_sectors * new_data_disks;
5925 spin_unlock_irq(&conf->device_lock);
5926 /* Ok, those stripe are ready. We can start scheduling
5927 * reads on the source stripes.
5928 * The source stripes are determined by mapping the first and last
5929 * block on the destination stripes.
5932 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5935 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5936 * new_data_disks - 1),
5938 if (last_sector >= mddev->dev_sectors)
5939 last_sector = mddev->dev_sectors - 1;
5940 while (first_sector <= last_sector) {
5941 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5942 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5943 set_bit(STRIPE_HANDLE, &sh->state);
5944 raid5_release_stripe(sh);
5945 first_sector += STRIPE_SECTORS;
5947 /* Now that the sources are clearly marked, we can release
5948 * the destination stripes
5950 while (!list_empty(&stripes)) {
5951 sh = list_entry(stripes.next, struct stripe_head, lru);
5952 list_del_init(&sh->lru);
5953 raid5_release_stripe(sh);
5955 /* If this takes us to the resync_max point where we have to pause,
5956 * then we need to write out the superblock.
5958 sector_nr += reshape_sectors;
5959 retn = reshape_sectors;
5961 if (mddev->curr_resync_completed > mddev->resync_max ||
5962 (sector_nr - mddev->curr_resync_completed) * 2
5963 >= mddev->resync_max - mddev->curr_resync_completed) {
5964 /* Cannot proceed until we've updated the superblock... */
5965 wait_event(conf->wait_for_overlap,
5966 atomic_read(&conf->reshape_stripes) == 0
5967 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5968 if (atomic_read(&conf->reshape_stripes) != 0)
5970 mddev->reshape_position = conf->reshape_progress;
5971 mddev->curr_resync_completed = sector_nr;
5972 conf->reshape_checkpoint = jiffies;
5973 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
5974 md_wakeup_thread(mddev->thread);
5975 wait_event(mddev->sb_wait,
5976 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
5977 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5978 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5980 spin_lock_irq(&conf->device_lock);
5981 conf->reshape_safe = mddev->reshape_position;
5982 spin_unlock_irq(&conf->device_lock);
5983 wake_up(&conf->wait_for_overlap);
5984 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5990 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
5993 struct r5conf *conf = mddev->private;
5994 struct stripe_head *sh;
5995 sector_t max_sector = mddev->dev_sectors;
5996 sector_t sync_blocks;
5997 int still_degraded = 0;
6000 if (sector_nr >= max_sector) {
6001 /* just being told to finish up .. nothing much to do */
6003 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6008 if (mddev->curr_resync < max_sector) /* aborted */
6009 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6011 else /* completed sync */
6013 bitmap_close_sync(mddev->bitmap);
6018 /* Allow raid5_quiesce to complete */
6019 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6021 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6022 return reshape_request(mddev, sector_nr, skipped);
6024 /* No need to check resync_max as we never do more than one
6025 * stripe, and as resync_max will always be on a chunk boundary,
6026 * if the check in md_do_sync didn't fire, there is no chance
6027 * of overstepping resync_max here
6030 /* if there is too many failed drives and we are trying
6031 * to resync, then assert that we are finished, because there is
6032 * nothing we can do.
6034 if (mddev->degraded >= conf->max_degraded &&
6035 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6036 sector_t rv = mddev->dev_sectors - sector_nr;
6040 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6042 !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6043 sync_blocks >= STRIPE_SECTORS) {
6044 /* we can skip this block, and probably more */
6045 sync_blocks /= STRIPE_SECTORS;
6047 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
6050 bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6052 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6054 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6055 /* make sure we don't swamp the stripe cache if someone else
6056 * is trying to get access
6058 schedule_timeout_uninterruptible(1);
6060 /* Need to check if array will still be degraded after recovery/resync
6061 * Note in case of > 1 drive failures it's possible we're rebuilding
6062 * one drive while leaving another faulty drive in array.
6065 for (i = 0; i < conf->raid_disks; i++) {
6066 struct md_rdev *rdev = ACCESS_ONCE(conf->disks[i].rdev);
6068 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6073 bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6075 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6076 set_bit(STRIPE_HANDLE, &sh->state);
6078 raid5_release_stripe(sh);
6080 return STRIPE_SECTORS;
6083 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6084 unsigned int offset)
6086 /* We may not be able to submit a whole bio at once as there
6087 * may not be enough stripe_heads available.
6088 * We cannot pre-allocate enough stripe_heads as we may need
6089 * more than exist in the cache (if we allow ever large chunks).
6090 * So we do one stripe head at a time and record in
6091 * ->bi_hw_segments how many have been done.
6093 * We *know* that this entire raid_bio is in one chunk, so
6094 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6096 struct stripe_head *sh;
6098 sector_t sector, logical_sector, last_sector;
6102 logical_sector = raid_bio->bi_iter.bi_sector &
6103 ~((sector_t)STRIPE_SECTORS-1);
6104 sector = raid5_compute_sector(conf, logical_sector,
6106 last_sector = bio_end_sector(raid_bio);
6108 for (; logical_sector < last_sector;
6109 logical_sector += STRIPE_SECTORS,
6110 sector += STRIPE_SECTORS,
6114 /* already done this stripe */
6117 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6120 /* failed to get a stripe - must wait */
6121 conf->retry_read_aligned = raid_bio;
6122 conf->retry_read_offset = scnt;
6126 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6127 raid5_release_stripe(sh);
6128 conf->retry_read_aligned = raid_bio;
6129 conf->retry_read_offset = scnt;
6133 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6135 raid5_release_stripe(sh);
6139 bio_endio(raid_bio);
6141 if (atomic_dec_and_test(&conf->active_aligned_reads))
6142 wake_up(&conf->wait_for_quiescent);
6146 static int handle_active_stripes(struct r5conf *conf, int group,
6147 struct r5worker *worker,
6148 struct list_head *temp_inactive_list)
6150 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6151 int i, batch_size = 0, hash;
6152 bool release_inactive = false;
6154 while (batch_size < MAX_STRIPE_BATCH &&
6155 (sh = __get_priority_stripe(conf, group)) != NULL)
6156 batch[batch_size++] = sh;
6158 if (batch_size == 0) {
6159 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6160 if (!list_empty(temp_inactive_list + i))
6162 if (i == NR_STRIPE_HASH_LOCKS) {
6163 spin_unlock_irq(&conf->device_lock);
6164 r5l_flush_stripe_to_raid(conf->log);
6165 spin_lock_irq(&conf->device_lock);
6168 release_inactive = true;
6170 spin_unlock_irq(&conf->device_lock);
6172 release_inactive_stripe_list(conf, temp_inactive_list,
6173 NR_STRIPE_HASH_LOCKS);
6175 r5l_flush_stripe_to_raid(conf->log);
6176 if (release_inactive) {
6177 spin_lock_irq(&conf->device_lock);
6181 for (i = 0; i < batch_size; i++)
6182 handle_stripe(batch[i]);
6183 log_write_stripe_run(conf);
6187 spin_lock_irq(&conf->device_lock);
6188 for (i = 0; i < batch_size; i++) {
6189 hash = batch[i]->hash_lock_index;
6190 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6195 static void raid5_do_work(struct work_struct *work)
6197 struct r5worker *worker = container_of(work, struct r5worker, work);
6198 struct r5worker_group *group = worker->group;
6199 struct r5conf *conf = group->conf;
6200 struct mddev *mddev = conf->mddev;
6201 int group_id = group - conf->worker_groups;
6203 struct blk_plug plug;
6205 pr_debug("+++ raid5worker active\n");
6207 blk_start_plug(&plug);
6209 spin_lock_irq(&conf->device_lock);
6211 int batch_size, released;
6213 released = release_stripe_list(conf, worker->temp_inactive_list);
6215 batch_size = handle_active_stripes(conf, group_id, worker,
6216 worker->temp_inactive_list);
6217 worker->working = false;
6218 if (!batch_size && !released)
6220 handled += batch_size;
6221 wait_event_lock_irq(mddev->sb_wait,
6222 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6225 pr_debug("%d stripes handled\n", handled);
6227 spin_unlock_irq(&conf->device_lock);
6229 flush_deferred_bios(conf);
6231 r5l_flush_stripe_to_raid(conf->log);
6233 async_tx_issue_pending_all();
6234 blk_finish_plug(&plug);
6236 pr_debug("--- raid5worker inactive\n");
6240 * This is our raid5 kernel thread.
6242 * We scan the hash table for stripes which can be handled now.
6243 * During the scan, completed stripes are saved for us by the interrupt
6244 * handler, so that they will not have to wait for our next wakeup.
6246 static void raid5d(struct md_thread *thread)
6248 struct mddev *mddev = thread->mddev;
6249 struct r5conf *conf = mddev->private;
6251 struct blk_plug plug;
6253 pr_debug("+++ raid5d active\n");
6255 md_check_recovery(mddev);
6257 blk_start_plug(&plug);
6259 spin_lock_irq(&conf->device_lock);
6262 int batch_size, released;
6263 unsigned int offset;
6265 released = release_stripe_list(conf, conf->temp_inactive_list);
6267 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6270 !list_empty(&conf->bitmap_list)) {
6271 /* Now is a good time to flush some bitmap updates */
6273 spin_unlock_irq(&conf->device_lock);
6274 bitmap_unplug(mddev->bitmap);
6275 spin_lock_irq(&conf->device_lock);
6276 conf->seq_write = conf->seq_flush;
6277 activate_bit_delay(conf, conf->temp_inactive_list);
6279 raid5_activate_delayed(conf);
6281 while ((bio = remove_bio_from_retry(conf, &offset))) {
6283 spin_unlock_irq(&conf->device_lock);
6284 ok = retry_aligned_read(conf, bio, offset);
6285 spin_lock_irq(&conf->device_lock);
6291 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6292 conf->temp_inactive_list);
6293 if (!batch_size && !released)
6295 handled += batch_size;
6297 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6298 spin_unlock_irq(&conf->device_lock);
6299 md_check_recovery(mddev);
6300 spin_lock_irq(&conf->device_lock);
6303 pr_debug("%d stripes handled\n", handled);
6305 spin_unlock_irq(&conf->device_lock);
6306 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6307 mutex_trylock(&conf->cache_size_mutex)) {
6308 grow_one_stripe(conf, __GFP_NOWARN);
6309 /* Set flag even if allocation failed. This helps
6310 * slow down allocation requests when mem is short
6312 set_bit(R5_DID_ALLOC, &conf->cache_state);
6313 mutex_unlock(&conf->cache_size_mutex);
6316 flush_deferred_bios(conf);
6318 r5l_flush_stripe_to_raid(conf->log);
6320 async_tx_issue_pending_all();
6321 blk_finish_plug(&plug);
6323 pr_debug("--- raid5d inactive\n");
6327 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6329 struct r5conf *conf;
6331 spin_lock(&mddev->lock);
6332 conf = mddev->private;
6334 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6335 spin_unlock(&mddev->lock);
6340 raid5_set_cache_size(struct mddev *mddev, int size)
6342 struct r5conf *conf = mddev->private;
6344 if (size <= 16 || size > 32768)
6347 conf->min_nr_stripes = size;
6348 mutex_lock(&conf->cache_size_mutex);
6349 while (size < conf->max_nr_stripes &&
6350 drop_one_stripe(conf))
6352 mutex_unlock(&conf->cache_size_mutex);
6354 md_allow_write(mddev);
6356 mutex_lock(&conf->cache_size_mutex);
6357 while (size > conf->max_nr_stripes)
6358 if (!grow_one_stripe(conf, GFP_KERNEL))
6360 mutex_unlock(&conf->cache_size_mutex);
6364 EXPORT_SYMBOL(raid5_set_cache_size);
6367 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6369 struct r5conf *conf;
6373 if (len >= PAGE_SIZE)
6375 if (kstrtoul(page, 10, &new))
6377 err = mddev_lock(mddev);
6380 conf = mddev->private;
6384 err = raid5_set_cache_size(mddev, new);
6385 mddev_unlock(mddev);
6390 static struct md_sysfs_entry
6391 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6392 raid5_show_stripe_cache_size,
6393 raid5_store_stripe_cache_size);
6396 raid5_show_rmw_level(struct mddev *mddev, char *page)
6398 struct r5conf *conf = mddev->private;
6400 return sprintf(page, "%d\n", conf->rmw_level);
6406 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6408 struct r5conf *conf = mddev->private;
6414 if (len >= PAGE_SIZE)
6417 if (kstrtoul(page, 10, &new))
6420 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6423 if (new != PARITY_DISABLE_RMW &&
6424 new != PARITY_ENABLE_RMW &&
6425 new != PARITY_PREFER_RMW)
6428 conf->rmw_level = new;
6432 static struct md_sysfs_entry
6433 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6434 raid5_show_rmw_level,
6435 raid5_store_rmw_level);
6439 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6441 struct r5conf *conf;
6443 spin_lock(&mddev->lock);
6444 conf = mddev->private;
6446 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6447 spin_unlock(&mddev->lock);
6452 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6454 struct r5conf *conf;
6458 if (len >= PAGE_SIZE)
6460 if (kstrtoul(page, 10, &new))
6463 err = mddev_lock(mddev);
6466 conf = mddev->private;
6469 else if (new > conf->min_nr_stripes)
6472 conf->bypass_threshold = new;
6473 mddev_unlock(mddev);
6477 static struct md_sysfs_entry
6478 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6480 raid5_show_preread_threshold,
6481 raid5_store_preread_threshold);
6484 raid5_show_skip_copy(struct mddev *mddev, char *page)
6486 struct r5conf *conf;
6488 spin_lock(&mddev->lock);
6489 conf = mddev->private;
6491 ret = sprintf(page, "%d\n", conf->skip_copy);
6492 spin_unlock(&mddev->lock);
6497 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6499 struct r5conf *conf;
6503 if (len >= PAGE_SIZE)
6505 if (kstrtoul(page, 10, &new))
6509 err = mddev_lock(mddev);
6512 conf = mddev->private;
6515 else if (new != conf->skip_copy) {
6516 mddev_suspend(mddev);
6517 conf->skip_copy = new;
6519 mddev->queue->backing_dev_info->capabilities |=
6520 BDI_CAP_STABLE_WRITES;
6522 mddev->queue->backing_dev_info->capabilities &=
6523 ~BDI_CAP_STABLE_WRITES;
6524 mddev_resume(mddev);
6526 mddev_unlock(mddev);
6530 static struct md_sysfs_entry
6531 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6532 raid5_show_skip_copy,
6533 raid5_store_skip_copy);
6536 stripe_cache_active_show(struct mddev *mddev, char *page)
6538 struct r5conf *conf = mddev->private;
6540 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6545 static struct md_sysfs_entry
6546 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6549 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6551 struct r5conf *conf;
6553 spin_lock(&mddev->lock);
6554 conf = mddev->private;
6556 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6557 spin_unlock(&mddev->lock);
6561 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6563 int *worker_cnt_per_group,
6564 struct r5worker_group **worker_groups);
6566 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6568 struct r5conf *conf;
6571 struct r5worker_group *new_groups, *old_groups;
6572 int group_cnt, worker_cnt_per_group;
6574 if (len >= PAGE_SIZE)
6576 if (kstrtoul(page, 10, &new))
6579 err = mddev_lock(mddev);
6582 conf = mddev->private;
6585 else if (new != conf->worker_cnt_per_group) {
6586 mddev_suspend(mddev);
6588 old_groups = conf->worker_groups;
6590 flush_workqueue(raid5_wq);
6592 err = alloc_thread_groups(conf, new,
6593 &group_cnt, &worker_cnt_per_group,
6596 spin_lock_irq(&conf->device_lock);
6597 conf->group_cnt = group_cnt;
6598 conf->worker_cnt_per_group = worker_cnt_per_group;
6599 conf->worker_groups = new_groups;
6600 spin_unlock_irq(&conf->device_lock);
6603 kfree(old_groups[0].workers);
6606 mddev_resume(mddev);
6608 mddev_unlock(mddev);
6613 static struct md_sysfs_entry
6614 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6615 raid5_show_group_thread_cnt,
6616 raid5_store_group_thread_cnt);
6618 static struct attribute *raid5_attrs[] = {
6619 &raid5_stripecache_size.attr,
6620 &raid5_stripecache_active.attr,
6621 &raid5_preread_bypass_threshold.attr,
6622 &raid5_group_thread_cnt.attr,
6623 &raid5_skip_copy.attr,
6624 &raid5_rmw_level.attr,
6625 &r5c_journal_mode.attr,
6628 static struct attribute_group raid5_attrs_group = {
6630 .attrs = raid5_attrs,
6633 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6635 int *worker_cnt_per_group,
6636 struct r5worker_group **worker_groups)
6640 struct r5worker *workers;
6642 *worker_cnt_per_group = cnt;
6645 *worker_groups = NULL;
6648 *group_cnt = num_possible_nodes();
6649 size = sizeof(struct r5worker) * cnt;
6650 workers = kzalloc(size * *group_cnt, GFP_NOIO);
6651 *worker_groups = kzalloc(sizeof(struct r5worker_group) *
6652 *group_cnt, GFP_NOIO);
6653 if (!*worker_groups || !workers) {
6655 kfree(*worker_groups);
6659 for (i = 0; i < *group_cnt; i++) {
6660 struct r5worker_group *group;
6662 group = &(*worker_groups)[i];
6663 INIT_LIST_HEAD(&group->handle_list);
6664 INIT_LIST_HEAD(&group->loprio_list);
6666 group->workers = workers + i * cnt;
6668 for (j = 0; j < cnt; j++) {
6669 struct r5worker *worker = group->workers + j;
6670 worker->group = group;
6671 INIT_WORK(&worker->work, raid5_do_work);
6673 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6674 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6681 static void free_thread_groups(struct r5conf *conf)
6683 if (conf->worker_groups)
6684 kfree(conf->worker_groups[0].workers);
6685 kfree(conf->worker_groups);
6686 conf->worker_groups = NULL;
6690 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6692 struct r5conf *conf = mddev->private;
6695 sectors = mddev->dev_sectors;
6697 /* size is defined by the smallest of previous and new size */
6698 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6700 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6701 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6702 return sectors * (raid_disks - conf->max_degraded);
6705 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6707 safe_put_page(percpu->spare_page);
6708 if (percpu->scribble)
6709 flex_array_free(percpu->scribble);
6710 percpu->spare_page = NULL;
6711 percpu->scribble = NULL;
6714 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6716 if (conf->level == 6 && !percpu->spare_page)
6717 percpu->spare_page = alloc_page(GFP_KERNEL);
6718 if (!percpu->scribble)
6719 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6720 conf->previous_raid_disks),
6721 max(conf->chunk_sectors,
6722 conf->prev_chunk_sectors)
6726 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6727 free_scratch_buffer(conf, percpu);
6734 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
6736 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6738 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6742 static void raid5_free_percpu(struct r5conf *conf)
6747 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6748 free_percpu(conf->percpu);
6751 static void free_conf(struct r5conf *conf)
6757 if (conf->shrinker.nr_deferred)
6758 unregister_shrinker(&conf->shrinker);
6760 free_thread_groups(conf);
6761 shrink_stripes(conf);
6762 raid5_free_percpu(conf);
6763 for (i = 0; i < conf->pool_size; i++)
6764 if (conf->disks[i].extra_page)
6765 put_page(conf->disks[i].extra_page);
6767 if (conf->bio_split)
6768 bioset_free(conf->bio_split);
6769 kfree(conf->stripe_hashtbl);
6770 kfree(conf->pending_data);
6774 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
6776 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
6777 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6779 if (alloc_scratch_buffer(conf, percpu)) {
6780 pr_warn("%s: failed memory allocation for cpu%u\n",
6787 static int raid5_alloc_percpu(struct r5conf *conf)
6791 conf->percpu = alloc_percpu(struct raid5_percpu);
6795 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
6797 conf->scribble_disks = max(conf->raid_disks,
6798 conf->previous_raid_disks);
6799 conf->scribble_sectors = max(conf->chunk_sectors,
6800 conf->prev_chunk_sectors);
6805 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6806 struct shrink_control *sc)
6808 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6809 unsigned long ret = SHRINK_STOP;
6811 if (mutex_trylock(&conf->cache_size_mutex)) {
6813 while (ret < sc->nr_to_scan &&
6814 conf->max_nr_stripes > conf->min_nr_stripes) {
6815 if (drop_one_stripe(conf) == 0) {
6821 mutex_unlock(&conf->cache_size_mutex);
6826 static unsigned long raid5_cache_count(struct shrinker *shrink,
6827 struct shrink_control *sc)
6829 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6831 if (conf->max_nr_stripes < conf->min_nr_stripes)
6832 /* unlikely, but not impossible */
6834 return conf->max_nr_stripes - conf->min_nr_stripes;
6837 static struct r5conf *setup_conf(struct mddev *mddev)
6839 struct r5conf *conf;
6840 int raid_disk, memory, max_disks;
6841 struct md_rdev *rdev;
6842 struct disk_info *disk;
6845 int group_cnt, worker_cnt_per_group;
6846 struct r5worker_group *new_group;
6848 if (mddev->new_level != 5
6849 && mddev->new_level != 4
6850 && mddev->new_level != 6) {
6851 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6852 mdname(mddev), mddev->new_level);
6853 return ERR_PTR(-EIO);
6855 if ((mddev->new_level == 5
6856 && !algorithm_valid_raid5(mddev->new_layout)) ||
6857 (mddev->new_level == 6
6858 && !algorithm_valid_raid6(mddev->new_layout))) {
6859 pr_warn("md/raid:%s: layout %d not supported\n",
6860 mdname(mddev), mddev->new_layout);
6861 return ERR_PTR(-EIO);
6863 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6864 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6865 mdname(mddev), mddev->raid_disks);
6866 return ERR_PTR(-EINVAL);
6869 if (!mddev->new_chunk_sectors ||
6870 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6871 !is_power_of_2(mddev->new_chunk_sectors)) {
6872 pr_warn("md/raid:%s: invalid chunk size %d\n",
6873 mdname(mddev), mddev->new_chunk_sectors << 9);
6874 return ERR_PTR(-EINVAL);
6877 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6880 INIT_LIST_HEAD(&conf->free_list);
6881 INIT_LIST_HEAD(&conf->pending_list);
6882 conf->pending_data = kzalloc(sizeof(struct r5pending_data) *
6883 PENDING_IO_MAX, GFP_KERNEL);
6884 if (!conf->pending_data)
6886 for (i = 0; i < PENDING_IO_MAX; i++)
6887 list_add(&conf->pending_data[i].sibling, &conf->free_list);
6888 /* Don't enable multi-threading by default*/
6889 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6891 conf->group_cnt = group_cnt;
6892 conf->worker_cnt_per_group = worker_cnt_per_group;
6893 conf->worker_groups = new_group;
6896 spin_lock_init(&conf->device_lock);
6897 seqcount_init(&conf->gen_lock);
6898 mutex_init(&conf->cache_size_mutex);
6899 init_waitqueue_head(&conf->wait_for_quiescent);
6900 init_waitqueue_head(&conf->wait_for_stripe);
6901 init_waitqueue_head(&conf->wait_for_overlap);
6902 INIT_LIST_HEAD(&conf->handle_list);
6903 INIT_LIST_HEAD(&conf->loprio_list);
6904 INIT_LIST_HEAD(&conf->hold_list);
6905 INIT_LIST_HEAD(&conf->delayed_list);
6906 INIT_LIST_HEAD(&conf->bitmap_list);
6907 init_llist_head(&conf->released_stripes);
6908 atomic_set(&conf->active_stripes, 0);
6909 atomic_set(&conf->preread_active_stripes, 0);
6910 atomic_set(&conf->active_aligned_reads, 0);
6911 spin_lock_init(&conf->pending_bios_lock);
6912 conf->batch_bio_dispatch = true;
6913 rdev_for_each(rdev, mddev) {
6914 if (test_bit(Journal, &rdev->flags))
6916 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
6917 conf->batch_bio_dispatch = false;
6922 conf->bypass_threshold = BYPASS_THRESHOLD;
6923 conf->recovery_disabled = mddev->recovery_disabled - 1;
6925 conf->raid_disks = mddev->raid_disks;
6926 if (mddev->reshape_position == MaxSector)
6927 conf->previous_raid_disks = mddev->raid_disks;
6929 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6930 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6932 conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
6938 for (i = 0; i < max_disks; i++) {
6939 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
6940 if (!conf->disks[i].extra_page)
6944 conf->bio_split = bioset_create(BIO_POOL_SIZE, 0, 0);
6945 if (!conf->bio_split)
6947 conf->mddev = mddev;
6949 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
6952 /* We init hash_locks[0] separately to that it can be used
6953 * as the reference lock in the spin_lock_nest_lock() call
6954 * in lock_all_device_hash_locks_irq in order to convince
6955 * lockdep that we know what we are doing.
6957 spin_lock_init(conf->hash_locks);
6958 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
6959 spin_lock_init(conf->hash_locks + i);
6961 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6962 INIT_LIST_HEAD(conf->inactive_list + i);
6964 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6965 INIT_LIST_HEAD(conf->temp_inactive_list + i);
6967 atomic_set(&conf->r5c_cached_full_stripes, 0);
6968 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
6969 atomic_set(&conf->r5c_cached_partial_stripes, 0);
6970 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
6971 atomic_set(&conf->r5c_flushing_full_stripes, 0);
6972 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
6974 conf->level = mddev->new_level;
6975 conf->chunk_sectors = mddev->new_chunk_sectors;
6976 if (raid5_alloc_percpu(conf) != 0)
6979 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
6981 rdev_for_each(rdev, mddev) {
6982 raid_disk = rdev->raid_disk;
6983 if (raid_disk >= max_disks
6984 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
6986 disk = conf->disks + raid_disk;
6988 if (test_bit(Replacement, &rdev->flags)) {
6989 if (disk->replacement)
6991 disk->replacement = rdev;
6998 if (test_bit(In_sync, &rdev->flags)) {
6999 char b[BDEVNAME_SIZE];
7000 pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7001 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7002 } else if (rdev->saved_raid_disk != raid_disk)
7003 /* Cannot rely on bitmap to complete recovery */
7007 conf->level = mddev->new_level;
7008 if (conf->level == 6) {
7009 conf->max_degraded = 2;
7010 if (raid6_call.xor_syndrome)
7011 conf->rmw_level = PARITY_ENABLE_RMW;
7013 conf->rmw_level = PARITY_DISABLE_RMW;
7015 conf->max_degraded = 1;
7016 conf->rmw_level = PARITY_ENABLE_RMW;
7018 conf->algorithm = mddev->new_layout;
7019 conf->reshape_progress = mddev->reshape_position;
7020 if (conf->reshape_progress != MaxSector) {
7021 conf->prev_chunk_sectors = mddev->chunk_sectors;
7022 conf->prev_algo = mddev->layout;
7024 conf->prev_chunk_sectors = conf->chunk_sectors;
7025 conf->prev_algo = conf->algorithm;
7028 conf->min_nr_stripes = NR_STRIPES;
7029 if (mddev->reshape_position != MaxSector) {
7030 int stripes = max_t(int,
7031 ((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4,
7032 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4);
7033 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7034 if (conf->min_nr_stripes != NR_STRIPES)
7035 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7036 mdname(mddev), conf->min_nr_stripes);
7038 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7039 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7040 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7041 if (grow_stripes(conf, conf->min_nr_stripes)) {
7042 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7043 mdname(mddev), memory);
7046 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7048 * Losing a stripe head costs more than the time to refill it,
7049 * it reduces the queue depth and so can hurt throughput.
7050 * So set it rather large, scaled by number of devices.
7052 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7053 conf->shrinker.scan_objects = raid5_cache_scan;
7054 conf->shrinker.count_objects = raid5_cache_count;
7055 conf->shrinker.batch = 128;
7056 conf->shrinker.flags = 0;
7057 if (register_shrinker(&conf->shrinker)) {
7058 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7063 sprintf(pers_name, "raid%d", mddev->new_level);
7064 conf->thread = md_register_thread(raid5d, mddev, pers_name);
7065 if (!conf->thread) {
7066 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7076 return ERR_PTR(-EIO);
7078 return ERR_PTR(-ENOMEM);
7081 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7084 case ALGORITHM_PARITY_0:
7085 if (raid_disk < max_degraded)
7088 case ALGORITHM_PARITY_N:
7089 if (raid_disk >= raid_disks - max_degraded)
7092 case ALGORITHM_PARITY_0_6:
7093 if (raid_disk == 0 ||
7094 raid_disk == raid_disks - 1)
7097 case ALGORITHM_LEFT_ASYMMETRIC_6:
7098 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7099 case ALGORITHM_LEFT_SYMMETRIC_6:
7100 case ALGORITHM_RIGHT_SYMMETRIC_6:
7101 if (raid_disk == raid_disks - 1)
7107 static int raid5_run(struct mddev *mddev)
7109 struct r5conf *conf;
7110 int working_disks = 0;
7111 int dirty_parity_disks = 0;
7112 struct md_rdev *rdev;
7113 struct md_rdev *journal_dev = NULL;
7114 sector_t reshape_offset = 0;
7116 long long min_offset_diff = 0;
7119 if (mddev_init_writes_pending(mddev) < 0)
7122 if (mddev->recovery_cp != MaxSector)
7123 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7126 rdev_for_each(rdev, mddev) {
7129 if (test_bit(Journal, &rdev->flags)) {
7133 if (rdev->raid_disk < 0)
7135 diff = (rdev->new_data_offset - rdev->data_offset);
7137 min_offset_diff = diff;
7139 } else if (mddev->reshape_backwards &&
7140 diff < min_offset_diff)
7141 min_offset_diff = diff;
7142 else if (!mddev->reshape_backwards &&
7143 diff > min_offset_diff)
7144 min_offset_diff = diff;
7147 if (mddev->reshape_position != MaxSector) {
7148 /* Check that we can continue the reshape.
7149 * Difficulties arise if the stripe we would write to
7150 * next is at or after the stripe we would read from next.
7151 * For a reshape that changes the number of devices, this
7152 * is only possible for a very short time, and mdadm makes
7153 * sure that time appears to have past before assembling
7154 * the array. So we fail if that time hasn't passed.
7155 * For a reshape that keeps the number of devices the same
7156 * mdadm must be monitoring the reshape can keeping the
7157 * critical areas read-only and backed up. It will start
7158 * the array in read-only mode, so we check for that.
7160 sector_t here_new, here_old;
7162 int max_degraded = (mddev->level == 6 ? 2 : 1);
7167 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7172 if (mddev->new_level != mddev->level) {
7173 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7177 old_disks = mddev->raid_disks - mddev->delta_disks;
7178 /* reshape_position must be on a new-stripe boundary, and one
7179 * further up in new geometry must map after here in old
7181 * If the chunk sizes are different, then as we perform reshape
7182 * in units of the largest of the two, reshape_position needs
7183 * be a multiple of the largest chunk size times new data disks.
7185 here_new = mddev->reshape_position;
7186 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7187 new_data_disks = mddev->raid_disks - max_degraded;
7188 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7189 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7193 reshape_offset = here_new * chunk_sectors;
7194 /* here_new is the stripe we will write to */
7195 here_old = mddev->reshape_position;
7196 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7197 /* here_old is the first stripe that we might need to read
7199 if (mddev->delta_disks == 0) {
7200 /* We cannot be sure it is safe to start an in-place
7201 * reshape. It is only safe if user-space is monitoring
7202 * and taking constant backups.
7203 * mdadm always starts a situation like this in
7204 * readonly mode so it can take control before
7205 * allowing any writes. So just check for that.
7207 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7208 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7209 /* not really in-place - so OK */;
7210 else if (mddev->ro == 0) {
7211 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7215 } else if (mddev->reshape_backwards
7216 ? (here_new * chunk_sectors + min_offset_diff <=
7217 here_old * chunk_sectors)
7218 : (here_new * chunk_sectors >=
7219 here_old * chunk_sectors + (-min_offset_diff))) {
7220 /* Reading from the same stripe as writing to - bad */
7221 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7225 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7226 /* OK, we should be able to continue; */
7228 BUG_ON(mddev->level != mddev->new_level);
7229 BUG_ON(mddev->layout != mddev->new_layout);
7230 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7231 BUG_ON(mddev->delta_disks != 0);
7234 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7235 test_bit(MD_HAS_PPL, &mddev->flags)) {
7236 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7238 clear_bit(MD_HAS_PPL, &mddev->flags);
7239 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7242 if (mddev->private == NULL)
7243 conf = setup_conf(mddev);
7245 conf = mddev->private;
7248 return PTR_ERR(conf);
7250 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7252 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7255 set_disk_ro(mddev->gendisk, 1);
7256 } else if (mddev->recovery_cp == MaxSector)
7257 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7260 conf->min_offset_diff = min_offset_diff;
7261 mddev->thread = conf->thread;
7262 conf->thread = NULL;
7263 mddev->private = conf;
7265 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7267 rdev = conf->disks[i].rdev;
7268 if (!rdev && conf->disks[i].replacement) {
7269 /* The replacement is all we have yet */
7270 rdev = conf->disks[i].replacement;
7271 conf->disks[i].replacement = NULL;
7272 clear_bit(Replacement, &rdev->flags);
7273 conf->disks[i].rdev = rdev;
7277 if (conf->disks[i].replacement &&
7278 conf->reshape_progress != MaxSector) {
7279 /* replacements and reshape simply do not mix. */
7280 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7283 if (test_bit(In_sync, &rdev->flags)) {
7287 /* This disc is not fully in-sync. However if it
7288 * just stored parity (beyond the recovery_offset),
7289 * when we don't need to be concerned about the
7290 * array being dirty.
7291 * When reshape goes 'backwards', we never have
7292 * partially completed devices, so we only need
7293 * to worry about reshape going forwards.
7295 /* Hack because v0.91 doesn't store recovery_offset properly. */
7296 if (mddev->major_version == 0 &&
7297 mddev->minor_version > 90)
7298 rdev->recovery_offset = reshape_offset;
7300 if (rdev->recovery_offset < reshape_offset) {
7301 /* We need to check old and new layout */
7302 if (!only_parity(rdev->raid_disk,
7305 conf->max_degraded))
7308 if (!only_parity(rdev->raid_disk,
7310 conf->previous_raid_disks,
7311 conf->max_degraded))
7313 dirty_parity_disks++;
7317 * 0 for a fully functional array, 1 or 2 for a degraded array.
7319 mddev->degraded = raid5_calc_degraded(conf);
7321 if (has_failed(conf)) {
7322 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7323 mdname(mddev), mddev->degraded, conf->raid_disks);
7327 /* device size must be a multiple of chunk size */
7328 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7329 mddev->resync_max_sectors = mddev->dev_sectors;
7331 if (mddev->degraded > dirty_parity_disks &&
7332 mddev->recovery_cp != MaxSector) {
7333 if (test_bit(MD_HAS_PPL, &mddev->flags))
7334 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7336 else if (mddev->ok_start_degraded)
7337 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7340 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7346 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7347 mdname(mddev), conf->level,
7348 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7351 print_raid5_conf(conf);
7353 if (conf->reshape_progress != MaxSector) {
7354 conf->reshape_safe = conf->reshape_progress;
7355 atomic_set(&conf->reshape_stripes, 0);
7356 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7357 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7358 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7359 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7360 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7364 /* Ok, everything is just fine now */
7365 if (mddev->to_remove == &raid5_attrs_group)
7366 mddev->to_remove = NULL;
7367 else if (mddev->kobj.sd &&
7368 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7369 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7371 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7375 /* read-ahead size must cover two whole stripes, which
7376 * is 2 * (datadisks) * chunksize where 'n' is the
7377 * number of raid devices
7379 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7380 int stripe = data_disks *
7381 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7382 if (mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
7383 mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
7385 chunk_size = mddev->chunk_sectors << 9;
7386 blk_queue_io_min(mddev->queue, chunk_size);
7387 blk_queue_io_opt(mddev->queue, chunk_size *
7388 (conf->raid_disks - conf->max_degraded));
7389 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7391 * We can only discard a whole stripe. It doesn't make sense to
7392 * discard data disk but write parity disk
7394 stripe = stripe * PAGE_SIZE;
7395 /* Round up to power of 2, as discard handling
7396 * currently assumes that */
7397 while ((stripe-1) & stripe)
7398 stripe = (stripe | (stripe-1)) + 1;
7399 mddev->queue->limits.discard_alignment = stripe;
7400 mddev->queue->limits.discard_granularity = stripe;
7402 blk_queue_max_write_same_sectors(mddev->queue, 0);
7403 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7405 rdev_for_each(rdev, mddev) {
7406 disk_stack_limits(mddev->gendisk, rdev->bdev,
7407 rdev->data_offset << 9);
7408 disk_stack_limits(mddev->gendisk, rdev->bdev,
7409 rdev->new_data_offset << 9);
7413 * zeroing is required, otherwise data
7414 * could be lost. Consider a scenario: discard a stripe
7415 * (the stripe could be inconsistent if
7416 * discard_zeroes_data is 0); write one disk of the
7417 * stripe (the stripe could be inconsistent again
7418 * depending on which disks are used to calculate
7419 * parity); the disk is broken; The stripe data of this
7422 * We only allow DISCARD if the sysadmin has confirmed that
7423 * only safe devices are in use by setting a module parameter.
7424 * A better idea might be to turn DISCARD into WRITE_ZEROES
7425 * requests, as that is required to be safe.
7427 if (devices_handle_discard_safely &&
7428 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7429 mddev->queue->limits.discard_granularity >= stripe)
7430 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
7433 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
7436 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7439 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7444 md_unregister_thread(&mddev->thread);
7445 print_raid5_conf(conf);
7447 mddev->private = NULL;
7448 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7452 static void raid5_free(struct mddev *mddev, void *priv)
7454 struct r5conf *conf = priv;
7457 mddev->to_remove = &raid5_attrs_group;
7460 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7462 struct r5conf *conf = mddev->private;
7465 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7466 conf->chunk_sectors / 2, mddev->layout);
7467 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7469 for (i = 0; i < conf->raid_disks; i++) {
7470 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7471 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7474 seq_printf (seq, "]");
7477 static void print_raid5_conf (struct r5conf *conf)
7480 struct disk_info *tmp;
7482 pr_debug("RAID conf printout:\n");
7484 pr_debug("(conf==NULL)\n");
7487 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7489 conf->raid_disks - conf->mddev->degraded);
7491 for (i = 0; i < conf->raid_disks; i++) {
7492 char b[BDEVNAME_SIZE];
7493 tmp = conf->disks + i;
7495 pr_debug(" disk %d, o:%d, dev:%s\n",
7496 i, !test_bit(Faulty, &tmp->rdev->flags),
7497 bdevname(tmp->rdev->bdev, b));
7501 static int raid5_spare_active(struct mddev *mddev)
7504 struct r5conf *conf = mddev->private;
7505 struct disk_info *tmp;
7507 unsigned long flags;
7509 for (i = 0; i < conf->raid_disks; i++) {
7510 tmp = conf->disks + i;
7511 if (tmp->replacement
7512 && tmp->replacement->recovery_offset == MaxSector
7513 && !test_bit(Faulty, &tmp->replacement->flags)
7514 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7515 /* Replacement has just become active. */
7517 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7520 /* Replaced device not technically faulty,
7521 * but we need to be sure it gets removed
7522 * and never re-added.
7524 set_bit(Faulty, &tmp->rdev->flags);
7525 sysfs_notify_dirent_safe(
7526 tmp->rdev->sysfs_state);
7528 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7529 } else if (tmp->rdev
7530 && tmp->rdev->recovery_offset == MaxSector
7531 && !test_bit(Faulty, &tmp->rdev->flags)
7532 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7534 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7537 spin_lock_irqsave(&conf->device_lock, flags);
7538 mddev->degraded = raid5_calc_degraded(conf);
7539 spin_unlock_irqrestore(&conf->device_lock, flags);
7540 print_raid5_conf(conf);
7544 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7546 struct r5conf *conf = mddev->private;
7548 int number = rdev->raid_disk;
7549 struct md_rdev **rdevp;
7550 struct disk_info *p = conf->disks + number;
7552 print_raid5_conf(conf);
7553 if (test_bit(Journal, &rdev->flags) && conf->log) {
7555 * we can't wait pending write here, as this is called in
7556 * raid5d, wait will deadlock.
7557 * neilb: there is no locking about new writes here,
7558 * so this cannot be safe.
7560 if (atomic_read(&conf->active_stripes) ||
7561 atomic_read(&conf->r5c_cached_full_stripes) ||
7562 atomic_read(&conf->r5c_cached_partial_stripes)) {
7568 if (rdev == p->rdev)
7570 else if (rdev == p->replacement)
7571 rdevp = &p->replacement;
7575 if (number >= conf->raid_disks &&
7576 conf->reshape_progress == MaxSector)
7577 clear_bit(In_sync, &rdev->flags);
7579 if (test_bit(In_sync, &rdev->flags) ||
7580 atomic_read(&rdev->nr_pending)) {
7584 /* Only remove non-faulty devices if recovery
7587 if (!test_bit(Faulty, &rdev->flags) &&
7588 mddev->recovery_disabled != conf->recovery_disabled &&
7589 !has_failed(conf) &&
7590 (!p->replacement || p->replacement == rdev) &&
7591 number < conf->raid_disks) {
7596 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7598 if (atomic_read(&rdev->nr_pending)) {
7599 /* lost the race, try later */
7605 err = log_modify(conf, rdev, false);
7609 if (p->replacement) {
7610 /* We must have just cleared 'rdev' */
7611 p->rdev = p->replacement;
7612 clear_bit(Replacement, &p->replacement->flags);
7613 smp_mb(); /* Make sure other CPUs may see both as identical
7614 * but will never see neither - if they are careful
7616 p->replacement = NULL;
7619 err = log_modify(conf, p->rdev, true);
7622 clear_bit(WantReplacement, &rdev->flags);
7625 print_raid5_conf(conf);
7629 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7631 struct r5conf *conf = mddev->private;
7634 struct disk_info *p;
7636 int last = conf->raid_disks - 1;
7638 if (test_bit(Journal, &rdev->flags)) {
7642 rdev->raid_disk = 0;
7644 * The array is in readonly mode if journal is missing, so no
7645 * write requests running. We should be safe
7647 log_init(conf, rdev, false);
7650 if (mddev->recovery_disabled == conf->recovery_disabled)
7653 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7654 /* no point adding a device */
7657 if (rdev->raid_disk >= 0)
7658 first = last = rdev->raid_disk;
7661 * find the disk ... but prefer rdev->saved_raid_disk
7664 if (rdev->saved_raid_disk >= 0 &&
7665 rdev->saved_raid_disk >= first &&
7666 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7667 first = rdev->saved_raid_disk;
7669 for (disk = first; disk <= last; disk++) {
7670 p = conf->disks + disk;
7671 if (p->rdev == NULL) {
7672 clear_bit(In_sync, &rdev->flags);
7673 rdev->raid_disk = disk;
7674 if (rdev->saved_raid_disk != disk)
7676 rcu_assign_pointer(p->rdev, rdev);
7678 err = log_modify(conf, rdev, true);
7683 for (disk = first; disk <= last; disk++) {
7684 p = conf->disks + disk;
7685 if (test_bit(WantReplacement, &p->rdev->flags) &&
7686 p->replacement == NULL) {
7687 clear_bit(In_sync, &rdev->flags);
7688 set_bit(Replacement, &rdev->flags);
7689 rdev->raid_disk = disk;
7692 rcu_assign_pointer(p->replacement, rdev);
7697 print_raid5_conf(conf);
7701 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7703 /* no resync is happening, and there is enough space
7704 * on all devices, so we can resize.
7705 * We need to make sure resync covers any new space.
7706 * If the array is shrinking we should possibly wait until
7707 * any io in the removed space completes, but it hardly seems
7711 struct r5conf *conf = mddev->private;
7713 if (conf->log || raid5_has_ppl(conf))
7715 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7716 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7717 if (mddev->external_size &&
7718 mddev->array_sectors > newsize)
7720 if (mddev->bitmap) {
7721 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
7725 md_set_array_sectors(mddev, newsize);
7726 if (sectors > mddev->dev_sectors &&
7727 mddev->recovery_cp > mddev->dev_sectors) {
7728 mddev->recovery_cp = mddev->dev_sectors;
7729 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7731 mddev->dev_sectors = sectors;
7732 mddev->resync_max_sectors = sectors;
7736 static int check_stripe_cache(struct mddev *mddev)
7738 /* Can only proceed if there are plenty of stripe_heads.
7739 * We need a minimum of one full stripe,, and for sensible progress
7740 * it is best to have about 4 times that.
7741 * If we require 4 times, then the default 256 4K stripe_heads will
7742 * allow for chunk sizes up to 256K, which is probably OK.
7743 * If the chunk size is greater, user-space should request more
7744 * stripe_heads first.
7746 struct r5conf *conf = mddev->private;
7747 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7748 > conf->min_nr_stripes ||
7749 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7750 > conf->min_nr_stripes) {
7751 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7753 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7760 static int check_reshape(struct mddev *mddev)
7762 struct r5conf *conf = mddev->private;
7764 if (conf->log || raid5_has_ppl(conf))
7766 if (mddev->delta_disks == 0 &&
7767 mddev->new_layout == mddev->layout &&
7768 mddev->new_chunk_sectors == mddev->chunk_sectors)
7769 return 0; /* nothing to do */
7770 if (has_failed(conf))
7772 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7773 /* We might be able to shrink, but the devices must
7774 * be made bigger first.
7775 * For raid6, 4 is the minimum size.
7776 * Otherwise 2 is the minimum
7779 if (mddev->level == 6)
7781 if (mddev->raid_disks + mddev->delta_disks < min)
7785 if (!check_stripe_cache(mddev))
7788 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7789 mddev->delta_disks > 0)
7790 if (resize_chunks(conf,
7791 conf->previous_raid_disks
7792 + max(0, mddev->delta_disks),
7793 max(mddev->new_chunk_sectors,
7794 mddev->chunk_sectors)
7798 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
7799 return 0; /* never bother to shrink */
7800 return resize_stripes(conf, (conf->previous_raid_disks
7801 + mddev->delta_disks));
7804 static int raid5_start_reshape(struct mddev *mddev)
7806 struct r5conf *conf = mddev->private;
7807 struct md_rdev *rdev;
7809 unsigned long flags;
7811 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7814 if (!check_stripe_cache(mddev))
7817 if (has_failed(conf))
7820 rdev_for_each(rdev, mddev) {
7821 if (!test_bit(In_sync, &rdev->flags)
7822 && !test_bit(Faulty, &rdev->flags))
7826 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7827 /* Not enough devices even to make a degraded array
7832 /* Refuse to reduce size of the array. Any reductions in
7833 * array size must be through explicit setting of array_size
7836 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7837 < mddev->array_sectors) {
7838 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
7843 atomic_set(&conf->reshape_stripes, 0);
7844 spin_lock_irq(&conf->device_lock);
7845 write_seqcount_begin(&conf->gen_lock);
7846 conf->previous_raid_disks = conf->raid_disks;
7847 conf->raid_disks += mddev->delta_disks;
7848 conf->prev_chunk_sectors = conf->chunk_sectors;
7849 conf->chunk_sectors = mddev->new_chunk_sectors;
7850 conf->prev_algo = conf->algorithm;
7851 conf->algorithm = mddev->new_layout;
7853 /* Code that selects data_offset needs to see the generation update
7854 * if reshape_progress has been set - so a memory barrier needed.
7857 if (mddev->reshape_backwards)
7858 conf->reshape_progress = raid5_size(mddev, 0, 0);
7860 conf->reshape_progress = 0;
7861 conf->reshape_safe = conf->reshape_progress;
7862 write_seqcount_end(&conf->gen_lock);
7863 spin_unlock_irq(&conf->device_lock);
7865 /* Now make sure any requests that proceeded on the assumption
7866 * the reshape wasn't running - like Discard or Read - have
7869 mddev_suspend(mddev);
7870 mddev_resume(mddev);
7872 /* Add some new drives, as many as will fit.
7873 * We know there are enough to make the newly sized array work.
7874 * Don't add devices if we are reducing the number of
7875 * devices in the array. This is because it is not possible
7876 * to correctly record the "partially reconstructed" state of
7877 * such devices during the reshape and confusion could result.
7879 if (mddev->delta_disks >= 0) {
7880 rdev_for_each(rdev, mddev)
7881 if (rdev->raid_disk < 0 &&
7882 !test_bit(Faulty, &rdev->flags)) {
7883 if (raid5_add_disk(mddev, rdev) == 0) {
7885 >= conf->previous_raid_disks)
7886 set_bit(In_sync, &rdev->flags);
7888 rdev->recovery_offset = 0;
7890 if (sysfs_link_rdev(mddev, rdev))
7891 /* Failure here is OK */;
7893 } else if (rdev->raid_disk >= conf->previous_raid_disks
7894 && !test_bit(Faulty, &rdev->flags)) {
7895 /* This is a spare that was manually added */
7896 set_bit(In_sync, &rdev->flags);
7899 /* When a reshape changes the number of devices,
7900 * ->degraded is measured against the larger of the
7901 * pre and post number of devices.
7903 spin_lock_irqsave(&conf->device_lock, flags);
7904 mddev->degraded = raid5_calc_degraded(conf);
7905 spin_unlock_irqrestore(&conf->device_lock, flags);
7907 mddev->raid_disks = conf->raid_disks;
7908 mddev->reshape_position = conf->reshape_progress;
7909 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
7911 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7912 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7913 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7914 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7915 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7916 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7918 if (!mddev->sync_thread) {
7919 mddev->recovery = 0;
7920 spin_lock_irq(&conf->device_lock);
7921 write_seqcount_begin(&conf->gen_lock);
7922 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7923 mddev->new_chunk_sectors =
7924 conf->chunk_sectors = conf->prev_chunk_sectors;
7925 mddev->new_layout = conf->algorithm = conf->prev_algo;
7926 rdev_for_each(rdev, mddev)
7927 rdev->new_data_offset = rdev->data_offset;
7929 conf->generation --;
7930 conf->reshape_progress = MaxSector;
7931 mddev->reshape_position = MaxSector;
7932 write_seqcount_end(&conf->gen_lock);
7933 spin_unlock_irq(&conf->device_lock);
7936 conf->reshape_checkpoint = jiffies;
7937 md_wakeup_thread(mddev->sync_thread);
7938 md_new_event(mddev);
7942 /* This is called from the reshape thread and should make any
7943 * changes needed in 'conf'
7945 static void end_reshape(struct r5conf *conf)
7948 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
7950 spin_lock_irq(&conf->device_lock);
7951 conf->previous_raid_disks = conf->raid_disks;
7952 md_finish_reshape(conf->mddev);
7954 conf->reshape_progress = MaxSector;
7955 conf->mddev->reshape_position = MaxSector;
7956 spin_unlock_irq(&conf->device_lock);
7957 wake_up(&conf->wait_for_overlap);
7959 /* read-ahead size must cover two whole stripes, which is
7960 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
7962 if (conf->mddev->queue) {
7963 int data_disks = conf->raid_disks - conf->max_degraded;
7964 int stripe = data_disks * ((conf->chunk_sectors << 9)
7966 if (conf->mddev->queue->backing_dev_info->ra_pages < 2 * stripe)
7967 conf->mddev->queue->backing_dev_info->ra_pages = 2 * stripe;
7972 /* This is called from the raid5d thread with mddev_lock held.
7973 * It makes config changes to the device.
7975 static void raid5_finish_reshape(struct mddev *mddev)
7977 struct r5conf *conf = mddev->private;
7979 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7981 if (mddev->delta_disks > 0) {
7982 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7984 set_capacity(mddev->gendisk, mddev->array_sectors);
7985 revalidate_disk(mddev->gendisk);
7989 spin_lock_irq(&conf->device_lock);
7990 mddev->degraded = raid5_calc_degraded(conf);
7991 spin_unlock_irq(&conf->device_lock);
7992 for (d = conf->raid_disks ;
7993 d < conf->raid_disks - mddev->delta_disks;
7995 struct md_rdev *rdev = conf->disks[d].rdev;
7997 clear_bit(In_sync, &rdev->flags);
7998 rdev = conf->disks[d].replacement;
8000 clear_bit(In_sync, &rdev->flags);
8003 mddev->layout = conf->algorithm;
8004 mddev->chunk_sectors = conf->chunk_sectors;
8005 mddev->reshape_position = MaxSector;
8006 mddev->delta_disks = 0;
8007 mddev->reshape_backwards = 0;
8011 static void raid5_quiesce(struct mddev *mddev, int state)
8013 struct r5conf *conf = mddev->private;
8016 case 2: /* resume for a suspend */
8017 wake_up(&conf->wait_for_overlap);
8020 case 1: /* stop all writes */
8021 lock_all_device_hash_locks_irq(conf);
8022 /* '2' tells resync/reshape to pause so that all
8023 * active stripes can drain
8025 r5c_flush_cache(conf, INT_MAX);
8027 wait_event_cmd(conf->wait_for_quiescent,
8028 atomic_read(&conf->active_stripes) == 0 &&
8029 atomic_read(&conf->active_aligned_reads) == 0,
8030 unlock_all_device_hash_locks_irq(conf),
8031 lock_all_device_hash_locks_irq(conf));
8033 unlock_all_device_hash_locks_irq(conf);
8034 /* allow reshape to continue */
8035 wake_up(&conf->wait_for_overlap);
8038 case 0: /* re-enable writes */
8039 lock_all_device_hash_locks_irq(conf);
8041 wake_up(&conf->wait_for_quiescent);
8042 wake_up(&conf->wait_for_overlap);
8043 unlock_all_device_hash_locks_irq(conf);
8046 r5l_quiesce(conf->log, state);
8049 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8051 struct r0conf *raid0_conf = mddev->private;
8054 /* for raid0 takeover only one zone is supported */
8055 if (raid0_conf->nr_strip_zones > 1) {
8056 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8058 return ERR_PTR(-EINVAL);
8061 sectors = raid0_conf->strip_zone[0].zone_end;
8062 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8063 mddev->dev_sectors = sectors;
8064 mddev->new_level = level;
8065 mddev->new_layout = ALGORITHM_PARITY_N;
8066 mddev->new_chunk_sectors = mddev->chunk_sectors;
8067 mddev->raid_disks += 1;
8068 mddev->delta_disks = 1;
8069 /* make sure it will be not marked as dirty */
8070 mddev->recovery_cp = MaxSector;
8072 return setup_conf(mddev);
8075 static void *raid5_takeover_raid1(struct mddev *mddev)
8080 if (mddev->raid_disks != 2 ||
8081 mddev->degraded > 1)
8082 return ERR_PTR(-EINVAL);
8084 /* Should check if there are write-behind devices? */
8086 chunksect = 64*2; /* 64K by default */
8088 /* The array must be an exact multiple of chunksize */
8089 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8092 if ((chunksect<<9) < STRIPE_SIZE)
8093 /* array size does not allow a suitable chunk size */
8094 return ERR_PTR(-EINVAL);
8096 mddev->new_level = 5;
8097 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8098 mddev->new_chunk_sectors = chunksect;
8100 ret = setup_conf(mddev);
8102 mddev_clear_unsupported_flags(mddev,
8103 UNSUPPORTED_MDDEV_FLAGS);
8107 static void *raid5_takeover_raid6(struct mddev *mddev)
8111 switch (mddev->layout) {
8112 case ALGORITHM_LEFT_ASYMMETRIC_6:
8113 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8115 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8116 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8118 case ALGORITHM_LEFT_SYMMETRIC_6:
8119 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8121 case ALGORITHM_RIGHT_SYMMETRIC_6:
8122 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8124 case ALGORITHM_PARITY_0_6:
8125 new_layout = ALGORITHM_PARITY_0;
8127 case ALGORITHM_PARITY_N:
8128 new_layout = ALGORITHM_PARITY_N;
8131 return ERR_PTR(-EINVAL);
8133 mddev->new_level = 5;
8134 mddev->new_layout = new_layout;
8135 mddev->delta_disks = -1;
8136 mddev->raid_disks -= 1;
8137 return setup_conf(mddev);
8140 static int raid5_check_reshape(struct mddev *mddev)
8142 /* For a 2-drive array, the layout and chunk size can be changed
8143 * immediately as not restriping is needed.
8144 * For larger arrays we record the new value - after validation
8145 * to be used by a reshape pass.
8147 struct r5conf *conf = mddev->private;
8148 int new_chunk = mddev->new_chunk_sectors;
8150 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8152 if (new_chunk > 0) {
8153 if (!is_power_of_2(new_chunk))
8155 if (new_chunk < (PAGE_SIZE>>9))
8157 if (mddev->array_sectors & (new_chunk-1))
8158 /* not factor of array size */
8162 /* They look valid */
8164 if (mddev->raid_disks == 2) {
8165 /* can make the change immediately */
8166 if (mddev->new_layout >= 0) {
8167 conf->algorithm = mddev->new_layout;
8168 mddev->layout = mddev->new_layout;
8170 if (new_chunk > 0) {
8171 conf->chunk_sectors = new_chunk ;
8172 mddev->chunk_sectors = new_chunk;
8174 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8175 md_wakeup_thread(mddev->thread);
8177 return check_reshape(mddev);
8180 static int raid6_check_reshape(struct mddev *mddev)
8182 int new_chunk = mddev->new_chunk_sectors;
8184 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8186 if (new_chunk > 0) {
8187 if (!is_power_of_2(new_chunk))
8189 if (new_chunk < (PAGE_SIZE >> 9))
8191 if (mddev->array_sectors & (new_chunk-1))
8192 /* not factor of array size */
8196 /* They look valid */
8197 return check_reshape(mddev);
8200 static void *raid5_takeover(struct mddev *mddev)
8202 /* raid5 can take over:
8203 * raid0 - if there is only one strip zone - make it a raid4 layout
8204 * raid1 - if there are two drives. We need to know the chunk size
8205 * raid4 - trivial - just use a raid4 layout.
8206 * raid6 - Providing it is a *_6 layout
8208 if (mddev->level == 0)
8209 return raid45_takeover_raid0(mddev, 5);
8210 if (mddev->level == 1)
8211 return raid5_takeover_raid1(mddev);
8212 if (mddev->level == 4) {
8213 mddev->new_layout = ALGORITHM_PARITY_N;
8214 mddev->new_level = 5;
8215 return setup_conf(mddev);
8217 if (mddev->level == 6)
8218 return raid5_takeover_raid6(mddev);
8220 return ERR_PTR(-EINVAL);
8223 static void *raid4_takeover(struct mddev *mddev)
8225 /* raid4 can take over:
8226 * raid0 - if there is only one strip zone
8227 * raid5 - if layout is right
8229 if (mddev->level == 0)
8230 return raid45_takeover_raid0(mddev, 4);
8231 if (mddev->level == 5 &&
8232 mddev->layout == ALGORITHM_PARITY_N) {
8233 mddev->new_layout = 0;
8234 mddev->new_level = 4;
8235 return setup_conf(mddev);
8237 return ERR_PTR(-EINVAL);
8240 static struct md_personality raid5_personality;
8242 static void *raid6_takeover(struct mddev *mddev)
8244 /* Currently can only take over a raid5. We map the
8245 * personality to an equivalent raid6 personality
8246 * with the Q block at the end.
8250 if (mddev->pers != &raid5_personality)
8251 return ERR_PTR(-EINVAL);
8252 if (mddev->degraded > 1)
8253 return ERR_PTR(-EINVAL);
8254 if (mddev->raid_disks > 253)
8255 return ERR_PTR(-EINVAL);
8256 if (mddev->raid_disks < 3)
8257 return ERR_PTR(-EINVAL);
8259 switch (mddev->layout) {
8260 case ALGORITHM_LEFT_ASYMMETRIC:
8261 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8263 case ALGORITHM_RIGHT_ASYMMETRIC:
8264 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8266 case ALGORITHM_LEFT_SYMMETRIC:
8267 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8269 case ALGORITHM_RIGHT_SYMMETRIC:
8270 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8272 case ALGORITHM_PARITY_0:
8273 new_layout = ALGORITHM_PARITY_0_6;
8275 case ALGORITHM_PARITY_N:
8276 new_layout = ALGORITHM_PARITY_N;
8279 return ERR_PTR(-EINVAL);
8281 mddev->new_level = 6;
8282 mddev->new_layout = new_layout;
8283 mddev->delta_disks = 1;
8284 mddev->raid_disks += 1;
8285 return setup_conf(mddev);
8288 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8290 struct r5conf *conf;
8293 err = mddev_lock(mddev);
8296 conf = mddev->private;
8298 mddev_unlock(mddev);
8302 if (strncmp(buf, "ppl", 3) == 0) {
8303 /* ppl only works with RAID 5 */
8304 if (!raid5_has_ppl(conf) && conf->level == 5) {
8305 err = log_init(conf, NULL, true);
8307 err = resize_stripes(conf, conf->pool_size);
8313 } else if (strncmp(buf, "resync", 6) == 0) {
8314 if (raid5_has_ppl(conf)) {
8315 mddev_suspend(mddev);
8317 mddev_resume(mddev);
8318 err = resize_stripes(conf, conf->pool_size);
8319 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8320 r5l_log_disk_error(conf)) {
8321 bool journal_dev_exists = false;
8322 struct md_rdev *rdev;
8324 rdev_for_each(rdev, mddev)
8325 if (test_bit(Journal, &rdev->flags)) {
8326 journal_dev_exists = true;
8330 if (!journal_dev_exists) {
8331 mddev_suspend(mddev);
8332 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8333 mddev_resume(mddev);
8334 } else /* need remove journal device first */
8343 md_update_sb(mddev, 1);
8345 mddev_unlock(mddev);
8350 static struct md_personality raid6_personality =
8354 .owner = THIS_MODULE,
8355 .make_request = raid5_make_request,
8358 .status = raid5_status,
8359 .error_handler = raid5_error,
8360 .hot_add_disk = raid5_add_disk,
8361 .hot_remove_disk= raid5_remove_disk,
8362 .spare_active = raid5_spare_active,
8363 .sync_request = raid5_sync_request,
8364 .resize = raid5_resize,
8366 .check_reshape = raid6_check_reshape,
8367 .start_reshape = raid5_start_reshape,
8368 .finish_reshape = raid5_finish_reshape,
8369 .quiesce = raid5_quiesce,
8370 .takeover = raid6_takeover,
8371 .congested = raid5_congested,
8372 .change_consistency_policy = raid5_change_consistency_policy,
8374 static struct md_personality raid5_personality =
8378 .owner = THIS_MODULE,
8379 .make_request = raid5_make_request,
8382 .status = raid5_status,
8383 .error_handler = raid5_error,
8384 .hot_add_disk = raid5_add_disk,
8385 .hot_remove_disk= raid5_remove_disk,
8386 .spare_active = raid5_spare_active,
8387 .sync_request = raid5_sync_request,
8388 .resize = raid5_resize,
8390 .check_reshape = raid5_check_reshape,
8391 .start_reshape = raid5_start_reshape,
8392 .finish_reshape = raid5_finish_reshape,
8393 .quiesce = raid5_quiesce,
8394 .takeover = raid5_takeover,
8395 .congested = raid5_congested,
8396 .change_consistency_policy = raid5_change_consistency_policy,
8399 static struct md_personality raid4_personality =
8403 .owner = THIS_MODULE,
8404 .make_request = raid5_make_request,
8407 .status = raid5_status,
8408 .error_handler = raid5_error,
8409 .hot_add_disk = raid5_add_disk,
8410 .hot_remove_disk= raid5_remove_disk,
8411 .spare_active = raid5_spare_active,
8412 .sync_request = raid5_sync_request,
8413 .resize = raid5_resize,
8415 .check_reshape = raid5_check_reshape,
8416 .start_reshape = raid5_start_reshape,
8417 .finish_reshape = raid5_finish_reshape,
8418 .quiesce = raid5_quiesce,
8419 .takeover = raid4_takeover,
8420 .congested = raid5_congested,
8421 .change_consistency_policy = raid5_change_consistency_policy,
8424 static int __init raid5_init(void)
8428 raid5_wq = alloc_workqueue("raid5wq",
8429 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8433 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8435 raid456_cpu_up_prepare,
8438 destroy_workqueue(raid5_wq);
8441 register_md_personality(&raid6_personality);
8442 register_md_personality(&raid5_personality);
8443 register_md_personality(&raid4_personality);
8447 static void raid5_exit(void)
8449 unregister_md_personality(&raid6_personality);
8450 unregister_md_personality(&raid5_personality);
8451 unregister_md_personality(&raid4_personality);
8452 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8453 destroy_workqueue(raid5_wq);
8456 module_init(raid5_init);
8457 module_exit(raid5_exit);
8458 MODULE_LICENSE("GPL");
8459 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8460 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8461 MODULE_ALIAS("md-raid5");
8462 MODULE_ALIAS("md-raid4");
8463 MODULE_ALIAS("md-level-5");
8464 MODULE_ALIAS("md-level-4");
8465 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8466 MODULE_ALIAS("md-raid6");
8467 MODULE_ALIAS("md-level-6");
8469 /* This used to be two separate modules, they were: */
8470 MODULE_ALIAS("raid5");
8471 MODULE_ALIAS("raid6");