WIP FPC-III support
[linux/fpc-iii.git] / drivers / md / raid5.c
blob3a90cc0e43ca8eccba2b352fb9f9ab278e1d744e
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * raid5.c : Multiple Devices driver for Linux
4 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
5 * Copyright (C) 1999, 2000 Ingo Molnar
6 * Copyright (C) 2002, 2003 H. Peter Anvin
8 * RAID-4/5/6 management functions.
9 * Thanks to Penguin Computing for making the RAID-6 development possible
10 * by donating a test server!
14 * BITMAP UNPLUGGING:
16 * The sequencing for updating the bitmap reliably is a little
17 * subtle (and I got it wrong the first time) so it deserves some
18 * explanation.
20 * We group bitmap updates into batches. Each batch has a number.
21 * We may write out several batches at once, but that isn't very important.
22 * conf->seq_write is the number of the last batch successfully written.
23 * conf->seq_flush is the number of the last batch that was closed to
24 * new additions.
25 * When we discover that we will need to write to any block in a stripe
26 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
27 * the number of the batch it will be in. This is seq_flush+1.
28 * When we are ready to do a write, if that batch hasn't been written yet,
29 * we plug the array and queue the stripe for later.
30 * When an unplug happens, we increment bm_flush, thus closing the current
31 * batch.
32 * When we notice that bm_flush > bm_write, we write out all pending updates
33 * to the bitmap, and advance bm_write to where bm_flush was.
34 * This may occasionally write a bit out twice, but is sure never to
35 * miss any bits.
38 #include <linux/blkdev.h>
39 #include <linux/kthread.h>
40 #include <linux/raid/pq.h>
41 #include <linux/async_tx.h>
42 #include <linux/module.h>
43 #include <linux/async.h>
44 #include <linux/seq_file.h>
45 #include <linux/cpu.h>
46 #include <linux/slab.h>
47 #include <linux/ratelimit.h>
48 #include <linux/nodemask.h>
50 #include <trace/events/block.h>
51 #include <linux/list_sort.h>
53 #include "md.h"
54 #include "raid5.h"
55 #include "raid0.h"
56 #include "md-bitmap.h"
57 #include "raid5-log.h"
59 #define UNSUPPORTED_MDDEV_FLAGS (1L << MD_FAILFAST_SUPPORTED)
61 #define cpu_to_group(cpu) cpu_to_node(cpu)
62 #define ANY_GROUP NUMA_NO_NODE
64 static bool devices_handle_discard_safely = false;
65 module_param(devices_handle_discard_safely, bool, 0644);
66 MODULE_PARM_DESC(devices_handle_discard_safely,
67 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
68 static struct workqueue_struct *raid5_wq;
70 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
72 int hash = (sect >> RAID5_STRIPE_SHIFT(conf)) & HASH_MASK;
73 return &conf->stripe_hashtbl[hash];
76 static inline int stripe_hash_locks_hash(struct r5conf *conf, sector_t sect)
78 return (sect >> RAID5_STRIPE_SHIFT(conf)) & STRIPE_HASH_LOCKS_MASK;
81 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
83 spin_lock_irq(conf->hash_locks + hash);
84 spin_lock(&conf->device_lock);
87 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
89 spin_unlock(&conf->device_lock);
90 spin_unlock_irq(conf->hash_locks + hash);
93 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
95 int i;
96 spin_lock_irq(conf->hash_locks);
97 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
98 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
99 spin_lock(&conf->device_lock);
102 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
104 int i;
105 spin_unlock(&conf->device_lock);
106 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
107 spin_unlock(conf->hash_locks + i);
108 spin_unlock_irq(conf->hash_locks);
111 /* Find first data disk in a raid6 stripe */
112 static inline int raid6_d0(struct stripe_head *sh)
114 if (sh->ddf_layout)
115 /* ddf always start from first device */
116 return 0;
117 /* md starts just after Q block */
118 if (sh->qd_idx == sh->disks - 1)
119 return 0;
120 else
121 return sh->qd_idx + 1;
123 static inline int raid6_next_disk(int disk, int raid_disks)
125 disk++;
126 return (disk < raid_disks) ? disk : 0;
129 /* When walking through the disks in a raid5, starting at raid6_d0,
130 * We need to map each disk to a 'slot', where the data disks are slot
131 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
132 * is raid_disks-1. This help does that mapping.
134 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
135 int *count, int syndrome_disks)
137 int slot = *count;
139 if (sh->ddf_layout)
140 (*count)++;
141 if (idx == sh->pd_idx)
142 return syndrome_disks;
143 if (idx == sh->qd_idx)
144 return syndrome_disks + 1;
145 if (!sh->ddf_layout)
146 (*count)++;
147 return slot;
150 static void print_raid5_conf (struct r5conf *conf);
152 static int stripe_operations_active(struct stripe_head *sh)
154 return sh->check_state || sh->reconstruct_state ||
155 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
156 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
159 static bool stripe_is_lowprio(struct stripe_head *sh)
161 return (test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) ||
162 test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state)) &&
163 !test_bit(STRIPE_R5C_CACHING, &sh->state);
166 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
168 struct r5conf *conf = sh->raid_conf;
169 struct r5worker_group *group;
170 int thread_cnt;
171 int i, cpu = sh->cpu;
173 if (!cpu_online(cpu)) {
174 cpu = cpumask_any(cpu_online_mask);
175 sh->cpu = cpu;
178 if (list_empty(&sh->lru)) {
179 struct r5worker_group *group;
180 group = conf->worker_groups + cpu_to_group(cpu);
181 if (stripe_is_lowprio(sh))
182 list_add_tail(&sh->lru, &group->loprio_list);
183 else
184 list_add_tail(&sh->lru, &group->handle_list);
185 group->stripes_cnt++;
186 sh->group = group;
189 if (conf->worker_cnt_per_group == 0) {
190 md_wakeup_thread(conf->mddev->thread);
191 return;
194 group = conf->worker_groups + cpu_to_group(sh->cpu);
196 group->workers[0].working = true;
197 /* at least one worker should run to avoid race */
198 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
200 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
201 /* wakeup more workers */
202 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
203 if (group->workers[i].working == false) {
204 group->workers[i].working = true;
205 queue_work_on(sh->cpu, raid5_wq,
206 &group->workers[i].work);
207 thread_cnt--;
212 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
213 struct list_head *temp_inactive_list)
215 int i;
216 int injournal = 0; /* number of date pages with R5_InJournal */
218 BUG_ON(!list_empty(&sh->lru));
219 BUG_ON(atomic_read(&conf->active_stripes)==0);
221 if (r5c_is_writeback(conf->log))
222 for (i = sh->disks; i--; )
223 if (test_bit(R5_InJournal, &sh->dev[i].flags))
224 injournal++;
226 * In the following cases, the stripe cannot be released to cached
227 * lists. Therefore, we make the stripe write out and set
228 * STRIPE_HANDLE:
229 * 1. when quiesce in r5c write back;
230 * 2. when resync is requested fot the stripe.
232 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) ||
233 (conf->quiesce && r5c_is_writeback(conf->log) &&
234 !test_bit(STRIPE_HANDLE, &sh->state) && injournal != 0)) {
235 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
236 r5c_make_stripe_write_out(sh);
237 set_bit(STRIPE_HANDLE, &sh->state);
240 if (test_bit(STRIPE_HANDLE, &sh->state)) {
241 if (test_bit(STRIPE_DELAYED, &sh->state) &&
242 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
243 list_add_tail(&sh->lru, &conf->delayed_list);
244 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
245 sh->bm_seq - conf->seq_write > 0)
246 list_add_tail(&sh->lru, &conf->bitmap_list);
247 else {
248 clear_bit(STRIPE_DELAYED, &sh->state);
249 clear_bit(STRIPE_BIT_DELAY, &sh->state);
250 if (conf->worker_cnt_per_group == 0) {
251 if (stripe_is_lowprio(sh))
252 list_add_tail(&sh->lru,
253 &conf->loprio_list);
254 else
255 list_add_tail(&sh->lru,
256 &conf->handle_list);
257 } else {
258 raid5_wakeup_stripe_thread(sh);
259 return;
262 md_wakeup_thread(conf->mddev->thread);
263 } else {
264 BUG_ON(stripe_operations_active(sh));
265 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
266 if (atomic_dec_return(&conf->preread_active_stripes)
267 < IO_THRESHOLD)
268 md_wakeup_thread(conf->mddev->thread);
269 atomic_dec(&conf->active_stripes);
270 if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
271 if (!r5c_is_writeback(conf->log))
272 list_add_tail(&sh->lru, temp_inactive_list);
273 else {
274 WARN_ON(test_bit(R5_InJournal, &sh->dev[sh->pd_idx].flags));
275 if (injournal == 0)
276 list_add_tail(&sh->lru, temp_inactive_list);
277 else if (injournal == conf->raid_disks - conf->max_degraded) {
278 /* full stripe */
279 if (!test_and_set_bit(STRIPE_R5C_FULL_STRIPE, &sh->state))
280 atomic_inc(&conf->r5c_cached_full_stripes);
281 if (test_and_clear_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state))
282 atomic_dec(&conf->r5c_cached_partial_stripes);
283 list_add_tail(&sh->lru, &conf->r5c_full_stripe_list);
284 r5c_check_cached_full_stripe(conf);
285 } else
287 * STRIPE_R5C_PARTIAL_STRIPE is set in
288 * r5c_try_caching_write(). No need to
289 * set it again.
291 list_add_tail(&sh->lru, &conf->r5c_partial_stripe_list);
297 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
298 struct list_head *temp_inactive_list)
300 if (atomic_dec_and_test(&sh->count))
301 do_release_stripe(conf, sh, temp_inactive_list);
305 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
307 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
308 * given time. Adding stripes only takes device lock, while deleting stripes
309 * only takes hash lock.
311 static void release_inactive_stripe_list(struct r5conf *conf,
312 struct list_head *temp_inactive_list,
313 int hash)
315 int size;
316 bool do_wakeup = false;
317 unsigned long flags;
319 if (hash == NR_STRIPE_HASH_LOCKS) {
320 size = NR_STRIPE_HASH_LOCKS;
321 hash = NR_STRIPE_HASH_LOCKS - 1;
322 } else
323 size = 1;
324 while (size) {
325 struct list_head *list = &temp_inactive_list[size - 1];
328 * We don't hold any lock here yet, raid5_get_active_stripe() might
329 * remove stripes from the list
331 if (!list_empty_careful(list)) {
332 spin_lock_irqsave(conf->hash_locks + hash, flags);
333 if (list_empty(conf->inactive_list + hash) &&
334 !list_empty(list))
335 atomic_dec(&conf->empty_inactive_list_nr);
336 list_splice_tail_init(list, conf->inactive_list + hash);
337 do_wakeup = true;
338 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
340 size--;
341 hash--;
344 if (do_wakeup) {
345 wake_up(&conf->wait_for_stripe);
346 if (atomic_read(&conf->active_stripes) == 0)
347 wake_up(&conf->wait_for_quiescent);
348 if (conf->retry_read_aligned)
349 md_wakeup_thread(conf->mddev->thread);
353 /* should hold conf->device_lock already */
354 static int release_stripe_list(struct r5conf *conf,
355 struct list_head *temp_inactive_list)
357 struct stripe_head *sh, *t;
358 int count = 0;
359 struct llist_node *head;
361 head = llist_del_all(&conf->released_stripes);
362 head = llist_reverse_order(head);
363 llist_for_each_entry_safe(sh, t, head, release_list) {
364 int hash;
366 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
367 smp_mb();
368 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
370 * Don't worry the bit is set here, because if the bit is set
371 * again, the count is always > 1. This is true for
372 * STRIPE_ON_UNPLUG_LIST bit too.
374 hash = sh->hash_lock_index;
375 __release_stripe(conf, sh, &temp_inactive_list[hash]);
376 count++;
379 return count;
382 void raid5_release_stripe(struct stripe_head *sh)
384 struct r5conf *conf = sh->raid_conf;
385 unsigned long flags;
386 struct list_head list;
387 int hash;
388 bool wakeup;
390 /* Avoid release_list until the last reference.
392 if (atomic_add_unless(&sh->count, -1, 1))
393 return;
395 if (unlikely(!conf->mddev->thread) ||
396 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
397 goto slow_path;
398 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
399 if (wakeup)
400 md_wakeup_thread(conf->mddev->thread);
401 return;
402 slow_path:
403 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
404 if (atomic_dec_and_lock_irqsave(&sh->count, &conf->device_lock, flags)) {
405 INIT_LIST_HEAD(&list);
406 hash = sh->hash_lock_index;
407 do_release_stripe(conf, sh, &list);
408 spin_unlock_irqrestore(&conf->device_lock, flags);
409 release_inactive_stripe_list(conf, &list, hash);
413 static inline void remove_hash(struct stripe_head *sh)
415 pr_debug("remove_hash(), stripe %llu\n",
416 (unsigned long long)sh->sector);
418 hlist_del_init(&sh->hash);
421 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
423 struct hlist_head *hp = stripe_hash(conf, sh->sector);
425 pr_debug("insert_hash(), stripe %llu\n",
426 (unsigned long long)sh->sector);
428 hlist_add_head(&sh->hash, hp);
431 /* find an idle stripe, make sure it is unhashed, and return it. */
432 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
434 struct stripe_head *sh = NULL;
435 struct list_head *first;
437 if (list_empty(conf->inactive_list + hash))
438 goto out;
439 first = (conf->inactive_list + hash)->next;
440 sh = list_entry(first, struct stripe_head, lru);
441 list_del_init(first);
442 remove_hash(sh);
443 atomic_inc(&conf->active_stripes);
444 BUG_ON(hash != sh->hash_lock_index);
445 if (list_empty(conf->inactive_list + hash))
446 atomic_inc(&conf->empty_inactive_list_nr);
447 out:
448 return sh;
451 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
452 static void free_stripe_pages(struct stripe_head *sh)
454 int i;
455 struct page *p;
457 /* Have not allocate page pool */
458 if (!sh->pages)
459 return;
461 for (i = 0; i < sh->nr_pages; i++) {
462 p = sh->pages[i];
463 if (p)
464 put_page(p);
465 sh->pages[i] = NULL;
469 static int alloc_stripe_pages(struct stripe_head *sh, gfp_t gfp)
471 int i;
472 struct page *p;
474 for (i = 0; i < sh->nr_pages; i++) {
475 /* The page have allocated. */
476 if (sh->pages[i])
477 continue;
479 p = alloc_page(gfp);
480 if (!p) {
481 free_stripe_pages(sh);
482 return -ENOMEM;
484 sh->pages[i] = p;
486 return 0;
489 static int
490 init_stripe_shared_pages(struct stripe_head *sh, struct r5conf *conf, int disks)
492 int nr_pages, cnt;
494 if (sh->pages)
495 return 0;
497 /* Each of the sh->dev[i] need one conf->stripe_size */
498 cnt = PAGE_SIZE / conf->stripe_size;
499 nr_pages = (disks + cnt - 1) / cnt;
501 sh->pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
502 if (!sh->pages)
503 return -ENOMEM;
504 sh->nr_pages = nr_pages;
505 sh->stripes_per_page = cnt;
506 return 0;
508 #endif
510 static void shrink_buffers(struct stripe_head *sh)
512 int i;
513 int num = sh->raid_conf->pool_size;
515 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
516 for (i = 0; i < num ; i++) {
517 struct page *p;
519 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
520 p = sh->dev[i].page;
521 if (!p)
522 continue;
523 sh->dev[i].page = NULL;
524 put_page(p);
526 #else
527 for (i = 0; i < num; i++)
528 sh->dev[i].page = NULL;
529 free_stripe_pages(sh); /* Free pages */
530 #endif
533 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
535 int i;
536 int num = sh->raid_conf->pool_size;
538 #if PAGE_SIZE == DEFAULT_STRIPE_SIZE
539 for (i = 0; i < num; i++) {
540 struct page *page;
542 if (!(page = alloc_page(gfp))) {
543 return 1;
545 sh->dev[i].page = page;
546 sh->dev[i].orig_page = page;
547 sh->dev[i].offset = 0;
549 #else
550 if (alloc_stripe_pages(sh, gfp))
551 return -ENOMEM;
553 for (i = 0; i < num; i++) {
554 sh->dev[i].page = raid5_get_dev_page(sh, i);
555 sh->dev[i].orig_page = sh->dev[i].page;
556 sh->dev[i].offset = raid5_get_page_offset(sh, i);
558 #endif
559 return 0;
562 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
563 struct stripe_head *sh);
565 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
567 struct r5conf *conf = sh->raid_conf;
568 int i, seq;
570 BUG_ON(atomic_read(&sh->count) != 0);
571 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
572 BUG_ON(stripe_operations_active(sh));
573 BUG_ON(sh->batch_head);
575 pr_debug("init_stripe called, stripe %llu\n",
576 (unsigned long long)sector);
577 retry:
578 seq = read_seqcount_begin(&conf->gen_lock);
579 sh->generation = conf->generation - previous;
580 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
581 sh->sector = sector;
582 stripe_set_idx(sector, conf, previous, sh);
583 sh->state = 0;
585 for (i = sh->disks; i--; ) {
586 struct r5dev *dev = &sh->dev[i];
588 if (dev->toread || dev->read || dev->towrite || dev->written ||
589 test_bit(R5_LOCKED, &dev->flags)) {
590 pr_err("sector=%llx i=%d %p %p %p %p %d\n",
591 (unsigned long long)sh->sector, i, dev->toread,
592 dev->read, dev->towrite, dev->written,
593 test_bit(R5_LOCKED, &dev->flags));
594 WARN_ON(1);
596 dev->flags = 0;
597 dev->sector = raid5_compute_blocknr(sh, i, previous);
599 if (read_seqcount_retry(&conf->gen_lock, seq))
600 goto retry;
601 sh->overwrite_disks = 0;
602 insert_hash(conf, sh);
603 sh->cpu = smp_processor_id();
604 set_bit(STRIPE_BATCH_READY, &sh->state);
607 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
608 short generation)
610 struct stripe_head *sh;
612 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
613 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
614 if (sh->sector == sector && sh->generation == generation)
615 return sh;
616 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
617 return NULL;
621 * Need to check if array has failed when deciding whether to:
622 * - start an array
623 * - remove non-faulty devices
624 * - add a spare
625 * - allow a reshape
626 * This determination is simple when no reshape is happening.
627 * However if there is a reshape, we need to carefully check
628 * both the before and after sections.
629 * This is because some failed devices may only affect one
630 * of the two sections, and some non-in_sync devices may
631 * be insync in the section most affected by failed devices.
633 int raid5_calc_degraded(struct r5conf *conf)
635 int degraded, degraded2;
636 int i;
638 rcu_read_lock();
639 degraded = 0;
640 for (i = 0; i < conf->previous_raid_disks; i++) {
641 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
642 if (rdev && test_bit(Faulty, &rdev->flags))
643 rdev = rcu_dereference(conf->disks[i].replacement);
644 if (!rdev || test_bit(Faulty, &rdev->flags))
645 degraded++;
646 else if (test_bit(In_sync, &rdev->flags))
648 else
649 /* not in-sync or faulty.
650 * If the reshape increases the number of devices,
651 * this is being recovered by the reshape, so
652 * this 'previous' section is not in_sync.
653 * If the number of devices is being reduced however,
654 * the device can only be part of the array if
655 * we are reverting a reshape, so this section will
656 * be in-sync.
658 if (conf->raid_disks >= conf->previous_raid_disks)
659 degraded++;
661 rcu_read_unlock();
662 if (conf->raid_disks == conf->previous_raid_disks)
663 return degraded;
664 rcu_read_lock();
665 degraded2 = 0;
666 for (i = 0; i < conf->raid_disks; i++) {
667 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
668 if (rdev && test_bit(Faulty, &rdev->flags))
669 rdev = rcu_dereference(conf->disks[i].replacement);
670 if (!rdev || test_bit(Faulty, &rdev->flags))
671 degraded2++;
672 else if (test_bit(In_sync, &rdev->flags))
674 else
675 /* not in-sync or faulty.
676 * If reshape increases the number of devices, this
677 * section has already been recovered, else it
678 * almost certainly hasn't.
680 if (conf->raid_disks <= conf->previous_raid_disks)
681 degraded2++;
683 rcu_read_unlock();
684 if (degraded2 > degraded)
685 return degraded2;
686 return degraded;
689 static int has_failed(struct r5conf *conf)
691 int degraded;
693 if (conf->mddev->reshape_position == MaxSector)
694 return conf->mddev->degraded > conf->max_degraded;
696 degraded = raid5_calc_degraded(conf);
697 if (degraded > conf->max_degraded)
698 return 1;
699 return 0;
702 struct stripe_head *
703 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
704 int previous, int noblock, int noquiesce)
706 struct stripe_head *sh;
707 int hash = stripe_hash_locks_hash(conf, sector);
708 int inc_empty_inactive_list_flag;
710 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
712 spin_lock_irq(conf->hash_locks + hash);
714 do {
715 wait_event_lock_irq(conf->wait_for_quiescent,
716 conf->quiesce == 0 || noquiesce,
717 *(conf->hash_locks + hash));
718 sh = __find_stripe(conf, sector, conf->generation - previous);
719 if (!sh) {
720 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
721 sh = get_free_stripe(conf, hash);
722 if (!sh && !test_bit(R5_DID_ALLOC,
723 &conf->cache_state))
724 set_bit(R5_ALLOC_MORE,
725 &conf->cache_state);
727 if (noblock && sh == NULL)
728 break;
730 r5c_check_stripe_cache_usage(conf);
731 if (!sh) {
732 set_bit(R5_INACTIVE_BLOCKED,
733 &conf->cache_state);
734 r5l_wake_reclaim(conf->log, 0);
735 wait_event_lock_irq(
736 conf->wait_for_stripe,
737 !list_empty(conf->inactive_list + hash) &&
738 (atomic_read(&conf->active_stripes)
739 < (conf->max_nr_stripes * 3 / 4)
740 || !test_bit(R5_INACTIVE_BLOCKED,
741 &conf->cache_state)),
742 *(conf->hash_locks + hash));
743 clear_bit(R5_INACTIVE_BLOCKED,
744 &conf->cache_state);
745 } else {
746 init_stripe(sh, sector, previous);
747 atomic_inc(&sh->count);
749 } else if (!atomic_inc_not_zero(&sh->count)) {
750 spin_lock(&conf->device_lock);
751 if (!atomic_read(&sh->count)) {
752 if (!test_bit(STRIPE_HANDLE, &sh->state))
753 atomic_inc(&conf->active_stripes);
754 BUG_ON(list_empty(&sh->lru) &&
755 !test_bit(STRIPE_EXPANDING, &sh->state));
756 inc_empty_inactive_list_flag = 0;
757 if (!list_empty(conf->inactive_list + hash))
758 inc_empty_inactive_list_flag = 1;
759 list_del_init(&sh->lru);
760 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
761 atomic_inc(&conf->empty_inactive_list_nr);
762 if (sh->group) {
763 sh->group->stripes_cnt--;
764 sh->group = NULL;
767 atomic_inc(&sh->count);
768 spin_unlock(&conf->device_lock);
770 } while (sh == NULL);
772 spin_unlock_irq(conf->hash_locks + hash);
773 return sh;
776 static bool is_full_stripe_write(struct stripe_head *sh)
778 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
779 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
782 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
783 __acquires(&sh1->stripe_lock)
784 __acquires(&sh2->stripe_lock)
786 if (sh1 > sh2) {
787 spin_lock_irq(&sh2->stripe_lock);
788 spin_lock_nested(&sh1->stripe_lock, 1);
789 } else {
790 spin_lock_irq(&sh1->stripe_lock);
791 spin_lock_nested(&sh2->stripe_lock, 1);
795 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
796 __releases(&sh1->stripe_lock)
797 __releases(&sh2->stripe_lock)
799 spin_unlock(&sh1->stripe_lock);
800 spin_unlock_irq(&sh2->stripe_lock);
803 /* Only freshly new full stripe normal write stripe can be added to a batch list */
804 static bool stripe_can_batch(struct stripe_head *sh)
806 struct r5conf *conf = sh->raid_conf;
808 if (raid5_has_log(conf) || raid5_has_ppl(conf))
809 return false;
810 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
811 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
812 is_full_stripe_write(sh);
815 /* we only do back search */
816 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
818 struct stripe_head *head;
819 sector_t head_sector, tmp_sec;
820 int hash;
821 int dd_idx;
822 int inc_empty_inactive_list_flag;
824 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
825 tmp_sec = sh->sector;
826 if (!sector_div(tmp_sec, conf->chunk_sectors))
827 return;
828 head_sector = sh->sector - RAID5_STRIPE_SECTORS(conf);
830 hash = stripe_hash_locks_hash(conf, head_sector);
831 spin_lock_irq(conf->hash_locks + hash);
832 head = __find_stripe(conf, head_sector, conf->generation);
833 if (head && !atomic_inc_not_zero(&head->count)) {
834 spin_lock(&conf->device_lock);
835 if (!atomic_read(&head->count)) {
836 if (!test_bit(STRIPE_HANDLE, &head->state))
837 atomic_inc(&conf->active_stripes);
838 BUG_ON(list_empty(&head->lru) &&
839 !test_bit(STRIPE_EXPANDING, &head->state));
840 inc_empty_inactive_list_flag = 0;
841 if (!list_empty(conf->inactive_list + hash))
842 inc_empty_inactive_list_flag = 1;
843 list_del_init(&head->lru);
844 if (list_empty(conf->inactive_list + hash) && inc_empty_inactive_list_flag)
845 atomic_inc(&conf->empty_inactive_list_nr);
846 if (head->group) {
847 head->group->stripes_cnt--;
848 head->group = NULL;
851 atomic_inc(&head->count);
852 spin_unlock(&conf->device_lock);
854 spin_unlock_irq(conf->hash_locks + hash);
856 if (!head)
857 return;
858 if (!stripe_can_batch(head))
859 goto out;
861 lock_two_stripes(head, sh);
862 /* clear_batch_ready clear the flag */
863 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
864 goto unlock_out;
866 if (sh->batch_head)
867 goto unlock_out;
869 dd_idx = 0;
870 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
871 dd_idx++;
872 if (head->dev[dd_idx].towrite->bi_opf != sh->dev[dd_idx].towrite->bi_opf ||
873 bio_op(head->dev[dd_idx].towrite) != bio_op(sh->dev[dd_idx].towrite))
874 goto unlock_out;
876 if (head->batch_head) {
877 spin_lock(&head->batch_head->batch_lock);
878 /* This batch list is already running */
879 if (!stripe_can_batch(head)) {
880 spin_unlock(&head->batch_head->batch_lock);
881 goto unlock_out;
884 * We must assign batch_head of this stripe within the
885 * batch_lock, otherwise clear_batch_ready of batch head
886 * stripe could clear BATCH_READY bit of this stripe and
887 * this stripe->batch_head doesn't get assigned, which
888 * could confuse clear_batch_ready for this stripe
890 sh->batch_head = head->batch_head;
893 * at this point, head's BATCH_READY could be cleared, but we
894 * can still add the stripe to batch list
896 list_add(&sh->batch_list, &head->batch_list);
897 spin_unlock(&head->batch_head->batch_lock);
898 } else {
899 head->batch_head = head;
900 sh->batch_head = head->batch_head;
901 spin_lock(&head->batch_lock);
902 list_add_tail(&sh->batch_list, &head->batch_list);
903 spin_unlock(&head->batch_lock);
906 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
907 if (atomic_dec_return(&conf->preread_active_stripes)
908 < IO_THRESHOLD)
909 md_wakeup_thread(conf->mddev->thread);
911 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
912 int seq = sh->bm_seq;
913 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
914 sh->batch_head->bm_seq > seq)
915 seq = sh->batch_head->bm_seq;
916 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
917 sh->batch_head->bm_seq = seq;
920 atomic_inc(&sh->count);
921 unlock_out:
922 unlock_two_stripes(head, sh);
923 out:
924 raid5_release_stripe(head);
927 /* Determine if 'data_offset' or 'new_data_offset' should be used
928 * in this stripe_head.
930 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
932 sector_t progress = conf->reshape_progress;
933 /* Need a memory barrier to make sure we see the value
934 * of conf->generation, or ->data_offset that was set before
935 * reshape_progress was updated.
937 smp_rmb();
938 if (progress == MaxSector)
939 return 0;
940 if (sh->generation == conf->generation - 1)
941 return 0;
942 /* We are in a reshape, and this is a new-generation stripe,
943 * so use new_data_offset.
945 return 1;
948 static void dispatch_bio_list(struct bio_list *tmp)
950 struct bio *bio;
952 while ((bio = bio_list_pop(tmp)))
953 submit_bio_noacct(bio);
956 static int cmp_stripe(void *priv, struct list_head *a, struct list_head *b)
958 const struct r5pending_data *da = list_entry(a,
959 struct r5pending_data, sibling);
960 const struct r5pending_data *db = list_entry(b,
961 struct r5pending_data, sibling);
962 if (da->sector > db->sector)
963 return 1;
964 if (da->sector < db->sector)
965 return -1;
966 return 0;
969 static void dispatch_defer_bios(struct r5conf *conf, int target,
970 struct bio_list *list)
972 struct r5pending_data *data;
973 struct list_head *first, *next = NULL;
974 int cnt = 0;
976 if (conf->pending_data_cnt == 0)
977 return;
979 list_sort(NULL, &conf->pending_list, cmp_stripe);
981 first = conf->pending_list.next;
983 /* temporarily move the head */
984 if (conf->next_pending_data)
985 list_move_tail(&conf->pending_list,
986 &conf->next_pending_data->sibling);
988 while (!list_empty(&conf->pending_list)) {
989 data = list_first_entry(&conf->pending_list,
990 struct r5pending_data, sibling);
991 if (&data->sibling == first)
992 first = data->sibling.next;
993 next = data->sibling.next;
995 bio_list_merge(list, &data->bios);
996 list_move(&data->sibling, &conf->free_list);
997 cnt++;
998 if (cnt >= target)
999 break;
1001 conf->pending_data_cnt -= cnt;
1002 BUG_ON(conf->pending_data_cnt < 0 || cnt < target);
1004 if (next != &conf->pending_list)
1005 conf->next_pending_data = list_entry(next,
1006 struct r5pending_data, sibling);
1007 else
1008 conf->next_pending_data = NULL;
1009 /* list isn't empty */
1010 if (first != &conf->pending_list)
1011 list_move_tail(&conf->pending_list, first);
1014 static void flush_deferred_bios(struct r5conf *conf)
1016 struct bio_list tmp = BIO_EMPTY_LIST;
1018 if (conf->pending_data_cnt == 0)
1019 return;
1021 spin_lock(&conf->pending_bios_lock);
1022 dispatch_defer_bios(conf, conf->pending_data_cnt, &tmp);
1023 BUG_ON(conf->pending_data_cnt != 0);
1024 spin_unlock(&conf->pending_bios_lock);
1026 dispatch_bio_list(&tmp);
1029 static void defer_issue_bios(struct r5conf *conf, sector_t sector,
1030 struct bio_list *bios)
1032 struct bio_list tmp = BIO_EMPTY_LIST;
1033 struct r5pending_data *ent;
1035 spin_lock(&conf->pending_bios_lock);
1036 ent = list_first_entry(&conf->free_list, struct r5pending_data,
1037 sibling);
1038 list_move_tail(&ent->sibling, &conf->pending_list);
1039 ent->sector = sector;
1040 bio_list_init(&ent->bios);
1041 bio_list_merge(&ent->bios, bios);
1042 conf->pending_data_cnt++;
1043 if (conf->pending_data_cnt >= PENDING_IO_MAX)
1044 dispatch_defer_bios(conf, PENDING_IO_ONE_FLUSH, &tmp);
1046 spin_unlock(&conf->pending_bios_lock);
1048 dispatch_bio_list(&tmp);
1051 static void
1052 raid5_end_read_request(struct bio *bi);
1053 static void
1054 raid5_end_write_request(struct bio *bi);
1056 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
1058 struct r5conf *conf = sh->raid_conf;
1059 int i, disks = sh->disks;
1060 struct stripe_head *head_sh = sh;
1061 struct bio_list pending_bios = BIO_EMPTY_LIST;
1062 bool should_defer;
1064 might_sleep();
1066 if (log_stripe(sh, s) == 0)
1067 return;
1069 should_defer = conf->batch_bio_dispatch && conf->group_cnt;
1071 for (i = disks; i--; ) {
1072 int op, op_flags = 0;
1073 int replace_only = 0;
1074 struct bio *bi, *rbi;
1075 struct md_rdev *rdev, *rrdev = NULL;
1077 sh = head_sh;
1078 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
1079 op = REQ_OP_WRITE;
1080 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
1081 op_flags = REQ_FUA;
1082 if (test_bit(R5_Discard, &sh->dev[i].flags))
1083 op = REQ_OP_DISCARD;
1084 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
1085 op = REQ_OP_READ;
1086 else if (test_and_clear_bit(R5_WantReplace,
1087 &sh->dev[i].flags)) {
1088 op = REQ_OP_WRITE;
1089 replace_only = 1;
1090 } else
1091 continue;
1092 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
1093 op_flags |= REQ_SYNC;
1095 again:
1096 bi = &sh->dev[i].req;
1097 rbi = &sh->dev[i].rreq; /* For writing to replacement */
1099 rcu_read_lock();
1100 rrdev = rcu_dereference(conf->disks[i].replacement);
1101 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
1102 rdev = rcu_dereference(conf->disks[i].rdev);
1103 if (!rdev) {
1104 rdev = rrdev;
1105 rrdev = NULL;
1107 if (op_is_write(op)) {
1108 if (replace_only)
1109 rdev = NULL;
1110 if (rdev == rrdev)
1111 /* We raced and saw duplicates */
1112 rrdev = NULL;
1113 } else {
1114 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
1115 rdev = rrdev;
1116 rrdev = NULL;
1119 if (rdev && test_bit(Faulty, &rdev->flags))
1120 rdev = NULL;
1121 if (rdev)
1122 atomic_inc(&rdev->nr_pending);
1123 if (rrdev && test_bit(Faulty, &rrdev->flags))
1124 rrdev = NULL;
1125 if (rrdev)
1126 atomic_inc(&rrdev->nr_pending);
1127 rcu_read_unlock();
1129 /* We have already checked bad blocks for reads. Now
1130 * need to check for writes. We never accept write errors
1131 * on the replacement, so we don't to check rrdev.
1133 while (op_is_write(op) && rdev &&
1134 test_bit(WriteErrorSeen, &rdev->flags)) {
1135 sector_t first_bad;
1136 int bad_sectors;
1137 int bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
1138 &first_bad, &bad_sectors);
1139 if (!bad)
1140 break;
1142 if (bad < 0) {
1143 set_bit(BlockedBadBlocks, &rdev->flags);
1144 if (!conf->mddev->external &&
1145 conf->mddev->sb_flags) {
1146 /* It is very unlikely, but we might
1147 * still need to write out the
1148 * bad block log - better give it
1149 * a chance*/
1150 md_check_recovery(conf->mddev);
1153 * Because md_wait_for_blocked_rdev
1154 * will dec nr_pending, we must
1155 * increment it first.
1157 atomic_inc(&rdev->nr_pending);
1158 md_wait_for_blocked_rdev(rdev, conf->mddev);
1159 } else {
1160 /* Acknowledged bad block - skip the write */
1161 rdev_dec_pending(rdev, conf->mddev);
1162 rdev = NULL;
1166 if (rdev) {
1167 if (s->syncing || s->expanding || s->expanded
1168 || s->replacing)
1169 md_sync_acct(rdev->bdev, RAID5_STRIPE_SECTORS(conf));
1171 set_bit(STRIPE_IO_STARTED, &sh->state);
1173 bio_set_dev(bi, rdev->bdev);
1174 bio_set_op_attrs(bi, op, op_flags);
1175 bi->bi_end_io = op_is_write(op)
1176 ? raid5_end_write_request
1177 : raid5_end_read_request;
1178 bi->bi_private = sh;
1180 pr_debug("%s: for %llu schedule op %d on disc %d\n",
1181 __func__, (unsigned long long)sh->sector,
1182 bi->bi_opf, i);
1183 atomic_inc(&sh->count);
1184 if (sh != head_sh)
1185 atomic_inc(&head_sh->count);
1186 if (use_new_offset(conf, sh))
1187 bi->bi_iter.bi_sector = (sh->sector
1188 + rdev->new_data_offset);
1189 else
1190 bi->bi_iter.bi_sector = (sh->sector
1191 + rdev->data_offset);
1192 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1193 bi->bi_opf |= REQ_NOMERGE;
1195 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1196 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1198 if (!op_is_write(op) &&
1199 test_bit(R5_InJournal, &sh->dev[i].flags))
1201 * issuing read for a page in journal, this
1202 * must be preparing for prexor in rmw; read
1203 * the data into orig_page
1205 sh->dev[i].vec.bv_page = sh->dev[i].orig_page;
1206 else
1207 sh->dev[i].vec.bv_page = sh->dev[i].page;
1208 bi->bi_vcnt = 1;
1209 bi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1210 bi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1211 bi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1212 bi->bi_write_hint = sh->dev[i].write_hint;
1213 if (!rrdev)
1214 sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1216 * If this is discard request, set bi_vcnt 0. We don't
1217 * want to confuse SCSI because SCSI will replace payload
1219 if (op == REQ_OP_DISCARD)
1220 bi->bi_vcnt = 0;
1221 if (rrdev)
1222 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1224 if (conf->mddev->gendisk)
1225 trace_block_bio_remap(bi,
1226 disk_devt(conf->mddev->gendisk),
1227 sh->dev[i].sector);
1228 if (should_defer && op_is_write(op))
1229 bio_list_add(&pending_bios, bi);
1230 else
1231 submit_bio_noacct(bi);
1233 if (rrdev) {
1234 if (s->syncing || s->expanding || s->expanded
1235 || s->replacing)
1236 md_sync_acct(rrdev->bdev, RAID5_STRIPE_SECTORS(conf));
1238 set_bit(STRIPE_IO_STARTED, &sh->state);
1240 bio_set_dev(rbi, rrdev->bdev);
1241 bio_set_op_attrs(rbi, op, op_flags);
1242 BUG_ON(!op_is_write(op));
1243 rbi->bi_end_io = raid5_end_write_request;
1244 rbi->bi_private = sh;
1246 pr_debug("%s: for %llu schedule op %d on "
1247 "replacement disc %d\n",
1248 __func__, (unsigned long long)sh->sector,
1249 rbi->bi_opf, i);
1250 atomic_inc(&sh->count);
1251 if (sh != head_sh)
1252 atomic_inc(&head_sh->count);
1253 if (use_new_offset(conf, sh))
1254 rbi->bi_iter.bi_sector = (sh->sector
1255 + rrdev->new_data_offset);
1256 else
1257 rbi->bi_iter.bi_sector = (sh->sector
1258 + rrdev->data_offset);
1259 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1260 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1261 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1262 rbi->bi_vcnt = 1;
1263 rbi->bi_io_vec[0].bv_len = RAID5_STRIPE_SIZE(conf);
1264 rbi->bi_io_vec[0].bv_offset = sh->dev[i].offset;
1265 rbi->bi_iter.bi_size = RAID5_STRIPE_SIZE(conf);
1266 rbi->bi_write_hint = sh->dev[i].write_hint;
1267 sh->dev[i].write_hint = RWH_WRITE_LIFE_NOT_SET;
1269 * If this is discard request, set bi_vcnt 0. We don't
1270 * want to confuse SCSI because SCSI will replace payload
1272 if (op == REQ_OP_DISCARD)
1273 rbi->bi_vcnt = 0;
1274 if (conf->mddev->gendisk)
1275 trace_block_bio_remap(rbi,
1276 disk_devt(conf->mddev->gendisk),
1277 sh->dev[i].sector);
1278 if (should_defer && op_is_write(op))
1279 bio_list_add(&pending_bios, rbi);
1280 else
1281 submit_bio_noacct(rbi);
1283 if (!rdev && !rrdev) {
1284 if (op_is_write(op))
1285 set_bit(STRIPE_DEGRADED, &sh->state);
1286 pr_debug("skip op %d on disc %d for sector %llu\n",
1287 bi->bi_opf, i, (unsigned long long)sh->sector);
1288 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1289 set_bit(STRIPE_HANDLE, &sh->state);
1292 if (!head_sh->batch_head)
1293 continue;
1294 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1295 batch_list);
1296 if (sh != head_sh)
1297 goto again;
1300 if (should_defer && !bio_list_empty(&pending_bios))
1301 defer_issue_bios(conf, head_sh->sector, &pending_bios);
1304 static struct dma_async_tx_descriptor *
1305 async_copy_data(int frombio, struct bio *bio, struct page **page,
1306 unsigned int poff, sector_t sector, struct dma_async_tx_descriptor *tx,
1307 struct stripe_head *sh, int no_skipcopy)
1309 struct bio_vec bvl;
1310 struct bvec_iter iter;
1311 struct page *bio_page;
1312 int page_offset;
1313 struct async_submit_ctl submit;
1314 enum async_tx_flags flags = 0;
1315 struct r5conf *conf = sh->raid_conf;
1317 if (bio->bi_iter.bi_sector >= sector)
1318 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1319 else
1320 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1322 if (frombio)
1323 flags |= ASYNC_TX_FENCE;
1324 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1326 bio_for_each_segment(bvl, bio, iter) {
1327 int len = bvl.bv_len;
1328 int clen;
1329 int b_offset = 0;
1331 if (page_offset < 0) {
1332 b_offset = -page_offset;
1333 page_offset += b_offset;
1334 len -= b_offset;
1337 if (len > 0 && page_offset + len > RAID5_STRIPE_SIZE(conf))
1338 clen = RAID5_STRIPE_SIZE(conf) - page_offset;
1339 else
1340 clen = len;
1342 if (clen > 0) {
1343 b_offset += bvl.bv_offset;
1344 bio_page = bvl.bv_page;
1345 if (frombio) {
1346 if (conf->skip_copy &&
1347 b_offset == 0 && page_offset == 0 &&
1348 clen == RAID5_STRIPE_SIZE(conf) &&
1349 !no_skipcopy)
1350 *page = bio_page;
1351 else
1352 tx = async_memcpy(*page, bio_page, page_offset + poff,
1353 b_offset, clen, &submit);
1354 } else
1355 tx = async_memcpy(bio_page, *page, b_offset,
1356 page_offset + poff, clen, &submit);
1358 /* chain the operations */
1359 submit.depend_tx = tx;
1361 if (clen < len) /* hit end of page */
1362 break;
1363 page_offset += len;
1366 return tx;
1369 static void ops_complete_biofill(void *stripe_head_ref)
1371 struct stripe_head *sh = stripe_head_ref;
1372 int i;
1373 struct r5conf *conf = sh->raid_conf;
1375 pr_debug("%s: stripe %llu\n", __func__,
1376 (unsigned long long)sh->sector);
1378 /* clear completed biofills */
1379 for (i = sh->disks; i--; ) {
1380 struct r5dev *dev = &sh->dev[i];
1382 /* acknowledge completion of a biofill operation */
1383 /* and check if we need to reply to a read request,
1384 * new R5_Wantfill requests are held off until
1385 * !STRIPE_BIOFILL_RUN
1387 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1388 struct bio *rbi, *rbi2;
1390 BUG_ON(!dev->read);
1391 rbi = dev->read;
1392 dev->read = NULL;
1393 while (rbi && rbi->bi_iter.bi_sector <
1394 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1395 rbi2 = r5_next_bio(conf, rbi, dev->sector);
1396 bio_endio(rbi);
1397 rbi = rbi2;
1401 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1403 set_bit(STRIPE_HANDLE, &sh->state);
1404 raid5_release_stripe(sh);
1407 static void ops_run_biofill(struct stripe_head *sh)
1409 struct dma_async_tx_descriptor *tx = NULL;
1410 struct async_submit_ctl submit;
1411 int i;
1412 struct r5conf *conf = sh->raid_conf;
1414 BUG_ON(sh->batch_head);
1415 pr_debug("%s: stripe %llu\n", __func__,
1416 (unsigned long long)sh->sector);
1418 for (i = sh->disks; i--; ) {
1419 struct r5dev *dev = &sh->dev[i];
1420 if (test_bit(R5_Wantfill, &dev->flags)) {
1421 struct bio *rbi;
1422 spin_lock_irq(&sh->stripe_lock);
1423 dev->read = rbi = dev->toread;
1424 dev->toread = NULL;
1425 spin_unlock_irq(&sh->stripe_lock);
1426 while (rbi && rbi->bi_iter.bi_sector <
1427 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1428 tx = async_copy_data(0, rbi, &dev->page,
1429 dev->offset,
1430 dev->sector, tx, sh, 0);
1431 rbi = r5_next_bio(conf, rbi, dev->sector);
1436 atomic_inc(&sh->count);
1437 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1438 async_trigger_callback(&submit);
1441 static void mark_target_uptodate(struct stripe_head *sh, int target)
1443 struct r5dev *tgt;
1445 if (target < 0)
1446 return;
1448 tgt = &sh->dev[target];
1449 set_bit(R5_UPTODATE, &tgt->flags);
1450 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1451 clear_bit(R5_Wantcompute, &tgt->flags);
1454 static void ops_complete_compute(void *stripe_head_ref)
1456 struct stripe_head *sh = stripe_head_ref;
1458 pr_debug("%s: stripe %llu\n", __func__,
1459 (unsigned long long)sh->sector);
1461 /* mark the computed target(s) as uptodate */
1462 mark_target_uptodate(sh, sh->ops.target);
1463 mark_target_uptodate(sh, sh->ops.target2);
1465 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1466 if (sh->check_state == check_state_compute_run)
1467 sh->check_state = check_state_compute_result;
1468 set_bit(STRIPE_HANDLE, &sh->state);
1469 raid5_release_stripe(sh);
1472 /* return a pointer to the address conversion region of the scribble buffer */
1473 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1475 return percpu->scribble + i * percpu->scribble_obj_size;
1478 /* return a pointer to the address conversion region of the scribble buffer */
1479 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1480 struct raid5_percpu *percpu, int i)
1482 return (void *) (to_addr_page(percpu, i) + sh->disks + 2);
1486 * Return a pointer to record offset address.
1488 static unsigned int *
1489 to_addr_offs(struct stripe_head *sh, struct raid5_percpu *percpu)
1491 return (unsigned int *) (to_addr_conv(sh, percpu, 0) + sh->disks + 2);
1494 static struct dma_async_tx_descriptor *
1495 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1497 int disks = sh->disks;
1498 struct page **xor_srcs = to_addr_page(percpu, 0);
1499 unsigned int *off_srcs = to_addr_offs(sh, percpu);
1500 int target = sh->ops.target;
1501 struct r5dev *tgt = &sh->dev[target];
1502 struct page *xor_dest = tgt->page;
1503 unsigned int off_dest = tgt->offset;
1504 int count = 0;
1505 struct dma_async_tx_descriptor *tx;
1506 struct async_submit_ctl submit;
1507 int i;
1509 BUG_ON(sh->batch_head);
1511 pr_debug("%s: stripe %llu block: %d\n",
1512 __func__, (unsigned long long)sh->sector, target);
1513 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1515 for (i = disks; i--; ) {
1516 if (i != target) {
1517 off_srcs[count] = sh->dev[i].offset;
1518 xor_srcs[count++] = sh->dev[i].page;
1522 atomic_inc(&sh->count);
1524 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1525 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1526 if (unlikely(count == 1))
1527 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
1528 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1529 else
1530 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1531 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1533 return tx;
1536 /* set_syndrome_sources - populate source buffers for gen_syndrome
1537 * @srcs - (struct page *) array of size sh->disks
1538 * @offs - (unsigned int) array of offset for each page
1539 * @sh - stripe_head to parse
1541 * Populates srcs in proper layout order for the stripe and returns the
1542 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1543 * destination buffer is recorded in srcs[count] and the Q destination
1544 * is recorded in srcs[count+1]].
1546 static int set_syndrome_sources(struct page **srcs,
1547 unsigned int *offs,
1548 struct stripe_head *sh,
1549 int srctype)
1551 int disks = sh->disks;
1552 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1553 int d0_idx = raid6_d0(sh);
1554 int count;
1555 int i;
1557 for (i = 0; i < disks; i++)
1558 srcs[i] = NULL;
1560 count = 0;
1561 i = d0_idx;
1562 do {
1563 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1564 struct r5dev *dev = &sh->dev[i];
1566 if (i == sh->qd_idx || i == sh->pd_idx ||
1567 (srctype == SYNDROME_SRC_ALL) ||
1568 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1569 (test_bit(R5_Wantdrain, &dev->flags) ||
1570 test_bit(R5_InJournal, &dev->flags))) ||
1571 (srctype == SYNDROME_SRC_WRITTEN &&
1572 (dev->written ||
1573 test_bit(R5_InJournal, &dev->flags)))) {
1574 if (test_bit(R5_InJournal, &dev->flags))
1575 srcs[slot] = sh->dev[i].orig_page;
1576 else
1577 srcs[slot] = sh->dev[i].page;
1579 * For R5_InJournal, PAGE_SIZE must be 4KB and will
1580 * not shared page. In that case, dev[i].offset
1581 * is 0.
1583 offs[slot] = sh->dev[i].offset;
1585 i = raid6_next_disk(i, disks);
1586 } while (i != d0_idx);
1588 return syndrome_disks;
1591 static struct dma_async_tx_descriptor *
1592 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1594 int disks = sh->disks;
1595 struct page **blocks = to_addr_page(percpu, 0);
1596 unsigned int *offs = to_addr_offs(sh, percpu);
1597 int target;
1598 int qd_idx = sh->qd_idx;
1599 struct dma_async_tx_descriptor *tx;
1600 struct async_submit_ctl submit;
1601 struct r5dev *tgt;
1602 struct page *dest;
1603 unsigned int dest_off;
1604 int i;
1605 int count;
1607 BUG_ON(sh->batch_head);
1608 if (sh->ops.target < 0)
1609 target = sh->ops.target2;
1610 else if (sh->ops.target2 < 0)
1611 target = sh->ops.target;
1612 else
1613 /* we should only have one valid target */
1614 BUG();
1615 BUG_ON(target < 0);
1616 pr_debug("%s: stripe %llu block: %d\n",
1617 __func__, (unsigned long long)sh->sector, target);
1619 tgt = &sh->dev[target];
1620 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1621 dest = tgt->page;
1622 dest_off = tgt->offset;
1624 atomic_inc(&sh->count);
1626 if (target == qd_idx) {
1627 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1628 blocks[count] = NULL; /* regenerating p is not necessary */
1629 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1630 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1631 ops_complete_compute, sh,
1632 to_addr_conv(sh, percpu, 0));
1633 tx = async_gen_syndrome(blocks, offs, count+2,
1634 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1635 } else {
1636 /* Compute any data- or p-drive using XOR */
1637 count = 0;
1638 for (i = disks; i-- ; ) {
1639 if (i == target || i == qd_idx)
1640 continue;
1641 offs[count] = sh->dev[i].offset;
1642 blocks[count++] = sh->dev[i].page;
1645 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1646 NULL, ops_complete_compute, sh,
1647 to_addr_conv(sh, percpu, 0));
1648 tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1649 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1652 return tx;
1655 static struct dma_async_tx_descriptor *
1656 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1658 int i, count, disks = sh->disks;
1659 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1660 int d0_idx = raid6_d0(sh);
1661 int faila = -1, failb = -1;
1662 int target = sh->ops.target;
1663 int target2 = sh->ops.target2;
1664 struct r5dev *tgt = &sh->dev[target];
1665 struct r5dev *tgt2 = &sh->dev[target2];
1666 struct dma_async_tx_descriptor *tx;
1667 struct page **blocks = to_addr_page(percpu, 0);
1668 unsigned int *offs = to_addr_offs(sh, percpu);
1669 struct async_submit_ctl submit;
1671 BUG_ON(sh->batch_head);
1672 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1673 __func__, (unsigned long long)sh->sector, target, target2);
1674 BUG_ON(target < 0 || target2 < 0);
1675 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1676 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1678 /* we need to open-code set_syndrome_sources to handle the
1679 * slot number conversion for 'faila' and 'failb'
1681 for (i = 0; i < disks ; i++) {
1682 offs[i] = 0;
1683 blocks[i] = NULL;
1685 count = 0;
1686 i = d0_idx;
1687 do {
1688 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1690 offs[slot] = sh->dev[i].offset;
1691 blocks[slot] = sh->dev[i].page;
1693 if (i == target)
1694 faila = slot;
1695 if (i == target2)
1696 failb = slot;
1697 i = raid6_next_disk(i, disks);
1698 } while (i != d0_idx);
1700 BUG_ON(faila == failb);
1701 if (failb < faila)
1702 swap(faila, failb);
1703 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1704 __func__, (unsigned long long)sh->sector, faila, failb);
1706 atomic_inc(&sh->count);
1708 if (failb == syndrome_disks+1) {
1709 /* Q disk is one of the missing disks */
1710 if (faila == syndrome_disks) {
1711 /* Missing P+Q, just recompute */
1712 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1713 ops_complete_compute, sh,
1714 to_addr_conv(sh, percpu, 0));
1715 return async_gen_syndrome(blocks, offs, syndrome_disks+2,
1716 RAID5_STRIPE_SIZE(sh->raid_conf),
1717 &submit);
1718 } else {
1719 struct page *dest;
1720 unsigned int dest_off;
1721 int data_target;
1722 int qd_idx = sh->qd_idx;
1724 /* Missing D+Q: recompute D from P, then recompute Q */
1725 if (target == qd_idx)
1726 data_target = target2;
1727 else
1728 data_target = target;
1730 count = 0;
1731 for (i = disks; i-- ; ) {
1732 if (i == data_target || i == qd_idx)
1733 continue;
1734 offs[count] = sh->dev[i].offset;
1735 blocks[count++] = sh->dev[i].page;
1737 dest = sh->dev[data_target].page;
1738 dest_off = sh->dev[data_target].offset;
1739 init_async_submit(&submit,
1740 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1741 NULL, NULL, NULL,
1742 to_addr_conv(sh, percpu, 0));
1743 tx = async_xor_offs(dest, dest_off, blocks, offs, count,
1744 RAID5_STRIPE_SIZE(sh->raid_conf),
1745 &submit);
1747 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_ALL);
1748 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1749 ops_complete_compute, sh,
1750 to_addr_conv(sh, percpu, 0));
1751 return async_gen_syndrome(blocks, offs, count+2,
1752 RAID5_STRIPE_SIZE(sh->raid_conf),
1753 &submit);
1755 } else {
1756 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1757 ops_complete_compute, sh,
1758 to_addr_conv(sh, percpu, 0));
1759 if (failb == syndrome_disks) {
1760 /* We're missing D+P. */
1761 return async_raid6_datap_recov(syndrome_disks+2,
1762 RAID5_STRIPE_SIZE(sh->raid_conf),
1763 faila,
1764 blocks, offs, &submit);
1765 } else {
1766 /* We're missing D+D. */
1767 return async_raid6_2data_recov(syndrome_disks+2,
1768 RAID5_STRIPE_SIZE(sh->raid_conf),
1769 faila, failb,
1770 blocks, offs, &submit);
1775 static void ops_complete_prexor(void *stripe_head_ref)
1777 struct stripe_head *sh = stripe_head_ref;
1779 pr_debug("%s: stripe %llu\n", __func__,
1780 (unsigned long long)sh->sector);
1782 if (r5c_is_writeback(sh->raid_conf->log))
1784 * raid5-cache write back uses orig_page during prexor.
1785 * After prexor, it is time to free orig_page
1787 r5c_release_extra_page(sh);
1790 static struct dma_async_tx_descriptor *
1791 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1792 struct dma_async_tx_descriptor *tx)
1794 int disks = sh->disks;
1795 struct page **xor_srcs = to_addr_page(percpu, 0);
1796 unsigned int *off_srcs = to_addr_offs(sh, percpu);
1797 int count = 0, pd_idx = sh->pd_idx, i;
1798 struct async_submit_ctl submit;
1800 /* existing parity data subtracted */
1801 unsigned int off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
1802 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1804 BUG_ON(sh->batch_head);
1805 pr_debug("%s: stripe %llu\n", __func__,
1806 (unsigned long long)sh->sector);
1808 for (i = disks; i--; ) {
1809 struct r5dev *dev = &sh->dev[i];
1810 /* Only process blocks that are known to be uptodate */
1811 if (test_bit(R5_InJournal, &dev->flags)) {
1813 * For this case, PAGE_SIZE must be equal to 4KB and
1814 * page offset is zero.
1816 off_srcs[count] = dev->offset;
1817 xor_srcs[count++] = dev->orig_page;
1818 } else if (test_bit(R5_Wantdrain, &dev->flags)) {
1819 off_srcs[count] = dev->offset;
1820 xor_srcs[count++] = dev->page;
1824 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1825 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1826 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
1827 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1829 return tx;
1832 static struct dma_async_tx_descriptor *
1833 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1834 struct dma_async_tx_descriptor *tx)
1836 struct page **blocks = to_addr_page(percpu, 0);
1837 unsigned int *offs = to_addr_offs(sh, percpu);
1838 int count;
1839 struct async_submit_ctl submit;
1841 pr_debug("%s: stripe %llu\n", __func__,
1842 (unsigned long long)sh->sector);
1844 count = set_syndrome_sources(blocks, offs, sh, SYNDROME_SRC_WANT_DRAIN);
1846 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1847 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1848 tx = async_gen_syndrome(blocks, offs, count+2,
1849 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
1851 return tx;
1854 static struct dma_async_tx_descriptor *
1855 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1857 struct r5conf *conf = sh->raid_conf;
1858 int disks = sh->disks;
1859 int i;
1860 struct stripe_head *head_sh = sh;
1862 pr_debug("%s: stripe %llu\n", __func__,
1863 (unsigned long long)sh->sector);
1865 for (i = disks; i--; ) {
1866 struct r5dev *dev;
1867 struct bio *chosen;
1869 sh = head_sh;
1870 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1871 struct bio *wbi;
1873 again:
1874 dev = &sh->dev[i];
1876 * clear R5_InJournal, so when rewriting a page in
1877 * journal, it is not skipped by r5l_log_stripe()
1879 clear_bit(R5_InJournal, &dev->flags);
1880 spin_lock_irq(&sh->stripe_lock);
1881 chosen = dev->towrite;
1882 dev->towrite = NULL;
1883 sh->overwrite_disks = 0;
1884 BUG_ON(dev->written);
1885 wbi = dev->written = chosen;
1886 spin_unlock_irq(&sh->stripe_lock);
1887 WARN_ON(dev->page != dev->orig_page);
1889 while (wbi && wbi->bi_iter.bi_sector <
1890 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
1891 if (wbi->bi_opf & REQ_FUA)
1892 set_bit(R5_WantFUA, &dev->flags);
1893 if (wbi->bi_opf & REQ_SYNC)
1894 set_bit(R5_SyncIO, &dev->flags);
1895 if (bio_op(wbi) == REQ_OP_DISCARD)
1896 set_bit(R5_Discard, &dev->flags);
1897 else {
1898 tx = async_copy_data(1, wbi, &dev->page,
1899 dev->offset,
1900 dev->sector, tx, sh,
1901 r5c_is_writeback(conf->log));
1902 if (dev->page != dev->orig_page &&
1903 !r5c_is_writeback(conf->log)) {
1904 set_bit(R5_SkipCopy, &dev->flags);
1905 clear_bit(R5_UPTODATE, &dev->flags);
1906 clear_bit(R5_OVERWRITE, &dev->flags);
1909 wbi = r5_next_bio(conf, wbi, dev->sector);
1912 if (head_sh->batch_head) {
1913 sh = list_first_entry(&sh->batch_list,
1914 struct stripe_head,
1915 batch_list);
1916 if (sh == head_sh)
1917 continue;
1918 goto again;
1923 return tx;
1926 static void ops_complete_reconstruct(void *stripe_head_ref)
1928 struct stripe_head *sh = stripe_head_ref;
1929 int disks = sh->disks;
1930 int pd_idx = sh->pd_idx;
1931 int qd_idx = sh->qd_idx;
1932 int i;
1933 bool fua = false, sync = false, discard = false;
1935 pr_debug("%s: stripe %llu\n", __func__,
1936 (unsigned long long)sh->sector);
1938 for (i = disks; i--; ) {
1939 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1940 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1941 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1944 for (i = disks; i--; ) {
1945 struct r5dev *dev = &sh->dev[i];
1947 if (dev->written || i == pd_idx || i == qd_idx) {
1948 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1949 set_bit(R5_UPTODATE, &dev->flags);
1950 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1951 set_bit(R5_Expanded, &dev->flags);
1953 if (fua)
1954 set_bit(R5_WantFUA, &dev->flags);
1955 if (sync)
1956 set_bit(R5_SyncIO, &dev->flags);
1960 if (sh->reconstruct_state == reconstruct_state_drain_run)
1961 sh->reconstruct_state = reconstruct_state_drain_result;
1962 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1963 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1964 else {
1965 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1966 sh->reconstruct_state = reconstruct_state_result;
1969 set_bit(STRIPE_HANDLE, &sh->state);
1970 raid5_release_stripe(sh);
1973 static void
1974 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1975 struct dma_async_tx_descriptor *tx)
1977 int disks = sh->disks;
1978 struct page **xor_srcs;
1979 unsigned int *off_srcs;
1980 struct async_submit_ctl submit;
1981 int count, pd_idx = sh->pd_idx, i;
1982 struct page *xor_dest;
1983 unsigned int off_dest;
1984 int prexor = 0;
1985 unsigned long flags;
1986 int j = 0;
1987 struct stripe_head *head_sh = sh;
1988 int last_stripe;
1990 pr_debug("%s: stripe %llu\n", __func__,
1991 (unsigned long long)sh->sector);
1993 for (i = 0; i < sh->disks; i++) {
1994 if (pd_idx == i)
1995 continue;
1996 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1997 break;
1999 if (i >= sh->disks) {
2000 atomic_inc(&sh->count);
2001 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
2002 ops_complete_reconstruct(sh);
2003 return;
2005 again:
2006 count = 0;
2007 xor_srcs = to_addr_page(percpu, j);
2008 off_srcs = to_addr_offs(sh, percpu);
2009 /* check if prexor is active which means only process blocks
2010 * that are part of a read-modify-write (written)
2012 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2013 prexor = 1;
2014 off_dest = off_srcs[count] = sh->dev[pd_idx].offset;
2015 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
2016 for (i = disks; i--; ) {
2017 struct r5dev *dev = &sh->dev[i];
2018 if (head_sh->dev[i].written ||
2019 test_bit(R5_InJournal, &head_sh->dev[i].flags)) {
2020 off_srcs[count] = dev->offset;
2021 xor_srcs[count++] = dev->page;
2024 } else {
2025 xor_dest = sh->dev[pd_idx].page;
2026 off_dest = sh->dev[pd_idx].offset;
2027 for (i = disks; i--; ) {
2028 struct r5dev *dev = &sh->dev[i];
2029 if (i != pd_idx) {
2030 off_srcs[count] = dev->offset;
2031 xor_srcs[count++] = dev->page;
2036 /* 1/ if we prexor'd then the dest is reused as a source
2037 * 2/ if we did not prexor then we are redoing the parity
2038 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
2039 * for the synchronous xor case
2041 last_stripe = !head_sh->batch_head ||
2042 list_first_entry(&sh->batch_list,
2043 struct stripe_head, batch_list) == head_sh;
2044 if (last_stripe) {
2045 flags = ASYNC_TX_ACK |
2046 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
2048 atomic_inc(&head_sh->count);
2049 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
2050 to_addr_conv(sh, percpu, j));
2051 } else {
2052 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
2053 init_async_submit(&submit, flags, tx, NULL, NULL,
2054 to_addr_conv(sh, percpu, j));
2057 if (unlikely(count == 1))
2058 tx = async_memcpy(xor_dest, xor_srcs[0], off_dest, off_srcs[0],
2059 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2060 else
2061 tx = async_xor_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2062 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2063 if (!last_stripe) {
2064 j++;
2065 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2066 batch_list);
2067 goto again;
2071 static void
2072 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
2073 struct dma_async_tx_descriptor *tx)
2075 struct async_submit_ctl submit;
2076 struct page **blocks;
2077 unsigned int *offs;
2078 int count, i, j = 0;
2079 struct stripe_head *head_sh = sh;
2080 int last_stripe;
2081 int synflags;
2082 unsigned long txflags;
2084 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
2086 for (i = 0; i < sh->disks; i++) {
2087 if (sh->pd_idx == i || sh->qd_idx == i)
2088 continue;
2089 if (!test_bit(R5_Discard, &sh->dev[i].flags))
2090 break;
2092 if (i >= sh->disks) {
2093 atomic_inc(&sh->count);
2094 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2095 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2096 ops_complete_reconstruct(sh);
2097 return;
2100 again:
2101 blocks = to_addr_page(percpu, j);
2102 offs = to_addr_offs(sh, percpu);
2104 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
2105 synflags = SYNDROME_SRC_WRITTEN;
2106 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
2107 } else {
2108 synflags = SYNDROME_SRC_ALL;
2109 txflags = ASYNC_TX_ACK;
2112 count = set_syndrome_sources(blocks, offs, sh, synflags);
2113 last_stripe = !head_sh->batch_head ||
2114 list_first_entry(&sh->batch_list,
2115 struct stripe_head, batch_list) == head_sh;
2117 if (last_stripe) {
2118 atomic_inc(&head_sh->count);
2119 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
2120 head_sh, to_addr_conv(sh, percpu, j));
2121 } else
2122 init_async_submit(&submit, 0, tx, NULL, NULL,
2123 to_addr_conv(sh, percpu, j));
2124 tx = async_gen_syndrome(blocks, offs, count+2,
2125 RAID5_STRIPE_SIZE(sh->raid_conf), &submit);
2126 if (!last_stripe) {
2127 j++;
2128 sh = list_first_entry(&sh->batch_list, struct stripe_head,
2129 batch_list);
2130 goto again;
2134 static void ops_complete_check(void *stripe_head_ref)
2136 struct stripe_head *sh = stripe_head_ref;
2138 pr_debug("%s: stripe %llu\n", __func__,
2139 (unsigned long long)sh->sector);
2141 sh->check_state = check_state_check_result;
2142 set_bit(STRIPE_HANDLE, &sh->state);
2143 raid5_release_stripe(sh);
2146 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
2148 int disks = sh->disks;
2149 int pd_idx = sh->pd_idx;
2150 int qd_idx = sh->qd_idx;
2151 struct page *xor_dest;
2152 unsigned int off_dest;
2153 struct page **xor_srcs = to_addr_page(percpu, 0);
2154 unsigned int *off_srcs = to_addr_offs(sh, percpu);
2155 struct dma_async_tx_descriptor *tx;
2156 struct async_submit_ctl submit;
2157 int count;
2158 int i;
2160 pr_debug("%s: stripe %llu\n", __func__,
2161 (unsigned long long)sh->sector);
2163 BUG_ON(sh->batch_head);
2164 count = 0;
2165 xor_dest = sh->dev[pd_idx].page;
2166 off_dest = sh->dev[pd_idx].offset;
2167 off_srcs[count] = off_dest;
2168 xor_srcs[count++] = xor_dest;
2169 for (i = disks; i--; ) {
2170 if (i == pd_idx || i == qd_idx)
2171 continue;
2172 off_srcs[count] = sh->dev[i].offset;
2173 xor_srcs[count++] = sh->dev[i].page;
2176 init_async_submit(&submit, 0, NULL, NULL, NULL,
2177 to_addr_conv(sh, percpu, 0));
2178 tx = async_xor_val_offs(xor_dest, off_dest, xor_srcs, off_srcs, count,
2179 RAID5_STRIPE_SIZE(sh->raid_conf),
2180 &sh->ops.zero_sum_result, &submit);
2182 atomic_inc(&sh->count);
2183 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
2184 tx = async_trigger_callback(&submit);
2187 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
2189 struct page **srcs = to_addr_page(percpu, 0);
2190 unsigned int *offs = to_addr_offs(sh, percpu);
2191 struct async_submit_ctl submit;
2192 int count;
2194 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
2195 (unsigned long long)sh->sector, checkp);
2197 BUG_ON(sh->batch_head);
2198 count = set_syndrome_sources(srcs, offs, sh, SYNDROME_SRC_ALL);
2199 if (!checkp)
2200 srcs[count] = NULL;
2202 atomic_inc(&sh->count);
2203 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
2204 sh, to_addr_conv(sh, percpu, 0));
2205 async_syndrome_val(srcs, offs, count+2,
2206 RAID5_STRIPE_SIZE(sh->raid_conf),
2207 &sh->ops.zero_sum_result, percpu->spare_page, 0, &submit);
2210 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
2212 int overlap_clear = 0, i, disks = sh->disks;
2213 struct dma_async_tx_descriptor *tx = NULL;
2214 struct r5conf *conf = sh->raid_conf;
2215 int level = conf->level;
2216 struct raid5_percpu *percpu;
2217 unsigned long cpu;
2219 cpu = get_cpu();
2220 percpu = per_cpu_ptr(conf->percpu, cpu);
2221 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
2222 ops_run_biofill(sh);
2223 overlap_clear++;
2226 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
2227 if (level < 6)
2228 tx = ops_run_compute5(sh, percpu);
2229 else {
2230 if (sh->ops.target2 < 0 || sh->ops.target < 0)
2231 tx = ops_run_compute6_1(sh, percpu);
2232 else
2233 tx = ops_run_compute6_2(sh, percpu);
2235 /* terminate the chain if reconstruct is not set to be run */
2236 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
2237 async_tx_ack(tx);
2240 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
2241 if (level < 6)
2242 tx = ops_run_prexor5(sh, percpu, tx);
2243 else
2244 tx = ops_run_prexor6(sh, percpu, tx);
2247 if (test_bit(STRIPE_OP_PARTIAL_PARITY, &ops_request))
2248 tx = ops_run_partial_parity(sh, percpu, tx);
2250 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
2251 tx = ops_run_biodrain(sh, tx);
2252 overlap_clear++;
2255 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
2256 if (level < 6)
2257 ops_run_reconstruct5(sh, percpu, tx);
2258 else
2259 ops_run_reconstruct6(sh, percpu, tx);
2262 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
2263 if (sh->check_state == check_state_run)
2264 ops_run_check_p(sh, percpu);
2265 else if (sh->check_state == check_state_run_q)
2266 ops_run_check_pq(sh, percpu, 0);
2267 else if (sh->check_state == check_state_run_pq)
2268 ops_run_check_pq(sh, percpu, 1);
2269 else
2270 BUG();
2273 if (overlap_clear && !sh->batch_head)
2274 for (i = disks; i--; ) {
2275 struct r5dev *dev = &sh->dev[i];
2276 if (test_and_clear_bit(R5_Overlap, &dev->flags))
2277 wake_up(&sh->raid_conf->wait_for_overlap);
2279 put_cpu();
2282 static void free_stripe(struct kmem_cache *sc, struct stripe_head *sh)
2284 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2285 kfree(sh->pages);
2286 #endif
2287 if (sh->ppl_page)
2288 __free_page(sh->ppl_page);
2289 kmem_cache_free(sc, sh);
2292 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp,
2293 int disks, struct r5conf *conf)
2295 struct stripe_head *sh;
2296 int i;
2298 sh = kmem_cache_zalloc(sc, gfp);
2299 if (sh) {
2300 spin_lock_init(&sh->stripe_lock);
2301 spin_lock_init(&sh->batch_lock);
2302 INIT_LIST_HEAD(&sh->batch_list);
2303 INIT_LIST_HEAD(&sh->lru);
2304 INIT_LIST_HEAD(&sh->r5c);
2305 INIT_LIST_HEAD(&sh->log_list);
2306 atomic_set(&sh->count, 1);
2307 sh->raid_conf = conf;
2308 sh->log_start = MaxSector;
2309 for (i = 0; i < disks; i++) {
2310 struct r5dev *dev = &sh->dev[i];
2312 bio_init(&dev->req, &dev->vec, 1);
2313 bio_init(&dev->rreq, &dev->rvec, 1);
2316 if (raid5_has_ppl(conf)) {
2317 sh->ppl_page = alloc_page(gfp);
2318 if (!sh->ppl_page) {
2319 free_stripe(sc, sh);
2320 return NULL;
2323 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2324 if (init_stripe_shared_pages(sh, conf, disks)) {
2325 free_stripe(sc, sh);
2326 return NULL;
2328 #endif
2330 return sh;
2332 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2334 struct stripe_head *sh;
2336 sh = alloc_stripe(conf->slab_cache, gfp, conf->pool_size, conf);
2337 if (!sh)
2338 return 0;
2340 if (grow_buffers(sh, gfp)) {
2341 shrink_buffers(sh);
2342 free_stripe(conf->slab_cache, sh);
2343 return 0;
2345 sh->hash_lock_index =
2346 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2347 /* we just created an active stripe so... */
2348 atomic_inc(&conf->active_stripes);
2350 raid5_release_stripe(sh);
2351 conf->max_nr_stripes++;
2352 return 1;
2355 static int grow_stripes(struct r5conf *conf, int num)
2357 struct kmem_cache *sc;
2358 size_t namelen = sizeof(conf->cache_name[0]);
2359 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2361 if (conf->mddev->gendisk)
2362 snprintf(conf->cache_name[0], namelen,
2363 "raid%d-%s", conf->level, mdname(conf->mddev));
2364 else
2365 snprintf(conf->cache_name[0], namelen,
2366 "raid%d-%p", conf->level, conf->mddev);
2367 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2369 conf->active_name = 0;
2370 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2371 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2372 0, 0, NULL);
2373 if (!sc)
2374 return 1;
2375 conf->slab_cache = sc;
2376 conf->pool_size = devs;
2377 while (num--)
2378 if (!grow_one_stripe(conf, GFP_KERNEL))
2379 return 1;
2381 return 0;
2385 * scribble_alloc - allocate percpu scribble buffer for required size
2386 * of the scribble region
2387 * @percpu: from for_each_present_cpu() of the caller
2388 * @num: total number of disks in the array
2389 * @cnt: scribble objs count for required size of the scribble region
2391 * The scribble buffer size must be enough to contain:
2392 * 1/ a struct page pointer for each device in the array +2
2393 * 2/ room to convert each entry in (1) to its corresponding dma
2394 * (dma_map_page()) or page (page_address()) address.
2396 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2397 * calculate over all devices (not just the data blocks), using zeros in place
2398 * of the P and Q blocks.
2400 static int scribble_alloc(struct raid5_percpu *percpu,
2401 int num, int cnt)
2403 size_t obj_size =
2404 sizeof(struct page *) * (num + 2) +
2405 sizeof(addr_conv_t) * (num + 2) +
2406 sizeof(unsigned int) * (num + 2);
2407 void *scribble;
2410 * If here is in raid array suspend context, it is in memalloc noio
2411 * context as well, there is no potential recursive memory reclaim
2412 * I/Os with the GFP_KERNEL flag.
2414 scribble = kvmalloc_array(cnt, obj_size, GFP_KERNEL);
2415 if (!scribble)
2416 return -ENOMEM;
2418 kvfree(percpu->scribble);
2420 percpu->scribble = scribble;
2421 percpu->scribble_obj_size = obj_size;
2422 return 0;
2425 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2427 unsigned long cpu;
2428 int err = 0;
2431 * Never shrink. And mddev_suspend() could deadlock if this is called
2432 * from raid5d. In that case, scribble_disks and scribble_sectors
2433 * should equal to new_disks and new_sectors
2435 if (conf->scribble_disks >= new_disks &&
2436 conf->scribble_sectors >= new_sectors)
2437 return 0;
2438 mddev_suspend(conf->mddev);
2439 get_online_cpus();
2441 for_each_present_cpu(cpu) {
2442 struct raid5_percpu *percpu;
2444 percpu = per_cpu_ptr(conf->percpu, cpu);
2445 err = scribble_alloc(percpu, new_disks,
2446 new_sectors / RAID5_STRIPE_SECTORS(conf));
2447 if (err)
2448 break;
2451 put_online_cpus();
2452 mddev_resume(conf->mddev);
2453 if (!err) {
2454 conf->scribble_disks = new_disks;
2455 conf->scribble_sectors = new_sectors;
2457 return err;
2460 static int resize_stripes(struct r5conf *conf, int newsize)
2462 /* Make all the stripes able to hold 'newsize' devices.
2463 * New slots in each stripe get 'page' set to a new page.
2465 * This happens in stages:
2466 * 1/ create a new kmem_cache and allocate the required number of
2467 * stripe_heads.
2468 * 2/ gather all the old stripe_heads and transfer the pages across
2469 * to the new stripe_heads. This will have the side effect of
2470 * freezing the array as once all stripe_heads have been collected,
2471 * no IO will be possible. Old stripe heads are freed once their
2472 * pages have been transferred over, and the old kmem_cache is
2473 * freed when all stripes are done.
2474 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2475 * we simple return a failure status - no need to clean anything up.
2476 * 4/ allocate new pages for the new slots in the new stripe_heads.
2477 * If this fails, we don't bother trying the shrink the
2478 * stripe_heads down again, we just leave them as they are.
2479 * As each stripe_head is processed the new one is released into
2480 * active service.
2482 * Once step2 is started, we cannot afford to wait for a write,
2483 * so we use GFP_NOIO allocations.
2485 struct stripe_head *osh, *nsh;
2486 LIST_HEAD(newstripes);
2487 struct disk_info *ndisks;
2488 int err = 0;
2489 struct kmem_cache *sc;
2490 int i;
2491 int hash, cnt;
2493 md_allow_write(conf->mddev);
2495 /* Step 1 */
2496 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2497 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2498 0, 0, NULL);
2499 if (!sc)
2500 return -ENOMEM;
2502 /* Need to ensure auto-resizing doesn't interfere */
2503 mutex_lock(&conf->cache_size_mutex);
2505 for (i = conf->max_nr_stripes; i; i--) {
2506 nsh = alloc_stripe(sc, GFP_KERNEL, newsize, conf);
2507 if (!nsh)
2508 break;
2510 list_add(&nsh->lru, &newstripes);
2512 if (i) {
2513 /* didn't get enough, give up */
2514 while (!list_empty(&newstripes)) {
2515 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2516 list_del(&nsh->lru);
2517 free_stripe(sc, nsh);
2519 kmem_cache_destroy(sc);
2520 mutex_unlock(&conf->cache_size_mutex);
2521 return -ENOMEM;
2523 /* Step 2 - Must use GFP_NOIO now.
2524 * OK, we have enough stripes, start collecting inactive
2525 * stripes and copying them over
2527 hash = 0;
2528 cnt = 0;
2529 list_for_each_entry(nsh, &newstripes, lru) {
2530 lock_device_hash_lock(conf, hash);
2531 wait_event_cmd(conf->wait_for_stripe,
2532 !list_empty(conf->inactive_list + hash),
2533 unlock_device_hash_lock(conf, hash),
2534 lock_device_hash_lock(conf, hash));
2535 osh = get_free_stripe(conf, hash);
2536 unlock_device_hash_lock(conf, hash);
2538 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2539 for (i = 0; i < osh->nr_pages; i++) {
2540 nsh->pages[i] = osh->pages[i];
2541 osh->pages[i] = NULL;
2543 #endif
2544 for(i=0; i<conf->pool_size; i++) {
2545 nsh->dev[i].page = osh->dev[i].page;
2546 nsh->dev[i].orig_page = osh->dev[i].page;
2547 nsh->dev[i].offset = osh->dev[i].offset;
2549 nsh->hash_lock_index = hash;
2550 free_stripe(conf->slab_cache, osh);
2551 cnt++;
2552 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2553 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2554 hash++;
2555 cnt = 0;
2558 kmem_cache_destroy(conf->slab_cache);
2560 /* Step 3.
2561 * At this point, we are holding all the stripes so the array
2562 * is completely stalled, so now is a good time to resize
2563 * conf->disks and the scribble region
2565 ndisks = kcalloc(newsize, sizeof(struct disk_info), GFP_NOIO);
2566 if (ndisks) {
2567 for (i = 0; i < conf->pool_size; i++)
2568 ndisks[i] = conf->disks[i];
2570 for (i = conf->pool_size; i < newsize; i++) {
2571 ndisks[i].extra_page = alloc_page(GFP_NOIO);
2572 if (!ndisks[i].extra_page)
2573 err = -ENOMEM;
2576 if (err) {
2577 for (i = conf->pool_size; i < newsize; i++)
2578 if (ndisks[i].extra_page)
2579 put_page(ndisks[i].extra_page);
2580 kfree(ndisks);
2581 } else {
2582 kfree(conf->disks);
2583 conf->disks = ndisks;
2585 } else
2586 err = -ENOMEM;
2588 conf->slab_cache = sc;
2589 conf->active_name = 1-conf->active_name;
2591 /* Step 4, return new stripes to service */
2592 while(!list_empty(&newstripes)) {
2593 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2594 list_del_init(&nsh->lru);
2596 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
2597 for (i = 0; i < nsh->nr_pages; i++) {
2598 if (nsh->pages[i])
2599 continue;
2600 nsh->pages[i] = alloc_page(GFP_NOIO);
2601 if (!nsh->pages[i])
2602 err = -ENOMEM;
2605 for (i = conf->raid_disks; i < newsize; i++) {
2606 if (nsh->dev[i].page)
2607 continue;
2608 nsh->dev[i].page = raid5_get_dev_page(nsh, i);
2609 nsh->dev[i].orig_page = nsh->dev[i].page;
2610 nsh->dev[i].offset = raid5_get_page_offset(nsh, i);
2612 #else
2613 for (i=conf->raid_disks; i < newsize; i++)
2614 if (nsh->dev[i].page == NULL) {
2615 struct page *p = alloc_page(GFP_NOIO);
2616 nsh->dev[i].page = p;
2617 nsh->dev[i].orig_page = p;
2618 nsh->dev[i].offset = 0;
2619 if (!p)
2620 err = -ENOMEM;
2622 #endif
2623 raid5_release_stripe(nsh);
2625 /* critical section pass, GFP_NOIO no longer needed */
2627 if (!err)
2628 conf->pool_size = newsize;
2629 mutex_unlock(&conf->cache_size_mutex);
2631 return err;
2634 static int drop_one_stripe(struct r5conf *conf)
2636 struct stripe_head *sh;
2637 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2639 spin_lock_irq(conf->hash_locks + hash);
2640 sh = get_free_stripe(conf, hash);
2641 spin_unlock_irq(conf->hash_locks + hash);
2642 if (!sh)
2643 return 0;
2644 BUG_ON(atomic_read(&sh->count));
2645 shrink_buffers(sh);
2646 free_stripe(conf->slab_cache, sh);
2647 atomic_dec(&conf->active_stripes);
2648 conf->max_nr_stripes--;
2649 return 1;
2652 static void shrink_stripes(struct r5conf *conf)
2654 while (conf->max_nr_stripes &&
2655 drop_one_stripe(conf))
2658 kmem_cache_destroy(conf->slab_cache);
2659 conf->slab_cache = NULL;
2662 static void raid5_end_read_request(struct bio * bi)
2664 struct stripe_head *sh = bi->bi_private;
2665 struct r5conf *conf = sh->raid_conf;
2666 int disks = sh->disks, i;
2667 char b[BDEVNAME_SIZE];
2668 struct md_rdev *rdev = NULL;
2669 sector_t s;
2671 for (i=0 ; i<disks; i++)
2672 if (bi == &sh->dev[i].req)
2673 break;
2675 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2676 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2677 bi->bi_status);
2678 if (i == disks) {
2679 bio_reset(bi);
2680 BUG();
2681 return;
2683 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2684 /* If replacement finished while this request was outstanding,
2685 * 'replacement' might be NULL already.
2686 * In that case it moved down to 'rdev'.
2687 * rdev is not removed until all requests are finished.
2689 rdev = conf->disks[i].replacement;
2690 if (!rdev)
2691 rdev = conf->disks[i].rdev;
2693 if (use_new_offset(conf, sh))
2694 s = sh->sector + rdev->new_data_offset;
2695 else
2696 s = sh->sector + rdev->data_offset;
2697 if (!bi->bi_status) {
2698 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2699 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2700 /* Note that this cannot happen on a
2701 * replacement device. We just fail those on
2702 * any error
2704 pr_info_ratelimited(
2705 "md/raid:%s: read error corrected (%lu sectors at %llu on %s)\n",
2706 mdname(conf->mddev), RAID5_STRIPE_SECTORS(conf),
2707 (unsigned long long)s,
2708 bdevname(rdev->bdev, b));
2709 atomic_add(RAID5_STRIPE_SECTORS(conf), &rdev->corrected_errors);
2710 clear_bit(R5_ReadError, &sh->dev[i].flags);
2711 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2712 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2713 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2715 if (test_bit(R5_InJournal, &sh->dev[i].flags))
2717 * end read for a page in journal, this
2718 * must be preparing for prexor in rmw
2720 set_bit(R5_OrigPageUPTDODATE, &sh->dev[i].flags);
2722 if (atomic_read(&rdev->read_errors))
2723 atomic_set(&rdev->read_errors, 0);
2724 } else {
2725 const char *bdn = bdevname(rdev->bdev, b);
2726 int retry = 0;
2727 int set_bad = 0;
2729 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2730 if (!(bi->bi_status == BLK_STS_PROTECTION))
2731 atomic_inc(&rdev->read_errors);
2732 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2733 pr_warn_ratelimited(
2734 "md/raid:%s: read error on replacement device (sector %llu on %s).\n",
2735 mdname(conf->mddev),
2736 (unsigned long long)s,
2737 bdn);
2738 else if (conf->mddev->degraded >= conf->max_degraded) {
2739 set_bad = 1;
2740 pr_warn_ratelimited(
2741 "md/raid:%s: read error not correctable (sector %llu on %s).\n",
2742 mdname(conf->mddev),
2743 (unsigned long long)s,
2744 bdn);
2745 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2746 /* Oh, no!!! */
2747 set_bad = 1;
2748 pr_warn_ratelimited(
2749 "md/raid:%s: read error NOT corrected!! (sector %llu on %s).\n",
2750 mdname(conf->mddev),
2751 (unsigned long long)s,
2752 bdn);
2753 } else if (atomic_read(&rdev->read_errors)
2754 > conf->max_nr_stripes) {
2755 if (!test_bit(Faulty, &rdev->flags)) {
2756 pr_warn("md/raid:%s: %d read_errors > %d stripes\n",
2757 mdname(conf->mddev),
2758 atomic_read(&rdev->read_errors),
2759 conf->max_nr_stripes);
2760 pr_warn("md/raid:%s: Too many read errors, failing device %s.\n",
2761 mdname(conf->mddev), bdn);
2763 } else
2764 retry = 1;
2765 if (set_bad && test_bit(In_sync, &rdev->flags)
2766 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2767 retry = 1;
2768 if (retry)
2769 if (sh->qd_idx >= 0 && sh->pd_idx == i)
2770 set_bit(R5_ReadError, &sh->dev[i].flags);
2771 else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2772 set_bit(R5_ReadError, &sh->dev[i].flags);
2773 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2774 } else
2775 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2776 else {
2777 clear_bit(R5_ReadError, &sh->dev[i].flags);
2778 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2779 if (!(set_bad
2780 && test_bit(In_sync, &rdev->flags)
2781 && rdev_set_badblocks(
2782 rdev, sh->sector, RAID5_STRIPE_SECTORS(conf), 0)))
2783 md_error(conf->mddev, rdev);
2786 rdev_dec_pending(rdev, conf->mddev);
2787 bio_reset(bi);
2788 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2789 set_bit(STRIPE_HANDLE, &sh->state);
2790 raid5_release_stripe(sh);
2793 static void raid5_end_write_request(struct bio *bi)
2795 struct stripe_head *sh = bi->bi_private;
2796 struct r5conf *conf = sh->raid_conf;
2797 int disks = sh->disks, i;
2798 struct md_rdev *rdev;
2799 sector_t first_bad;
2800 int bad_sectors;
2801 int replacement = 0;
2803 for (i = 0 ; i < disks; i++) {
2804 if (bi == &sh->dev[i].req) {
2805 rdev = conf->disks[i].rdev;
2806 break;
2808 if (bi == &sh->dev[i].rreq) {
2809 rdev = conf->disks[i].replacement;
2810 if (rdev)
2811 replacement = 1;
2812 else
2813 /* rdev was removed and 'replacement'
2814 * replaced it. rdev is not removed
2815 * until all requests are finished.
2817 rdev = conf->disks[i].rdev;
2818 break;
2821 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2822 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2823 bi->bi_status);
2824 if (i == disks) {
2825 bio_reset(bi);
2826 BUG();
2827 return;
2830 if (replacement) {
2831 if (bi->bi_status)
2832 md_error(conf->mddev, rdev);
2833 else if (is_badblock(rdev, sh->sector,
2834 RAID5_STRIPE_SECTORS(conf),
2835 &first_bad, &bad_sectors))
2836 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2837 } else {
2838 if (bi->bi_status) {
2839 set_bit(STRIPE_DEGRADED, &sh->state);
2840 set_bit(WriteErrorSeen, &rdev->flags);
2841 set_bit(R5_WriteError, &sh->dev[i].flags);
2842 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2843 set_bit(MD_RECOVERY_NEEDED,
2844 &rdev->mddev->recovery);
2845 } else if (is_badblock(rdev, sh->sector,
2846 RAID5_STRIPE_SECTORS(conf),
2847 &first_bad, &bad_sectors)) {
2848 set_bit(R5_MadeGood, &sh->dev[i].flags);
2849 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2850 /* That was a successful write so make
2851 * sure it looks like we already did
2852 * a re-write.
2854 set_bit(R5_ReWrite, &sh->dev[i].flags);
2857 rdev_dec_pending(rdev, conf->mddev);
2859 if (sh->batch_head && bi->bi_status && !replacement)
2860 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2862 bio_reset(bi);
2863 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2864 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2865 set_bit(STRIPE_HANDLE, &sh->state);
2866 raid5_release_stripe(sh);
2868 if (sh->batch_head && sh != sh->batch_head)
2869 raid5_release_stripe(sh->batch_head);
2872 static void raid5_error(struct mddev *mddev, struct md_rdev *rdev)
2874 char b[BDEVNAME_SIZE];
2875 struct r5conf *conf = mddev->private;
2876 unsigned long flags;
2877 pr_debug("raid456: error called\n");
2879 spin_lock_irqsave(&conf->device_lock, flags);
2881 if (test_bit(In_sync, &rdev->flags) &&
2882 mddev->degraded == conf->max_degraded) {
2884 * Don't allow to achieve failed state
2885 * Don't try to recover this device
2887 conf->recovery_disabled = mddev->recovery_disabled;
2888 spin_unlock_irqrestore(&conf->device_lock, flags);
2889 return;
2892 set_bit(Faulty, &rdev->flags);
2893 clear_bit(In_sync, &rdev->flags);
2894 mddev->degraded = raid5_calc_degraded(conf);
2895 spin_unlock_irqrestore(&conf->device_lock, flags);
2896 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2898 set_bit(Blocked, &rdev->flags);
2899 set_mask_bits(&mddev->sb_flags, 0,
2900 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_PENDING));
2901 pr_crit("md/raid:%s: Disk failure on %s, disabling device.\n"
2902 "md/raid:%s: Operation continuing on %d devices.\n",
2903 mdname(mddev),
2904 bdevname(rdev->bdev, b),
2905 mdname(mddev),
2906 conf->raid_disks - mddev->degraded);
2907 r5c_update_on_rdev_error(mddev, rdev);
2911 * Input: a 'big' sector number,
2912 * Output: index of the data and parity disk, and the sector # in them.
2914 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2915 int previous, int *dd_idx,
2916 struct stripe_head *sh)
2918 sector_t stripe, stripe2;
2919 sector_t chunk_number;
2920 unsigned int chunk_offset;
2921 int pd_idx, qd_idx;
2922 int ddf_layout = 0;
2923 sector_t new_sector;
2924 int algorithm = previous ? conf->prev_algo
2925 : conf->algorithm;
2926 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2927 : conf->chunk_sectors;
2928 int raid_disks = previous ? conf->previous_raid_disks
2929 : conf->raid_disks;
2930 int data_disks = raid_disks - conf->max_degraded;
2932 /* First compute the information on this sector */
2935 * Compute the chunk number and the sector offset inside the chunk
2937 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2938 chunk_number = r_sector;
2941 * Compute the stripe number
2943 stripe = chunk_number;
2944 *dd_idx = sector_div(stripe, data_disks);
2945 stripe2 = stripe;
2947 * Select the parity disk based on the user selected algorithm.
2949 pd_idx = qd_idx = -1;
2950 switch(conf->level) {
2951 case 4:
2952 pd_idx = data_disks;
2953 break;
2954 case 5:
2955 switch (algorithm) {
2956 case ALGORITHM_LEFT_ASYMMETRIC:
2957 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2958 if (*dd_idx >= pd_idx)
2959 (*dd_idx)++;
2960 break;
2961 case ALGORITHM_RIGHT_ASYMMETRIC:
2962 pd_idx = sector_div(stripe2, raid_disks);
2963 if (*dd_idx >= pd_idx)
2964 (*dd_idx)++;
2965 break;
2966 case ALGORITHM_LEFT_SYMMETRIC:
2967 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2968 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2969 break;
2970 case ALGORITHM_RIGHT_SYMMETRIC:
2971 pd_idx = sector_div(stripe2, raid_disks);
2972 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2973 break;
2974 case ALGORITHM_PARITY_0:
2975 pd_idx = 0;
2976 (*dd_idx)++;
2977 break;
2978 case ALGORITHM_PARITY_N:
2979 pd_idx = data_disks;
2980 break;
2981 default:
2982 BUG();
2984 break;
2985 case 6:
2987 switch (algorithm) {
2988 case ALGORITHM_LEFT_ASYMMETRIC:
2989 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2990 qd_idx = pd_idx + 1;
2991 if (pd_idx == raid_disks-1) {
2992 (*dd_idx)++; /* Q D D D P */
2993 qd_idx = 0;
2994 } else if (*dd_idx >= pd_idx)
2995 (*dd_idx) += 2; /* D D P Q D */
2996 break;
2997 case ALGORITHM_RIGHT_ASYMMETRIC:
2998 pd_idx = sector_div(stripe2, raid_disks);
2999 qd_idx = pd_idx + 1;
3000 if (pd_idx == raid_disks-1) {
3001 (*dd_idx)++; /* Q D D D P */
3002 qd_idx = 0;
3003 } else if (*dd_idx >= pd_idx)
3004 (*dd_idx) += 2; /* D D P Q D */
3005 break;
3006 case ALGORITHM_LEFT_SYMMETRIC:
3007 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3008 qd_idx = (pd_idx + 1) % raid_disks;
3009 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3010 break;
3011 case ALGORITHM_RIGHT_SYMMETRIC:
3012 pd_idx = sector_div(stripe2, raid_disks);
3013 qd_idx = (pd_idx + 1) % raid_disks;
3014 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
3015 break;
3017 case ALGORITHM_PARITY_0:
3018 pd_idx = 0;
3019 qd_idx = 1;
3020 (*dd_idx) += 2;
3021 break;
3022 case ALGORITHM_PARITY_N:
3023 pd_idx = data_disks;
3024 qd_idx = data_disks + 1;
3025 break;
3027 case ALGORITHM_ROTATING_ZERO_RESTART:
3028 /* Exactly the same as RIGHT_ASYMMETRIC, but or
3029 * of blocks for computing Q is different.
3031 pd_idx = sector_div(stripe2, raid_disks);
3032 qd_idx = pd_idx + 1;
3033 if (pd_idx == raid_disks-1) {
3034 (*dd_idx)++; /* Q D D D P */
3035 qd_idx = 0;
3036 } else if (*dd_idx >= pd_idx)
3037 (*dd_idx) += 2; /* D D P Q D */
3038 ddf_layout = 1;
3039 break;
3041 case ALGORITHM_ROTATING_N_RESTART:
3042 /* Same a left_asymmetric, by first stripe is
3043 * D D D P Q rather than
3044 * Q D D D P
3046 stripe2 += 1;
3047 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3048 qd_idx = pd_idx + 1;
3049 if (pd_idx == raid_disks-1) {
3050 (*dd_idx)++; /* Q D D D P */
3051 qd_idx = 0;
3052 } else if (*dd_idx >= pd_idx)
3053 (*dd_idx) += 2; /* D D P Q D */
3054 ddf_layout = 1;
3055 break;
3057 case ALGORITHM_ROTATING_N_CONTINUE:
3058 /* Same as left_symmetric but Q is before P */
3059 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
3060 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
3061 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
3062 ddf_layout = 1;
3063 break;
3065 case ALGORITHM_LEFT_ASYMMETRIC_6:
3066 /* RAID5 left_asymmetric, with Q on last device */
3067 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3068 if (*dd_idx >= pd_idx)
3069 (*dd_idx)++;
3070 qd_idx = raid_disks - 1;
3071 break;
3073 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3074 pd_idx = sector_div(stripe2, raid_disks-1);
3075 if (*dd_idx >= pd_idx)
3076 (*dd_idx)++;
3077 qd_idx = raid_disks - 1;
3078 break;
3080 case ALGORITHM_LEFT_SYMMETRIC_6:
3081 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
3082 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3083 qd_idx = raid_disks - 1;
3084 break;
3086 case ALGORITHM_RIGHT_SYMMETRIC_6:
3087 pd_idx = sector_div(stripe2, raid_disks-1);
3088 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
3089 qd_idx = raid_disks - 1;
3090 break;
3092 case ALGORITHM_PARITY_0_6:
3093 pd_idx = 0;
3094 (*dd_idx)++;
3095 qd_idx = raid_disks - 1;
3096 break;
3098 default:
3099 BUG();
3101 break;
3104 if (sh) {
3105 sh->pd_idx = pd_idx;
3106 sh->qd_idx = qd_idx;
3107 sh->ddf_layout = ddf_layout;
3110 * Finally, compute the new sector number
3112 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
3113 return new_sector;
3116 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
3118 struct r5conf *conf = sh->raid_conf;
3119 int raid_disks = sh->disks;
3120 int data_disks = raid_disks - conf->max_degraded;
3121 sector_t new_sector = sh->sector, check;
3122 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
3123 : conf->chunk_sectors;
3124 int algorithm = previous ? conf->prev_algo
3125 : conf->algorithm;
3126 sector_t stripe;
3127 int chunk_offset;
3128 sector_t chunk_number;
3129 int dummy1, dd_idx = i;
3130 sector_t r_sector;
3131 struct stripe_head sh2;
3133 chunk_offset = sector_div(new_sector, sectors_per_chunk);
3134 stripe = new_sector;
3136 if (i == sh->pd_idx)
3137 return 0;
3138 switch(conf->level) {
3139 case 4: break;
3140 case 5:
3141 switch (algorithm) {
3142 case ALGORITHM_LEFT_ASYMMETRIC:
3143 case ALGORITHM_RIGHT_ASYMMETRIC:
3144 if (i > sh->pd_idx)
3145 i--;
3146 break;
3147 case ALGORITHM_LEFT_SYMMETRIC:
3148 case ALGORITHM_RIGHT_SYMMETRIC:
3149 if (i < sh->pd_idx)
3150 i += raid_disks;
3151 i -= (sh->pd_idx + 1);
3152 break;
3153 case ALGORITHM_PARITY_0:
3154 i -= 1;
3155 break;
3156 case ALGORITHM_PARITY_N:
3157 break;
3158 default:
3159 BUG();
3161 break;
3162 case 6:
3163 if (i == sh->qd_idx)
3164 return 0; /* It is the Q disk */
3165 switch (algorithm) {
3166 case ALGORITHM_LEFT_ASYMMETRIC:
3167 case ALGORITHM_RIGHT_ASYMMETRIC:
3168 case ALGORITHM_ROTATING_ZERO_RESTART:
3169 case ALGORITHM_ROTATING_N_RESTART:
3170 if (sh->pd_idx == raid_disks-1)
3171 i--; /* Q D D D P */
3172 else if (i > sh->pd_idx)
3173 i -= 2; /* D D P Q D */
3174 break;
3175 case ALGORITHM_LEFT_SYMMETRIC:
3176 case ALGORITHM_RIGHT_SYMMETRIC:
3177 if (sh->pd_idx == raid_disks-1)
3178 i--; /* Q D D D P */
3179 else {
3180 /* D D P Q D */
3181 if (i < sh->pd_idx)
3182 i += raid_disks;
3183 i -= (sh->pd_idx + 2);
3185 break;
3186 case ALGORITHM_PARITY_0:
3187 i -= 2;
3188 break;
3189 case ALGORITHM_PARITY_N:
3190 break;
3191 case ALGORITHM_ROTATING_N_CONTINUE:
3192 /* Like left_symmetric, but P is before Q */
3193 if (sh->pd_idx == 0)
3194 i--; /* P D D D Q */
3195 else {
3196 /* D D Q P D */
3197 if (i < sh->pd_idx)
3198 i += raid_disks;
3199 i -= (sh->pd_idx + 1);
3201 break;
3202 case ALGORITHM_LEFT_ASYMMETRIC_6:
3203 case ALGORITHM_RIGHT_ASYMMETRIC_6:
3204 if (i > sh->pd_idx)
3205 i--;
3206 break;
3207 case ALGORITHM_LEFT_SYMMETRIC_6:
3208 case ALGORITHM_RIGHT_SYMMETRIC_6:
3209 if (i < sh->pd_idx)
3210 i += data_disks + 1;
3211 i -= (sh->pd_idx + 1);
3212 break;
3213 case ALGORITHM_PARITY_0_6:
3214 i -= 1;
3215 break;
3216 default:
3217 BUG();
3219 break;
3222 chunk_number = stripe * data_disks + i;
3223 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
3225 check = raid5_compute_sector(conf, r_sector,
3226 previous, &dummy1, &sh2);
3227 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
3228 || sh2.qd_idx != sh->qd_idx) {
3229 pr_warn("md/raid:%s: compute_blocknr: map not correct\n",
3230 mdname(conf->mddev));
3231 return 0;
3233 return r_sector;
3237 * There are cases where we want handle_stripe_dirtying() and
3238 * schedule_reconstruction() to delay towrite to some dev of a stripe.
3240 * This function checks whether we want to delay the towrite. Specifically,
3241 * we delay the towrite when:
3243 * 1. degraded stripe has a non-overwrite to the missing dev, AND this
3244 * stripe has data in journal (for other devices).
3246 * In this case, when reading data for the non-overwrite dev, it is
3247 * necessary to handle complex rmw of write back cache (prexor with
3248 * orig_page, and xor with page). To keep read path simple, we would
3249 * like to flush data in journal to RAID disks first, so complex rmw
3250 * is handled in the write patch (handle_stripe_dirtying).
3252 * 2. when journal space is critical (R5C_LOG_CRITICAL=1)
3254 * It is important to be able to flush all stripes in raid5-cache.
3255 * Therefore, we need reserve some space on the journal device for
3256 * these flushes. If flush operation includes pending writes to the
3257 * stripe, we need to reserve (conf->raid_disk + 1) pages per stripe
3258 * for the flush out. If we exclude these pending writes from flush
3259 * operation, we only need (conf->max_degraded + 1) pages per stripe.
3260 * Therefore, excluding pending writes in these cases enables more
3261 * efficient use of the journal device.
3263 * Note: To make sure the stripe makes progress, we only delay
3264 * towrite for stripes with data already in journal (injournal > 0).
3265 * When LOG_CRITICAL, stripes with injournal == 0 will be sent to
3266 * no_space_stripes list.
3268 * 3. during journal failure
3269 * In journal failure, we try to flush all cached data to raid disks
3270 * based on data in stripe cache. The array is read-only to upper
3271 * layers, so we would skip all pending writes.
3274 static inline bool delay_towrite(struct r5conf *conf,
3275 struct r5dev *dev,
3276 struct stripe_head_state *s)
3278 /* case 1 above */
3279 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3280 !test_bit(R5_Insync, &dev->flags) && s->injournal)
3281 return true;
3282 /* case 2 above */
3283 if (test_bit(R5C_LOG_CRITICAL, &conf->cache_state) &&
3284 s->injournal > 0)
3285 return true;
3286 /* case 3 above */
3287 if (s->log_failed && s->injournal)
3288 return true;
3289 return false;
3292 static void
3293 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
3294 int rcw, int expand)
3296 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
3297 struct r5conf *conf = sh->raid_conf;
3298 int level = conf->level;
3300 if (rcw) {
3302 * In some cases, handle_stripe_dirtying initially decided to
3303 * run rmw and allocates extra page for prexor. However, rcw is
3304 * cheaper later on. We need to free the extra page now,
3305 * because we won't be able to do that in ops_complete_prexor().
3307 r5c_release_extra_page(sh);
3309 for (i = disks; i--; ) {
3310 struct r5dev *dev = &sh->dev[i];
3312 if (dev->towrite && !delay_towrite(conf, dev, s)) {
3313 set_bit(R5_LOCKED, &dev->flags);
3314 set_bit(R5_Wantdrain, &dev->flags);
3315 if (!expand)
3316 clear_bit(R5_UPTODATE, &dev->flags);
3317 s->locked++;
3318 } else if (test_bit(R5_InJournal, &dev->flags)) {
3319 set_bit(R5_LOCKED, &dev->flags);
3320 s->locked++;
3323 /* if we are not expanding this is a proper write request, and
3324 * there will be bios with new data to be drained into the
3325 * stripe cache
3327 if (!expand) {
3328 if (!s->locked)
3329 /* False alarm, nothing to do */
3330 return;
3331 sh->reconstruct_state = reconstruct_state_drain_run;
3332 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3333 } else
3334 sh->reconstruct_state = reconstruct_state_run;
3336 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3338 if (s->locked + conf->max_degraded == disks)
3339 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
3340 atomic_inc(&conf->pending_full_writes);
3341 } else {
3342 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
3343 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
3344 BUG_ON(level == 6 &&
3345 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
3346 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
3348 for (i = disks; i--; ) {
3349 struct r5dev *dev = &sh->dev[i];
3350 if (i == pd_idx || i == qd_idx)
3351 continue;
3353 if (dev->towrite &&
3354 (test_bit(R5_UPTODATE, &dev->flags) ||
3355 test_bit(R5_Wantcompute, &dev->flags))) {
3356 set_bit(R5_Wantdrain, &dev->flags);
3357 set_bit(R5_LOCKED, &dev->flags);
3358 clear_bit(R5_UPTODATE, &dev->flags);
3359 s->locked++;
3360 } else if (test_bit(R5_InJournal, &dev->flags)) {
3361 set_bit(R5_LOCKED, &dev->flags);
3362 s->locked++;
3365 if (!s->locked)
3366 /* False alarm - nothing to do */
3367 return;
3368 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
3369 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
3370 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
3371 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
3374 /* keep the parity disk(s) locked while asynchronous operations
3375 * are in flight
3377 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
3378 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3379 s->locked++;
3381 if (level == 6) {
3382 int qd_idx = sh->qd_idx;
3383 struct r5dev *dev = &sh->dev[qd_idx];
3385 set_bit(R5_LOCKED, &dev->flags);
3386 clear_bit(R5_UPTODATE, &dev->flags);
3387 s->locked++;
3390 if (raid5_has_ppl(sh->raid_conf) && sh->ppl_page &&
3391 test_bit(STRIPE_OP_BIODRAIN, &s->ops_request) &&
3392 !test_bit(STRIPE_FULL_WRITE, &sh->state) &&
3393 test_bit(R5_Insync, &sh->dev[pd_idx].flags))
3394 set_bit(STRIPE_OP_PARTIAL_PARITY, &s->ops_request);
3396 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
3397 __func__, (unsigned long long)sh->sector,
3398 s->locked, s->ops_request);
3402 * Each stripe/dev can have one or more bion attached.
3403 * toread/towrite point to the first in a chain.
3404 * The bi_next chain must be in order.
3406 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
3407 int forwrite, int previous)
3409 struct bio **bip;
3410 struct r5conf *conf = sh->raid_conf;
3411 int firstwrite=0;
3413 pr_debug("adding bi b#%llu to stripe s#%llu\n",
3414 (unsigned long long)bi->bi_iter.bi_sector,
3415 (unsigned long long)sh->sector);
3417 spin_lock_irq(&sh->stripe_lock);
3418 sh->dev[dd_idx].write_hint = bi->bi_write_hint;
3419 /* Don't allow new IO added to stripes in batch list */
3420 if (sh->batch_head)
3421 goto overlap;
3422 if (forwrite) {
3423 bip = &sh->dev[dd_idx].towrite;
3424 if (*bip == NULL)
3425 firstwrite = 1;
3426 } else
3427 bip = &sh->dev[dd_idx].toread;
3428 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
3429 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
3430 goto overlap;
3431 bip = & (*bip)->bi_next;
3433 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
3434 goto overlap;
3436 if (forwrite && raid5_has_ppl(conf)) {
3438 * With PPL only writes to consecutive data chunks within a
3439 * stripe are allowed because for a single stripe_head we can
3440 * only have one PPL entry at a time, which describes one data
3441 * range. Not really an overlap, but wait_for_overlap can be
3442 * used to handle this.
3444 sector_t sector;
3445 sector_t first = 0;
3446 sector_t last = 0;
3447 int count = 0;
3448 int i;
3450 for (i = 0; i < sh->disks; i++) {
3451 if (i != sh->pd_idx &&
3452 (i == dd_idx || sh->dev[i].towrite)) {
3453 sector = sh->dev[i].sector;
3454 if (count == 0 || sector < first)
3455 first = sector;
3456 if (sector > last)
3457 last = sector;
3458 count++;
3462 if (first + conf->chunk_sectors * (count - 1) != last)
3463 goto overlap;
3466 if (!forwrite || previous)
3467 clear_bit(STRIPE_BATCH_READY, &sh->state);
3469 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3470 if (*bip)
3471 bi->bi_next = *bip;
3472 *bip = bi;
3473 bio_inc_remaining(bi);
3474 md_write_inc(conf->mddev, bi);
3476 if (forwrite) {
3477 /* check if page is covered */
3478 sector_t sector = sh->dev[dd_idx].sector;
3479 for (bi=sh->dev[dd_idx].towrite;
3480 sector < sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf) &&
3481 bi && bi->bi_iter.bi_sector <= sector;
3482 bi = r5_next_bio(conf, bi, sh->dev[dd_idx].sector)) {
3483 if (bio_end_sector(bi) >= sector)
3484 sector = bio_end_sector(bi);
3486 if (sector >= sh->dev[dd_idx].sector + RAID5_STRIPE_SECTORS(conf))
3487 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3488 sh->overwrite_disks++;
3491 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3492 (unsigned long long)(*bip)->bi_iter.bi_sector,
3493 (unsigned long long)sh->sector, dd_idx);
3495 if (conf->mddev->bitmap && firstwrite) {
3496 /* Cannot hold spinlock over bitmap_startwrite,
3497 * but must ensure this isn't added to a batch until
3498 * we have added to the bitmap and set bm_seq.
3499 * So set STRIPE_BITMAP_PENDING to prevent
3500 * batching.
3501 * If multiple add_stripe_bio() calls race here they
3502 * much all set STRIPE_BITMAP_PENDING. So only the first one
3503 * to complete "bitmap_startwrite" gets to set
3504 * STRIPE_BIT_DELAY. This is important as once a stripe
3505 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3506 * any more.
3508 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3509 spin_unlock_irq(&sh->stripe_lock);
3510 md_bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3511 RAID5_STRIPE_SECTORS(conf), 0);
3512 spin_lock_irq(&sh->stripe_lock);
3513 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3514 if (!sh->batch_head) {
3515 sh->bm_seq = conf->seq_flush+1;
3516 set_bit(STRIPE_BIT_DELAY, &sh->state);
3519 spin_unlock_irq(&sh->stripe_lock);
3521 if (stripe_can_batch(sh))
3522 stripe_add_to_batch_list(conf, sh);
3523 return 1;
3525 overlap:
3526 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3527 spin_unlock_irq(&sh->stripe_lock);
3528 return 0;
3531 static void end_reshape(struct r5conf *conf);
3533 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3534 struct stripe_head *sh)
3536 int sectors_per_chunk =
3537 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3538 int dd_idx;
3539 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3540 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3542 raid5_compute_sector(conf,
3543 stripe * (disks - conf->max_degraded)
3544 *sectors_per_chunk + chunk_offset,
3545 previous,
3546 &dd_idx, sh);
3549 static void
3550 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3551 struct stripe_head_state *s, int disks)
3553 int i;
3554 BUG_ON(sh->batch_head);
3555 for (i = disks; i--; ) {
3556 struct bio *bi;
3557 int bitmap_end = 0;
3559 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3560 struct md_rdev *rdev;
3561 rcu_read_lock();
3562 rdev = rcu_dereference(conf->disks[i].rdev);
3563 if (rdev && test_bit(In_sync, &rdev->flags) &&
3564 !test_bit(Faulty, &rdev->flags))
3565 atomic_inc(&rdev->nr_pending);
3566 else
3567 rdev = NULL;
3568 rcu_read_unlock();
3569 if (rdev) {
3570 if (!rdev_set_badblocks(
3571 rdev,
3572 sh->sector,
3573 RAID5_STRIPE_SECTORS(conf), 0))
3574 md_error(conf->mddev, rdev);
3575 rdev_dec_pending(rdev, conf->mddev);
3578 spin_lock_irq(&sh->stripe_lock);
3579 /* fail all writes first */
3580 bi = sh->dev[i].towrite;
3581 sh->dev[i].towrite = NULL;
3582 sh->overwrite_disks = 0;
3583 spin_unlock_irq(&sh->stripe_lock);
3584 if (bi)
3585 bitmap_end = 1;
3587 log_stripe_write_finished(sh);
3589 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3590 wake_up(&conf->wait_for_overlap);
3592 while (bi && bi->bi_iter.bi_sector <
3593 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3594 struct bio *nextbi = r5_next_bio(conf, bi, sh->dev[i].sector);
3596 md_write_end(conf->mddev);
3597 bio_io_error(bi);
3598 bi = nextbi;
3600 if (bitmap_end)
3601 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3602 RAID5_STRIPE_SECTORS(conf), 0, 0);
3603 bitmap_end = 0;
3604 /* and fail all 'written' */
3605 bi = sh->dev[i].written;
3606 sh->dev[i].written = NULL;
3607 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3608 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3609 sh->dev[i].page = sh->dev[i].orig_page;
3612 if (bi) bitmap_end = 1;
3613 while (bi && bi->bi_iter.bi_sector <
3614 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3615 struct bio *bi2 = r5_next_bio(conf, bi, sh->dev[i].sector);
3617 md_write_end(conf->mddev);
3618 bio_io_error(bi);
3619 bi = bi2;
3622 /* fail any reads if this device is non-operational and
3623 * the data has not reached the cache yet.
3625 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3626 s->failed > conf->max_degraded &&
3627 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3628 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3629 spin_lock_irq(&sh->stripe_lock);
3630 bi = sh->dev[i].toread;
3631 sh->dev[i].toread = NULL;
3632 spin_unlock_irq(&sh->stripe_lock);
3633 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3634 wake_up(&conf->wait_for_overlap);
3635 if (bi)
3636 s->to_read--;
3637 while (bi && bi->bi_iter.bi_sector <
3638 sh->dev[i].sector + RAID5_STRIPE_SECTORS(conf)) {
3639 struct bio *nextbi =
3640 r5_next_bio(conf, bi, sh->dev[i].sector);
3642 bio_io_error(bi);
3643 bi = nextbi;
3646 if (bitmap_end)
3647 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3648 RAID5_STRIPE_SECTORS(conf), 0, 0);
3649 /* If we were in the middle of a write the parity block might
3650 * still be locked - so just clear all R5_LOCKED flags
3652 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3654 s->to_write = 0;
3655 s->written = 0;
3657 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3658 if (atomic_dec_and_test(&conf->pending_full_writes))
3659 md_wakeup_thread(conf->mddev->thread);
3662 static void
3663 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3664 struct stripe_head_state *s)
3666 int abort = 0;
3667 int i;
3669 BUG_ON(sh->batch_head);
3670 clear_bit(STRIPE_SYNCING, &sh->state);
3671 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3672 wake_up(&conf->wait_for_overlap);
3673 s->syncing = 0;
3674 s->replacing = 0;
3675 /* There is nothing more to do for sync/check/repair.
3676 * Don't even need to abort as that is handled elsewhere
3677 * if needed, and not always wanted e.g. if there is a known
3678 * bad block here.
3679 * For recover/replace we need to record a bad block on all
3680 * non-sync devices, or abort the recovery
3682 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3683 /* During recovery devices cannot be removed, so
3684 * locking and refcounting of rdevs is not needed
3686 rcu_read_lock();
3687 for (i = 0; i < conf->raid_disks; i++) {
3688 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
3689 if (rdev
3690 && !test_bit(Faulty, &rdev->flags)
3691 && !test_bit(In_sync, &rdev->flags)
3692 && !rdev_set_badblocks(rdev, sh->sector,
3693 RAID5_STRIPE_SECTORS(conf), 0))
3694 abort = 1;
3695 rdev = rcu_dereference(conf->disks[i].replacement);
3696 if (rdev
3697 && !test_bit(Faulty, &rdev->flags)
3698 && !test_bit(In_sync, &rdev->flags)
3699 && !rdev_set_badblocks(rdev, sh->sector,
3700 RAID5_STRIPE_SECTORS(conf), 0))
3701 abort = 1;
3703 rcu_read_unlock();
3704 if (abort)
3705 conf->recovery_disabled =
3706 conf->mddev->recovery_disabled;
3708 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), !abort);
3711 static int want_replace(struct stripe_head *sh, int disk_idx)
3713 struct md_rdev *rdev;
3714 int rv = 0;
3716 rcu_read_lock();
3717 rdev = rcu_dereference(sh->raid_conf->disks[disk_idx].replacement);
3718 if (rdev
3719 && !test_bit(Faulty, &rdev->flags)
3720 && !test_bit(In_sync, &rdev->flags)
3721 && (rdev->recovery_offset <= sh->sector
3722 || rdev->mddev->recovery_cp <= sh->sector))
3723 rv = 1;
3724 rcu_read_unlock();
3725 return rv;
3728 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3729 int disk_idx, int disks)
3731 struct r5dev *dev = &sh->dev[disk_idx];
3732 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3733 &sh->dev[s->failed_num[1]] };
3734 int i;
3735 bool force_rcw = (sh->raid_conf->rmw_level == PARITY_DISABLE_RMW);
3738 if (test_bit(R5_LOCKED, &dev->flags) ||
3739 test_bit(R5_UPTODATE, &dev->flags))
3740 /* No point reading this as we already have it or have
3741 * decided to get it.
3743 return 0;
3745 if (dev->toread ||
3746 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3747 /* We need this block to directly satisfy a request */
3748 return 1;
3750 if (s->syncing || s->expanding ||
3751 (s->replacing && want_replace(sh, disk_idx)))
3752 /* When syncing, or expanding we read everything.
3753 * When replacing, we need the replaced block.
3755 return 1;
3757 if ((s->failed >= 1 && fdev[0]->toread) ||
3758 (s->failed >= 2 && fdev[1]->toread))
3759 /* If we want to read from a failed device, then
3760 * we need to actually read every other device.
3762 return 1;
3764 /* Sometimes neither read-modify-write nor reconstruct-write
3765 * cycles can work. In those cases we read every block we
3766 * can. Then the parity-update is certain to have enough to
3767 * work with.
3768 * This can only be a problem when we need to write something,
3769 * and some device has failed. If either of those tests
3770 * fail we need look no further.
3772 if (!s->failed || !s->to_write)
3773 return 0;
3775 if (test_bit(R5_Insync, &dev->flags) &&
3776 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3777 /* Pre-reads at not permitted until after short delay
3778 * to gather multiple requests. However if this
3779 * device is no Insync, the block could only be computed
3780 * and there is no need to delay that.
3782 return 0;
3784 for (i = 0; i < s->failed && i < 2; i++) {
3785 if (fdev[i]->towrite &&
3786 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3787 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3788 /* If we have a partial write to a failed
3789 * device, then we will need to reconstruct
3790 * the content of that device, so all other
3791 * devices must be read.
3793 return 1;
3795 if (s->failed >= 2 &&
3796 (fdev[i]->towrite ||
3797 s->failed_num[i] == sh->pd_idx ||
3798 s->failed_num[i] == sh->qd_idx) &&
3799 !test_bit(R5_UPTODATE, &fdev[i]->flags))
3800 /* In max degraded raid6, If the failed disk is P, Q,
3801 * or we want to read the failed disk, we need to do
3802 * reconstruct-write.
3804 force_rcw = true;
3807 /* If we are forced to do a reconstruct-write, because parity
3808 * cannot be trusted and we are currently recovering it, there
3809 * is extra need to be careful.
3810 * If one of the devices that we would need to read, because
3811 * it is not being overwritten (and maybe not written at all)
3812 * is missing/faulty, then we need to read everything we can.
3814 if (!force_rcw &&
3815 sh->sector < sh->raid_conf->mddev->recovery_cp)
3816 /* reconstruct-write isn't being forced */
3817 return 0;
3818 for (i = 0; i < s->failed && i < 2; i++) {
3819 if (s->failed_num[i] != sh->pd_idx &&
3820 s->failed_num[i] != sh->qd_idx &&
3821 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3822 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3823 return 1;
3826 return 0;
3829 /* fetch_block - checks the given member device to see if its data needs
3830 * to be read or computed to satisfy a request.
3832 * Returns 1 when no more member devices need to be checked, otherwise returns
3833 * 0 to tell the loop in handle_stripe_fill to continue
3835 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3836 int disk_idx, int disks)
3838 struct r5dev *dev = &sh->dev[disk_idx];
3840 /* is the data in this block needed, and can we get it? */
3841 if (need_this_block(sh, s, disk_idx, disks)) {
3842 /* we would like to get this block, possibly by computing it,
3843 * otherwise read it if the backing disk is insync
3845 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3846 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3847 BUG_ON(sh->batch_head);
3850 * In the raid6 case if the only non-uptodate disk is P
3851 * then we already trusted P to compute the other failed
3852 * drives. It is safe to compute rather than re-read P.
3853 * In other cases we only compute blocks from failed
3854 * devices, otherwise check/repair might fail to detect
3855 * a real inconsistency.
3858 if ((s->uptodate == disks - 1) &&
3859 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3860 (s->failed && (disk_idx == s->failed_num[0] ||
3861 disk_idx == s->failed_num[1])))) {
3862 /* have disk failed, and we're requested to fetch it;
3863 * do compute it
3865 pr_debug("Computing stripe %llu block %d\n",
3866 (unsigned long long)sh->sector, disk_idx);
3867 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3868 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3869 set_bit(R5_Wantcompute, &dev->flags);
3870 sh->ops.target = disk_idx;
3871 sh->ops.target2 = -1; /* no 2nd target */
3872 s->req_compute = 1;
3873 /* Careful: from this point on 'uptodate' is in the eye
3874 * of raid_run_ops which services 'compute' operations
3875 * before writes. R5_Wantcompute flags a block that will
3876 * be R5_UPTODATE by the time it is needed for a
3877 * subsequent operation.
3879 s->uptodate++;
3880 return 1;
3881 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3882 /* Computing 2-failure is *very* expensive; only
3883 * do it if failed >= 2
3885 int other;
3886 for (other = disks; other--; ) {
3887 if (other == disk_idx)
3888 continue;
3889 if (!test_bit(R5_UPTODATE,
3890 &sh->dev[other].flags))
3891 break;
3893 BUG_ON(other < 0);
3894 pr_debug("Computing stripe %llu blocks %d,%d\n",
3895 (unsigned long long)sh->sector,
3896 disk_idx, other);
3897 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3898 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3899 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3900 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3901 sh->ops.target = disk_idx;
3902 sh->ops.target2 = other;
3903 s->uptodate += 2;
3904 s->req_compute = 1;
3905 return 1;
3906 } else if (test_bit(R5_Insync, &dev->flags)) {
3907 set_bit(R5_LOCKED, &dev->flags);
3908 set_bit(R5_Wantread, &dev->flags);
3909 s->locked++;
3910 pr_debug("Reading block %d (sync=%d)\n",
3911 disk_idx, s->syncing);
3915 return 0;
3919 * handle_stripe_fill - read or compute data to satisfy pending requests.
3921 static void handle_stripe_fill(struct stripe_head *sh,
3922 struct stripe_head_state *s,
3923 int disks)
3925 int i;
3927 /* look for blocks to read/compute, skip this if a compute
3928 * is already in flight, or if the stripe contents are in the
3929 * midst of changing due to a write
3931 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3932 !sh->reconstruct_state) {
3935 * For degraded stripe with data in journal, do not handle
3936 * read requests yet, instead, flush the stripe to raid
3937 * disks first, this avoids handling complex rmw of write
3938 * back cache (prexor with orig_page, and then xor with
3939 * page) in the read path
3941 if (s->injournal && s->failed) {
3942 if (test_bit(STRIPE_R5C_CACHING, &sh->state))
3943 r5c_make_stripe_write_out(sh);
3944 goto out;
3947 for (i = disks; i--; )
3948 if (fetch_block(sh, s, i, disks))
3949 break;
3951 out:
3952 set_bit(STRIPE_HANDLE, &sh->state);
3955 static void break_stripe_batch_list(struct stripe_head *head_sh,
3956 unsigned long handle_flags);
3957 /* handle_stripe_clean_event
3958 * any written block on an uptodate or failed drive can be returned.
3959 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3960 * never LOCKED, so we don't need to test 'failed' directly.
3962 static void handle_stripe_clean_event(struct r5conf *conf,
3963 struct stripe_head *sh, int disks)
3965 int i;
3966 struct r5dev *dev;
3967 int discard_pending = 0;
3968 struct stripe_head *head_sh = sh;
3969 bool do_endio = false;
3971 for (i = disks; i--; )
3972 if (sh->dev[i].written) {
3973 dev = &sh->dev[i];
3974 if (!test_bit(R5_LOCKED, &dev->flags) &&
3975 (test_bit(R5_UPTODATE, &dev->flags) ||
3976 test_bit(R5_Discard, &dev->flags) ||
3977 test_bit(R5_SkipCopy, &dev->flags))) {
3978 /* We can return any write requests */
3979 struct bio *wbi, *wbi2;
3980 pr_debug("Return write for disc %d\n", i);
3981 if (test_and_clear_bit(R5_Discard, &dev->flags))
3982 clear_bit(R5_UPTODATE, &dev->flags);
3983 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3984 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3986 do_endio = true;
3988 returnbi:
3989 dev->page = dev->orig_page;
3990 wbi = dev->written;
3991 dev->written = NULL;
3992 while (wbi && wbi->bi_iter.bi_sector <
3993 dev->sector + RAID5_STRIPE_SECTORS(conf)) {
3994 wbi2 = r5_next_bio(conf, wbi, dev->sector);
3995 md_write_end(conf->mddev);
3996 bio_endio(wbi);
3997 wbi = wbi2;
3999 md_bitmap_endwrite(conf->mddev->bitmap, sh->sector,
4000 RAID5_STRIPE_SECTORS(conf),
4001 !test_bit(STRIPE_DEGRADED, &sh->state),
4003 if (head_sh->batch_head) {
4004 sh = list_first_entry(&sh->batch_list,
4005 struct stripe_head,
4006 batch_list);
4007 if (sh != head_sh) {
4008 dev = &sh->dev[i];
4009 goto returnbi;
4012 sh = head_sh;
4013 dev = &sh->dev[i];
4014 } else if (test_bit(R5_Discard, &dev->flags))
4015 discard_pending = 1;
4018 log_stripe_write_finished(sh);
4020 if (!discard_pending &&
4021 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
4022 int hash;
4023 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
4024 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4025 if (sh->qd_idx >= 0) {
4026 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
4027 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
4029 /* now that discard is done we can proceed with any sync */
4030 clear_bit(STRIPE_DISCARD, &sh->state);
4032 * SCSI discard will change some bio fields and the stripe has
4033 * no updated data, so remove it from hash list and the stripe
4034 * will be reinitialized
4036 unhash:
4037 hash = sh->hash_lock_index;
4038 spin_lock_irq(conf->hash_locks + hash);
4039 remove_hash(sh);
4040 spin_unlock_irq(conf->hash_locks + hash);
4041 if (head_sh->batch_head) {
4042 sh = list_first_entry(&sh->batch_list,
4043 struct stripe_head, batch_list);
4044 if (sh != head_sh)
4045 goto unhash;
4047 sh = head_sh;
4049 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
4050 set_bit(STRIPE_HANDLE, &sh->state);
4054 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
4055 if (atomic_dec_and_test(&conf->pending_full_writes))
4056 md_wakeup_thread(conf->mddev->thread);
4058 if (head_sh->batch_head && do_endio)
4059 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
4063 * For RMW in write back cache, we need extra page in prexor to store the
4064 * old data. This page is stored in dev->orig_page.
4066 * This function checks whether we have data for prexor. The exact logic
4067 * is:
4068 * R5_UPTODATE && (!R5_InJournal || R5_OrigPageUPTDODATE)
4070 static inline bool uptodate_for_rmw(struct r5dev *dev)
4072 return (test_bit(R5_UPTODATE, &dev->flags)) &&
4073 (!test_bit(R5_InJournal, &dev->flags) ||
4074 test_bit(R5_OrigPageUPTDODATE, &dev->flags));
4077 static int handle_stripe_dirtying(struct r5conf *conf,
4078 struct stripe_head *sh,
4079 struct stripe_head_state *s,
4080 int disks)
4082 int rmw = 0, rcw = 0, i;
4083 sector_t recovery_cp = conf->mddev->recovery_cp;
4085 /* Check whether resync is now happening or should start.
4086 * If yes, then the array is dirty (after unclean shutdown or
4087 * initial creation), so parity in some stripes might be inconsistent.
4088 * In this case, we need to always do reconstruct-write, to ensure
4089 * that in case of drive failure or read-error correction, we
4090 * generate correct data from the parity.
4092 if (conf->rmw_level == PARITY_DISABLE_RMW ||
4093 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
4094 s->failed == 0)) {
4095 /* Calculate the real rcw later - for now make it
4096 * look like rcw is cheaper
4098 rcw = 1; rmw = 2;
4099 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
4100 conf->rmw_level, (unsigned long long)recovery_cp,
4101 (unsigned long long)sh->sector);
4102 } else for (i = disks; i--; ) {
4103 /* would I have to read this buffer for read_modify_write */
4104 struct r5dev *dev = &sh->dev[i];
4105 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4106 i == sh->pd_idx || i == sh->qd_idx ||
4107 test_bit(R5_InJournal, &dev->flags)) &&
4108 !test_bit(R5_LOCKED, &dev->flags) &&
4109 !(uptodate_for_rmw(dev) ||
4110 test_bit(R5_Wantcompute, &dev->flags))) {
4111 if (test_bit(R5_Insync, &dev->flags))
4112 rmw++;
4113 else
4114 rmw += 2*disks; /* cannot read it */
4116 /* Would I have to read this buffer for reconstruct_write */
4117 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4118 i != sh->pd_idx && i != sh->qd_idx &&
4119 !test_bit(R5_LOCKED, &dev->flags) &&
4120 !(test_bit(R5_UPTODATE, &dev->flags) ||
4121 test_bit(R5_Wantcompute, &dev->flags))) {
4122 if (test_bit(R5_Insync, &dev->flags))
4123 rcw++;
4124 else
4125 rcw += 2*disks;
4129 pr_debug("for sector %llu state 0x%lx, rmw=%d rcw=%d\n",
4130 (unsigned long long)sh->sector, sh->state, rmw, rcw);
4131 set_bit(STRIPE_HANDLE, &sh->state);
4132 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_PREFER_RMW)) && rmw > 0) {
4133 /* prefer read-modify-write, but need to get some data */
4134 if (conf->mddev->queue)
4135 blk_add_trace_msg(conf->mddev->queue,
4136 "raid5 rmw %llu %d",
4137 (unsigned long long)sh->sector, rmw);
4138 for (i = disks; i--; ) {
4139 struct r5dev *dev = &sh->dev[i];
4140 if (test_bit(R5_InJournal, &dev->flags) &&
4141 dev->page == dev->orig_page &&
4142 !test_bit(R5_LOCKED, &sh->dev[sh->pd_idx].flags)) {
4143 /* alloc page for prexor */
4144 struct page *p = alloc_page(GFP_NOIO);
4146 if (p) {
4147 dev->orig_page = p;
4148 continue;
4152 * alloc_page() failed, try use
4153 * disk_info->extra_page
4155 if (!test_and_set_bit(R5C_EXTRA_PAGE_IN_USE,
4156 &conf->cache_state)) {
4157 r5c_use_extra_page(sh);
4158 break;
4161 /* extra_page in use, add to delayed_list */
4162 set_bit(STRIPE_DELAYED, &sh->state);
4163 s->waiting_extra_page = 1;
4164 return -EAGAIN;
4168 for (i = disks; i--; ) {
4169 struct r5dev *dev = &sh->dev[i];
4170 if (((dev->towrite && !delay_towrite(conf, dev, s)) ||
4171 i == sh->pd_idx || i == sh->qd_idx ||
4172 test_bit(R5_InJournal, &dev->flags)) &&
4173 !test_bit(R5_LOCKED, &dev->flags) &&
4174 !(uptodate_for_rmw(dev) ||
4175 test_bit(R5_Wantcompute, &dev->flags)) &&
4176 test_bit(R5_Insync, &dev->flags)) {
4177 if (test_bit(STRIPE_PREREAD_ACTIVE,
4178 &sh->state)) {
4179 pr_debug("Read_old block %d for r-m-w\n",
4181 set_bit(R5_LOCKED, &dev->flags);
4182 set_bit(R5_Wantread, &dev->flags);
4183 s->locked++;
4184 } else
4185 set_bit(STRIPE_DELAYED, &sh->state);
4189 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_PREFER_RMW)) && rcw > 0) {
4190 /* want reconstruct write, but need to get some data */
4191 int qread =0;
4192 rcw = 0;
4193 for (i = disks; i--; ) {
4194 struct r5dev *dev = &sh->dev[i];
4195 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
4196 i != sh->pd_idx && i != sh->qd_idx &&
4197 !test_bit(R5_LOCKED, &dev->flags) &&
4198 !(test_bit(R5_UPTODATE, &dev->flags) ||
4199 test_bit(R5_Wantcompute, &dev->flags))) {
4200 rcw++;
4201 if (test_bit(R5_Insync, &dev->flags) &&
4202 test_bit(STRIPE_PREREAD_ACTIVE,
4203 &sh->state)) {
4204 pr_debug("Read_old block "
4205 "%d for Reconstruct\n", i);
4206 set_bit(R5_LOCKED, &dev->flags);
4207 set_bit(R5_Wantread, &dev->flags);
4208 s->locked++;
4209 qread++;
4210 } else
4211 set_bit(STRIPE_DELAYED, &sh->state);
4214 if (rcw && conf->mddev->queue)
4215 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
4216 (unsigned long long)sh->sector,
4217 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
4220 if (rcw > disks && rmw > disks &&
4221 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4222 set_bit(STRIPE_DELAYED, &sh->state);
4224 /* now if nothing is locked, and if we have enough data,
4225 * we can start a write request
4227 /* since handle_stripe can be called at any time we need to handle the
4228 * case where a compute block operation has been submitted and then a
4229 * subsequent call wants to start a write request. raid_run_ops only
4230 * handles the case where compute block and reconstruct are requested
4231 * simultaneously. If this is not the case then new writes need to be
4232 * held off until the compute completes.
4234 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
4235 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
4236 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
4237 schedule_reconstruction(sh, s, rcw == 0, 0);
4238 return 0;
4241 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
4242 struct stripe_head_state *s, int disks)
4244 struct r5dev *dev = NULL;
4246 BUG_ON(sh->batch_head);
4247 set_bit(STRIPE_HANDLE, &sh->state);
4249 switch (sh->check_state) {
4250 case check_state_idle:
4251 /* start a new check operation if there are no failures */
4252 if (s->failed == 0) {
4253 BUG_ON(s->uptodate != disks);
4254 sh->check_state = check_state_run;
4255 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4256 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
4257 s->uptodate--;
4258 break;
4260 dev = &sh->dev[s->failed_num[0]];
4261 fallthrough;
4262 case check_state_compute_result:
4263 sh->check_state = check_state_idle;
4264 if (!dev)
4265 dev = &sh->dev[sh->pd_idx];
4267 /* check that a write has not made the stripe insync */
4268 if (test_bit(STRIPE_INSYNC, &sh->state))
4269 break;
4271 /* either failed parity check, or recovery is happening */
4272 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
4273 BUG_ON(s->uptodate != disks);
4275 set_bit(R5_LOCKED, &dev->flags);
4276 s->locked++;
4277 set_bit(R5_Wantwrite, &dev->flags);
4279 clear_bit(STRIPE_DEGRADED, &sh->state);
4280 set_bit(STRIPE_INSYNC, &sh->state);
4281 break;
4282 case check_state_run:
4283 break; /* we will be called again upon completion */
4284 case check_state_check_result:
4285 sh->check_state = check_state_idle;
4287 /* if a failure occurred during the check operation, leave
4288 * STRIPE_INSYNC not set and let the stripe be handled again
4290 if (s->failed)
4291 break;
4293 /* handle a successful check operation, if parity is correct
4294 * we are done. Otherwise update the mismatch count and repair
4295 * parity if !MD_RECOVERY_CHECK
4297 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
4298 /* parity is correct (on disc,
4299 * not in buffer any more)
4301 set_bit(STRIPE_INSYNC, &sh->state);
4302 else {
4303 atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4304 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4305 /* don't try to repair!! */
4306 set_bit(STRIPE_INSYNC, &sh->state);
4307 pr_warn_ratelimited("%s: mismatch sector in range "
4308 "%llu-%llu\n", mdname(conf->mddev),
4309 (unsigned long long) sh->sector,
4310 (unsigned long long) sh->sector +
4311 RAID5_STRIPE_SECTORS(conf));
4312 } else {
4313 sh->check_state = check_state_compute_run;
4314 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4315 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4316 set_bit(R5_Wantcompute,
4317 &sh->dev[sh->pd_idx].flags);
4318 sh->ops.target = sh->pd_idx;
4319 sh->ops.target2 = -1;
4320 s->uptodate++;
4323 break;
4324 case check_state_compute_run:
4325 break;
4326 default:
4327 pr_err("%s: unknown check_state: %d sector: %llu\n",
4328 __func__, sh->check_state,
4329 (unsigned long long) sh->sector);
4330 BUG();
4334 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
4335 struct stripe_head_state *s,
4336 int disks)
4338 int pd_idx = sh->pd_idx;
4339 int qd_idx = sh->qd_idx;
4340 struct r5dev *dev;
4342 BUG_ON(sh->batch_head);
4343 set_bit(STRIPE_HANDLE, &sh->state);
4345 BUG_ON(s->failed > 2);
4347 /* Want to check and possibly repair P and Q.
4348 * However there could be one 'failed' device, in which
4349 * case we can only check one of them, possibly using the
4350 * other to generate missing data
4353 switch (sh->check_state) {
4354 case check_state_idle:
4355 /* start a new check operation if there are < 2 failures */
4356 if (s->failed == s->q_failed) {
4357 /* The only possible failed device holds Q, so it
4358 * makes sense to check P (If anything else were failed,
4359 * we would have used P to recreate it).
4361 sh->check_state = check_state_run;
4363 if (!s->q_failed && s->failed < 2) {
4364 /* Q is not failed, and we didn't use it to generate
4365 * anything, so it makes sense to check it
4367 if (sh->check_state == check_state_run)
4368 sh->check_state = check_state_run_pq;
4369 else
4370 sh->check_state = check_state_run_q;
4373 /* discard potentially stale zero_sum_result */
4374 sh->ops.zero_sum_result = 0;
4376 if (sh->check_state == check_state_run) {
4377 /* async_xor_zero_sum destroys the contents of P */
4378 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
4379 s->uptodate--;
4381 if (sh->check_state >= check_state_run &&
4382 sh->check_state <= check_state_run_pq) {
4383 /* async_syndrome_zero_sum preserves P and Q, so
4384 * no need to mark them !uptodate here
4386 set_bit(STRIPE_OP_CHECK, &s->ops_request);
4387 break;
4390 /* we have 2-disk failure */
4391 BUG_ON(s->failed != 2);
4392 fallthrough;
4393 case check_state_compute_result:
4394 sh->check_state = check_state_idle;
4396 /* check that a write has not made the stripe insync */
4397 if (test_bit(STRIPE_INSYNC, &sh->state))
4398 break;
4400 /* now write out any block on a failed drive,
4401 * or P or Q if they were recomputed
4403 dev = NULL;
4404 if (s->failed == 2) {
4405 dev = &sh->dev[s->failed_num[1]];
4406 s->locked++;
4407 set_bit(R5_LOCKED, &dev->flags);
4408 set_bit(R5_Wantwrite, &dev->flags);
4410 if (s->failed >= 1) {
4411 dev = &sh->dev[s->failed_num[0]];
4412 s->locked++;
4413 set_bit(R5_LOCKED, &dev->flags);
4414 set_bit(R5_Wantwrite, &dev->flags);
4416 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4417 dev = &sh->dev[pd_idx];
4418 s->locked++;
4419 set_bit(R5_LOCKED, &dev->flags);
4420 set_bit(R5_Wantwrite, &dev->flags);
4422 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4423 dev = &sh->dev[qd_idx];
4424 s->locked++;
4425 set_bit(R5_LOCKED, &dev->flags);
4426 set_bit(R5_Wantwrite, &dev->flags);
4428 if (WARN_ONCE(dev && !test_bit(R5_UPTODATE, &dev->flags),
4429 "%s: disk%td not up to date\n",
4430 mdname(conf->mddev),
4431 dev - (struct r5dev *) &sh->dev)) {
4432 clear_bit(R5_LOCKED, &dev->flags);
4433 clear_bit(R5_Wantwrite, &dev->flags);
4434 s->locked--;
4436 clear_bit(STRIPE_DEGRADED, &sh->state);
4438 set_bit(STRIPE_INSYNC, &sh->state);
4439 break;
4440 case check_state_run:
4441 case check_state_run_q:
4442 case check_state_run_pq:
4443 break; /* we will be called again upon completion */
4444 case check_state_check_result:
4445 sh->check_state = check_state_idle;
4447 /* handle a successful check operation, if parity is correct
4448 * we are done. Otherwise update the mismatch count and repair
4449 * parity if !MD_RECOVERY_CHECK
4451 if (sh->ops.zero_sum_result == 0) {
4452 /* both parities are correct */
4453 if (!s->failed)
4454 set_bit(STRIPE_INSYNC, &sh->state);
4455 else {
4456 /* in contrast to the raid5 case we can validate
4457 * parity, but still have a failure to write
4458 * back
4460 sh->check_state = check_state_compute_result;
4461 /* Returning at this point means that we may go
4462 * off and bring p and/or q uptodate again so
4463 * we make sure to check zero_sum_result again
4464 * to verify if p or q need writeback
4467 } else {
4468 atomic64_add(RAID5_STRIPE_SECTORS(conf), &conf->mddev->resync_mismatches);
4469 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery)) {
4470 /* don't try to repair!! */
4471 set_bit(STRIPE_INSYNC, &sh->state);
4472 pr_warn_ratelimited("%s: mismatch sector in range "
4473 "%llu-%llu\n", mdname(conf->mddev),
4474 (unsigned long long) sh->sector,
4475 (unsigned long long) sh->sector +
4476 RAID5_STRIPE_SECTORS(conf));
4477 } else {
4478 int *target = &sh->ops.target;
4480 sh->ops.target = -1;
4481 sh->ops.target2 = -1;
4482 sh->check_state = check_state_compute_run;
4483 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
4484 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
4485 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
4486 set_bit(R5_Wantcompute,
4487 &sh->dev[pd_idx].flags);
4488 *target = pd_idx;
4489 target = &sh->ops.target2;
4490 s->uptodate++;
4492 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
4493 set_bit(R5_Wantcompute,
4494 &sh->dev[qd_idx].flags);
4495 *target = qd_idx;
4496 s->uptodate++;
4500 break;
4501 case check_state_compute_run:
4502 break;
4503 default:
4504 pr_warn("%s: unknown check_state: %d sector: %llu\n",
4505 __func__, sh->check_state,
4506 (unsigned long long) sh->sector);
4507 BUG();
4511 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
4513 int i;
4515 /* We have read all the blocks in this stripe and now we need to
4516 * copy some of them into a target stripe for expand.
4518 struct dma_async_tx_descriptor *tx = NULL;
4519 BUG_ON(sh->batch_head);
4520 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4521 for (i = 0; i < sh->disks; i++)
4522 if (i != sh->pd_idx && i != sh->qd_idx) {
4523 int dd_idx, j;
4524 struct stripe_head *sh2;
4525 struct async_submit_ctl submit;
4527 sector_t bn = raid5_compute_blocknr(sh, i, 1);
4528 sector_t s = raid5_compute_sector(conf, bn, 0,
4529 &dd_idx, NULL);
4530 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
4531 if (sh2 == NULL)
4532 /* so far only the early blocks of this stripe
4533 * have been requested. When later blocks
4534 * get requested, we will try again
4536 continue;
4537 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
4538 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
4539 /* must have already done this block */
4540 raid5_release_stripe(sh2);
4541 continue;
4544 /* place all the copies on one channel */
4545 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
4546 tx = async_memcpy(sh2->dev[dd_idx].page,
4547 sh->dev[i].page, sh2->dev[dd_idx].offset,
4548 sh->dev[i].offset, RAID5_STRIPE_SIZE(conf),
4549 &submit);
4551 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
4552 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4553 for (j = 0; j < conf->raid_disks; j++)
4554 if (j != sh2->pd_idx &&
4555 j != sh2->qd_idx &&
4556 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4557 break;
4558 if (j == conf->raid_disks) {
4559 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4560 set_bit(STRIPE_HANDLE, &sh2->state);
4562 raid5_release_stripe(sh2);
4565 /* done submitting copies, wait for them to complete */
4566 async_tx_quiesce(&tx);
4570 * handle_stripe - do things to a stripe.
4572 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4573 * state of various bits to see what needs to be done.
4574 * Possible results:
4575 * return some read requests which now have data
4576 * return some write requests which are safely on storage
4577 * schedule a read on some buffers
4578 * schedule a write of some buffers
4579 * return confirmation of parity correctness
4583 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4585 struct r5conf *conf = sh->raid_conf;
4586 int disks = sh->disks;
4587 struct r5dev *dev;
4588 int i;
4589 int do_recovery = 0;
4591 memset(s, 0, sizeof(*s));
4593 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4594 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4595 s->failed_num[0] = -1;
4596 s->failed_num[1] = -1;
4597 s->log_failed = r5l_log_disk_error(conf);
4599 /* Now to look around and see what can be done */
4600 rcu_read_lock();
4601 for (i=disks; i--; ) {
4602 struct md_rdev *rdev;
4603 sector_t first_bad;
4604 int bad_sectors;
4605 int is_bad = 0;
4607 dev = &sh->dev[i];
4609 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4610 i, dev->flags,
4611 dev->toread, dev->towrite, dev->written);
4612 /* maybe we can reply to a read
4614 * new wantfill requests are only permitted while
4615 * ops_complete_biofill is guaranteed to be inactive
4617 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4618 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4619 set_bit(R5_Wantfill, &dev->flags);
4621 /* now count some things */
4622 if (test_bit(R5_LOCKED, &dev->flags))
4623 s->locked++;
4624 if (test_bit(R5_UPTODATE, &dev->flags))
4625 s->uptodate++;
4626 if (test_bit(R5_Wantcompute, &dev->flags)) {
4627 s->compute++;
4628 BUG_ON(s->compute > 2);
4631 if (test_bit(R5_Wantfill, &dev->flags))
4632 s->to_fill++;
4633 else if (dev->toread)
4634 s->to_read++;
4635 if (dev->towrite) {
4636 s->to_write++;
4637 if (!test_bit(R5_OVERWRITE, &dev->flags))
4638 s->non_overwrite++;
4640 if (dev->written)
4641 s->written++;
4642 /* Prefer to use the replacement for reads, but only
4643 * if it is recovered enough and has no bad blocks.
4645 rdev = rcu_dereference(conf->disks[i].replacement);
4646 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4647 rdev->recovery_offset >= sh->sector + RAID5_STRIPE_SECTORS(conf) &&
4648 !is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4649 &first_bad, &bad_sectors))
4650 set_bit(R5_ReadRepl, &dev->flags);
4651 else {
4652 if (rdev && !test_bit(Faulty, &rdev->flags))
4653 set_bit(R5_NeedReplace, &dev->flags);
4654 else
4655 clear_bit(R5_NeedReplace, &dev->flags);
4656 rdev = rcu_dereference(conf->disks[i].rdev);
4657 clear_bit(R5_ReadRepl, &dev->flags);
4659 if (rdev && test_bit(Faulty, &rdev->flags))
4660 rdev = NULL;
4661 if (rdev) {
4662 is_bad = is_badblock(rdev, sh->sector, RAID5_STRIPE_SECTORS(conf),
4663 &first_bad, &bad_sectors);
4664 if (s->blocked_rdev == NULL
4665 && (test_bit(Blocked, &rdev->flags)
4666 || is_bad < 0)) {
4667 if (is_bad < 0)
4668 set_bit(BlockedBadBlocks,
4669 &rdev->flags);
4670 s->blocked_rdev = rdev;
4671 atomic_inc(&rdev->nr_pending);
4674 clear_bit(R5_Insync, &dev->flags);
4675 if (!rdev)
4676 /* Not in-sync */;
4677 else if (is_bad) {
4678 /* also not in-sync */
4679 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4680 test_bit(R5_UPTODATE, &dev->flags)) {
4681 /* treat as in-sync, but with a read error
4682 * which we can now try to correct
4684 set_bit(R5_Insync, &dev->flags);
4685 set_bit(R5_ReadError, &dev->flags);
4687 } else if (test_bit(In_sync, &rdev->flags))
4688 set_bit(R5_Insync, &dev->flags);
4689 else if (sh->sector + RAID5_STRIPE_SECTORS(conf) <= rdev->recovery_offset)
4690 /* in sync if before recovery_offset */
4691 set_bit(R5_Insync, &dev->flags);
4692 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4693 test_bit(R5_Expanded, &dev->flags))
4694 /* If we've reshaped into here, we assume it is Insync.
4695 * We will shortly update recovery_offset to make
4696 * it official.
4698 set_bit(R5_Insync, &dev->flags);
4700 if (test_bit(R5_WriteError, &dev->flags)) {
4701 /* This flag does not apply to '.replacement'
4702 * only to .rdev, so make sure to check that*/
4703 struct md_rdev *rdev2 = rcu_dereference(
4704 conf->disks[i].rdev);
4705 if (rdev2 == rdev)
4706 clear_bit(R5_Insync, &dev->flags);
4707 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4708 s->handle_bad_blocks = 1;
4709 atomic_inc(&rdev2->nr_pending);
4710 } else
4711 clear_bit(R5_WriteError, &dev->flags);
4713 if (test_bit(R5_MadeGood, &dev->flags)) {
4714 /* This flag does not apply to '.replacement'
4715 * only to .rdev, so make sure to check that*/
4716 struct md_rdev *rdev2 = rcu_dereference(
4717 conf->disks[i].rdev);
4718 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4719 s->handle_bad_blocks = 1;
4720 atomic_inc(&rdev2->nr_pending);
4721 } else
4722 clear_bit(R5_MadeGood, &dev->flags);
4724 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4725 struct md_rdev *rdev2 = rcu_dereference(
4726 conf->disks[i].replacement);
4727 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4728 s->handle_bad_blocks = 1;
4729 atomic_inc(&rdev2->nr_pending);
4730 } else
4731 clear_bit(R5_MadeGoodRepl, &dev->flags);
4733 if (!test_bit(R5_Insync, &dev->flags)) {
4734 /* The ReadError flag will just be confusing now */
4735 clear_bit(R5_ReadError, &dev->flags);
4736 clear_bit(R5_ReWrite, &dev->flags);
4738 if (test_bit(R5_ReadError, &dev->flags))
4739 clear_bit(R5_Insync, &dev->flags);
4740 if (!test_bit(R5_Insync, &dev->flags)) {
4741 if (s->failed < 2)
4742 s->failed_num[s->failed] = i;
4743 s->failed++;
4744 if (rdev && !test_bit(Faulty, &rdev->flags))
4745 do_recovery = 1;
4746 else if (!rdev) {
4747 rdev = rcu_dereference(
4748 conf->disks[i].replacement);
4749 if (rdev && !test_bit(Faulty, &rdev->flags))
4750 do_recovery = 1;
4754 if (test_bit(R5_InJournal, &dev->flags))
4755 s->injournal++;
4756 if (test_bit(R5_InJournal, &dev->flags) && dev->written)
4757 s->just_cached++;
4759 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4760 /* If there is a failed device being replaced,
4761 * we must be recovering.
4762 * else if we are after recovery_cp, we must be syncing
4763 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4764 * else we can only be replacing
4765 * sync and recovery both need to read all devices, and so
4766 * use the same flag.
4768 if (do_recovery ||
4769 sh->sector >= conf->mddev->recovery_cp ||
4770 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4771 s->syncing = 1;
4772 else
4773 s->replacing = 1;
4775 rcu_read_unlock();
4779 * Return '1' if this is a member of batch, or '0' if it is a lone stripe or
4780 * a head which can now be handled.
4782 static int clear_batch_ready(struct stripe_head *sh)
4784 struct stripe_head *tmp;
4785 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4786 return (sh->batch_head && sh->batch_head != sh);
4787 spin_lock(&sh->stripe_lock);
4788 if (!sh->batch_head) {
4789 spin_unlock(&sh->stripe_lock);
4790 return 0;
4794 * this stripe could be added to a batch list before we check
4795 * BATCH_READY, skips it
4797 if (sh->batch_head != sh) {
4798 spin_unlock(&sh->stripe_lock);
4799 return 1;
4801 spin_lock(&sh->batch_lock);
4802 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4803 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4804 spin_unlock(&sh->batch_lock);
4805 spin_unlock(&sh->stripe_lock);
4808 * BATCH_READY is cleared, no new stripes can be added.
4809 * batch_list can be accessed without lock
4811 return 0;
4814 static void break_stripe_batch_list(struct stripe_head *head_sh,
4815 unsigned long handle_flags)
4817 struct stripe_head *sh, *next;
4818 int i;
4819 int do_wakeup = 0;
4821 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4823 list_del_init(&sh->batch_list);
4825 WARN_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4826 (1 << STRIPE_SYNCING) |
4827 (1 << STRIPE_REPLACED) |
4828 (1 << STRIPE_DELAYED) |
4829 (1 << STRIPE_BIT_DELAY) |
4830 (1 << STRIPE_FULL_WRITE) |
4831 (1 << STRIPE_BIOFILL_RUN) |
4832 (1 << STRIPE_COMPUTE_RUN) |
4833 (1 << STRIPE_DISCARD) |
4834 (1 << STRIPE_BATCH_READY) |
4835 (1 << STRIPE_BATCH_ERR) |
4836 (1 << STRIPE_BITMAP_PENDING)),
4837 "stripe state: %lx\n", sh->state);
4838 WARN_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4839 (1 << STRIPE_REPLACED)),
4840 "head stripe state: %lx\n", head_sh->state);
4842 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4843 (1 << STRIPE_PREREAD_ACTIVE) |
4844 (1 << STRIPE_DEGRADED) |
4845 (1 << STRIPE_ON_UNPLUG_LIST)),
4846 head_sh->state & (1 << STRIPE_INSYNC));
4848 sh->check_state = head_sh->check_state;
4849 sh->reconstruct_state = head_sh->reconstruct_state;
4850 spin_lock_irq(&sh->stripe_lock);
4851 sh->batch_head = NULL;
4852 spin_unlock_irq(&sh->stripe_lock);
4853 for (i = 0; i < sh->disks; i++) {
4854 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4855 do_wakeup = 1;
4856 sh->dev[i].flags = head_sh->dev[i].flags &
4857 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4859 if (handle_flags == 0 ||
4860 sh->state & handle_flags)
4861 set_bit(STRIPE_HANDLE, &sh->state);
4862 raid5_release_stripe(sh);
4864 spin_lock_irq(&head_sh->stripe_lock);
4865 head_sh->batch_head = NULL;
4866 spin_unlock_irq(&head_sh->stripe_lock);
4867 for (i = 0; i < head_sh->disks; i++)
4868 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4869 do_wakeup = 1;
4870 if (head_sh->state & handle_flags)
4871 set_bit(STRIPE_HANDLE, &head_sh->state);
4873 if (do_wakeup)
4874 wake_up(&head_sh->raid_conf->wait_for_overlap);
4877 static void handle_stripe(struct stripe_head *sh)
4879 struct stripe_head_state s;
4880 struct r5conf *conf = sh->raid_conf;
4881 int i;
4882 int prexor;
4883 int disks = sh->disks;
4884 struct r5dev *pdev, *qdev;
4886 clear_bit(STRIPE_HANDLE, &sh->state);
4889 * handle_stripe should not continue handle the batched stripe, only
4890 * the head of batch list or lone stripe can continue. Otherwise we
4891 * could see break_stripe_batch_list warns about the STRIPE_ACTIVE
4892 * is set for the batched stripe.
4894 if (clear_batch_ready(sh))
4895 return;
4897 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4898 /* already being handled, ensure it gets handled
4899 * again when current action finishes */
4900 set_bit(STRIPE_HANDLE, &sh->state);
4901 return;
4904 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4905 break_stripe_batch_list(sh, 0);
4907 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4908 spin_lock(&sh->stripe_lock);
4910 * Cannot process 'sync' concurrently with 'discard'.
4911 * Flush data in r5cache before 'sync'.
4913 if (!test_bit(STRIPE_R5C_PARTIAL_STRIPE, &sh->state) &&
4914 !test_bit(STRIPE_R5C_FULL_STRIPE, &sh->state) &&
4915 !test_bit(STRIPE_DISCARD, &sh->state) &&
4916 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4917 set_bit(STRIPE_SYNCING, &sh->state);
4918 clear_bit(STRIPE_INSYNC, &sh->state);
4919 clear_bit(STRIPE_REPLACED, &sh->state);
4921 spin_unlock(&sh->stripe_lock);
4923 clear_bit(STRIPE_DELAYED, &sh->state);
4925 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4926 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4927 (unsigned long long)sh->sector, sh->state,
4928 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4929 sh->check_state, sh->reconstruct_state);
4931 analyse_stripe(sh, &s);
4933 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4934 goto finish;
4936 if (s.handle_bad_blocks ||
4937 test_bit(MD_SB_CHANGE_PENDING, &conf->mddev->sb_flags)) {
4938 set_bit(STRIPE_HANDLE, &sh->state);
4939 goto finish;
4942 if (unlikely(s.blocked_rdev)) {
4943 if (s.syncing || s.expanding || s.expanded ||
4944 s.replacing || s.to_write || s.written) {
4945 set_bit(STRIPE_HANDLE, &sh->state);
4946 goto finish;
4948 /* There is nothing for the blocked_rdev to block */
4949 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4950 s.blocked_rdev = NULL;
4953 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4954 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4955 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4958 pr_debug("locked=%d uptodate=%d to_read=%d"
4959 " to_write=%d failed=%d failed_num=%d,%d\n",
4960 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4961 s.failed_num[0], s.failed_num[1]);
4963 * check if the array has lost more than max_degraded devices and,
4964 * if so, some requests might need to be failed.
4966 * When journal device failed (log_failed), we will only process
4967 * the stripe if there is data need write to raid disks
4969 if (s.failed > conf->max_degraded ||
4970 (s.log_failed && s.injournal == 0)) {
4971 sh->check_state = 0;
4972 sh->reconstruct_state = 0;
4973 break_stripe_batch_list(sh, 0);
4974 if (s.to_read+s.to_write+s.written)
4975 handle_failed_stripe(conf, sh, &s, disks);
4976 if (s.syncing + s.replacing)
4977 handle_failed_sync(conf, sh, &s);
4980 /* Now we check to see if any write operations have recently
4981 * completed
4983 prexor = 0;
4984 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4985 prexor = 1;
4986 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4987 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4988 sh->reconstruct_state = reconstruct_state_idle;
4990 /* All the 'written' buffers and the parity block are ready to
4991 * be written back to disk
4993 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4994 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4995 BUG_ON(sh->qd_idx >= 0 &&
4996 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4997 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4998 for (i = disks; i--; ) {
4999 struct r5dev *dev = &sh->dev[i];
5000 if (test_bit(R5_LOCKED, &dev->flags) &&
5001 (i == sh->pd_idx || i == sh->qd_idx ||
5002 dev->written || test_bit(R5_InJournal,
5003 &dev->flags))) {
5004 pr_debug("Writing block %d\n", i);
5005 set_bit(R5_Wantwrite, &dev->flags);
5006 if (prexor)
5007 continue;
5008 if (s.failed > 1)
5009 continue;
5010 if (!test_bit(R5_Insync, &dev->flags) ||
5011 ((i == sh->pd_idx || i == sh->qd_idx) &&
5012 s.failed == 0))
5013 set_bit(STRIPE_INSYNC, &sh->state);
5016 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5017 s.dec_preread_active = 1;
5021 * might be able to return some write requests if the parity blocks
5022 * are safe, or on a failed drive
5024 pdev = &sh->dev[sh->pd_idx];
5025 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
5026 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
5027 qdev = &sh->dev[sh->qd_idx];
5028 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
5029 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
5030 || conf->level < 6;
5032 if (s.written &&
5033 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
5034 && !test_bit(R5_LOCKED, &pdev->flags)
5035 && (test_bit(R5_UPTODATE, &pdev->flags) ||
5036 test_bit(R5_Discard, &pdev->flags))))) &&
5037 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
5038 && !test_bit(R5_LOCKED, &qdev->flags)
5039 && (test_bit(R5_UPTODATE, &qdev->flags) ||
5040 test_bit(R5_Discard, &qdev->flags))))))
5041 handle_stripe_clean_event(conf, sh, disks);
5043 if (s.just_cached)
5044 r5c_handle_cached_data_endio(conf, sh, disks);
5045 log_stripe_write_finished(sh);
5047 /* Now we might consider reading some blocks, either to check/generate
5048 * parity, or to satisfy requests
5049 * or to load a block that is being partially written.
5051 if (s.to_read || s.non_overwrite
5052 || (s.to_write && s.failed)
5053 || (s.syncing && (s.uptodate + s.compute < disks))
5054 || s.replacing
5055 || s.expanding)
5056 handle_stripe_fill(sh, &s, disks);
5059 * When the stripe finishes full journal write cycle (write to journal
5060 * and raid disk), this is the clean up procedure so it is ready for
5061 * next operation.
5063 r5c_finish_stripe_write_out(conf, sh, &s);
5066 * Now to consider new write requests, cache write back and what else,
5067 * if anything should be read. We do not handle new writes when:
5068 * 1/ A 'write' operation (copy+xor) is already in flight.
5069 * 2/ A 'check' operation is in flight, as it may clobber the parity
5070 * block.
5071 * 3/ A r5c cache log write is in flight.
5074 if (!sh->reconstruct_state && !sh->check_state && !sh->log_io) {
5075 if (!r5c_is_writeback(conf->log)) {
5076 if (s.to_write)
5077 handle_stripe_dirtying(conf, sh, &s, disks);
5078 } else { /* write back cache */
5079 int ret = 0;
5081 /* First, try handle writes in caching phase */
5082 if (s.to_write)
5083 ret = r5c_try_caching_write(conf, sh, &s,
5084 disks);
5086 * If caching phase failed: ret == -EAGAIN
5087 * OR
5088 * stripe under reclaim: !caching && injournal
5090 * fall back to handle_stripe_dirtying()
5092 if (ret == -EAGAIN ||
5093 /* stripe under reclaim: !caching && injournal */
5094 (!test_bit(STRIPE_R5C_CACHING, &sh->state) &&
5095 s.injournal > 0)) {
5096 ret = handle_stripe_dirtying(conf, sh, &s,
5097 disks);
5098 if (ret == -EAGAIN)
5099 goto finish;
5104 /* maybe we need to check and possibly fix the parity for this stripe
5105 * Any reads will already have been scheduled, so we just see if enough
5106 * data is available. The parity check is held off while parity
5107 * dependent operations are in flight.
5109 if (sh->check_state ||
5110 (s.syncing && s.locked == 0 &&
5111 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5112 !test_bit(STRIPE_INSYNC, &sh->state))) {
5113 if (conf->level == 6)
5114 handle_parity_checks6(conf, sh, &s, disks);
5115 else
5116 handle_parity_checks5(conf, sh, &s, disks);
5119 if ((s.replacing || s.syncing) && s.locked == 0
5120 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
5121 && !test_bit(STRIPE_REPLACED, &sh->state)) {
5122 /* Write out to replacement devices where possible */
5123 for (i = 0; i < conf->raid_disks; i++)
5124 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
5125 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
5126 set_bit(R5_WantReplace, &sh->dev[i].flags);
5127 set_bit(R5_LOCKED, &sh->dev[i].flags);
5128 s.locked++;
5130 if (s.replacing)
5131 set_bit(STRIPE_INSYNC, &sh->state);
5132 set_bit(STRIPE_REPLACED, &sh->state);
5134 if ((s.syncing || s.replacing) && s.locked == 0 &&
5135 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
5136 test_bit(STRIPE_INSYNC, &sh->state)) {
5137 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5138 clear_bit(STRIPE_SYNCING, &sh->state);
5139 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
5140 wake_up(&conf->wait_for_overlap);
5143 /* If the failed drives are just a ReadError, then we might need
5144 * to progress the repair/check process
5146 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
5147 for (i = 0; i < s.failed; i++) {
5148 struct r5dev *dev = &sh->dev[s.failed_num[i]];
5149 if (test_bit(R5_ReadError, &dev->flags)
5150 && !test_bit(R5_LOCKED, &dev->flags)
5151 && test_bit(R5_UPTODATE, &dev->flags)
5153 if (!test_bit(R5_ReWrite, &dev->flags)) {
5154 set_bit(R5_Wantwrite, &dev->flags);
5155 set_bit(R5_ReWrite, &dev->flags);
5156 } else
5157 /* let's read it back */
5158 set_bit(R5_Wantread, &dev->flags);
5159 set_bit(R5_LOCKED, &dev->flags);
5160 s.locked++;
5164 /* Finish reconstruct operations initiated by the expansion process */
5165 if (sh->reconstruct_state == reconstruct_state_result) {
5166 struct stripe_head *sh_src
5167 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
5168 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
5169 /* sh cannot be written until sh_src has been read.
5170 * so arrange for sh to be delayed a little
5172 set_bit(STRIPE_DELAYED, &sh->state);
5173 set_bit(STRIPE_HANDLE, &sh->state);
5174 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
5175 &sh_src->state))
5176 atomic_inc(&conf->preread_active_stripes);
5177 raid5_release_stripe(sh_src);
5178 goto finish;
5180 if (sh_src)
5181 raid5_release_stripe(sh_src);
5183 sh->reconstruct_state = reconstruct_state_idle;
5184 clear_bit(STRIPE_EXPANDING, &sh->state);
5185 for (i = conf->raid_disks; i--; ) {
5186 set_bit(R5_Wantwrite, &sh->dev[i].flags);
5187 set_bit(R5_LOCKED, &sh->dev[i].flags);
5188 s.locked++;
5192 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
5193 !sh->reconstruct_state) {
5194 /* Need to write out all blocks after computing parity */
5195 sh->disks = conf->raid_disks;
5196 stripe_set_idx(sh->sector, conf, 0, sh);
5197 schedule_reconstruction(sh, &s, 1, 1);
5198 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
5199 clear_bit(STRIPE_EXPAND_READY, &sh->state);
5200 atomic_dec(&conf->reshape_stripes);
5201 wake_up(&conf->wait_for_overlap);
5202 md_done_sync(conf->mddev, RAID5_STRIPE_SECTORS(conf), 1);
5205 if (s.expanding && s.locked == 0 &&
5206 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
5207 handle_stripe_expansion(conf, sh);
5209 finish:
5210 /* wait for this device to become unblocked */
5211 if (unlikely(s.blocked_rdev)) {
5212 if (conf->mddev->external)
5213 md_wait_for_blocked_rdev(s.blocked_rdev,
5214 conf->mddev);
5215 else
5216 /* Internal metadata will immediately
5217 * be written by raid5d, so we don't
5218 * need to wait here.
5220 rdev_dec_pending(s.blocked_rdev,
5221 conf->mddev);
5224 if (s.handle_bad_blocks)
5225 for (i = disks; i--; ) {
5226 struct md_rdev *rdev;
5227 struct r5dev *dev = &sh->dev[i];
5228 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
5229 /* We own a safe reference to the rdev */
5230 rdev = conf->disks[i].rdev;
5231 if (!rdev_set_badblocks(rdev, sh->sector,
5232 RAID5_STRIPE_SECTORS(conf), 0))
5233 md_error(conf->mddev, rdev);
5234 rdev_dec_pending(rdev, conf->mddev);
5236 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
5237 rdev = conf->disks[i].rdev;
5238 rdev_clear_badblocks(rdev, sh->sector,
5239 RAID5_STRIPE_SECTORS(conf), 0);
5240 rdev_dec_pending(rdev, conf->mddev);
5242 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
5243 rdev = conf->disks[i].replacement;
5244 if (!rdev)
5245 /* rdev have been moved down */
5246 rdev = conf->disks[i].rdev;
5247 rdev_clear_badblocks(rdev, sh->sector,
5248 RAID5_STRIPE_SECTORS(conf), 0);
5249 rdev_dec_pending(rdev, conf->mddev);
5253 if (s.ops_request)
5254 raid_run_ops(sh, s.ops_request);
5256 ops_run_io(sh, &s);
5258 if (s.dec_preread_active) {
5259 /* We delay this until after ops_run_io so that if make_request
5260 * is waiting on a flush, it won't continue until the writes
5261 * have actually been submitted.
5263 atomic_dec(&conf->preread_active_stripes);
5264 if (atomic_read(&conf->preread_active_stripes) <
5265 IO_THRESHOLD)
5266 md_wakeup_thread(conf->mddev->thread);
5269 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
5272 static void raid5_activate_delayed(struct r5conf *conf)
5274 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
5275 while (!list_empty(&conf->delayed_list)) {
5276 struct list_head *l = conf->delayed_list.next;
5277 struct stripe_head *sh;
5278 sh = list_entry(l, struct stripe_head, lru);
5279 list_del_init(l);
5280 clear_bit(STRIPE_DELAYED, &sh->state);
5281 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5282 atomic_inc(&conf->preread_active_stripes);
5283 list_add_tail(&sh->lru, &conf->hold_list);
5284 raid5_wakeup_stripe_thread(sh);
5289 static void activate_bit_delay(struct r5conf *conf,
5290 struct list_head *temp_inactive_list)
5292 /* device_lock is held */
5293 struct list_head head;
5294 list_add(&head, &conf->bitmap_list);
5295 list_del_init(&conf->bitmap_list);
5296 while (!list_empty(&head)) {
5297 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
5298 int hash;
5299 list_del_init(&sh->lru);
5300 atomic_inc(&sh->count);
5301 hash = sh->hash_lock_index;
5302 __release_stripe(conf, sh, &temp_inactive_list[hash]);
5306 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
5308 struct r5conf *conf = mddev->private;
5309 sector_t sector = bio->bi_iter.bi_sector;
5310 unsigned int chunk_sectors;
5311 unsigned int bio_sectors = bio_sectors(bio);
5313 WARN_ON_ONCE(bio->bi_partno);
5315 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
5316 return chunk_sectors >=
5317 ((sector & (chunk_sectors - 1)) + bio_sectors);
5321 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
5322 * later sampled by raid5d.
5324 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
5326 unsigned long flags;
5328 spin_lock_irqsave(&conf->device_lock, flags);
5330 bi->bi_next = conf->retry_read_aligned_list;
5331 conf->retry_read_aligned_list = bi;
5333 spin_unlock_irqrestore(&conf->device_lock, flags);
5334 md_wakeup_thread(conf->mddev->thread);
5337 static struct bio *remove_bio_from_retry(struct r5conf *conf,
5338 unsigned int *offset)
5340 struct bio *bi;
5342 bi = conf->retry_read_aligned;
5343 if (bi) {
5344 *offset = conf->retry_read_offset;
5345 conf->retry_read_aligned = NULL;
5346 return bi;
5348 bi = conf->retry_read_aligned_list;
5349 if(bi) {
5350 conf->retry_read_aligned_list = bi->bi_next;
5351 bi->bi_next = NULL;
5352 *offset = 0;
5355 return bi;
5359 * The "raid5_align_endio" should check if the read succeeded and if it
5360 * did, call bio_endio on the original bio (having bio_put the new bio
5361 * first).
5362 * If the read failed..
5364 static void raid5_align_endio(struct bio *bi)
5366 struct bio* raid_bi = bi->bi_private;
5367 struct mddev *mddev;
5368 struct r5conf *conf;
5369 struct md_rdev *rdev;
5370 blk_status_t error = bi->bi_status;
5372 bio_put(bi);
5374 rdev = (void*)raid_bi->bi_next;
5375 raid_bi->bi_next = NULL;
5376 mddev = rdev->mddev;
5377 conf = mddev->private;
5379 rdev_dec_pending(rdev, conf->mddev);
5381 if (!error) {
5382 bio_endio(raid_bi);
5383 if (atomic_dec_and_test(&conf->active_aligned_reads))
5384 wake_up(&conf->wait_for_quiescent);
5385 return;
5388 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
5390 add_bio_to_retry(raid_bi, conf);
5393 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
5395 struct r5conf *conf = mddev->private;
5396 int dd_idx;
5397 struct bio* align_bi;
5398 struct md_rdev *rdev;
5399 sector_t end_sector;
5401 if (!in_chunk_boundary(mddev, raid_bio)) {
5402 pr_debug("%s: non aligned\n", __func__);
5403 return 0;
5406 * use bio_clone_fast to make a copy of the bio
5408 align_bi = bio_clone_fast(raid_bio, GFP_NOIO, &mddev->bio_set);
5409 if (!align_bi)
5410 return 0;
5412 * set bi_end_io to a new function, and set bi_private to the
5413 * original bio.
5415 align_bi->bi_end_io = raid5_align_endio;
5416 align_bi->bi_private = raid_bio;
5418 * compute position
5420 align_bi->bi_iter.bi_sector =
5421 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
5422 0, &dd_idx, NULL);
5424 end_sector = bio_end_sector(align_bi);
5425 rcu_read_lock();
5426 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
5427 if (!rdev || test_bit(Faulty, &rdev->flags) ||
5428 rdev->recovery_offset < end_sector) {
5429 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
5430 if (rdev &&
5431 (test_bit(Faulty, &rdev->flags) ||
5432 !(test_bit(In_sync, &rdev->flags) ||
5433 rdev->recovery_offset >= end_sector)))
5434 rdev = NULL;
5437 if (r5c_big_stripe_cached(conf, align_bi->bi_iter.bi_sector)) {
5438 rcu_read_unlock();
5439 bio_put(align_bi);
5440 return 0;
5443 if (rdev) {
5444 sector_t first_bad;
5445 int bad_sectors;
5447 atomic_inc(&rdev->nr_pending);
5448 rcu_read_unlock();
5449 raid_bio->bi_next = (void*)rdev;
5450 bio_set_dev(align_bi, rdev->bdev);
5452 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
5453 bio_sectors(align_bi),
5454 &first_bad, &bad_sectors)) {
5455 bio_put(align_bi);
5456 rdev_dec_pending(rdev, mddev);
5457 return 0;
5460 /* No reshape active, so we can trust rdev->data_offset */
5461 align_bi->bi_iter.bi_sector += rdev->data_offset;
5463 spin_lock_irq(&conf->device_lock);
5464 wait_event_lock_irq(conf->wait_for_quiescent,
5465 conf->quiesce == 0,
5466 conf->device_lock);
5467 atomic_inc(&conf->active_aligned_reads);
5468 spin_unlock_irq(&conf->device_lock);
5470 if (mddev->gendisk)
5471 trace_block_bio_remap(align_bi, disk_devt(mddev->gendisk),
5472 raid_bio->bi_iter.bi_sector);
5473 submit_bio_noacct(align_bi);
5474 return 1;
5475 } else {
5476 rcu_read_unlock();
5477 bio_put(align_bi);
5478 return 0;
5482 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
5484 struct bio *split;
5485 sector_t sector = raid_bio->bi_iter.bi_sector;
5486 unsigned chunk_sects = mddev->chunk_sectors;
5487 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
5489 if (sectors < bio_sectors(raid_bio)) {
5490 struct r5conf *conf = mddev->private;
5491 split = bio_split(raid_bio, sectors, GFP_NOIO, &conf->bio_split);
5492 bio_chain(split, raid_bio);
5493 submit_bio_noacct(raid_bio);
5494 raid_bio = split;
5497 if (!raid5_read_one_chunk(mddev, raid_bio))
5498 return raid_bio;
5500 return NULL;
5503 /* __get_priority_stripe - get the next stripe to process
5505 * Full stripe writes are allowed to pass preread active stripes up until
5506 * the bypass_threshold is exceeded. In general the bypass_count
5507 * increments when the handle_list is handled before the hold_list; however, it
5508 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
5509 * stripe with in flight i/o. The bypass_count will be reset when the
5510 * head of the hold_list has changed, i.e. the head was promoted to the
5511 * handle_list.
5513 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
5515 struct stripe_head *sh, *tmp;
5516 struct list_head *handle_list = NULL;
5517 struct r5worker_group *wg;
5518 bool second_try = !r5c_is_writeback(conf->log) &&
5519 !r5l_log_disk_error(conf);
5520 bool try_loprio = test_bit(R5C_LOG_TIGHT, &conf->cache_state) ||
5521 r5l_log_disk_error(conf);
5523 again:
5524 wg = NULL;
5525 sh = NULL;
5526 if (conf->worker_cnt_per_group == 0) {
5527 handle_list = try_loprio ? &conf->loprio_list :
5528 &conf->handle_list;
5529 } else if (group != ANY_GROUP) {
5530 handle_list = try_loprio ? &conf->worker_groups[group].loprio_list :
5531 &conf->worker_groups[group].handle_list;
5532 wg = &conf->worker_groups[group];
5533 } else {
5534 int i;
5535 for (i = 0; i < conf->group_cnt; i++) {
5536 handle_list = try_loprio ? &conf->worker_groups[i].loprio_list :
5537 &conf->worker_groups[i].handle_list;
5538 wg = &conf->worker_groups[i];
5539 if (!list_empty(handle_list))
5540 break;
5544 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
5545 __func__,
5546 list_empty(handle_list) ? "empty" : "busy",
5547 list_empty(&conf->hold_list) ? "empty" : "busy",
5548 atomic_read(&conf->pending_full_writes), conf->bypass_count);
5550 if (!list_empty(handle_list)) {
5551 sh = list_entry(handle_list->next, typeof(*sh), lru);
5553 if (list_empty(&conf->hold_list))
5554 conf->bypass_count = 0;
5555 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
5556 if (conf->hold_list.next == conf->last_hold)
5557 conf->bypass_count++;
5558 else {
5559 conf->last_hold = conf->hold_list.next;
5560 conf->bypass_count -= conf->bypass_threshold;
5561 if (conf->bypass_count < 0)
5562 conf->bypass_count = 0;
5565 } else if (!list_empty(&conf->hold_list) &&
5566 ((conf->bypass_threshold &&
5567 conf->bypass_count > conf->bypass_threshold) ||
5568 atomic_read(&conf->pending_full_writes) == 0)) {
5570 list_for_each_entry(tmp, &conf->hold_list, lru) {
5571 if (conf->worker_cnt_per_group == 0 ||
5572 group == ANY_GROUP ||
5573 !cpu_online(tmp->cpu) ||
5574 cpu_to_group(tmp->cpu) == group) {
5575 sh = tmp;
5576 break;
5580 if (sh) {
5581 conf->bypass_count -= conf->bypass_threshold;
5582 if (conf->bypass_count < 0)
5583 conf->bypass_count = 0;
5585 wg = NULL;
5588 if (!sh) {
5589 if (second_try)
5590 return NULL;
5591 second_try = true;
5592 try_loprio = !try_loprio;
5593 goto again;
5596 if (wg) {
5597 wg->stripes_cnt--;
5598 sh->group = NULL;
5600 list_del_init(&sh->lru);
5601 BUG_ON(atomic_inc_return(&sh->count) != 1);
5602 return sh;
5605 struct raid5_plug_cb {
5606 struct blk_plug_cb cb;
5607 struct list_head list;
5608 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5611 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5613 struct raid5_plug_cb *cb = container_of(
5614 blk_cb, struct raid5_plug_cb, cb);
5615 struct stripe_head *sh;
5616 struct mddev *mddev = cb->cb.data;
5617 struct r5conf *conf = mddev->private;
5618 int cnt = 0;
5619 int hash;
5621 if (cb->list.next && !list_empty(&cb->list)) {
5622 spin_lock_irq(&conf->device_lock);
5623 while (!list_empty(&cb->list)) {
5624 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5625 list_del_init(&sh->lru);
5627 * avoid race release_stripe_plug() sees
5628 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5629 * is still in our list
5631 smp_mb__before_atomic();
5632 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5634 * STRIPE_ON_RELEASE_LIST could be set here. In that
5635 * case, the count is always > 1 here
5637 hash = sh->hash_lock_index;
5638 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5639 cnt++;
5641 spin_unlock_irq(&conf->device_lock);
5643 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5644 NR_STRIPE_HASH_LOCKS);
5645 if (mddev->queue)
5646 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5647 kfree(cb);
5650 static void release_stripe_plug(struct mddev *mddev,
5651 struct stripe_head *sh)
5653 struct blk_plug_cb *blk_cb = blk_check_plugged(
5654 raid5_unplug, mddev,
5655 sizeof(struct raid5_plug_cb));
5656 struct raid5_plug_cb *cb;
5658 if (!blk_cb) {
5659 raid5_release_stripe(sh);
5660 return;
5663 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5665 if (cb->list.next == NULL) {
5666 int i;
5667 INIT_LIST_HEAD(&cb->list);
5668 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5669 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5672 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5673 list_add_tail(&sh->lru, &cb->list);
5674 else
5675 raid5_release_stripe(sh);
5678 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5680 struct r5conf *conf = mddev->private;
5681 sector_t logical_sector, last_sector;
5682 struct stripe_head *sh;
5683 int stripe_sectors;
5685 if (mddev->reshape_position != MaxSector)
5686 /* Skip discard while reshape is happening */
5687 return;
5689 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5690 last_sector = bio_end_sector(bi);
5692 bi->bi_next = NULL;
5694 stripe_sectors = conf->chunk_sectors *
5695 (conf->raid_disks - conf->max_degraded);
5696 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5697 stripe_sectors);
5698 sector_div(last_sector, stripe_sectors);
5700 logical_sector *= conf->chunk_sectors;
5701 last_sector *= conf->chunk_sectors;
5703 for (; logical_sector < last_sector;
5704 logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5705 DEFINE_WAIT(w);
5706 int d;
5707 again:
5708 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5709 prepare_to_wait(&conf->wait_for_overlap, &w,
5710 TASK_UNINTERRUPTIBLE);
5711 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5712 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5713 raid5_release_stripe(sh);
5714 schedule();
5715 goto again;
5717 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5718 spin_lock_irq(&sh->stripe_lock);
5719 for (d = 0; d < conf->raid_disks; d++) {
5720 if (d == sh->pd_idx || d == sh->qd_idx)
5721 continue;
5722 if (sh->dev[d].towrite || sh->dev[d].toread) {
5723 set_bit(R5_Overlap, &sh->dev[d].flags);
5724 spin_unlock_irq(&sh->stripe_lock);
5725 raid5_release_stripe(sh);
5726 schedule();
5727 goto again;
5730 set_bit(STRIPE_DISCARD, &sh->state);
5731 finish_wait(&conf->wait_for_overlap, &w);
5732 sh->overwrite_disks = 0;
5733 for (d = 0; d < conf->raid_disks; d++) {
5734 if (d == sh->pd_idx || d == sh->qd_idx)
5735 continue;
5736 sh->dev[d].towrite = bi;
5737 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5738 bio_inc_remaining(bi);
5739 md_write_inc(mddev, bi);
5740 sh->overwrite_disks++;
5742 spin_unlock_irq(&sh->stripe_lock);
5743 if (conf->mddev->bitmap) {
5744 for (d = 0;
5745 d < conf->raid_disks - conf->max_degraded;
5746 d++)
5747 md_bitmap_startwrite(mddev->bitmap,
5748 sh->sector,
5749 RAID5_STRIPE_SECTORS(conf),
5751 sh->bm_seq = conf->seq_flush + 1;
5752 set_bit(STRIPE_BIT_DELAY, &sh->state);
5755 set_bit(STRIPE_HANDLE, &sh->state);
5756 clear_bit(STRIPE_DELAYED, &sh->state);
5757 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5758 atomic_inc(&conf->preread_active_stripes);
5759 release_stripe_plug(mddev, sh);
5762 bio_endio(bi);
5765 static bool raid5_make_request(struct mddev *mddev, struct bio * bi)
5767 struct r5conf *conf = mddev->private;
5768 int dd_idx;
5769 sector_t new_sector;
5770 sector_t logical_sector, last_sector;
5771 struct stripe_head *sh;
5772 const int rw = bio_data_dir(bi);
5773 DEFINE_WAIT(w);
5774 bool do_prepare;
5775 bool do_flush = false;
5777 if (unlikely(bi->bi_opf & REQ_PREFLUSH)) {
5778 int ret = log_handle_flush_request(conf, bi);
5780 if (ret == 0)
5781 return true;
5782 if (ret == -ENODEV) {
5783 if (md_flush_request(mddev, bi))
5784 return true;
5786 /* ret == -EAGAIN, fallback */
5788 * if r5l_handle_flush_request() didn't clear REQ_PREFLUSH,
5789 * we need to flush journal device
5791 do_flush = bi->bi_opf & REQ_PREFLUSH;
5794 if (!md_write_start(mddev, bi))
5795 return false;
5797 * If array is degraded, better not do chunk aligned read because
5798 * later we might have to read it again in order to reconstruct
5799 * data on failed drives.
5801 if (rw == READ && mddev->degraded == 0 &&
5802 mddev->reshape_position == MaxSector) {
5803 bi = chunk_aligned_read(mddev, bi);
5804 if (!bi)
5805 return true;
5808 if (unlikely(bio_op(bi) == REQ_OP_DISCARD)) {
5809 make_discard_request(mddev, bi);
5810 md_write_end(mddev);
5811 return true;
5814 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
5815 last_sector = bio_end_sector(bi);
5816 bi->bi_next = NULL;
5818 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5819 for (; logical_sector < last_sector; logical_sector += RAID5_STRIPE_SECTORS(conf)) {
5820 int previous;
5821 int seq;
5823 do_prepare = false;
5824 retry:
5825 seq = read_seqcount_begin(&conf->gen_lock);
5826 previous = 0;
5827 if (do_prepare)
5828 prepare_to_wait(&conf->wait_for_overlap, &w,
5829 TASK_UNINTERRUPTIBLE);
5830 if (unlikely(conf->reshape_progress != MaxSector)) {
5831 /* spinlock is needed as reshape_progress may be
5832 * 64bit on a 32bit platform, and so it might be
5833 * possible to see a half-updated value
5834 * Of course reshape_progress could change after
5835 * the lock is dropped, so once we get a reference
5836 * to the stripe that we think it is, we will have
5837 * to check again.
5839 spin_lock_irq(&conf->device_lock);
5840 if (mddev->reshape_backwards
5841 ? logical_sector < conf->reshape_progress
5842 : logical_sector >= conf->reshape_progress) {
5843 previous = 1;
5844 } else {
5845 if (mddev->reshape_backwards
5846 ? logical_sector < conf->reshape_safe
5847 : logical_sector >= conf->reshape_safe) {
5848 spin_unlock_irq(&conf->device_lock);
5849 schedule();
5850 do_prepare = true;
5851 goto retry;
5854 spin_unlock_irq(&conf->device_lock);
5857 new_sector = raid5_compute_sector(conf, logical_sector,
5858 previous,
5859 &dd_idx, NULL);
5860 pr_debug("raid456: raid5_make_request, sector %llu logical %llu\n",
5861 (unsigned long long)new_sector,
5862 (unsigned long long)logical_sector);
5864 sh = raid5_get_active_stripe(conf, new_sector, previous,
5865 (bi->bi_opf & REQ_RAHEAD), 0);
5866 if (sh) {
5867 if (unlikely(previous)) {
5868 /* expansion might have moved on while waiting for a
5869 * stripe, so we must do the range check again.
5870 * Expansion could still move past after this
5871 * test, but as we are holding a reference to
5872 * 'sh', we know that if that happens,
5873 * STRIPE_EXPANDING will get set and the expansion
5874 * won't proceed until we finish with the stripe.
5876 int must_retry = 0;
5877 spin_lock_irq(&conf->device_lock);
5878 if (mddev->reshape_backwards
5879 ? logical_sector >= conf->reshape_progress
5880 : logical_sector < conf->reshape_progress)
5881 /* mismatch, need to try again */
5882 must_retry = 1;
5883 spin_unlock_irq(&conf->device_lock);
5884 if (must_retry) {
5885 raid5_release_stripe(sh);
5886 schedule();
5887 do_prepare = true;
5888 goto retry;
5891 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5892 /* Might have got the wrong stripe_head
5893 * by accident
5895 raid5_release_stripe(sh);
5896 goto retry;
5899 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5900 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5901 /* Stripe is busy expanding or
5902 * add failed due to overlap. Flush everything
5903 * and wait a while
5905 md_wakeup_thread(mddev->thread);
5906 raid5_release_stripe(sh);
5907 schedule();
5908 do_prepare = true;
5909 goto retry;
5911 if (do_flush) {
5912 set_bit(STRIPE_R5C_PREFLUSH, &sh->state);
5913 /* we only need flush for one stripe */
5914 do_flush = false;
5917 set_bit(STRIPE_HANDLE, &sh->state);
5918 clear_bit(STRIPE_DELAYED, &sh->state);
5919 if ((!sh->batch_head || sh == sh->batch_head) &&
5920 (bi->bi_opf & REQ_SYNC) &&
5921 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5922 atomic_inc(&conf->preread_active_stripes);
5923 release_stripe_plug(mddev, sh);
5924 } else {
5925 /* cannot get stripe for read-ahead, just give-up */
5926 bi->bi_status = BLK_STS_IOERR;
5927 break;
5930 finish_wait(&conf->wait_for_overlap, &w);
5932 if (rw == WRITE)
5933 md_write_end(mddev);
5934 bio_endio(bi);
5935 return true;
5938 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5940 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5942 /* reshaping is quite different to recovery/resync so it is
5943 * handled quite separately ... here.
5945 * On each call to sync_request, we gather one chunk worth of
5946 * destination stripes and flag them as expanding.
5947 * Then we find all the source stripes and request reads.
5948 * As the reads complete, handle_stripe will copy the data
5949 * into the destination stripe and release that stripe.
5951 struct r5conf *conf = mddev->private;
5952 struct stripe_head *sh;
5953 struct md_rdev *rdev;
5954 sector_t first_sector, last_sector;
5955 int raid_disks = conf->previous_raid_disks;
5956 int data_disks = raid_disks - conf->max_degraded;
5957 int new_data_disks = conf->raid_disks - conf->max_degraded;
5958 int i;
5959 int dd_idx;
5960 sector_t writepos, readpos, safepos;
5961 sector_t stripe_addr;
5962 int reshape_sectors;
5963 struct list_head stripes;
5964 sector_t retn;
5966 if (sector_nr == 0) {
5967 /* If restarting in the middle, skip the initial sectors */
5968 if (mddev->reshape_backwards &&
5969 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5970 sector_nr = raid5_size(mddev, 0, 0)
5971 - conf->reshape_progress;
5972 } else if (mddev->reshape_backwards &&
5973 conf->reshape_progress == MaxSector) {
5974 /* shouldn't happen, but just in case, finish up.*/
5975 sector_nr = MaxSector;
5976 } else if (!mddev->reshape_backwards &&
5977 conf->reshape_progress > 0)
5978 sector_nr = conf->reshape_progress;
5979 sector_div(sector_nr, new_data_disks);
5980 if (sector_nr) {
5981 mddev->curr_resync_completed = sector_nr;
5982 sysfs_notify_dirent_safe(mddev->sysfs_completed);
5983 *skipped = 1;
5984 retn = sector_nr;
5985 goto finish;
5989 /* We need to process a full chunk at a time.
5990 * If old and new chunk sizes differ, we need to process the
5991 * largest of these
5994 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5996 /* We update the metadata at least every 10 seconds, or when
5997 * the data about to be copied would over-write the source of
5998 * the data at the front of the range. i.e. one new_stripe
5999 * along from reshape_progress new_maps to after where
6000 * reshape_safe old_maps to
6002 writepos = conf->reshape_progress;
6003 sector_div(writepos, new_data_disks);
6004 readpos = conf->reshape_progress;
6005 sector_div(readpos, data_disks);
6006 safepos = conf->reshape_safe;
6007 sector_div(safepos, data_disks);
6008 if (mddev->reshape_backwards) {
6009 BUG_ON(writepos < reshape_sectors);
6010 writepos -= reshape_sectors;
6011 readpos += reshape_sectors;
6012 safepos += reshape_sectors;
6013 } else {
6014 writepos += reshape_sectors;
6015 /* readpos and safepos are worst-case calculations.
6016 * A negative number is overly pessimistic, and causes
6017 * obvious problems for unsigned storage. So clip to 0.
6019 readpos -= min_t(sector_t, reshape_sectors, readpos);
6020 safepos -= min_t(sector_t, reshape_sectors, safepos);
6023 /* Having calculated the 'writepos' possibly use it
6024 * to set 'stripe_addr' which is where we will write to.
6026 if (mddev->reshape_backwards) {
6027 BUG_ON(conf->reshape_progress == 0);
6028 stripe_addr = writepos;
6029 BUG_ON((mddev->dev_sectors &
6030 ~((sector_t)reshape_sectors - 1))
6031 - reshape_sectors - stripe_addr
6032 != sector_nr);
6033 } else {
6034 BUG_ON(writepos != sector_nr + reshape_sectors);
6035 stripe_addr = sector_nr;
6038 /* 'writepos' is the most advanced device address we might write.
6039 * 'readpos' is the least advanced device address we might read.
6040 * 'safepos' is the least address recorded in the metadata as having
6041 * been reshaped.
6042 * If there is a min_offset_diff, these are adjusted either by
6043 * increasing the safepos/readpos if diff is negative, or
6044 * increasing writepos if diff is positive.
6045 * If 'readpos' is then behind 'writepos', there is no way that we can
6046 * ensure safety in the face of a crash - that must be done by userspace
6047 * making a backup of the data. So in that case there is no particular
6048 * rush to update metadata.
6049 * Otherwise if 'safepos' is behind 'writepos', then we really need to
6050 * update the metadata to advance 'safepos' to match 'readpos' so that
6051 * we can be safe in the event of a crash.
6052 * So we insist on updating metadata if safepos is behind writepos and
6053 * readpos is beyond writepos.
6054 * In any case, update the metadata every 10 seconds.
6055 * Maybe that number should be configurable, but I'm not sure it is
6056 * worth it.... maybe it could be a multiple of safemode_delay???
6058 if (conf->min_offset_diff < 0) {
6059 safepos += -conf->min_offset_diff;
6060 readpos += -conf->min_offset_diff;
6061 } else
6062 writepos += conf->min_offset_diff;
6064 if ((mddev->reshape_backwards
6065 ? (safepos > writepos && readpos < writepos)
6066 : (safepos < writepos && readpos > writepos)) ||
6067 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
6068 /* Cannot proceed until we've updated the superblock... */
6069 wait_event(conf->wait_for_overlap,
6070 atomic_read(&conf->reshape_stripes)==0
6071 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6072 if (atomic_read(&conf->reshape_stripes) != 0)
6073 return 0;
6074 mddev->reshape_position = conf->reshape_progress;
6075 mddev->curr_resync_completed = sector_nr;
6076 if (!mddev->reshape_backwards)
6077 /* Can update recovery_offset */
6078 rdev_for_each(rdev, mddev)
6079 if (rdev->raid_disk >= 0 &&
6080 !test_bit(Journal, &rdev->flags) &&
6081 !test_bit(In_sync, &rdev->flags) &&
6082 rdev->recovery_offset < sector_nr)
6083 rdev->recovery_offset = sector_nr;
6085 conf->reshape_checkpoint = jiffies;
6086 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6087 md_wakeup_thread(mddev->thread);
6088 wait_event(mddev->sb_wait, mddev->sb_flags == 0 ||
6089 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6090 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6091 return 0;
6092 spin_lock_irq(&conf->device_lock);
6093 conf->reshape_safe = mddev->reshape_position;
6094 spin_unlock_irq(&conf->device_lock);
6095 wake_up(&conf->wait_for_overlap);
6096 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6099 INIT_LIST_HEAD(&stripes);
6100 for (i = 0; i < reshape_sectors; i += RAID5_STRIPE_SECTORS(conf)) {
6101 int j;
6102 int skipped_disk = 0;
6103 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
6104 set_bit(STRIPE_EXPANDING, &sh->state);
6105 atomic_inc(&conf->reshape_stripes);
6106 /* If any of this stripe is beyond the end of the old
6107 * array, then we need to zero those blocks
6109 for (j=sh->disks; j--;) {
6110 sector_t s;
6111 if (j == sh->pd_idx)
6112 continue;
6113 if (conf->level == 6 &&
6114 j == sh->qd_idx)
6115 continue;
6116 s = raid5_compute_blocknr(sh, j, 0);
6117 if (s < raid5_size(mddev, 0, 0)) {
6118 skipped_disk = 1;
6119 continue;
6121 memset(page_address(sh->dev[j].page), 0, RAID5_STRIPE_SIZE(conf));
6122 set_bit(R5_Expanded, &sh->dev[j].flags);
6123 set_bit(R5_UPTODATE, &sh->dev[j].flags);
6125 if (!skipped_disk) {
6126 set_bit(STRIPE_EXPAND_READY, &sh->state);
6127 set_bit(STRIPE_HANDLE, &sh->state);
6129 list_add(&sh->lru, &stripes);
6131 spin_lock_irq(&conf->device_lock);
6132 if (mddev->reshape_backwards)
6133 conf->reshape_progress -= reshape_sectors * new_data_disks;
6134 else
6135 conf->reshape_progress += reshape_sectors * new_data_disks;
6136 spin_unlock_irq(&conf->device_lock);
6137 /* Ok, those stripe are ready. We can start scheduling
6138 * reads on the source stripes.
6139 * The source stripes are determined by mapping the first and last
6140 * block on the destination stripes.
6142 first_sector =
6143 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
6144 1, &dd_idx, NULL);
6145 last_sector =
6146 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
6147 * new_data_disks - 1),
6148 1, &dd_idx, NULL);
6149 if (last_sector >= mddev->dev_sectors)
6150 last_sector = mddev->dev_sectors - 1;
6151 while (first_sector <= last_sector) {
6152 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
6153 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
6154 set_bit(STRIPE_HANDLE, &sh->state);
6155 raid5_release_stripe(sh);
6156 first_sector += RAID5_STRIPE_SECTORS(conf);
6158 /* Now that the sources are clearly marked, we can release
6159 * the destination stripes
6161 while (!list_empty(&stripes)) {
6162 sh = list_entry(stripes.next, struct stripe_head, lru);
6163 list_del_init(&sh->lru);
6164 raid5_release_stripe(sh);
6166 /* If this takes us to the resync_max point where we have to pause,
6167 * then we need to write out the superblock.
6169 sector_nr += reshape_sectors;
6170 retn = reshape_sectors;
6171 finish:
6172 if (mddev->curr_resync_completed > mddev->resync_max ||
6173 (sector_nr - mddev->curr_resync_completed) * 2
6174 >= mddev->resync_max - mddev->curr_resync_completed) {
6175 /* Cannot proceed until we've updated the superblock... */
6176 wait_event(conf->wait_for_overlap,
6177 atomic_read(&conf->reshape_stripes) == 0
6178 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6179 if (atomic_read(&conf->reshape_stripes) != 0)
6180 goto ret;
6181 mddev->reshape_position = conf->reshape_progress;
6182 mddev->curr_resync_completed = sector_nr;
6183 if (!mddev->reshape_backwards)
6184 /* Can update recovery_offset */
6185 rdev_for_each(rdev, mddev)
6186 if (rdev->raid_disk >= 0 &&
6187 !test_bit(Journal, &rdev->flags) &&
6188 !test_bit(In_sync, &rdev->flags) &&
6189 rdev->recovery_offset < sector_nr)
6190 rdev->recovery_offset = sector_nr;
6191 conf->reshape_checkpoint = jiffies;
6192 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6193 md_wakeup_thread(mddev->thread);
6194 wait_event(mddev->sb_wait,
6195 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)
6196 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
6197 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6198 goto ret;
6199 spin_lock_irq(&conf->device_lock);
6200 conf->reshape_safe = mddev->reshape_position;
6201 spin_unlock_irq(&conf->device_lock);
6202 wake_up(&conf->wait_for_overlap);
6203 sysfs_notify_dirent_safe(mddev->sysfs_completed);
6205 ret:
6206 return retn;
6209 static inline sector_t raid5_sync_request(struct mddev *mddev, sector_t sector_nr,
6210 int *skipped)
6212 struct r5conf *conf = mddev->private;
6213 struct stripe_head *sh;
6214 sector_t max_sector = mddev->dev_sectors;
6215 sector_t sync_blocks;
6216 int still_degraded = 0;
6217 int i;
6219 if (sector_nr >= max_sector) {
6220 /* just being told to finish up .. nothing much to do */
6222 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
6223 end_reshape(conf);
6224 return 0;
6227 if (mddev->curr_resync < max_sector) /* aborted */
6228 md_bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
6229 &sync_blocks, 1);
6230 else /* completed sync */
6231 conf->fullsync = 0;
6232 md_bitmap_close_sync(mddev->bitmap);
6234 return 0;
6237 /* Allow raid5_quiesce to complete */
6238 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
6240 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6241 return reshape_request(mddev, sector_nr, skipped);
6243 /* No need to check resync_max as we never do more than one
6244 * stripe, and as resync_max will always be on a chunk boundary,
6245 * if the check in md_do_sync didn't fire, there is no chance
6246 * of overstepping resync_max here
6249 /* if there is too many failed drives and we are trying
6250 * to resync, then assert that we are finished, because there is
6251 * nothing we can do.
6253 if (mddev->degraded >= conf->max_degraded &&
6254 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6255 sector_t rv = mddev->dev_sectors - sector_nr;
6256 *skipped = 1;
6257 return rv;
6259 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
6260 !conf->fullsync &&
6261 !md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
6262 sync_blocks >= RAID5_STRIPE_SECTORS(conf)) {
6263 /* we can skip this block, and probably more */
6264 do_div(sync_blocks, RAID5_STRIPE_SECTORS(conf));
6265 *skipped = 1;
6266 /* keep things rounded to whole stripes */
6267 return sync_blocks * RAID5_STRIPE_SECTORS(conf);
6270 md_bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
6272 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
6273 if (sh == NULL) {
6274 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
6275 /* make sure we don't swamp the stripe cache if someone else
6276 * is trying to get access
6278 schedule_timeout_uninterruptible(1);
6280 /* Need to check if array will still be degraded after recovery/resync
6281 * Note in case of > 1 drive failures it's possible we're rebuilding
6282 * one drive while leaving another faulty drive in array.
6284 rcu_read_lock();
6285 for (i = 0; i < conf->raid_disks; i++) {
6286 struct md_rdev *rdev = READ_ONCE(conf->disks[i].rdev);
6288 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
6289 still_degraded = 1;
6291 rcu_read_unlock();
6293 md_bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
6295 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
6296 set_bit(STRIPE_HANDLE, &sh->state);
6298 raid5_release_stripe(sh);
6300 return RAID5_STRIPE_SECTORS(conf);
6303 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio,
6304 unsigned int offset)
6306 /* We may not be able to submit a whole bio at once as there
6307 * may not be enough stripe_heads available.
6308 * We cannot pre-allocate enough stripe_heads as we may need
6309 * more than exist in the cache (if we allow ever large chunks).
6310 * So we do one stripe head at a time and record in
6311 * ->bi_hw_segments how many have been done.
6313 * We *know* that this entire raid_bio is in one chunk, so
6314 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
6316 struct stripe_head *sh;
6317 int dd_idx;
6318 sector_t sector, logical_sector, last_sector;
6319 int scnt = 0;
6320 int handled = 0;
6322 logical_sector = raid_bio->bi_iter.bi_sector &
6323 ~((sector_t)RAID5_STRIPE_SECTORS(conf)-1);
6324 sector = raid5_compute_sector(conf, logical_sector,
6325 0, &dd_idx, NULL);
6326 last_sector = bio_end_sector(raid_bio);
6328 for (; logical_sector < last_sector;
6329 logical_sector += RAID5_STRIPE_SECTORS(conf),
6330 sector += RAID5_STRIPE_SECTORS(conf),
6331 scnt++) {
6333 if (scnt < offset)
6334 /* already done this stripe */
6335 continue;
6337 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
6339 if (!sh) {
6340 /* failed to get a stripe - must wait */
6341 conf->retry_read_aligned = raid_bio;
6342 conf->retry_read_offset = scnt;
6343 return handled;
6346 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
6347 raid5_release_stripe(sh);
6348 conf->retry_read_aligned = raid_bio;
6349 conf->retry_read_offset = scnt;
6350 return handled;
6353 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
6354 handle_stripe(sh);
6355 raid5_release_stripe(sh);
6356 handled++;
6359 bio_endio(raid_bio);
6361 if (atomic_dec_and_test(&conf->active_aligned_reads))
6362 wake_up(&conf->wait_for_quiescent);
6363 return handled;
6366 static int handle_active_stripes(struct r5conf *conf, int group,
6367 struct r5worker *worker,
6368 struct list_head *temp_inactive_list)
6369 __releases(&conf->device_lock)
6370 __acquires(&conf->device_lock)
6372 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
6373 int i, batch_size = 0, hash;
6374 bool release_inactive = false;
6376 while (batch_size < MAX_STRIPE_BATCH &&
6377 (sh = __get_priority_stripe(conf, group)) != NULL)
6378 batch[batch_size++] = sh;
6380 if (batch_size == 0) {
6381 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6382 if (!list_empty(temp_inactive_list + i))
6383 break;
6384 if (i == NR_STRIPE_HASH_LOCKS) {
6385 spin_unlock_irq(&conf->device_lock);
6386 log_flush_stripe_to_raid(conf);
6387 spin_lock_irq(&conf->device_lock);
6388 return batch_size;
6390 release_inactive = true;
6392 spin_unlock_irq(&conf->device_lock);
6394 release_inactive_stripe_list(conf, temp_inactive_list,
6395 NR_STRIPE_HASH_LOCKS);
6397 r5l_flush_stripe_to_raid(conf->log);
6398 if (release_inactive) {
6399 spin_lock_irq(&conf->device_lock);
6400 return 0;
6403 for (i = 0; i < batch_size; i++)
6404 handle_stripe(batch[i]);
6405 log_write_stripe_run(conf);
6407 cond_resched();
6409 spin_lock_irq(&conf->device_lock);
6410 for (i = 0; i < batch_size; i++) {
6411 hash = batch[i]->hash_lock_index;
6412 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
6414 return batch_size;
6417 static void raid5_do_work(struct work_struct *work)
6419 struct r5worker *worker = container_of(work, struct r5worker, work);
6420 struct r5worker_group *group = worker->group;
6421 struct r5conf *conf = group->conf;
6422 struct mddev *mddev = conf->mddev;
6423 int group_id = group - conf->worker_groups;
6424 int handled;
6425 struct blk_plug plug;
6427 pr_debug("+++ raid5worker active\n");
6429 blk_start_plug(&plug);
6430 handled = 0;
6431 spin_lock_irq(&conf->device_lock);
6432 while (1) {
6433 int batch_size, released;
6435 released = release_stripe_list(conf, worker->temp_inactive_list);
6437 batch_size = handle_active_stripes(conf, group_id, worker,
6438 worker->temp_inactive_list);
6439 worker->working = false;
6440 if (!batch_size && !released)
6441 break;
6442 handled += batch_size;
6443 wait_event_lock_irq(mddev->sb_wait,
6444 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags),
6445 conf->device_lock);
6447 pr_debug("%d stripes handled\n", handled);
6449 spin_unlock_irq(&conf->device_lock);
6451 flush_deferred_bios(conf);
6453 r5l_flush_stripe_to_raid(conf->log);
6455 async_tx_issue_pending_all();
6456 blk_finish_plug(&plug);
6458 pr_debug("--- raid5worker inactive\n");
6462 * This is our raid5 kernel thread.
6464 * We scan the hash table for stripes which can be handled now.
6465 * During the scan, completed stripes are saved for us by the interrupt
6466 * handler, so that they will not have to wait for our next wakeup.
6468 static void raid5d(struct md_thread *thread)
6470 struct mddev *mddev = thread->mddev;
6471 struct r5conf *conf = mddev->private;
6472 int handled;
6473 struct blk_plug plug;
6475 pr_debug("+++ raid5d active\n");
6477 md_check_recovery(mddev);
6479 blk_start_plug(&plug);
6480 handled = 0;
6481 spin_lock_irq(&conf->device_lock);
6482 while (1) {
6483 struct bio *bio;
6484 int batch_size, released;
6485 unsigned int offset;
6487 released = release_stripe_list(conf, conf->temp_inactive_list);
6488 if (released)
6489 clear_bit(R5_DID_ALLOC, &conf->cache_state);
6491 if (
6492 !list_empty(&conf->bitmap_list)) {
6493 /* Now is a good time to flush some bitmap updates */
6494 conf->seq_flush++;
6495 spin_unlock_irq(&conf->device_lock);
6496 md_bitmap_unplug(mddev->bitmap);
6497 spin_lock_irq(&conf->device_lock);
6498 conf->seq_write = conf->seq_flush;
6499 activate_bit_delay(conf, conf->temp_inactive_list);
6501 raid5_activate_delayed(conf);
6503 while ((bio = remove_bio_from_retry(conf, &offset))) {
6504 int ok;
6505 spin_unlock_irq(&conf->device_lock);
6506 ok = retry_aligned_read(conf, bio, offset);
6507 spin_lock_irq(&conf->device_lock);
6508 if (!ok)
6509 break;
6510 handled++;
6513 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
6514 conf->temp_inactive_list);
6515 if (!batch_size && !released)
6516 break;
6517 handled += batch_size;
6519 if (mddev->sb_flags & ~(1 << MD_SB_CHANGE_PENDING)) {
6520 spin_unlock_irq(&conf->device_lock);
6521 md_check_recovery(mddev);
6522 spin_lock_irq(&conf->device_lock);
6525 pr_debug("%d stripes handled\n", handled);
6527 spin_unlock_irq(&conf->device_lock);
6528 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
6529 mutex_trylock(&conf->cache_size_mutex)) {
6530 grow_one_stripe(conf, __GFP_NOWARN);
6531 /* Set flag even if allocation failed. This helps
6532 * slow down allocation requests when mem is short
6534 set_bit(R5_DID_ALLOC, &conf->cache_state);
6535 mutex_unlock(&conf->cache_size_mutex);
6538 flush_deferred_bios(conf);
6540 r5l_flush_stripe_to_raid(conf->log);
6542 async_tx_issue_pending_all();
6543 blk_finish_plug(&plug);
6545 pr_debug("--- raid5d inactive\n");
6548 static ssize_t
6549 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
6551 struct r5conf *conf;
6552 int ret = 0;
6553 spin_lock(&mddev->lock);
6554 conf = mddev->private;
6555 if (conf)
6556 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
6557 spin_unlock(&mddev->lock);
6558 return ret;
6562 raid5_set_cache_size(struct mddev *mddev, int size)
6564 int result = 0;
6565 struct r5conf *conf = mddev->private;
6567 if (size <= 16 || size > 32768)
6568 return -EINVAL;
6570 conf->min_nr_stripes = size;
6571 mutex_lock(&conf->cache_size_mutex);
6572 while (size < conf->max_nr_stripes &&
6573 drop_one_stripe(conf))
6575 mutex_unlock(&conf->cache_size_mutex);
6577 md_allow_write(mddev);
6579 mutex_lock(&conf->cache_size_mutex);
6580 while (size > conf->max_nr_stripes)
6581 if (!grow_one_stripe(conf, GFP_KERNEL)) {
6582 conf->min_nr_stripes = conf->max_nr_stripes;
6583 result = -ENOMEM;
6584 break;
6586 mutex_unlock(&conf->cache_size_mutex);
6588 return result;
6590 EXPORT_SYMBOL(raid5_set_cache_size);
6592 static ssize_t
6593 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6595 struct r5conf *conf;
6596 unsigned long new;
6597 int err;
6599 if (len >= PAGE_SIZE)
6600 return -EINVAL;
6601 if (kstrtoul(page, 10, &new))
6602 return -EINVAL;
6603 err = mddev_lock(mddev);
6604 if (err)
6605 return err;
6606 conf = mddev->private;
6607 if (!conf)
6608 err = -ENODEV;
6609 else
6610 err = raid5_set_cache_size(mddev, new);
6611 mddev_unlock(mddev);
6613 return err ?: len;
6616 static struct md_sysfs_entry
6617 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6618 raid5_show_stripe_cache_size,
6619 raid5_store_stripe_cache_size);
6621 static ssize_t
6622 raid5_show_rmw_level(struct mddev *mddev, char *page)
6624 struct r5conf *conf = mddev->private;
6625 if (conf)
6626 return sprintf(page, "%d\n", conf->rmw_level);
6627 else
6628 return 0;
6631 static ssize_t
6632 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6634 struct r5conf *conf = mddev->private;
6635 unsigned long new;
6637 if (!conf)
6638 return -ENODEV;
6640 if (len >= PAGE_SIZE)
6641 return -EINVAL;
6643 if (kstrtoul(page, 10, &new))
6644 return -EINVAL;
6646 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6647 return -EINVAL;
6649 if (new != PARITY_DISABLE_RMW &&
6650 new != PARITY_ENABLE_RMW &&
6651 new != PARITY_PREFER_RMW)
6652 return -EINVAL;
6654 conf->rmw_level = new;
6655 return len;
6658 static struct md_sysfs_entry
6659 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6660 raid5_show_rmw_level,
6661 raid5_store_rmw_level);
6663 static ssize_t
6664 raid5_show_stripe_size(struct mddev *mddev, char *page)
6666 struct r5conf *conf;
6667 int ret = 0;
6669 spin_lock(&mddev->lock);
6670 conf = mddev->private;
6671 if (conf)
6672 ret = sprintf(page, "%lu\n", RAID5_STRIPE_SIZE(conf));
6673 spin_unlock(&mddev->lock);
6674 return ret;
6677 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
6678 static ssize_t
6679 raid5_store_stripe_size(struct mddev *mddev, const char *page, size_t len)
6681 struct r5conf *conf;
6682 unsigned long new;
6683 int err;
6684 int size;
6686 if (len >= PAGE_SIZE)
6687 return -EINVAL;
6688 if (kstrtoul(page, 10, &new))
6689 return -EINVAL;
6692 * The value should not be bigger than PAGE_SIZE. It requires to
6693 * be multiple of DEFAULT_STRIPE_SIZE and the value should be power
6694 * of two.
6696 if (new % DEFAULT_STRIPE_SIZE != 0 ||
6697 new > PAGE_SIZE || new == 0 ||
6698 new != roundup_pow_of_two(new))
6699 return -EINVAL;
6701 err = mddev_lock(mddev);
6702 if (err)
6703 return err;
6705 conf = mddev->private;
6706 if (!conf) {
6707 err = -ENODEV;
6708 goto out_unlock;
6711 if (new == conf->stripe_size)
6712 goto out_unlock;
6714 pr_debug("md/raid: change stripe_size from %lu to %lu\n",
6715 conf->stripe_size, new);
6717 if (mddev->sync_thread ||
6718 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6719 mddev->reshape_position != MaxSector ||
6720 mddev->sysfs_active) {
6721 err = -EBUSY;
6722 goto out_unlock;
6725 mddev_suspend(mddev);
6726 mutex_lock(&conf->cache_size_mutex);
6727 size = conf->max_nr_stripes;
6729 shrink_stripes(conf);
6731 conf->stripe_size = new;
6732 conf->stripe_shift = ilog2(new) - 9;
6733 conf->stripe_sectors = new >> 9;
6734 if (grow_stripes(conf, size)) {
6735 pr_warn("md/raid:%s: couldn't allocate buffers\n",
6736 mdname(mddev));
6737 err = -ENOMEM;
6739 mutex_unlock(&conf->cache_size_mutex);
6740 mddev_resume(mddev);
6742 out_unlock:
6743 mddev_unlock(mddev);
6744 return err ?: len;
6747 static struct md_sysfs_entry
6748 raid5_stripe_size = __ATTR(stripe_size, 0644,
6749 raid5_show_stripe_size,
6750 raid5_store_stripe_size);
6751 #else
6752 static struct md_sysfs_entry
6753 raid5_stripe_size = __ATTR(stripe_size, 0444,
6754 raid5_show_stripe_size,
6755 NULL);
6756 #endif
6758 static ssize_t
6759 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6761 struct r5conf *conf;
6762 int ret = 0;
6763 spin_lock(&mddev->lock);
6764 conf = mddev->private;
6765 if (conf)
6766 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6767 spin_unlock(&mddev->lock);
6768 return ret;
6771 static ssize_t
6772 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6774 struct r5conf *conf;
6775 unsigned long new;
6776 int err;
6778 if (len >= PAGE_SIZE)
6779 return -EINVAL;
6780 if (kstrtoul(page, 10, &new))
6781 return -EINVAL;
6783 err = mddev_lock(mddev);
6784 if (err)
6785 return err;
6786 conf = mddev->private;
6787 if (!conf)
6788 err = -ENODEV;
6789 else if (new > conf->min_nr_stripes)
6790 err = -EINVAL;
6791 else
6792 conf->bypass_threshold = new;
6793 mddev_unlock(mddev);
6794 return err ?: len;
6797 static struct md_sysfs_entry
6798 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6799 S_IRUGO | S_IWUSR,
6800 raid5_show_preread_threshold,
6801 raid5_store_preread_threshold);
6803 static ssize_t
6804 raid5_show_skip_copy(struct mddev *mddev, char *page)
6806 struct r5conf *conf;
6807 int ret = 0;
6808 spin_lock(&mddev->lock);
6809 conf = mddev->private;
6810 if (conf)
6811 ret = sprintf(page, "%d\n", conf->skip_copy);
6812 spin_unlock(&mddev->lock);
6813 return ret;
6816 static ssize_t
6817 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6819 struct r5conf *conf;
6820 unsigned long new;
6821 int err;
6823 if (len >= PAGE_SIZE)
6824 return -EINVAL;
6825 if (kstrtoul(page, 10, &new))
6826 return -EINVAL;
6827 new = !!new;
6829 err = mddev_lock(mddev);
6830 if (err)
6831 return err;
6832 conf = mddev->private;
6833 if (!conf)
6834 err = -ENODEV;
6835 else if (new != conf->skip_copy) {
6836 struct request_queue *q = mddev->queue;
6838 mddev_suspend(mddev);
6839 conf->skip_copy = new;
6840 if (new)
6841 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, q);
6842 else
6843 blk_queue_flag_clear(QUEUE_FLAG_STABLE_WRITES, q);
6844 mddev_resume(mddev);
6846 mddev_unlock(mddev);
6847 return err ?: len;
6850 static struct md_sysfs_entry
6851 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6852 raid5_show_skip_copy,
6853 raid5_store_skip_copy);
6855 static ssize_t
6856 stripe_cache_active_show(struct mddev *mddev, char *page)
6858 struct r5conf *conf = mddev->private;
6859 if (conf)
6860 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6861 else
6862 return 0;
6865 static struct md_sysfs_entry
6866 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6868 static ssize_t
6869 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6871 struct r5conf *conf;
6872 int ret = 0;
6873 spin_lock(&mddev->lock);
6874 conf = mddev->private;
6875 if (conf)
6876 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6877 spin_unlock(&mddev->lock);
6878 return ret;
6881 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6882 int *group_cnt,
6883 struct r5worker_group **worker_groups);
6884 static ssize_t
6885 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6887 struct r5conf *conf;
6888 unsigned int new;
6889 int err;
6890 struct r5worker_group *new_groups, *old_groups;
6891 int group_cnt;
6893 if (len >= PAGE_SIZE)
6894 return -EINVAL;
6895 if (kstrtouint(page, 10, &new))
6896 return -EINVAL;
6897 /* 8192 should be big enough */
6898 if (new > 8192)
6899 return -EINVAL;
6901 err = mddev_lock(mddev);
6902 if (err)
6903 return err;
6904 conf = mddev->private;
6905 if (!conf)
6906 err = -ENODEV;
6907 else if (new != conf->worker_cnt_per_group) {
6908 mddev_suspend(mddev);
6910 old_groups = conf->worker_groups;
6911 if (old_groups)
6912 flush_workqueue(raid5_wq);
6914 err = alloc_thread_groups(conf, new, &group_cnt, &new_groups);
6915 if (!err) {
6916 spin_lock_irq(&conf->device_lock);
6917 conf->group_cnt = group_cnt;
6918 conf->worker_cnt_per_group = new;
6919 conf->worker_groups = new_groups;
6920 spin_unlock_irq(&conf->device_lock);
6922 if (old_groups)
6923 kfree(old_groups[0].workers);
6924 kfree(old_groups);
6926 mddev_resume(mddev);
6928 mddev_unlock(mddev);
6930 return err ?: len;
6933 static struct md_sysfs_entry
6934 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6935 raid5_show_group_thread_cnt,
6936 raid5_store_group_thread_cnt);
6938 static struct attribute *raid5_attrs[] = {
6939 &raid5_stripecache_size.attr,
6940 &raid5_stripecache_active.attr,
6941 &raid5_preread_bypass_threshold.attr,
6942 &raid5_group_thread_cnt.attr,
6943 &raid5_skip_copy.attr,
6944 &raid5_rmw_level.attr,
6945 &raid5_stripe_size.attr,
6946 &r5c_journal_mode.attr,
6947 &ppl_write_hint.attr,
6948 NULL,
6950 static struct attribute_group raid5_attrs_group = {
6951 .name = NULL,
6952 .attrs = raid5_attrs,
6955 static int alloc_thread_groups(struct r5conf *conf, int cnt, int *group_cnt,
6956 struct r5worker_group **worker_groups)
6958 int i, j, k;
6959 ssize_t size;
6960 struct r5worker *workers;
6962 if (cnt == 0) {
6963 *group_cnt = 0;
6964 *worker_groups = NULL;
6965 return 0;
6967 *group_cnt = num_possible_nodes();
6968 size = sizeof(struct r5worker) * cnt;
6969 workers = kcalloc(size, *group_cnt, GFP_NOIO);
6970 *worker_groups = kcalloc(*group_cnt, sizeof(struct r5worker_group),
6971 GFP_NOIO);
6972 if (!*worker_groups || !workers) {
6973 kfree(workers);
6974 kfree(*worker_groups);
6975 return -ENOMEM;
6978 for (i = 0; i < *group_cnt; i++) {
6979 struct r5worker_group *group;
6981 group = &(*worker_groups)[i];
6982 INIT_LIST_HEAD(&group->handle_list);
6983 INIT_LIST_HEAD(&group->loprio_list);
6984 group->conf = conf;
6985 group->workers = workers + i * cnt;
6987 for (j = 0; j < cnt; j++) {
6988 struct r5worker *worker = group->workers + j;
6989 worker->group = group;
6990 INIT_WORK(&worker->work, raid5_do_work);
6992 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6993 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6997 return 0;
7000 static void free_thread_groups(struct r5conf *conf)
7002 if (conf->worker_groups)
7003 kfree(conf->worker_groups[0].workers);
7004 kfree(conf->worker_groups);
7005 conf->worker_groups = NULL;
7008 static sector_t
7009 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
7011 struct r5conf *conf = mddev->private;
7013 if (!sectors)
7014 sectors = mddev->dev_sectors;
7015 if (!raid_disks)
7016 /* size is defined by the smallest of previous and new size */
7017 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
7019 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7020 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
7021 return sectors * (raid_disks - conf->max_degraded);
7024 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7026 safe_put_page(percpu->spare_page);
7027 percpu->spare_page = NULL;
7028 kvfree(percpu->scribble);
7029 percpu->scribble = NULL;
7032 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
7034 if (conf->level == 6 && !percpu->spare_page) {
7035 percpu->spare_page = alloc_page(GFP_KERNEL);
7036 if (!percpu->spare_page)
7037 return -ENOMEM;
7040 if (scribble_alloc(percpu,
7041 max(conf->raid_disks,
7042 conf->previous_raid_disks),
7043 max(conf->chunk_sectors,
7044 conf->prev_chunk_sectors)
7045 / RAID5_STRIPE_SECTORS(conf))) {
7046 free_scratch_buffer(conf, percpu);
7047 return -ENOMEM;
7050 return 0;
7053 static int raid456_cpu_dead(unsigned int cpu, struct hlist_node *node)
7055 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7057 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
7058 return 0;
7061 static void raid5_free_percpu(struct r5conf *conf)
7063 if (!conf->percpu)
7064 return;
7066 cpuhp_state_remove_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7067 free_percpu(conf->percpu);
7070 static void free_conf(struct r5conf *conf)
7072 int i;
7074 log_exit(conf);
7076 unregister_shrinker(&conf->shrinker);
7077 free_thread_groups(conf);
7078 shrink_stripes(conf);
7079 raid5_free_percpu(conf);
7080 for (i = 0; i < conf->pool_size; i++)
7081 if (conf->disks[i].extra_page)
7082 put_page(conf->disks[i].extra_page);
7083 kfree(conf->disks);
7084 bioset_exit(&conf->bio_split);
7085 kfree(conf->stripe_hashtbl);
7086 kfree(conf->pending_data);
7087 kfree(conf);
7090 static int raid456_cpu_up_prepare(unsigned int cpu, struct hlist_node *node)
7092 struct r5conf *conf = hlist_entry_safe(node, struct r5conf, node);
7093 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
7095 if (alloc_scratch_buffer(conf, percpu)) {
7096 pr_warn("%s: failed memory allocation for cpu%u\n",
7097 __func__, cpu);
7098 return -ENOMEM;
7100 return 0;
7103 static int raid5_alloc_percpu(struct r5conf *conf)
7105 int err = 0;
7107 conf->percpu = alloc_percpu(struct raid5_percpu);
7108 if (!conf->percpu)
7109 return -ENOMEM;
7111 err = cpuhp_state_add_instance(CPUHP_MD_RAID5_PREPARE, &conf->node);
7112 if (!err) {
7113 conf->scribble_disks = max(conf->raid_disks,
7114 conf->previous_raid_disks);
7115 conf->scribble_sectors = max(conf->chunk_sectors,
7116 conf->prev_chunk_sectors);
7118 return err;
7121 static unsigned long raid5_cache_scan(struct shrinker *shrink,
7122 struct shrink_control *sc)
7124 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7125 unsigned long ret = SHRINK_STOP;
7127 if (mutex_trylock(&conf->cache_size_mutex)) {
7128 ret= 0;
7129 while (ret < sc->nr_to_scan &&
7130 conf->max_nr_stripes > conf->min_nr_stripes) {
7131 if (drop_one_stripe(conf) == 0) {
7132 ret = SHRINK_STOP;
7133 break;
7135 ret++;
7137 mutex_unlock(&conf->cache_size_mutex);
7139 return ret;
7142 static unsigned long raid5_cache_count(struct shrinker *shrink,
7143 struct shrink_control *sc)
7145 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
7147 if (conf->max_nr_stripes < conf->min_nr_stripes)
7148 /* unlikely, but not impossible */
7149 return 0;
7150 return conf->max_nr_stripes - conf->min_nr_stripes;
7153 static struct r5conf *setup_conf(struct mddev *mddev)
7155 struct r5conf *conf;
7156 int raid_disk, memory, max_disks;
7157 struct md_rdev *rdev;
7158 struct disk_info *disk;
7159 char pers_name[6];
7160 int i;
7161 int group_cnt;
7162 struct r5worker_group *new_group;
7163 int ret;
7165 if (mddev->new_level != 5
7166 && mddev->new_level != 4
7167 && mddev->new_level != 6) {
7168 pr_warn("md/raid:%s: raid level not set to 4/5/6 (%d)\n",
7169 mdname(mddev), mddev->new_level);
7170 return ERR_PTR(-EIO);
7172 if ((mddev->new_level == 5
7173 && !algorithm_valid_raid5(mddev->new_layout)) ||
7174 (mddev->new_level == 6
7175 && !algorithm_valid_raid6(mddev->new_layout))) {
7176 pr_warn("md/raid:%s: layout %d not supported\n",
7177 mdname(mddev), mddev->new_layout);
7178 return ERR_PTR(-EIO);
7180 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
7181 pr_warn("md/raid:%s: not enough configured devices (%d, minimum 4)\n",
7182 mdname(mddev), mddev->raid_disks);
7183 return ERR_PTR(-EINVAL);
7186 if (!mddev->new_chunk_sectors ||
7187 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
7188 !is_power_of_2(mddev->new_chunk_sectors)) {
7189 pr_warn("md/raid:%s: invalid chunk size %d\n",
7190 mdname(mddev), mddev->new_chunk_sectors << 9);
7191 return ERR_PTR(-EINVAL);
7194 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
7195 if (conf == NULL)
7196 goto abort;
7198 #if PAGE_SIZE != DEFAULT_STRIPE_SIZE
7199 conf->stripe_size = DEFAULT_STRIPE_SIZE;
7200 conf->stripe_shift = ilog2(DEFAULT_STRIPE_SIZE) - 9;
7201 conf->stripe_sectors = DEFAULT_STRIPE_SIZE >> 9;
7202 #endif
7203 INIT_LIST_HEAD(&conf->free_list);
7204 INIT_LIST_HEAD(&conf->pending_list);
7205 conf->pending_data = kcalloc(PENDING_IO_MAX,
7206 sizeof(struct r5pending_data),
7207 GFP_KERNEL);
7208 if (!conf->pending_data)
7209 goto abort;
7210 for (i = 0; i < PENDING_IO_MAX; i++)
7211 list_add(&conf->pending_data[i].sibling, &conf->free_list);
7212 /* Don't enable multi-threading by default*/
7213 if (!alloc_thread_groups(conf, 0, &group_cnt, &new_group)) {
7214 conf->group_cnt = group_cnt;
7215 conf->worker_cnt_per_group = 0;
7216 conf->worker_groups = new_group;
7217 } else
7218 goto abort;
7219 spin_lock_init(&conf->device_lock);
7220 seqcount_spinlock_init(&conf->gen_lock, &conf->device_lock);
7221 mutex_init(&conf->cache_size_mutex);
7222 init_waitqueue_head(&conf->wait_for_quiescent);
7223 init_waitqueue_head(&conf->wait_for_stripe);
7224 init_waitqueue_head(&conf->wait_for_overlap);
7225 INIT_LIST_HEAD(&conf->handle_list);
7226 INIT_LIST_HEAD(&conf->loprio_list);
7227 INIT_LIST_HEAD(&conf->hold_list);
7228 INIT_LIST_HEAD(&conf->delayed_list);
7229 INIT_LIST_HEAD(&conf->bitmap_list);
7230 init_llist_head(&conf->released_stripes);
7231 atomic_set(&conf->active_stripes, 0);
7232 atomic_set(&conf->preread_active_stripes, 0);
7233 atomic_set(&conf->active_aligned_reads, 0);
7234 spin_lock_init(&conf->pending_bios_lock);
7235 conf->batch_bio_dispatch = true;
7236 rdev_for_each(rdev, mddev) {
7237 if (test_bit(Journal, &rdev->flags))
7238 continue;
7239 if (blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
7240 conf->batch_bio_dispatch = false;
7241 break;
7245 conf->bypass_threshold = BYPASS_THRESHOLD;
7246 conf->recovery_disabled = mddev->recovery_disabled - 1;
7248 conf->raid_disks = mddev->raid_disks;
7249 if (mddev->reshape_position == MaxSector)
7250 conf->previous_raid_disks = mddev->raid_disks;
7251 else
7252 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
7253 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
7255 conf->disks = kcalloc(max_disks, sizeof(struct disk_info),
7256 GFP_KERNEL);
7258 if (!conf->disks)
7259 goto abort;
7261 for (i = 0; i < max_disks; i++) {
7262 conf->disks[i].extra_page = alloc_page(GFP_KERNEL);
7263 if (!conf->disks[i].extra_page)
7264 goto abort;
7267 ret = bioset_init(&conf->bio_split, BIO_POOL_SIZE, 0, 0);
7268 if (ret)
7269 goto abort;
7270 conf->mddev = mddev;
7272 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
7273 goto abort;
7275 /* We init hash_locks[0] separately to that it can be used
7276 * as the reference lock in the spin_lock_nest_lock() call
7277 * in lock_all_device_hash_locks_irq in order to convince
7278 * lockdep that we know what we are doing.
7280 spin_lock_init(conf->hash_locks);
7281 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
7282 spin_lock_init(conf->hash_locks + i);
7284 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7285 INIT_LIST_HEAD(conf->inactive_list + i);
7287 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
7288 INIT_LIST_HEAD(conf->temp_inactive_list + i);
7290 atomic_set(&conf->r5c_cached_full_stripes, 0);
7291 INIT_LIST_HEAD(&conf->r5c_full_stripe_list);
7292 atomic_set(&conf->r5c_cached_partial_stripes, 0);
7293 INIT_LIST_HEAD(&conf->r5c_partial_stripe_list);
7294 atomic_set(&conf->r5c_flushing_full_stripes, 0);
7295 atomic_set(&conf->r5c_flushing_partial_stripes, 0);
7297 conf->level = mddev->new_level;
7298 conf->chunk_sectors = mddev->new_chunk_sectors;
7299 if (raid5_alloc_percpu(conf) != 0)
7300 goto abort;
7302 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
7304 rdev_for_each(rdev, mddev) {
7305 raid_disk = rdev->raid_disk;
7306 if (raid_disk >= max_disks
7307 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
7308 continue;
7309 disk = conf->disks + raid_disk;
7311 if (test_bit(Replacement, &rdev->flags)) {
7312 if (disk->replacement)
7313 goto abort;
7314 disk->replacement = rdev;
7315 } else {
7316 if (disk->rdev)
7317 goto abort;
7318 disk->rdev = rdev;
7321 if (test_bit(In_sync, &rdev->flags)) {
7322 char b[BDEVNAME_SIZE];
7323 pr_info("md/raid:%s: device %s operational as raid disk %d\n",
7324 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
7325 } else if (rdev->saved_raid_disk != raid_disk)
7326 /* Cannot rely on bitmap to complete recovery */
7327 conf->fullsync = 1;
7330 conf->level = mddev->new_level;
7331 if (conf->level == 6) {
7332 conf->max_degraded = 2;
7333 if (raid6_call.xor_syndrome)
7334 conf->rmw_level = PARITY_ENABLE_RMW;
7335 else
7336 conf->rmw_level = PARITY_DISABLE_RMW;
7337 } else {
7338 conf->max_degraded = 1;
7339 conf->rmw_level = PARITY_ENABLE_RMW;
7341 conf->algorithm = mddev->new_layout;
7342 conf->reshape_progress = mddev->reshape_position;
7343 if (conf->reshape_progress != MaxSector) {
7344 conf->prev_chunk_sectors = mddev->chunk_sectors;
7345 conf->prev_algo = mddev->layout;
7346 } else {
7347 conf->prev_chunk_sectors = conf->chunk_sectors;
7348 conf->prev_algo = conf->algorithm;
7351 conf->min_nr_stripes = NR_STRIPES;
7352 if (mddev->reshape_position != MaxSector) {
7353 int stripes = max_t(int,
7354 ((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4,
7355 ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4);
7356 conf->min_nr_stripes = max(NR_STRIPES, stripes);
7357 if (conf->min_nr_stripes != NR_STRIPES)
7358 pr_info("md/raid:%s: force stripe size %d for reshape\n",
7359 mdname(mddev), conf->min_nr_stripes);
7361 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
7362 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
7363 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
7364 if (grow_stripes(conf, conf->min_nr_stripes)) {
7365 pr_warn("md/raid:%s: couldn't allocate %dkB for buffers\n",
7366 mdname(mddev), memory);
7367 goto abort;
7368 } else
7369 pr_debug("md/raid:%s: allocated %dkB\n", mdname(mddev), memory);
7371 * Losing a stripe head costs more than the time to refill it,
7372 * it reduces the queue depth and so can hurt throughput.
7373 * So set it rather large, scaled by number of devices.
7375 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
7376 conf->shrinker.scan_objects = raid5_cache_scan;
7377 conf->shrinker.count_objects = raid5_cache_count;
7378 conf->shrinker.batch = 128;
7379 conf->shrinker.flags = 0;
7380 if (register_shrinker(&conf->shrinker)) {
7381 pr_warn("md/raid:%s: couldn't register shrinker.\n",
7382 mdname(mddev));
7383 goto abort;
7386 sprintf(pers_name, "raid%d", mddev->new_level);
7387 conf->thread = md_register_thread(raid5d, mddev, pers_name);
7388 if (!conf->thread) {
7389 pr_warn("md/raid:%s: couldn't allocate thread.\n",
7390 mdname(mddev));
7391 goto abort;
7394 return conf;
7396 abort:
7397 if (conf) {
7398 free_conf(conf);
7399 return ERR_PTR(-EIO);
7400 } else
7401 return ERR_PTR(-ENOMEM);
7404 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
7406 switch (algo) {
7407 case ALGORITHM_PARITY_0:
7408 if (raid_disk < max_degraded)
7409 return 1;
7410 break;
7411 case ALGORITHM_PARITY_N:
7412 if (raid_disk >= raid_disks - max_degraded)
7413 return 1;
7414 break;
7415 case ALGORITHM_PARITY_0_6:
7416 if (raid_disk == 0 ||
7417 raid_disk == raid_disks - 1)
7418 return 1;
7419 break;
7420 case ALGORITHM_LEFT_ASYMMETRIC_6:
7421 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7422 case ALGORITHM_LEFT_SYMMETRIC_6:
7423 case ALGORITHM_RIGHT_SYMMETRIC_6:
7424 if (raid_disk == raid_disks - 1)
7425 return 1;
7427 return 0;
7430 static void raid5_set_io_opt(struct r5conf *conf)
7432 blk_queue_io_opt(conf->mddev->queue, (conf->chunk_sectors << 9) *
7433 (conf->raid_disks - conf->max_degraded));
7436 static int raid5_run(struct mddev *mddev)
7438 struct r5conf *conf;
7439 int working_disks = 0;
7440 int dirty_parity_disks = 0;
7441 struct md_rdev *rdev;
7442 struct md_rdev *journal_dev = NULL;
7443 sector_t reshape_offset = 0;
7444 int i;
7445 long long min_offset_diff = 0;
7446 int first = 1;
7448 if (mddev_init_writes_pending(mddev) < 0)
7449 return -ENOMEM;
7451 if (mddev->recovery_cp != MaxSector)
7452 pr_notice("md/raid:%s: not clean -- starting background reconstruction\n",
7453 mdname(mddev));
7455 rdev_for_each(rdev, mddev) {
7456 long long diff;
7458 if (test_bit(Journal, &rdev->flags)) {
7459 journal_dev = rdev;
7460 continue;
7462 if (rdev->raid_disk < 0)
7463 continue;
7464 diff = (rdev->new_data_offset - rdev->data_offset);
7465 if (first) {
7466 min_offset_diff = diff;
7467 first = 0;
7468 } else if (mddev->reshape_backwards &&
7469 diff < min_offset_diff)
7470 min_offset_diff = diff;
7471 else if (!mddev->reshape_backwards &&
7472 diff > min_offset_diff)
7473 min_offset_diff = diff;
7476 if ((test_bit(MD_HAS_JOURNAL, &mddev->flags) || journal_dev) &&
7477 (mddev->bitmap_info.offset || mddev->bitmap_info.file)) {
7478 pr_notice("md/raid:%s: array cannot have both journal and bitmap\n",
7479 mdname(mddev));
7480 return -EINVAL;
7483 if (mddev->reshape_position != MaxSector) {
7484 /* Check that we can continue the reshape.
7485 * Difficulties arise if the stripe we would write to
7486 * next is at or after the stripe we would read from next.
7487 * For a reshape that changes the number of devices, this
7488 * is only possible for a very short time, and mdadm makes
7489 * sure that time appears to have past before assembling
7490 * the array. So we fail if that time hasn't passed.
7491 * For a reshape that keeps the number of devices the same
7492 * mdadm must be monitoring the reshape can keeping the
7493 * critical areas read-only and backed up. It will start
7494 * the array in read-only mode, so we check for that.
7496 sector_t here_new, here_old;
7497 int old_disks;
7498 int max_degraded = (mddev->level == 6 ? 2 : 1);
7499 int chunk_sectors;
7500 int new_data_disks;
7502 if (journal_dev) {
7503 pr_warn("md/raid:%s: don't support reshape with journal - aborting.\n",
7504 mdname(mddev));
7505 return -EINVAL;
7508 if (mddev->new_level != mddev->level) {
7509 pr_warn("md/raid:%s: unsupported reshape required - aborting.\n",
7510 mdname(mddev));
7511 return -EINVAL;
7513 old_disks = mddev->raid_disks - mddev->delta_disks;
7514 /* reshape_position must be on a new-stripe boundary, and one
7515 * further up in new geometry must map after here in old
7516 * geometry.
7517 * If the chunk sizes are different, then as we perform reshape
7518 * in units of the largest of the two, reshape_position needs
7519 * be a multiple of the largest chunk size times new data disks.
7521 here_new = mddev->reshape_position;
7522 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
7523 new_data_disks = mddev->raid_disks - max_degraded;
7524 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
7525 pr_warn("md/raid:%s: reshape_position not on a stripe boundary\n",
7526 mdname(mddev));
7527 return -EINVAL;
7529 reshape_offset = here_new * chunk_sectors;
7530 /* here_new is the stripe we will write to */
7531 here_old = mddev->reshape_position;
7532 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
7533 /* here_old is the first stripe that we might need to read
7534 * from */
7535 if (mddev->delta_disks == 0) {
7536 /* We cannot be sure it is safe to start an in-place
7537 * reshape. It is only safe if user-space is monitoring
7538 * and taking constant backups.
7539 * mdadm always starts a situation like this in
7540 * readonly mode so it can take control before
7541 * allowing any writes. So just check for that.
7543 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
7544 abs(min_offset_diff) >= mddev->new_chunk_sectors)
7545 /* not really in-place - so OK */;
7546 else if (mddev->ro == 0) {
7547 pr_warn("md/raid:%s: in-place reshape must be started in read-only mode - aborting\n",
7548 mdname(mddev));
7549 return -EINVAL;
7551 } else if (mddev->reshape_backwards
7552 ? (here_new * chunk_sectors + min_offset_diff <=
7553 here_old * chunk_sectors)
7554 : (here_new * chunk_sectors >=
7555 here_old * chunk_sectors + (-min_offset_diff))) {
7556 /* Reading from the same stripe as writing to - bad */
7557 pr_warn("md/raid:%s: reshape_position too early for auto-recovery - aborting.\n",
7558 mdname(mddev));
7559 return -EINVAL;
7561 pr_debug("md/raid:%s: reshape will continue\n", mdname(mddev));
7562 /* OK, we should be able to continue; */
7563 } else {
7564 BUG_ON(mddev->level != mddev->new_level);
7565 BUG_ON(mddev->layout != mddev->new_layout);
7566 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
7567 BUG_ON(mddev->delta_disks != 0);
7570 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) &&
7571 test_bit(MD_HAS_PPL, &mddev->flags)) {
7572 pr_warn("md/raid:%s: using journal device and PPL not allowed - disabling PPL\n",
7573 mdname(mddev));
7574 clear_bit(MD_HAS_PPL, &mddev->flags);
7575 clear_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags);
7578 if (mddev->private == NULL)
7579 conf = setup_conf(mddev);
7580 else
7581 conf = mddev->private;
7583 if (IS_ERR(conf))
7584 return PTR_ERR(conf);
7586 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
7587 if (!journal_dev) {
7588 pr_warn("md/raid:%s: journal disk is missing, force array readonly\n",
7589 mdname(mddev));
7590 mddev->ro = 1;
7591 set_disk_ro(mddev->gendisk, 1);
7592 } else if (mddev->recovery_cp == MaxSector)
7593 set_bit(MD_JOURNAL_CLEAN, &mddev->flags);
7596 conf->min_offset_diff = min_offset_diff;
7597 mddev->thread = conf->thread;
7598 conf->thread = NULL;
7599 mddev->private = conf;
7601 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
7602 i++) {
7603 rdev = conf->disks[i].rdev;
7604 if (!rdev && conf->disks[i].replacement) {
7605 /* The replacement is all we have yet */
7606 rdev = conf->disks[i].replacement;
7607 conf->disks[i].replacement = NULL;
7608 clear_bit(Replacement, &rdev->flags);
7609 conf->disks[i].rdev = rdev;
7611 if (!rdev)
7612 continue;
7613 if (conf->disks[i].replacement &&
7614 conf->reshape_progress != MaxSector) {
7615 /* replacements and reshape simply do not mix. */
7616 pr_warn("md: cannot handle concurrent replacement and reshape.\n");
7617 goto abort;
7619 if (test_bit(In_sync, &rdev->flags)) {
7620 working_disks++;
7621 continue;
7623 /* This disc is not fully in-sync. However if it
7624 * just stored parity (beyond the recovery_offset),
7625 * when we don't need to be concerned about the
7626 * array being dirty.
7627 * When reshape goes 'backwards', we never have
7628 * partially completed devices, so we only need
7629 * to worry about reshape going forwards.
7631 /* Hack because v0.91 doesn't store recovery_offset properly. */
7632 if (mddev->major_version == 0 &&
7633 mddev->minor_version > 90)
7634 rdev->recovery_offset = reshape_offset;
7636 if (rdev->recovery_offset < reshape_offset) {
7637 /* We need to check old and new layout */
7638 if (!only_parity(rdev->raid_disk,
7639 conf->algorithm,
7640 conf->raid_disks,
7641 conf->max_degraded))
7642 continue;
7644 if (!only_parity(rdev->raid_disk,
7645 conf->prev_algo,
7646 conf->previous_raid_disks,
7647 conf->max_degraded))
7648 continue;
7649 dirty_parity_disks++;
7653 * 0 for a fully functional array, 1 or 2 for a degraded array.
7655 mddev->degraded = raid5_calc_degraded(conf);
7657 if (has_failed(conf)) {
7658 pr_crit("md/raid:%s: not enough operational devices (%d/%d failed)\n",
7659 mdname(mddev), mddev->degraded, conf->raid_disks);
7660 goto abort;
7663 /* device size must be a multiple of chunk size */
7664 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
7665 mddev->resync_max_sectors = mddev->dev_sectors;
7667 if (mddev->degraded > dirty_parity_disks &&
7668 mddev->recovery_cp != MaxSector) {
7669 if (test_bit(MD_HAS_PPL, &mddev->flags))
7670 pr_crit("md/raid:%s: starting dirty degraded array with PPL.\n",
7671 mdname(mddev));
7672 else if (mddev->ok_start_degraded)
7673 pr_crit("md/raid:%s: starting dirty degraded array - data corruption possible.\n",
7674 mdname(mddev));
7675 else {
7676 pr_crit("md/raid:%s: cannot start dirty degraded array.\n",
7677 mdname(mddev));
7678 goto abort;
7682 pr_info("md/raid:%s: raid level %d active with %d out of %d devices, algorithm %d\n",
7683 mdname(mddev), conf->level,
7684 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
7685 mddev->new_layout);
7687 print_raid5_conf(conf);
7689 if (conf->reshape_progress != MaxSector) {
7690 conf->reshape_safe = conf->reshape_progress;
7691 atomic_set(&conf->reshape_stripes, 0);
7692 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7693 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7694 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7695 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7696 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7697 "reshape");
7698 if (!mddev->sync_thread)
7699 goto abort;
7702 /* Ok, everything is just fine now */
7703 if (mddev->to_remove == &raid5_attrs_group)
7704 mddev->to_remove = NULL;
7705 else if (mddev->kobj.sd &&
7706 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
7707 pr_warn("raid5: failed to create sysfs attributes for %s\n",
7708 mdname(mddev));
7709 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7711 if (mddev->queue) {
7712 int chunk_size;
7713 /* read-ahead size must cover two whole stripes, which
7714 * is 2 * (datadisks) * chunksize where 'n' is the
7715 * number of raid devices
7717 int data_disks = conf->previous_raid_disks - conf->max_degraded;
7718 int stripe = data_disks *
7719 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
7721 chunk_size = mddev->chunk_sectors << 9;
7722 blk_queue_io_min(mddev->queue, chunk_size);
7723 raid5_set_io_opt(conf);
7724 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7726 * We can only discard a whole stripe. It doesn't make sense to
7727 * discard data disk but write parity disk
7729 stripe = stripe * PAGE_SIZE;
7730 /* Round up to power of 2, as discard handling
7731 * currently assumes that */
7732 while ((stripe-1) & stripe)
7733 stripe = (stripe | (stripe-1)) + 1;
7734 mddev->queue->limits.discard_alignment = stripe;
7735 mddev->queue->limits.discard_granularity = stripe;
7737 blk_queue_max_write_same_sectors(mddev->queue, 0);
7738 blk_queue_max_write_zeroes_sectors(mddev->queue, 0);
7740 rdev_for_each(rdev, mddev) {
7741 disk_stack_limits(mddev->gendisk, rdev->bdev,
7742 rdev->data_offset << 9);
7743 disk_stack_limits(mddev->gendisk, rdev->bdev,
7744 rdev->new_data_offset << 9);
7748 * zeroing is required, otherwise data
7749 * could be lost. Consider a scenario: discard a stripe
7750 * (the stripe could be inconsistent if
7751 * discard_zeroes_data is 0); write one disk of the
7752 * stripe (the stripe could be inconsistent again
7753 * depending on which disks are used to calculate
7754 * parity); the disk is broken; The stripe data of this
7755 * disk is lost.
7757 * We only allow DISCARD if the sysadmin has confirmed that
7758 * only safe devices are in use by setting a module parameter.
7759 * A better idea might be to turn DISCARD into WRITE_ZEROES
7760 * requests, as that is required to be safe.
7762 if (devices_handle_discard_safely &&
7763 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7764 mddev->queue->limits.discard_granularity >= stripe)
7765 blk_queue_flag_set(QUEUE_FLAG_DISCARD,
7766 mddev->queue);
7767 else
7768 blk_queue_flag_clear(QUEUE_FLAG_DISCARD,
7769 mddev->queue);
7771 blk_queue_max_hw_sectors(mddev->queue, UINT_MAX);
7774 if (log_init(conf, journal_dev, raid5_has_ppl(conf)))
7775 goto abort;
7777 return 0;
7778 abort:
7779 md_unregister_thread(&mddev->thread);
7780 print_raid5_conf(conf);
7781 free_conf(conf);
7782 mddev->private = NULL;
7783 pr_warn("md/raid:%s: failed to run raid set.\n", mdname(mddev));
7784 return -EIO;
7787 static void raid5_free(struct mddev *mddev, void *priv)
7789 struct r5conf *conf = priv;
7791 free_conf(conf);
7792 mddev->to_remove = &raid5_attrs_group;
7795 static void raid5_status(struct seq_file *seq, struct mddev *mddev)
7797 struct r5conf *conf = mddev->private;
7798 int i;
7800 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7801 conf->chunk_sectors / 2, mddev->layout);
7802 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7803 rcu_read_lock();
7804 for (i = 0; i < conf->raid_disks; i++) {
7805 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
7806 seq_printf (seq, "%s", rdev && test_bit(In_sync, &rdev->flags) ? "U" : "_");
7808 rcu_read_unlock();
7809 seq_printf (seq, "]");
7812 static void print_raid5_conf (struct r5conf *conf)
7814 int i;
7815 struct disk_info *tmp;
7817 pr_debug("RAID conf printout:\n");
7818 if (!conf) {
7819 pr_debug("(conf==NULL)\n");
7820 return;
7822 pr_debug(" --- level:%d rd:%d wd:%d\n", conf->level,
7823 conf->raid_disks,
7824 conf->raid_disks - conf->mddev->degraded);
7826 for (i = 0; i < conf->raid_disks; i++) {
7827 char b[BDEVNAME_SIZE];
7828 tmp = conf->disks + i;
7829 if (tmp->rdev)
7830 pr_debug(" disk %d, o:%d, dev:%s\n",
7831 i, !test_bit(Faulty, &tmp->rdev->flags),
7832 bdevname(tmp->rdev->bdev, b));
7836 static int raid5_spare_active(struct mddev *mddev)
7838 int i;
7839 struct r5conf *conf = mddev->private;
7840 struct disk_info *tmp;
7841 int count = 0;
7842 unsigned long flags;
7844 for (i = 0; i < conf->raid_disks; i++) {
7845 tmp = conf->disks + i;
7846 if (tmp->replacement
7847 && tmp->replacement->recovery_offset == MaxSector
7848 && !test_bit(Faulty, &tmp->replacement->flags)
7849 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7850 /* Replacement has just become active. */
7851 if (!tmp->rdev
7852 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7853 count++;
7854 if (tmp->rdev) {
7855 /* Replaced device not technically faulty,
7856 * but we need to be sure it gets removed
7857 * and never re-added.
7859 set_bit(Faulty, &tmp->rdev->flags);
7860 sysfs_notify_dirent_safe(
7861 tmp->rdev->sysfs_state);
7863 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7864 } else if (tmp->rdev
7865 && tmp->rdev->recovery_offset == MaxSector
7866 && !test_bit(Faulty, &tmp->rdev->flags)
7867 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7868 count++;
7869 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7872 spin_lock_irqsave(&conf->device_lock, flags);
7873 mddev->degraded = raid5_calc_degraded(conf);
7874 spin_unlock_irqrestore(&conf->device_lock, flags);
7875 print_raid5_conf(conf);
7876 return count;
7879 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7881 struct r5conf *conf = mddev->private;
7882 int err = 0;
7883 int number = rdev->raid_disk;
7884 struct md_rdev **rdevp;
7885 struct disk_info *p = conf->disks + number;
7887 print_raid5_conf(conf);
7888 if (test_bit(Journal, &rdev->flags) && conf->log) {
7890 * we can't wait pending write here, as this is called in
7891 * raid5d, wait will deadlock.
7892 * neilb: there is no locking about new writes here,
7893 * so this cannot be safe.
7895 if (atomic_read(&conf->active_stripes) ||
7896 atomic_read(&conf->r5c_cached_full_stripes) ||
7897 atomic_read(&conf->r5c_cached_partial_stripes)) {
7898 return -EBUSY;
7900 log_exit(conf);
7901 return 0;
7903 if (rdev == p->rdev)
7904 rdevp = &p->rdev;
7905 else if (rdev == p->replacement)
7906 rdevp = &p->replacement;
7907 else
7908 return 0;
7910 if (number >= conf->raid_disks &&
7911 conf->reshape_progress == MaxSector)
7912 clear_bit(In_sync, &rdev->flags);
7914 if (test_bit(In_sync, &rdev->flags) ||
7915 atomic_read(&rdev->nr_pending)) {
7916 err = -EBUSY;
7917 goto abort;
7919 /* Only remove non-faulty devices if recovery
7920 * isn't possible.
7922 if (!test_bit(Faulty, &rdev->flags) &&
7923 mddev->recovery_disabled != conf->recovery_disabled &&
7924 !has_failed(conf) &&
7925 (!p->replacement || p->replacement == rdev) &&
7926 number < conf->raid_disks) {
7927 err = -EBUSY;
7928 goto abort;
7930 *rdevp = NULL;
7931 if (!test_bit(RemoveSynchronized, &rdev->flags)) {
7932 synchronize_rcu();
7933 if (atomic_read(&rdev->nr_pending)) {
7934 /* lost the race, try later */
7935 err = -EBUSY;
7936 *rdevp = rdev;
7939 if (!err) {
7940 err = log_modify(conf, rdev, false);
7941 if (err)
7942 goto abort;
7944 if (p->replacement) {
7945 /* We must have just cleared 'rdev' */
7946 p->rdev = p->replacement;
7947 clear_bit(Replacement, &p->replacement->flags);
7948 smp_mb(); /* Make sure other CPUs may see both as identical
7949 * but will never see neither - if they are careful
7951 p->replacement = NULL;
7953 if (!err)
7954 err = log_modify(conf, p->rdev, true);
7957 clear_bit(WantReplacement, &rdev->flags);
7958 abort:
7960 print_raid5_conf(conf);
7961 return err;
7964 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7966 struct r5conf *conf = mddev->private;
7967 int ret, err = -EEXIST;
7968 int disk;
7969 struct disk_info *p;
7970 int first = 0;
7971 int last = conf->raid_disks - 1;
7973 if (test_bit(Journal, &rdev->flags)) {
7974 if (conf->log)
7975 return -EBUSY;
7977 rdev->raid_disk = 0;
7979 * The array is in readonly mode if journal is missing, so no
7980 * write requests running. We should be safe
7982 ret = log_init(conf, rdev, false);
7983 if (ret)
7984 return ret;
7986 ret = r5l_start(conf->log);
7987 if (ret)
7988 return ret;
7990 return 0;
7992 if (mddev->recovery_disabled == conf->recovery_disabled)
7993 return -EBUSY;
7995 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7996 /* no point adding a device */
7997 return -EINVAL;
7999 if (rdev->raid_disk >= 0)
8000 first = last = rdev->raid_disk;
8003 * find the disk ... but prefer rdev->saved_raid_disk
8004 * if possible.
8006 if (rdev->saved_raid_disk >= 0 &&
8007 rdev->saved_raid_disk >= first &&
8008 conf->disks[rdev->saved_raid_disk].rdev == NULL)
8009 first = rdev->saved_raid_disk;
8011 for (disk = first; disk <= last; disk++) {
8012 p = conf->disks + disk;
8013 if (p->rdev == NULL) {
8014 clear_bit(In_sync, &rdev->flags);
8015 rdev->raid_disk = disk;
8016 if (rdev->saved_raid_disk != disk)
8017 conf->fullsync = 1;
8018 rcu_assign_pointer(p->rdev, rdev);
8020 err = log_modify(conf, rdev, true);
8022 goto out;
8025 for (disk = first; disk <= last; disk++) {
8026 p = conf->disks + disk;
8027 if (test_bit(WantReplacement, &p->rdev->flags) &&
8028 p->replacement == NULL) {
8029 clear_bit(In_sync, &rdev->flags);
8030 set_bit(Replacement, &rdev->flags);
8031 rdev->raid_disk = disk;
8032 err = 0;
8033 conf->fullsync = 1;
8034 rcu_assign_pointer(p->replacement, rdev);
8035 break;
8038 out:
8039 print_raid5_conf(conf);
8040 return err;
8043 static int raid5_resize(struct mddev *mddev, sector_t sectors)
8045 /* no resync is happening, and there is enough space
8046 * on all devices, so we can resize.
8047 * We need to make sure resync covers any new space.
8048 * If the array is shrinking we should possibly wait until
8049 * any io in the removed space completes, but it hardly seems
8050 * worth it.
8052 sector_t newsize;
8053 struct r5conf *conf = mddev->private;
8055 if (raid5_has_log(conf) || raid5_has_ppl(conf))
8056 return -EINVAL;
8057 sectors &= ~((sector_t)conf->chunk_sectors - 1);
8058 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
8059 if (mddev->external_size &&
8060 mddev->array_sectors > newsize)
8061 return -EINVAL;
8062 if (mddev->bitmap) {
8063 int ret = md_bitmap_resize(mddev->bitmap, sectors, 0, 0);
8064 if (ret)
8065 return ret;
8067 md_set_array_sectors(mddev, newsize);
8068 if (sectors > mddev->dev_sectors &&
8069 mddev->recovery_cp > mddev->dev_sectors) {
8070 mddev->recovery_cp = mddev->dev_sectors;
8071 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8073 mddev->dev_sectors = sectors;
8074 mddev->resync_max_sectors = sectors;
8075 return 0;
8078 static int check_stripe_cache(struct mddev *mddev)
8080 /* Can only proceed if there are plenty of stripe_heads.
8081 * We need a minimum of one full stripe,, and for sensible progress
8082 * it is best to have about 4 times that.
8083 * If we require 4 times, then the default 256 4K stripe_heads will
8084 * allow for chunk sizes up to 256K, which is probably OK.
8085 * If the chunk size is greater, user-space should request more
8086 * stripe_heads first.
8088 struct r5conf *conf = mddev->private;
8089 if (((mddev->chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8090 > conf->min_nr_stripes ||
8091 ((mddev->new_chunk_sectors << 9) / RAID5_STRIPE_SIZE(conf)) * 4
8092 > conf->min_nr_stripes) {
8093 pr_warn("md/raid:%s: reshape: not enough stripes. Needed %lu\n",
8094 mdname(mddev),
8095 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
8096 / RAID5_STRIPE_SIZE(conf))*4);
8097 return 0;
8099 return 1;
8102 static int check_reshape(struct mddev *mddev)
8104 struct r5conf *conf = mddev->private;
8106 if (raid5_has_log(conf) || raid5_has_ppl(conf))
8107 return -EINVAL;
8108 if (mddev->delta_disks == 0 &&
8109 mddev->new_layout == mddev->layout &&
8110 mddev->new_chunk_sectors == mddev->chunk_sectors)
8111 return 0; /* nothing to do */
8112 if (has_failed(conf))
8113 return -EINVAL;
8114 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
8115 /* We might be able to shrink, but the devices must
8116 * be made bigger first.
8117 * For raid6, 4 is the minimum size.
8118 * Otherwise 2 is the minimum
8120 int min = 2;
8121 if (mddev->level == 6)
8122 min = 4;
8123 if (mddev->raid_disks + mddev->delta_disks < min)
8124 return -EINVAL;
8127 if (!check_stripe_cache(mddev))
8128 return -ENOSPC;
8130 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
8131 mddev->delta_disks > 0)
8132 if (resize_chunks(conf,
8133 conf->previous_raid_disks
8134 + max(0, mddev->delta_disks),
8135 max(mddev->new_chunk_sectors,
8136 mddev->chunk_sectors)
8137 ) < 0)
8138 return -ENOMEM;
8140 if (conf->previous_raid_disks + mddev->delta_disks <= conf->pool_size)
8141 return 0; /* never bother to shrink */
8142 return resize_stripes(conf, (conf->previous_raid_disks
8143 + mddev->delta_disks));
8146 static int raid5_start_reshape(struct mddev *mddev)
8148 struct r5conf *conf = mddev->private;
8149 struct md_rdev *rdev;
8150 int spares = 0;
8151 unsigned long flags;
8153 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8154 return -EBUSY;
8156 if (!check_stripe_cache(mddev))
8157 return -ENOSPC;
8159 if (has_failed(conf))
8160 return -EINVAL;
8162 rdev_for_each(rdev, mddev) {
8163 if (!test_bit(In_sync, &rdev->flags)
8164 && !test_bit(Faulty, &rdev->flags))
8165 spares++;
8168 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
8169 /* Not enough devices even to make a degraded array
8170 * of that size
8172 return -EINVAL;
8174 /* Refuse to reduce size of the array. Any reductions in
8175 * array size must be through explicit setting of array_size
8176 * attribute.
8178 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
8179 < mddev->array_sectors) {
8180 pr_warn("md/raid:%s: array size must be reduced before number of disks\n",
8181 mdname(mddev));
8182 return -EINVAL;
8185 atomic_set(&conf->reshape_stripes, 0);
8186 spin_lock_irq(&conf->device_lock);
8187 write_seqcount_begin(&conf->gen_lock);
8188 conf->previous_raid_disks = conf->raid_disks;
8189 conf->raid_disks += mddev->delta_disks;
8190 conf->prev_chunk_sectors = conf->chunk_sectors;
8191 conf->chunk_sectors = mddev->new_chunk_sectors;
8192 conf->prev_algo = conf->algorithm;
8193 conf->algorithm = mddev->new_layout;
8194 conf->generation++;
8195 /* Code that selects data_offset needs to see the generation update
8196 * if reshape_progress has been set - so a memory barrier needed.
8198 smp_mb();
8199 if (mddev->reshape_backwards)
8200 conf->reshape_progress = raid5_size(mddev, 0, 0);
8201 else
8202 conf->reshape_progress = 0;
8203 conf->reshape_safe = conf->reshape_progress;
8204 write_seqcount_end(&conf->gen_lock);
8205 spin_unlock_irq(&conf->device_lock);
8207 /* Now make sure any requests that proceeded on the assumption
8208 * the reshape wasn't running - like Discard or Read - have
8209 * completed.
8211 mddev_suspend(mddev);
8212 mddev_resume(mddev);
8214 /* Add some new drives, as many as will fit.
8215 * We know there are enough to make the newly sized array work.
8216 * Don't add devices if we are reducing the number of
8217 * devices in the array. This is because it is not possible
8218 * to correctly record the "partially reconstructed" state of
8219 * such devices during the reshape and confusion could result.
8221 if (mddev->delta_disks >= 0) {
8222 rdev_for_each(rdev, mddev)
8223 if (rdev->raid_disk < 0 &&
8224 !test_bit(Faulty, &rdev->flags)) {
8225 if (raid5_add_disk(mddev, rdev) == 0) {
8226 if (rdev->raid_disk
8227 >= conf->previous_raid_disks)
8228 set_bit(In_sync, &rdev->flags);
8229 else
8230 rdev->recovery_offset = 0;
8232 /* Failure here is OK */
8233 sysfs_link_rdev(mddev, rdev);
8235 } else if (rdev->raid_disk >= conf->previous_raid_disks
8236 && !test_bit(Faulty, &rdev->flags)) {
8237 /* This is a spare that was manually added */
8238 set_bit(In_sync, &rdev->flags);
8241 /* When a reshape changes the number of devices,
8242 * ->degraded is measured against the larger of the
8243 * pre and post number of devices.
8245 spin_lock_irqsave(&conf->device_lock, flags);
8246 mddev->degraded = raid5_calc_degraded(conf);
8247 spin_unlock_irqrestore(&conf->device_lock, flags);
8249 mddev->raid_disks = conf->raid_disks;
8250 mddev->reshape_position = conf->reshape_progress;
8251 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8253 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8254 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8255 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8256 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8257 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8258 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
8259 "reshape");
8260 if (!mddev->sync_thread) {
8261 mddev->recovery = 0;
8262 spin_lock_irq(&conf->device_lock);
8263 write_seqcount_begin(&conf->gen_lock);
8264 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
8265 mddev->new_chunk_sectors =
8266 conf->chunk_sectors = conf->prev_chunk_sectors;
8267 mddev->new_layout = conf->algorithm = conf->prev_algo;
8268 rdev_for_each(rdev, mddev)
8269 rdev->new_data_offset = rdev->data_offset;
8270 smp_wmb();
8271 conf->generation --;
8272 conf->reshape_progress = MaxSector;
8273 mddev->reshape_position = MaxSector;
8274 write_seqcount_end(&conf->gen_lock);
8275 spin_unlock_irq(&conf->device_lock);
8276 return -EAGAIN;
8278 conf->reshape_checkpoint = jiffies;
8279 md_wakeup_thread(mddev->sync_thread);
8280 md_new_event(mddev);
8281 return 0;
8284 /* This is called from the reshape thread and should make any
8285 * changes needed in 'conf'
8287 static void end_reshape(struct r5conf *conf)
8290 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
8291 struct md_rdev *rdev;
8293 spin_lock_irq(&conf->device_lock);
8294 conf->previous_raid_disks = conf->raid_disks;
8295 md_finish_reshape(conf->mddev);
8296 smp_wmb();
8297 conf->reshape_progress = MaxSector;
8298 conf->mddev->reshape_position = MaxSector;
8299 rdev_for_each(rdev, conf->mddev)
8300 if (rdev->raid_disk >= 0 &&
8301 !test_bit(Journal, &rdev->flags) &&
8302 !test_bit(In_sync, &rdev->flags))
8303 rdev->recovery_offset = MaxSector;
8304 spin_unlock_irq(&conf->device_lock);
8305 wake_up(&conf->wait_for_overlap);
8307 if (conf->mddev->queue)
8308 raid5_set_io_opt(conf);
8312 /* This is called from the raid5d thread with mddev_lock held.
8313 * It makes config changes to the device.
8315 static void raid5_finish_reshape(struct mddev *mddev)
8317 struct r5conf *conf = mddev->private;
8319 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8321 if (mddev->delta_disks <= 0) {
8322 int d;
8323 spin_lock_irq(&conf->device_lock);
8324 mddev->degraded = raid5_calc_degraded(conf);
8325 spin_unlock_irq(&conf->device_lock);
8326 for (d = conf->raid_disks ;
8327 d < conf->raid_disks - mddev->delta_disks;
8328 d++) {
8329 struct md_rdev *rdev = conf->disks[d].rdev;
8330 if (rdev)
8331 clear_bit(In_sync, &rdev->flags);
8332 rdev = conf->disks[d].replacement;
8333 if (rdev)
8334 clear_bit(In_sync, &rdev->flags);
8337 mddev->layout = conf->algorithm;
8338 mddev->chunk_sectors = conf->chunk_sectors;
8339 mddev->reshape_position = MaxSector;
8340 mddev->delta_disks = 0;
8341 mddev->reshape_backwards = 0;
8345 static void raid5_quiesce(struct mddev *mddev, int quiesce)
8347 struct r5conf *conf = mddev->private;
8349 if (quiesce) {
8350 /* stop all writes */
8351 lock_all_device_hash_locks_irq(conf);
8352 /* '2' tells resync/reshape to pause so that all
8353 * active stripes can drain
8355 r5c_flush_cache(conf, INT_MAX);
8356 conf->quiesce = 2;
8357 wait_event_cmd(conf->wait_for_quiescent,
8358 atomic_read(&conf->active_stripes) == 0 &&
8359 atomic_read(&conf->active_aligned_reads) == 0,
8360 unlock_all_device_hash_locks_irq(conf),
8361 lock_all_device_hash_locks_irq(conf));
8362 conf->quiesce = 1;
8363 unlock_all_device_hash_locks_irq(conf);
8364 /* allow reshape to continue */
8365 wake_up(&conf->wait_for_overlap);
8366 } else {
8367 /* re-enable writes */
8368 lock_all_device_hash_locks_irq(conf);
8369 conf->quiesce = 0;
8370 wake_up(&conf->wait_for_quiescent);
8371 wake_up(&conf->wait_for_overlap);
8372 unlock_all_device_hash_locks_irq(conf);
8374 log_quiesce(conf, quiesce);
8377 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
8379 struct r0conf *raid0_conf = mddev->private;
8380 sector_t sectors;
8382 /* for raid0 takeover only one zone is supported */
8383 if (raid0_conf->nr_strip_zones > 1) {
8384 pr_warn("md/raid:%s: cannot takeover raid0 with more than one zone.\n",
8385 mdname(mddev));
8386 return ERR_PTR(-EINVAL);
8389 sectors = raid0_conf->strip_zone[0].zone_end;
8390 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
8391 mddev->dev_sectors = sectors;
8392 mddev->new_level = level;
8393 mddev->new_layout = ALGORITHM_PARITY_N;
8394 mddev->new_chunk_sectors = mddev->chunk_sectors;
8395 mddev->raid_disks += 1;
8396 mddev->delta_disks = 1;
8397 /* make sure it will be not marked as dirty */
8398 mddev->recovery_cp = MaxSector;
8400 return setup_conf(mddev);
8403 static void *raid5_takeover_raid1(struct mddev *mddev)
8405 int chunksect;
8406 void *ret;
8408 if (mddev->raid_disks != 2 ||
8409 mddev->degraded > 1)
8410 return ERR_PTR(-EINVAL);
8412 /* Should check if there are write-behind devices? */
8414 chunksect = 64*2; /* 64K by default */
8416 /* The array must be an exact multiple of chunksize */
8417 while (chunksect && (mddev->array_sectors & (chunksect-1)))
8418 chunksect >>= 1;
8420 if ((chunksect<<9) < RAID5_STRIPE_SIZE((struct r5conf *)mddev->private))
8421 /* array size does not allow a suitable chunk size */
8422 return ERR_PTR(-EINVAL);
8424 mddev->new_level = 5;
8425 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
8426 mddev->new_chunk_sectors = chunksect;
8428 ret = setup_conf(mddev);
8429 if (!IS_ERR(ret))
8430 mddev_clear_unsupported_flags(mddev,
8431 UNSUPPORTED_MDDEV_FLAGS);
8432 return ret;
8435 static void *raid5_takeover_raid6(struct mddev *mddev)
8437 int new_layout;
8439 switch (mddev->layout) {
8440 case ALGORITHM_LEFT_ASYMMETRIC_6:
8441 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
8442 break;
8443 case ALGORITHM_RIGHT_ASYMMETRIC_6:
8444 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
8445 break;
8446 case ALGORITHM_LEFT_SYMMETRIC_6:
8447 new_layout = ALGORITHM_LEFT_SYMMETRIC;
8448 break;
8449 case ALGORITHM_RIGHT_SYMMETRIC_6:
8450 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
8451 break;
8452 case ALGORITHM_PARITY_0_6:
8453 new_layout = ALGORITHM_PARITY_0;
8454 break;
8455 case ALGORITHM_PARITY_N:
8456 new_layout = ALGORITHM_PARITY_N;
8457 break;
8458 default:
8459 return ERR_PTR(-EINVAL);
8461 mddev->new_level = 5;
8462 mddev->new_layout = new_layout;
8463 mddev->delta_disks = -1;
8464 mddev->raid_disks -= 1;
8465 return setup_conf(mddev);
8468 static int raid5_check_reshape(struct mddev *mddev)
8470 /* For a 2-drive array, the layout and chunk size can be changed
8471 * immediately as not restriping is needed.
8472 * For larger arrays we record the new value - after validation
8473 * to be used by a reshape pass.
8475 struct r5conf *conf = mddev->private;
8476 int new_chunk = mddev->new_chunk_sectors;
8478 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
8479 return -EINVAL;
8480 if (new_chunk > 0) {
8481 if (!is_power_of_2(new_chunk))
8482 return -EINVAL;
8483 if (new_chunk < (PAGE_SIZE>>9))
8484 return -EINVAL;
8485 if (mddev->array_sectors & (new_chunk-1))
8486 /* not factor of array size */
8487 return -EINVAL;
8490 /* They look valid */
8492 if (mddev->raid_disks == 2) {
8493 /* can make the change immediately */
8494 if (mddev->new_layout >= 0) {
8495 conf->algorithm = mddev->new_layout;
8496 mddev->layout = mddev->new_layout;
8498 if (new_chunk > 0) {
8499 conf->chunk_sectors = new_chunk ;
8500 mddev->chunk_sectors = new_chunk;
8502 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8503 md_wakeup_thread(mddev->thread);
8505 return check_reshape(mddev);
8508 static int raid6_check_reshape(struct mddev *mddev)
8510 int new_chunk = mddev->new_chunk_sectors;
8512 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
8513 return -EINVAL;
8514 if (new_chunk > 0) {
8515 if (!is_power_of_2(new_chunk))
8516 return -EINVAL;
8517 if (new_chunk < (PAGE_SIZE >> 9))
8518 return -EINVAL;
8519 if (mddev->array_sectors & (new_chunk-1))
8520 /* not factor of array size */
8521 return -EINVAL;
8524 /* They look valid */
8525 return check_reshape(mddev);
8528 static void *raid5_takeover(struct mddev *mddev)
8530 /* raid5 can take over:
8531 * raid0 - if there is only one strip zone - make it a raid4 layout
8532 * raid1 - if there are two drives. We need to know the chunk size
8533 * raid4 - trivial - just use a raid4 layout.
8534 * raid6 - Providing it is a *_6 layout
8536 if (mddev->level == 0)
8537 return raid45_takeover_raid0(mddev, 5);
8538 if (mddev->level == 1)
8539 return raid5_takeover_raid1(mddev);
8540 if (mddev->level == 4) {
8541 mddev->new_layout = ALGORITHM_PARITY_N;
8542 mddev->new_level = 5;
8543 return setup_conf(mddev);
8545 if (mddev->level == 6)
8546 return raid5_takeover_raid6(mddev);
8548 return ERR_PTR(-EINVAL);
8551 static void *raid4_takeover(struct mddev *mddev)
8553 /* raid4 can take over:
8554 * raid0 - if there is only one strip zone
8555 * raid5 - if layout is right
8557 if (mddev->level == 0)
8558 return raid45_takeover_raid0(mddev, 4);
8559 if (mddev->level == 5 &&
8560 mddev->layout == ALGORITHM_PARITY_N) {
8561 mddev->new_layout = 0;
8562 mddev->new_level = 4;
8563 return setup_conf(mddev);
8565 return ERR_PTR(-EINVAL);
8568 static struct md_personality raid5_personality;
8570 static void *raid6_takeover(struct mddev *mddev)
8572 /* Currently can only take over a raid5. We map the
8573 * personality to an equivalent raid6 personality
8574 * with the Q block at the end.
8576 int new_layout;
8578 if (mddev->pers != &raid5_personality)
8579 return ERR_PTR(-EINVAL);
8580 if (mddev->degraded > 1)
8581 return ERR_PTR(-EINVAL);
8582 if (mddev->raid_disks > 253)
8583 return ERR_PTR(-EINVAL);
8584 if (mddev->raid_disks < 3)
8585 return ERR_PTR(-EINVAL);
8587 switch (mddev->layout) {
8588 case ALGORITHM_LEFT_ASYMMETRIC:
8589 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
8590 break;
8591 case ALGORITHM_RIGHT_ASYMMETRIC:
8592 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
8593 break;
8594 case ALGORITHM_LEFT_SYMMETRIC:
8595 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
8596 break;
8597 case ALGORITHM_RIGHT_SYMMETRIC:
8598 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
8599 break;
8600 case ALGORITHM_PARITY_0:
8601 new_layout = ALGORITHM_PARITY_0_6;
8602 break;
8603 case ALGORITHM_PARITY_N:
8604 new_layout = ALGORITHM_PARITY_N;
8605 break;
8606 default:
8607 return ERR_PTR(-EINVAL);
8609 mddev->new_level = 6;
8610 mddev->new_layout = new_layout;
8611 mddev->delta_disks = 1;
8612 mddev->raid_disks += 1;
8613 return setup_conf(mddev);
8616 static int raid5_change_consistency_policy(struct mddev *mddev, const char *buf)
8618 struct r5conf *conf;
8619 int err;
8621 err = mddev_lock(mddev);
8622 if (err)
8623 return err;
8624 conf = mddev->private;
8625 if (!conf) {
8626 mddev_unlock(mddev);
8627 return -ENODEV;
8630 if (strncmp(buf, "ppl", 3) == 0) {
8631 /* ppl only works with RAID 5 */
8632 if (!raid5_has_ppl(conf) && conf->level == 5) {
8633 err = log_init(conf, NULL, true);
8634 if (!err) {
8635 err = resize_stripes(conf, conf->pool_size);
8636 if (err)
8637 log_exit(conf);
8639 } else
8640 err = -EINVAL;
8641 } else if (strncmp(buf, "resync", 6) == 0) {
8642 if (raid5_has_ppl(conf)) {
8643 mddev_suspend(mddev);
8644 log_exit(conf);
8645 mddev_resume(mddev);
8646 err = resize_stripes(conf, conf->pool_size);
8647 } else if (test_bit(MD_HAS_JOURNAL, &conf->mddev->flags) &&
8648 r5l_log_disk_error(conf)) {
8649 bool journal_dev_exists = false;
8650 struct md_rdev *rdev;
8652 rdev_for_each(rdev, mddev)
8653 if (test_bit(Journal, &rdev->flags)) {
8654 journal_dev_exists = true;
8655 break;
8658 if (!journal_dev_exists) {
8659 mddev_suspend(mddev);
8660 clear_bit(MD_HAS_JOURNAL, &mddev->flags);
8661 mddev_resume(mddev);
8662 } else /* need remove journal device first */
8663 err = -EBUSY;
8664 } else
8665 err = -EINVAL;
8666 } else {
8667 err = -EINVAL;
8670 if (!err)
8671 md_update_sb(mddev, 1);
8673 mddev_unlock(mddev);
8675 return err;
8678 static int raid5_start(struct mddev *mddev)
8680 struct r5conf *conf = mddev->private;
8682 return r5l_start(conf->log);
8685 static struct md_personality raid6_personality =
8687 .name = "raid6",
8688 .level = 6,
8689 .owner = THIS_MODULE,
8690 .make_request = raid5_make_request,
8691 .run = raid5_run,
8692 .start = raid5_start,
8693 .free = raid5_free,
8694 .status = raid5_status,
8695 .error_handler = raid5_error,
8696 .hot_add_disk = raid5_add_disk,
8697 .hot_remove_disk= raid5_remove_disk,
8698 .spare_active = raid5_spare_active,
8699 .sync_request = raid5_sync_request,
8700 .resize = raid5_resize,
8701 .size = raid5_size,
8702 .check_reshape = raid6_check_reshape,
8703 .start_reshape = raid5_start_reshape,
8704 .finish_reshape = raid5_finish_reshape,
8705 .quiesce = raid5_quiesce,
8706 .takeover = raid6_takeover,
8707 .change_consistency_policy = raid5_change_consistency_policy,
8709 static struct md_personality raid5_personality =
8711 .name = "raid5",
8712 .level = 5,
8713 .owner = THIS_MODULE,
8714 .make_request = raid5_make_request,
8715 .run = raid5_run,
8716 .start = raid5_start,
8717 .free = raid5_free,
8718 .status = raid5_status,
8719 .error_handler = raid5_error,
8720 .hot_add_disk = raid5_add_disk,
8721 .hot_remove_disk= raid5_remove_disk,
8722 .spare_active = raid5_spare_active,
8723 .sync_request = raid5_sync_request,
8724 .resize = raid5_resize,
8725 .size = raid5_size,
8726 .check_reshape = raid5_check_reshape,
8727 .start_reshape = raid5_start_reshape,
8728 .finish_reshape = raid5_finish_reshape,
8729 .quiesce = raid5_quiesce,
8730 .takeover = raid5_takeover,
8731 .change_consistency_policy = raid5_change_consistency_policy,
8734 static struct md_personality raid4_personality =
8736 .name = "raid4",
8737 .level = 4,
8738 .owner = THIS_MODULE,
8739 .make_request = raid5_make_request,
8740 .run = raid5_run,
8741 .start = raid5_start,
8742 .free = raid5_free,
8743 .status = raid5_status,
8744 .error_handler = raid5_error,
8745 .hot_add_disk = raid5_add_disk,
8746 .hot_remove_disk= raid5_remove_disk,
8747 .spare_active = raid5_spare_active,
8748 .sync_request = raid5_sync_request,
8749 .resize = raid5_resize,
8750 .size = raid5_size,
8751 .check_reshape = raid5_check_reshape,
8752 .start_reshape = raid5_start_reshape,
8753 .finish_reshape = raid5_finish_reshape,
8754 .quiesce = raid5_quiesce,
8755 .takeover = raid4_takeover,
8756 .change_consistency_policy = raid5_change_consistency_policy,
8759 static int __init raid5_init(void)
8761 int ret;
8763 raid5_wq = alloc_workqueue("raid5wq",
8764 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
8765 if (!raid5_wq)
8766 return -ENOMEM;
8768 ret = cpuhp_setup_state_multi(CPUHP_MD_RAID5_PREPARE,
8769 "md/raid5:prepare",
8770 raid456_cpu_up_prepare,
8771 raid456_cpu_dead);
8772 if (ret) {
8773 destroy_workqueue(raid5_wq);
8774 return ret;
8776 register_md_personality(&raid6_personality);
8777 register_md_personality(&raid5_personality);
8778 register_md_personality(&raid4_personality);
8779 return 0;
8782 static void raid5_exit(void)
8784 unregister_md_personality(&raid6_personality);
8785 unregister_md_personality(&raid5_personality);
8786 unregister_md_personality(&raid4_personality);
8787 cpuhp_remove_multi_state(CPUHP_MD_RAID5_PREPARE);
8788 destroy_workqueue(raid5_wq);
8791 module_init(raid5_init);
8792 module_exit(raid5_exit);
8793 MODULE_LICENSE("GPL");
8794 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
8795 MODULE_ALIAS("md-personality-4"); /* RAID5 */
8796 MODULE_ALIAS("md-raid5");
8797 MODULE_ALIAS("md-raid4");
8798 MODULE_ALIAS("md-level-5");
8799 MODULE_ALIAS("md-level-4");
8800 MODULE_ALIAS("md-personality-8"); /* RAID6 */
8801 MODULE_ALIAS("md-raid6");
8802 MODULE_ALIAS("md-level-6");
8804 /* This used to be two separate modules, they were: */
8805 MODULE_ALIAS("raid5");
8806 MODULE_ALIAS("raid6");