dm thin metadata: fix __udivdi3 undefined on 32-bit
[linux/fpc-iii.git] / drivers / md / raid5.c
blob0841d8f10a58ce1c081867d7cd7932758a89ab0c
1 /*
2 * raid5.c : Multiple Devices driver for Linux
3 * Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
4 * Copyright (C) 1999, 2000 Ingo Molnar
5 * Copyright (C) 2002, 2003 H. Peter Anvin
7 * RAID-4/5/6 management functions.
8 * Thanks to Penguin Computing for making the RAID-6 development possible
9 * by donating a test server!
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2, or (at your option)
14 * any later version.
16 * You should have received a copy of the GNU General Public License
17 * (for example /usr/src/linux/COPYING); if not, write to the Free
18 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 * BITMAP UNPLUGGING:
24 * The sequencing for updating the bitmap reliably is a little
25 * subtle (and I got it wrong the first time) so it deserves some
26 * explanation.
28 * We group bitmap updates into batches. Each batch has a number.
29 * We may write out several batches at once, but that isn't very important.
30 * conf->seq_write is the number of the last batch successfully written.
31 * conf->seq_flush is the number of the last batch that was closed to
32 * new additions.
33 * When we discover that we will need to write to any block in a stripe
34 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
35 * the number of the batch it will be in. This is seq_flush+1.
36 * When we are ready to do a write, if that batch hasn't been written yet,
37 * we plug the array and queue the stripe for later.
38 * When an unplug happens, we increment bm_flush, thus closing the current
39 * batch.
40 * When we notice that bm_flush > bm_write, we write out all pending updates
41 * to the bitmap, and advance bm_write to where bm_flush was.
42 * This may occasionally write a bit out twice, but is sure never to
43 * miss any bits.
46 #include <linux/blkdev.h>
47 #include <linux/kthread.h>
48 #include <linux/raid/pq.h>
49 #include <linux/async_tx.h>
50 #include <linux/module.h>
51 #include <linux/async.h>
52 #include <linux/seq_file.h>
53 #include <linux/cpu.h>
54 #include <linux/slab.h>
55 #include <linux/ratelimit.h>
56 #include <linux/nodemask.h>
57 #include <linux/flex_array.h>
58 #include <trace/events/block.h>
60 #include "md.h"
61 #include "raid5.h"
62 #include "raid0.h"
63 #include "bitmap.h"
65 #define cpu_to_group(cpu) cpu_to_node(cpu)
66 #define ANY_GROUP NUMA_NO_NODE
68 static bool devices_handle_discard_safely = false;
69 module_param(devices_handle_discard_safely, bool, 0644);
70 MODULE_PARM_DESC(devices_handle_discard_safely,
71 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
72 static struct workqueue_struct *raid5_wq;
74 * Stripe cache
77 #define NR_STRIPES 256
78 #define STRIPE_SIZE PAGE_SIZE
79 #define STRIPE_SHIFT (PAGE_SHIFT - 9)
80 #define STRIPE_SECTORS (STRIPE_SIZE>>9)
81 #define IO_THRESHOLD 1
82 #define BYPASS_THRESHOLD 1
83 #define NR_HASH (PAGE_SIZE / sizeof(struct hlist_head))
84 #define HASH_MASK (NR_HASH - 1)
85 #define MAX_STRIPE_BATCH 8
87 static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
89 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
90 return &conf->stripe_hashtbl[hash];
93 static inline int stripe_hash_locks_hash(sector_t sect)
95 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
98 static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
100 spin_lock_irq(conf->hash_locks + hash);
101 spin_lock(&conf->device_lock);
104 static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
106 spin_unlock(&conf->device_lock);
107 spin_unlock_irq(conf->hash_locks + hash);
110 static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
112 int i;
113 spin_lock_irq(conf->hash_locks);
114 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
115 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
116 spin_lock(&conf->device_lock);
119 static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
121 int i;
122 spin_unlock(&conf->device_lock);
123 for (i = NR_STRIPE_HASH_LOCKS - 1; i; i--)
124 spin_unlock(conf->hash_locks + i);
125 spin_unlock_irq(conf->hash_locks);
128 /* bio's attached to a stripe+device for I/O are linked together in bi_sector
129 * order without overlap. There may be several bio's per stripe+device, and
130 * a bio could span several devices.
131 * When walking this list for a particular stripe+device, we must never proceed
132 * beyond a bio that extends past this device, as the next bio might no longer
133 * be valid.
134 * This function is used to determine the 'next' bio in the list, given the sector
135 * of the current stripe+device
137 static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
139 int sectors = bio_sectors(bio);
140 if (bio->bi_iter.bi_sector + sectors < sector + STRIPE_SECTORS)
141 return bio->bi_next;
142 else
143 return NULL;
147 * We maintain a biased count of active stripes in the bottom 16 bits of
148 * bi_phys_segments, and a count of processed stripes in the upper 16 bits
150 static inline int raid5_bi_processed_stripes(struct bio *bio)
152 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
153 return (atomic_read(segments) >> 16) & 0xffff;
156 static inline int raid5_dec_bi_active_stripes(struct bio *bio)
158 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
159 return atomic_sub_return(1, segments) & 0xffff;
162 static inline void raid5_inc_bi_active_stripes(struct bio *bio)
164 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
165 atomic_inc(segments);
168 static inline void raid5_set_bi_processed_stripes(struct bio *bio,
169 unsigned int cnt)
171 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
172 int old, new;
174 do {
175 old = atomic_read(segments);
176 new = (old & 0xffff) | (cnt << 16);
177 } while (atomic_cmpxchg(segments, old, new) != old);
180 static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
182 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
183 atomic_set(segments, cnt);
186 /* Find first data disk in a raid6 stripe */
187 static inline int raid6_d0(struct stripe_head *sh)
189 if (sh->ddf_layout)
190 /* ddf always start from first device */
191 return 0;
192 /* md starts just after Q block */
193 if (sh->qd_idx == sh->disks - 1)
194 return 0;
195 else
196 return sh->qd_idx + 1;
198 static inline int raid6_next_disk(int disk, int raid_disks)
200 disk++;
201 return (disk < raid_disks) ? disk : 0;
204 /* When walking through the disks in a raid5, starting at raid6_d0,
205 * We need to map each disk to a 'slot', where the data disks are slot
206 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
207 * is raid_disks-1. This help does that mapping.
209 static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
210 int *count, int syndrome_disks)
212 int slot = *count;
214 if (sh->ddf_layout)
215 (*count)++;
216 if (idx == sh->pd_idx)
217 return syndrome_disks;
218 if (idx == sh->qd_idx)
219 return syndrome_disks + 1;
220 if (!sh->ddf_layout)
221 (*count)++;
222 return slot;
225 static void return_io(struct bio_list *return_bi)
227 struct bio *bi;
228 while ((bi = bio_list_pop(return_bi)) != NULL) {
229 bi->bi_iter.bi_size = 0;
230 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
231 bi, 0);
232 bio_endio(bi);
236 static void print_raid5_conf (struct r5conf *conf);
238 static int stripe_operations_active(struct stripe_head *sh)
240 return sh->check_state || sh->reconstruct_state ||
241 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
242 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
245 static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
247 struct r5conf *conf = sh->raid_conf;
248 struct r5worker_group *group;
249 int thread_cnt;
250 int i, cpu = sh->cpu;
252 if (!cpu_online(cpu)) {
253 cpu = cpumask_any(cpu_online_mask);
254 sh->cpu = cpu;
257 if (list_empty(&sh->lru)) {
258 struct r5worker_group *group;
259 group = conf->worker_groups + cpu_to_group(cpu);
260 list_add_tail(&sh->lru, &group->handle_list);
261 group->stripes_cnt++;
262 sh->group = group;
265 if (conf->worker_cnt_per_group == 0) {
266 md_wakeup_thread(conf->mddev->thread);
267 return;
270 group = conf->worker_groups + cpu_to_group(sh->cpu);
272 group->workers[0].working = true;
273 /* at least one worker should run to avoid race */
274 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
276 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
277 /* wakeup more workers */
278 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
279 if (group->workers[i].working == false) {
280 group->workers[i].working = true;
281 queue_work_on(sh->cpu, raid5_wq,
282 &group->workers[i].work);
283 thread_cnt--;
288 static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
289 struct list_head *temp_inactive_list)
291 BUG_ON(!list_empty(&sh->lru));
292 BUG_ON(atomic_read(&conf->active_stripes)==0);
293 if (test_bit(STRIPE_HANDLE, &sh->state)) {
294 if (test_bit(STRIPE_DELAYED, &sh->state) &&
295 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
296 list_add_tail(&sh->lru, &conf->delayed_list);
297 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
298 sh->bm_seq - conf->seq_write > 0)
299 list_add_tail(&sh->lru, &conf->bitmap_list);
300 else {
301 clear_bit(STRIPE_DELAYED, &sh->state);
302 clear_bit(STRIPE_BIT_DELAY, &sh->state);
303 if (conf->worker_cnt_per_group == 0) {
304 list_add_tail(&sh->lru, &conf->handle_list);
305 } else {
306 raid5_wakeup_stripe_thread(sh);
307 return;
310 md_wakeup_thread(conf->mddev->thread);
311 } else {
312 BUG_ON(stripe_operations_active(sh));
313 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
314 if (atomic_dec_return(&conf->preread_active_stripes)
315 < IO_THRESHOLD)
316 md_wakeup_thread(conf->mddev->thread);
317 atomic_dec(&conf->active_stripes);
318 if (!test_bit(STRIPE_EXPANDING, &sh->state))
319 list_add_tail(&sh->lru, temp_inactive_list);
323 static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
324 struct list_head *temp_inactive_list)
326 if (atomic_dec_and_test(&sh->count))
327 do_release_stripe(conf, sh, temp_inactive_list);
331 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
333 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
334 * given time. Adding stripes only takes device lock, while deleting stripes
335 * only takes hash lock.
337 static void release_inactive_stripe_list(struct r5conf *conf,
338 struct list_head *temp_inactive_list,
339 int hash)
341 int size;
342 bool do_wakeup = false;
343 unsigned long flags;
345 if (hash == NR_STRIPE_HASH_LOCKS) {
346 size = NR_STRIPE_HASH_LOCKS;
347 hash = NR_STRIPE_HASH_LOCKS - 1;
348 } else
349 size = 1;
350 while (size) {
351 struct list_head *list = &temp_inactive_list[size - 1];
354 * We don't hold any lock here yet, raid5_get_active_stripe() might
355 * remove stripes from the list
357 if (!list_empty_careful(list)) {
358 spin_lock_irqsave(conf->hash_locks + hash, flags);
359 if (list_empty(conf->inactive_list + hash) &&
360 !list_empty(list))
361 atomic_dec(&conf->empty_inactive_list_nr);
362 list_splice_tail_init(list, conf->inactive_list + hash);
363 do_wakeup = true;
364 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
366 size--;
367 hash--;
370 if (do_wakeup) {
371 wake_up(&conf->wait_for_stripe);
372 if (atomic_read(&conf->active_stripes) == 0)
373 wake_up(&conf->wait_for_quiescent);
374 if (conf->retry_read_aligned)
375 md_wakeup_thread(conf->mddev->thread);
379 /* should hold conf->device_lock already */
380 static int release_stripe_list(struct r5conf *conf,
381 struct list_head *temp_inactive_list)
383 struct stripe_head *sh;
384 int count = 0;
385 struct llist_node *head;
387 head = llist_del_all(&conf->released_stripes);
388 head = llist_reverse_order(head);
389 while (head) {
390 int hash;
392 sh = llist_entry(head, struct stripe_head, release_list);
393 head = llist_next(head);
394 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
395 smp_mb();
396 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
398 * Don't worry the bit is set here, because if the bit is set
399 * again, the count is always > 1. This is true for
400 * STRIPE_ON_UNPLUG_LIST bit too.
402 hash = sh->hash_lock_index;
403 __release_stripe(conf, sh, &temp_inactive_list[hash]);
404 count++;
407 return count;
410 void raid5_release_stripe(struct stripe_head *sh)
412 struct r5conf *conf = sh->raid_conf;
413 unsigned long flags;
414 struct list_head list;
415 int hash;
416 bool wakeup;
418 /* Avoid release_list until the last reference.
420 if (atomic_add_unless(&sh->count, -1, 1))
421 return;
423 if (unlikely(!conf->mddev->thread) ||
424 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
425 goto slow_path;
426 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
427 if (wakeup)
428 md_wakeup_thread(conf->mddev->thread);
429 return;
430 slow_path:
431 local_irq_save(flags);
432 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
433 if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
434 INIT_LIST_HEAD(&list);
435 hash = sh->hash_lock_index;
436 do_release_stripe(conf, sh, &list);
437 spin_unlock(&conf->device_lock);
438 release_inactive_stripe_list(conf, &list, hash);
440 local_irq_restore(flags);
443 static inline void remove_hash(struct stripe_head *sh)
445 pr_debug("remove_hash(), stripe %llu\n",
446 (unsigned long long)sh->sector);
448 hlist_del_init(&sh->hash);
451 static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
453 struct hlist_head *hp = stripe_hash(conf, sh->sector);
455 pr_debug("insert_hash(), stripe %llu\n",
456 (unsigned long long)sh->sector);
458 hlist_add_head(&sh->hash, hp);
461 /* find an idle stripe, make sure it is unhashed, and return it. */
462 static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
464 struct stripe_head *sh = NULL;
465 struct list_head *first;
467 if (list_empty(conf->inactive_list + hash))
468 goto out;
469 first = (conf->inactive_list + hash)->next;
470 sh = list_entry(first, struct stripe_head, lru);
471 list_del_init(first);
472 remove_hash(sh);
473 atomic_inc(&conf->active_stripes);
474 BUG_ON(hash != sh->hash_lock_index);
475 if (list_empty(conf->inactive_list + hash))
476 atomic_inc(&conf->empty_inactive_list_nr);
477 out:
478 return sh;
481 static void shrink_buffers(struct stripe_head *sh)
483 struct page *p;
484 int i;
485 int num = sh->raid_conf->pool_size;
487 for (i = 0; i < num ; i++) {
488 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
489 p = sh->dev[i].page;
490 if (!p)
491 continue;
492 sh->dev[i].page = NULL;
493 put_page(p);
497 static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
499 int i;
500 int num = sh->raid_conf->pool_size;
502 for (i = 0; i < num; i++) {
503 struct page *page;
505 if (!(page = alloc_page(gfp))) {
506 return 1;
508 sh->dev[i].page = page;
509 sh->dev[i].orig_page = page;
511 return 0;
514 static void raid5_build_block(struct stripe_head *sh, int i, int previous);
515 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
516 struct stripe_head *sh);
518 static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
520 struct r5conf *conf = sh->raid_conf;
521 int i, seq;
523 BUG_ON(atomic_read(&sh->count) != 0);
524 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
525 BUG_ON(stripe_operations_active(sh));
526 BUG_ON(sh->batch_head);
528 pr_debug("init_stripe called, stripe %llu\n",
529 (unsigned long long)sector);
530 retry:
531 seq = read_seqcount_begin(&conf->gen_lock);
532 sh->generation = conf->generation - previous;
533 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
534 sh->sector = sector;
535 stripe_set_idx(sector, conf, previous, sh);
536 sh->state = 0;
538 for (i = sh->disks; i--; ) {
539 struct r5dev *dev = &sh->dev[i];
541 if (dev->toread || dev->read || dev->towrite || dev->written ||
542 test_bit(R5_LOCKED, &dev->flags)) {
543 printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
544 (unsigned long long)sh->sector, i, dev->toread,
545 dev->read, dev->towrite, dev->written,
546 test_bit(R5_LOCKED, &dev->flags));
547 WARN_ON(1);
549 dev->flags = 0;
550 raid5_build_block(sh, i, previous);
552 if (read_seqcount_retry(&conf->gen_lock, seq))
553 goto retry;
554 sh->overwrite_disks = 0;
555 insert_hash(conf, sh);
556 sh->cpu = smp_processor_id();
557 set_bit(STRIPE_BATCH_READY, &sh->state);
560 static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
561 short generation)
563 struct stripe_head *sh;
565 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
566 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
567 if (sh->sector == sector && sh->generation == generation)
568 return sh;
569 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
570 return NULL;
574 * Need to check if array has failed when deciding whether to:
575 * - start an array
576 * - remove non-faulty devices
577 * - add a spare
578 * - allow a reshape
579 * This determination is simple when no reshape is happening.
580 * However if there is a reshape, we need to carefully check
581 * both the before and after sections.
582 * This is because some failed devices may only affect one
583 * of the two sections, and some non-in_sync devices may
584 * be insync in the section most affected by failed devices.
586 static int calc_degraded(struct r5conf *conf)
588 int degraded, degraded2;
589 int i;
591 rcu_read_lock();
592 degraded = 0;
593 for (i = 0; i < conf->previous_raid_disks; i++) {
594 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
595 if (rdev && test_bit(Faulty, &rdev->flags))
596 rdev = rcu_dereference(conf->disks[i].replacement);
597 if (!rdev || test_bit(Faulty, &rdev->flags))
598 degraded++;
599 else if (test_bit(In_sync, &rdev->flags))
601 else
602 /* not in-sync or faulty.
603 * If the reshape increases the number of devices,
604 * this is being recovered by the reshape, so
605 * this 'previous' section is not in_sync.
606 * If the number of devices is being reduced however,
607 * the device can only be part of the array if
608 * we are reverting a reshape, so this section will
609 * be in-sync.
611 if (conf->raid_disks >= conf->previous_raid_disks)
612 degraded++;
614 rcu_read_unlock();
615 if (conf->raid_disks == conf->previous_raid_disks)
616 return degraded;
617 rcu_read_lock();
618 degraded2 = 0;
619 for (i = 0; i < conf->raid_disks; i++) {
620 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
621 if (rdev && test_bit(Faulty, &rdev->flags))
622 rdev = rcu_dereference(conf->disks[i].replacement);
623 if (!rdev || test_bit(Faulty, &rdev->flags))
624 degraded2++;
625 else if (test_bit(In_sync, &rdev->flags))
627 else
628 /* not in-sync or faulty.
629 * If reshape increases the number of devices, this
630 * section has already been recovered, else it
631 * almost certainly hasn't.
633 if (conf->raid_disks <= conf->previous_raid_disks)
634 degraded2++;
636 rcu_read_unlock();
637 if (degraded2 > degraded)
638 return degraded2;
639 return degraded;
642 static int has_failed(struct r5conf *conf)
644 int degraded;
646 if (conf->mddev->reshape_position == MaxSector)
647 return conf->mddev->degraded > conf->max_degraded;
649 degraded = calc_degraded(conf);
650 if (degraded > conf->max_degraded)
651 return 1;
652 return 0;
655 struct stripe_head *
656 raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
657 int previous, int noblock, int noquiesce)
659 struct stripe_head *sh;
660 int hash = stripe_hash_locks_hash(sector);
662 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
664 spin_lock_irq(conf->hash_locks + hash);
666 do {
667 wait_event_lock_irq(conf->wait_for_quiescent,
668 conf->quiesce == 0 || noquiesce,
669 *(conf->hash_locks + hash));
670 sh = __find_stripe(conf, sector, conf->generation - previous);
671 if (!sh) {
672 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
673 sh = get_free_stripe(conf, hash);
674 if (!sh && !test_bit(R5_DID_ALLOC,
675 &conf->cache_state))
676 set_bit(R5_ALLOC_MORE,
677 &conf->cache_state);
679 if (noblock && sh == NULL)
680 break;
681 if (!sh) {
682 set_bit(R5_INACTIVE_BLOCKED,
683 &conf->cache_state);
684 wait_event_lock_irq(
685 conf->wait_for_stripe,
686 !list_empty(conf->inactive_list + hash) &&
687 (atomic_read(&conf->active_stripes)
688 < (conf->max_nr_stripes * 3 / 4)
689 || !test_bit(R5_INACTIVE_BLOCKED,
690 &conf->cache_state)),
691 *(conf->hash_locks + hash));
692 clear_bit(R5_INACTIVE_BLOCKED,
693 &conf->cache_state);
694 } else {
695 init_stripe(sh, sector, previous);
696 atomic_inc(&sh->count);
698 } else if (!atomic_inc_not_zero(&sh->count)) {
699 spin_lock(&conf->device_lock);
700 if (!atomic_read(&sh->count)) {
701 if (!test_bit(STRIPE_HANDLE, &sh->state))
702 atomic_inc(&conf->active_stripes);
703 BUG_ON(list_empty(&sh->lru) &&
704 !test_bit(STRIPE_EXPANDING, &sh->state));
705 list_del_init(&sh->lru);
706 if (sh->group) {
707 sh->group->stripes_cnt--;
708 sh->group = NULL;
711 atomic_inc(&sh->count);
712 spin_unlock(&conf->device_lock);
714 } while (sh == NULL);
716 spin_unlock_irq(conf->hash_locks + hash);
717 return sh;
720 static bool is_full_stripe_write(struct stripe_head *sh)
722 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
723 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
726 static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
728 if (sh1 > sh2) {
729 spin_lock_irq(&sh2->stripe_lock);
730 spin_lock_nested(&sh1->stripe_lock, 1);
731 } else {
732 spin_lock_irq(&sh1->stripe_lock);
733 spin_lock_nested(&sh2->stripe_lock, 1);
737 static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
739 spin_unlock(&sh1->stripe_lock);
740 spin_unlock_irq(&sh2->stripe_lock);
743 /* Only freshly new full stripe normal write stripe can be added to a batch list */
744 static bool stripe_can_batch(struct stripe_head *sh)
746 struct r5conf *conf = sh->raid_conf;
748 if (conf->log)
749 return false;
750 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
751 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
752 is_full_stripe_write(sh);
755 /* we only do back search */
756 static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
758 struct stripe_head *head;
759 sector_t head_sector, tmp_sec;
760 int hash;
761 int dd_idx;
763 if (!stripe_can_batch(sh))
764 return;
765 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
766 tmp_sec = sh->sector;
767 if (!sector_div(tmp_sec, conf->chunk_sectors))
768 return;
769 head_sector = sh->sector - STRIPE_SECTORS;
771 hash = stripe_hash_locks_hash(head_sector);
772 spin_lock_irq(conf->hash_locks + hash);
773 head = __find_stripe(conf, head_sector, conf->generation);
774 if (head && !atomic_inc_not_zero(&head->count)) {
775 spin_lock(&conf->device_lock);
776 if (!atomic_read(&head->count)) {
777 if (!test_bit(STRIPE_HANDLE, &head->state))
778 atomic_inc(&conf->active_stripes);
779 BUG_ON(list_empty(&head->lru) &&
780 !test_bit(STRIPE_EXPANDING, &head->state));
781 list_del_init(&head->lru);
782 if (head->group) {
783 head->group->stripes_cnt--;
784 head->group = NULL;
787 atomic_inc(&head->count);
788 spin_unlock(&conf->device_lock);
790 spin_unlock_irq(conf->hash_locks + hash);
792 if (!head)
793 return;
794 if (!stripe_can_batch(head))
795 goto out;
797 lock_two_stripes(head, sh);
798 /* clear_batch_ready clear the flag */
799 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
800 goto unlock_out;
802 if (sh->batch_head)
803 goto unlock_out;
805 dd_idx = 0;
806 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
807 dd_idx++;
808 if (head->dev[dd_idx].towrite->bi_rw != sh->dev[dd_idx].towrite->bi_rw)
809 goto unlock_out;
811 if (head->batch_head) {
812 spin_lock(&head->batch_head->batch_lock);
813 /* This batch list is already running */
814 if (!stripe_can_batch(head)) {
815 spin_unlock(&head->batch_head->batch_lock);
816 goto unlock_out;
819 * We must assign batch_head of this stripe within the
820 * batch_lock, otherwise clear_batch_ready of batch head
821 * stripe could clear BATCH_READY bit of this stripe and
822 * this stripe->batch_head doesn't get assigned, which
823 * could confuse clear_batch_ready for this stripe
825 sh->batch_head = head->batch_head;
828 * at this point, head's BATCH_READY could be cleared, but we
829 * can still add the stripe to batch list
831 list_add(&sh->batch_list, &head->batch_list);
832 spin_unlock(&head->batch_head->batch_lock);
833 } else {
834 head->batch_head = head;
835 sh->batch_head = head->batch_head;
836 spin_lock(&head->batch_lock);
837 list_add_tail(&sh->batch_list, &head->batch_list);
838 spin_unlock(&head->batch_lock);
841 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
842 if (atomic_dec_return(&conf->preread_active_stripes)
843 < IO_THRESHOLD)
844 md_wakeup_thread(conf->mddev->thread);
846 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
847 int seq = sh->bm_seq;
848 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
849 sh->batch_head->bm_seq > seq)
850 seq = sh->batch_head->bm_seq;
851 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
852 sh->batch_head->bm_seq = seq;
855 atomic_inc(&sh->count);
856 unlock_out:
857 unlock_two_stripes(head, sh);
858 out:
859 raid5_release_stripe(head);
862 /* Determine if 'data_offset' or 'new_data_offset' should be used
863 * in this stripe_head.
865 static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
867 sector_t progress = conf->reshape_progress;
868 /* Need a memory barrier to make sure we see the value
869 * of conf->generation, or ->data_offset that was set before
870 * reshape_progress was updated.
872 smp_rmb();
873 if (progress == MaxSector)
874 return 0;
875 if (sh->generation == conf->generation - 1)
876 return 0;
877 /* We are in a reshape, and this is a new-generation stripe,
878 * so use new_data_offset.
880 return 1;
883 static void
884 raid5_end_read_request(struct bio *bi);
885 static void
886 raid5_end_write_request(struct bio *bi);
888 static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
890 struct r5conf *conf = sh->raid_conf;
891 int i, disks = sh->disks;
892 struct stripe_head *head_sh = sh;
894 might_sleep();
896 if (r5l_write_stripe(conf->log, sh) == 0)
897 return;
898 for (i = disks; i--; ) {
899 int rw;
900 int replace_only = 0;
901 struct bio *bi, *rbi;
902 struct md_rdev *rdev, *rrdev = NULL;
904 sh = head_sh;
905 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
906 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
907 rw = WRITE_FUA;
908 else
909 rw = WRITE;
910 if (test_bit(R5_Discard, &sh->dev[i].flags))
911 rw |= REQ_DISCARD;
912 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
913 rw = READ;
914 else if (test_and_clear_bit(R5_WantReplace,
915 &sh->dev[i].flags)) {
916 rw = WRITE;
917 replace_only = 1;
918 } else
919 continue;
920 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
921 rw |= REQ_SYNC;
923 again:
924 bi = &sh->dev[i].req;
925 rbi = &sh->dev[i].rreq; /* For writing to replacement */
927 rcu_read_lock();
928 rrdev = rcu_dereference(conf->disks[i].replacement);
929 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
930 rdev = rcu_dereference(conf->disks[i].rdev);
931 if (!rdev) {
932 rdev = rrdev;
933 rrdev = NULL;
935 if (rw & WRITE) {
936 if (replace_only)
937 rdev = NULL;
938 if (rdev == rrdev)
939 /* We raced and saw duplicates */
940 rrdev = NULL;
941 } else {
942 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
943 rdev = rrdev;
944 rrdev = NULL;
947 if (rdev && test_bit(Faulty, &rdev->flags))
948 rdev = NULL;
949 if (rdev)
950 atomic_inc(&rdev->nr_pending);
951 if (rrdev && test_bit(Faulty, &rrdev->flags))
952 rrdev = NULL;
953 if (rrdev)
954 atomic_inc(&rrdev->nr_pending);
955 rcu_read_unlock();
957 /* We have already checked bad blocks for reads. Now
958 * need to check for writes. We never accept write errors
959 * on the replacement, so we don't to check rrdev.
961 while ((rw & WRITE) && rdev &&
962 test_bit(WriteErrorSeen, &rdev->flags)) {
963 sector_t first_bad;
964 int bad_sectors;
965 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
966 &first_bad, &bad_sectors);
967 if (!bad)
968 break;
970 if (bad < 0) {
971 set_bit(BlockedBadBlocks, &rdev->flags);
972 if (!conf->mddev->external &&
973 conf->mddev->flags) {
974 /* It is very unlikely, but we might
975 * still need to write out the
976 * bad block log - better give it
977 * a chance*/
978 md_check_recovery(conf->mddev);
981 * Because md_wait_for_blocked_rdev
982 * will dec nr_pending, we must
983 * increment it first.
985 atomic_inc(&rdev->nr_pending);
986 md_wait_for_blocked_rdev(rdev, conf->mddev);
987 } else {
988 /* Acknowledged bad block - skip the write */
989 rdev_dec_pending(rdev, conf->mddev);
990 rdev = NULL;
994 if (rdev) {
995 if (s->syncing || s->expanding || s->expanded
996 || s->replacing)
997 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
999 set_bit(STRIPE_IO_STARTED, &sh->state);
1001 bio_reset(bi);
1002 bi->bi_bdev = rdev->bdev;
1003 bi->bi_rw = rw;
1004 bi->bi_end_io = (rw & WRITE)
1005 ? raid5_end_write_request
1006 : raid5_end_read_request;
1007 bi->bi_private = sh;
1009 pr_debug("%s: for %llu schedule op %ld on disc %d\n",
1010 __func__, (unsigned long long)sh->sector,
1011 bi->bi_rw, i);
1012 atomic_inc(&sh->count);
1013 if (sh != head_sh)
1014 atomic_inc(&head_sh->count);
1015 if (use_new_offset(conf, sh))
1016 bi->bi_iter.bi_sector = (sh->sector
1017 + rdev->new_data_offset);
1018 else
1019 bi->bi_iter.bi_sector = (sh->sector
1020 + rdev->data_offset);
1021 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1022 bi->bi_rw |= REQ_NOMERGE;
1024 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1025 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1026 sh->dev[i].vec.bv_page = sh->dev[i].page;
1027 bi->bi_vcnt = 1;
1028 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1029 bi->bi_io_vec[0].bv_offset = 0;
1030 bi->bi_iter.bi_size = STRIPE_SIZE;
1032 * If this is discard request, set bi_vcnt 0. We don't
1033 * want to confuse SCSI because SCSI will replace payload
1035 if (rw & REQ_DISCARD)
1036 bi->bi_vcnt = 0;
1037 if (rrdev)
1038 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1040 if (conf->mddev->gendisk)
1041 trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
1042 bi, disk_devt(conf->mddev->gendisk),
1043 sh->dev[i].sector);
1044 generic_make_request(bi);
1046 if (rrdev) {
1047 if (s->syncing || s->expanding || s->expanded
1048 || s->replacing)
1049 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1051 set_bit(STRIPE_IO_STARTED, &sh->state);
1053 bio_reset(rbi);
1054 rbi->bi_bdev = rrdev->bdev;
1055 rbi->bi_rw = rw;
1056 BUG_ON(!(rw & WRITE));
1057 rbi->bi_end_io = raid5_end_write_request;
1058 rbi->bi_private = sh;
1060 pr_debug("%s: for %llu schedule op %ld on "
1061 "replacement disc %d\n",
1062 __func__, (unsigned long long)sh->sector,
1063 rbi->bi_rw, i);
1064 atomic_inc(&sh->count);
1065 if (sh != head_sh)
1066 atomic_inc(&head_sh->count);
1067 if (use_new_offset(conf, sh))
1068 rbi->bi_iter.bi_sector = (sh->sector
1069 + rrdev->new_data_offset);
1070 else
1071 rbi->bi_iter.bi_sector = (sh->sector
1072 + rrdev->data_offset);
1073 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1074 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1075 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1076 rbi->bi_vcnt = 1;
1077 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1078 rbi->bi_io_vec[0].bv_offset = 0;
1079 rbi->bi_iter.bi_size = STRIPE_SIZE;
1081 * If this is discard request, set bi_vcnt 0. We don't
1082 * want to confuse SCSI because SCSI will replace payload
1084 if (rw & REQ_DISCARD)
1085 rbi->bi_vcnt = 0;
1086 if (conf->mddev->gendisk)
1087 trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
1088 rbi, disk_devt(conf->mddev->gendisk),
1089 sh->dev[i].sector);
1090 generic_make_request(rbi);
1092 if (!rdev && !rrdev) {
1093 if (rw & WRITE)
1094 set_bit(STRIPE_DEGRADED, &sh->state);
1095 pr_debug("skip op %ld on disc %d for sector %llu\n",
1096 bi->bi_rw, i, (unsigned long long)sh->sector);
1097 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1098 set_bit(STRIPE_HANDLE, &sh->state);
1101 if (!head_sh->batch_head)
1102 continue;
1103 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1104 batch_list);
1105 if (sh != head_sh)
1106 goto again;
1110 static struct dma_async_tx_descriptor *
1111 async_copy_data(int frombio, struct bio *bio, struct page **page,
1112 sector_t sector, struct dma_async_tx_descriptor *tx,
1113 struct stripe_head *sh)
1115 struct bio_vec bvl;
1116 struct bvec_iter iter;
1117 struct page *bio_page;
1118 int page_offset;
1119 struct async_submit_ctl submit;
1120 enum async_tx_flags flags = 0;
1122 if (bio->bi_iter.bi_sector >= sector)
1123 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1124 else
1125 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1127 if (frombio)
1128 flags |= ASYNC_TX_FENCE;
1129 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1131 bio_for_each_segment(bvl, bio, iter) {
1132 int len = bvl.bv_len;
1133 int clen;
1134 int b_offset = 0;
1136 if (page_offset < 0) {
1137 b_offset = -page_offset;
1138 page_offset += b_offset;
1139 len -= b_offset;
1142 if (len > 0 && page_offset + len > STRIPE_SIZE)
1143 clen = STRIPE_SIZE - page_offset;
1144 else
1145 clen = len;
1147 if (clen > 0) {
1148 b_offset += bvl.bv_offset;
1149 bio_page = bvl.bv_page;
1150 if (frombio) {
1151 if (sh->raid_conf->skip_copy &&
1152 b_offset == 0 && page_offset == 0 &&
1153 clen == STRIPE_SIZE)
1154 *page = bio_page;
1155 else
1156 tx = async_memcpy(*page, bio_page, page_offset,
1157 b_offset, clen, &submit);
1158 } else
1159 tx = async_memcpy(bio_page, *page, b_offset,
1160 page_offset, clen, &submit);
1162 /* chain the operations */
1163 submit.depend_tx = tx;
1165 if (clen < len) /* hit end of page */
1166 break;
1167 page_offset += len;
1170 return tx;
1173 static void ops_complete_biofill(void *stripe_head_ref)
1175 struct stripe_head *sh = stripe_head_ref;
1176 struct bio_list return_bi = BIO_EMPTY_LIST;
1177 int i;
1179 pr_debug("%s: stripe %llu\n", __func__,
1180 (unsigned long long)sh->sector);
1182 /* clear completed biofills */
1183 for (i = sh->disks; i--; ) {
1184 struct r5dev *dev = &sh->dev[i];
1186 /* acknowledge completion of a biofill operation */
1187 /* and check if we need to reply to a read request,
1188 * new R5_Wantfill requests are held off until
1189 * !STRIPE_BIOFILL_RUN
1191 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1192 struct bio *rbi, *rbi2;
1194 BUG_ON(!dev->read);
1195 rbi = dev->read;
1196 dev->read = NULL;
1197 while (rbi && rbi->bi_iter.bi_sector <
1198 dev->sector + STRIPE_SECTORS) {
1199 rbi2 = r5_next_bio(rbi, dev->sector);
1200 if (!raid5_dec_bi_active_stripes(rbi))
1201 bio_list_add(&return_bi, rbi);
1202 rbi = rbi2;
1206 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1208 return_io(&return_bi);
1210 set_bit(STRIPE_HANDLE, &sh->state);
1211 raid5_release_stripe(sh);
1214 static void ops_run_biofill(struct stripe_head *sh)
1216 struct dma_async_tx_descriptor *tx = NULL;
1217 struct async_submit_ctl submit;
1218 int i;
1220 BUG_ON(sh->batch_head);
1221 pr_debug("%s: stripe %llu\n", __func__,
1222 (unsigned long long)sh->sector);
1224 for (i = sh->disks; i--; ) {
1225 struct r5dev *dev = &sh->dev[i];
1226 if (test_bit(R5_Wantfill, &dev->flags)) {
1227 struct bio *rbi;
1228 spin_lock_irq(&sh->stripe_lock);
1229 dev->read = rbi = dev->toread;
1230 dev->toread = NULL;
1231 spin_unlock_irq(&sh->stripe_lock);
1232 while (rbi && rbi->bi_iter.bi_sector <
1233 dev->sector + STRIPE_SECTORS) {
1234 tx = async_copy_data(0, rbi, &dev->page,
1235 dev->sector, tx, sh);
1236 rbi = r5_next_bio(rbi, dev->sector);
1241 atomic_inc(&sh->count);
1242 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1243 async_trigger_callback(&submit);
1246 static void mark_target_uptodate(struct stripe_head *sh, int target)
1248 struct r5dev *tgt;
1250 if (target < 0)
1251 return;
1253 tgt = &sh->dev[target];
1254 set_bit(R5_UPTODATE, &tgt->flags);
1255 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1256 clear_bit(R5_Wantcompute, &tgt->flags);
1259 static void ops_complete_compute(void *stripe_head_ref)
1261 struct stripe_head *sh = stripe_head_ref;
1263 pr_debug("%s: stripe %llu\n", __func__,
1264 (unsigned long long)sh->sector);
1266 /* mark the computed target(s) as uptodate */
1267 mark_target_uptodate(sh, sh->ops.target);
1268 mark_target_uptodate(sh, sh->ops.target2);
1270 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1271 if (sh->check_state == check_state_compute_run)
1272 sh->check_state = check_state_compute_result;
1273 set_bit(STRIPE_HANDLE, &sh->state);
1274 raid5_release_stripe(sh);
1277 /* return a pointer to the address conversion region of the scribble buffer */
1278 static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1279 struct raid5_percpu *percpu, int i)
1281 void *addr;
1283 addr = flex_array_get(percpu->scribble, i);
1284 return addr + sizeof(struct page *) * (sh->disks + 2);
1287 /* return a pointer to the address conversion region of the scribble buffer */
1288 static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1290 void *addr;
1292 addr = flex_array_get(percpu->scribble, i);
1293 return addr;
1296 static struct dma_async_tx_descriptor *
1297 ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1299 int disks = sh->disks;
1300 struct page **xor_srcs = to_addr_page(percpu, 0);
1301 int target = sh->ops.target;
1302 struct r5dev *tgt = &sh->dev[target];
1303 struct page *xor_dest = tgt->page;
1304 int count = 0;
1305 struct dma_async_tx_descriptor *tx;
1306 struct async_submit_ctl submit;
1307 int i;
1309 BUG_ON(sh->batch_head);
1311 pr_debug("%s: stripe %llu block: %d\n",
1312 __func__, (unsigned long long)sh->sector, target);
1313 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1315 for (i = disks; i--; )
1316 if (i != target)
1317 xor_srcs[count++] = sh->dev[i].page;
1319 atomic_inc(&sh->count);
1321 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1322 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1323 if (unlikely(count == 1))
1324 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1325 else
1326 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1328 return tx;
1331 /* set_syndrome_sources - populate source buffers for gen_syndrome
1332 * @srcs - (struct page *) array of size sh->disks
1333 * @sh - stripe_head to parse
1335 * Populates srcs in proper layout order for the stripe and returns the
1336 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1337 * destination buffer is recorded in srcs[count] and the Q destination
1338 * is recorded in srcs[count+1]].
1340 static int set_syndrome_sources(struct page **srcs,
1341 struct stripe_head *sh,
1342 int srctype)
1344 int disks = sh->disks;
1345 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1346 int d0_idx = raid6_d0(sh);
1347 int count;
1348 int i;
1350 for (i = 0; i < disks; i++)
1351 srcs[i] = NULL;
1353 count = 0;
1354 i = d0_idx;
1355 do {
1356 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1357 struct r5dev *dev = &sh->dev[i];
1359 if (i == sh->qd_idx || i == sh->pd_idx ||
1360 (srctype == SYNDROME_SRC_ALL) ||
1361 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1362 test_bit(R5_Wantdrain, &dev->flags)) ||
1363 (srctype == SYNDROME_SRC_WRITTEN &&
1364 dev->written))
1365 srcs[slot] = sh->dev[i].page;
1366 i = raid6_next_disk(i, disks);
1367 } while (i != d0_idx);
1369 return syndrome_disks;
1372 static struct dma_async_tx_descriptor *
1373 ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1375 int disks = sh->disks;
1376 struct page **blocks = to_addr_page(percpu, 0);
1377 int target;
1378 int qd_idx = sh->qd_idx;
1379 struct dma_async_tx_descriptor *tx;
1380 struct async_submit_ctl submit;
1381 struct r5dev *tgt;
1382 struct page *dest;
1383 int i;
1384 int count;
1386 BUG_ON(sh->batch_head);
1387 if (sh->ops.target < 0)
1388 target = sh->ops.target2;
1389 else if (sh->ops.target2 < 0)
1390 target = sh->ops.target;
1391 else
1392 /* we should only have one valid target */
1393 BUG();
1394 BUG_ON(target < 0);
1395 pr_debug("%s: stripe %llu block: %d\n",
1396 __func__, (unsigned long long)sh->sector, target);
1398 tgt = &sh->dev[target];
1399 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1400 dest = tgt->page;
1402 atomic_inc(&sh->count);
1404 if (target == qd_idx) {
1405 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1406 blocks[count] = NULL; /* regenerating p is not necessary */
1407 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1408 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1409 ops_complete_compute, sh,
1410 to_addr_conv(sh, percpu, 0));
1411 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1412 } else {
1413 /* Compute any data- or p-drive using XOR */
1414 count = 0;
1415 for (i = disks; i-- ; ) {
1416 if (i == target || i == qd_idx)
1417 continue;
1418 blocks[count++] = sh->dev[i].page;
1421 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1422 NULL, ops_complete_compute, sh,
1423 to_addr_conv(sh, percpu, 0));
1424 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1427 return tx;
1430 static struct dma_async_tx_descriptor *
1431 ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1433 int i, count, disks = sh->disks;
1434 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1435 int d0_idx = raid6_d0(sh);
1436 int faila = -1, failb = -1;
1437 int target = sh->ops.target;
1438 int target2 = sh->ops.target2;
1439 struct r5dev *tgt = &sh->dev[target];
1440 struct r5dev *tgt2 = &sh->dev[target2];
1441 struct dma_async_tx_descriptor *tx;
1442 struct page **blocks = to_addr_page(percpu, 0);
1443 struct async_submit_ctl submit;
1445 BUG_ON(sh->batch_head);
1446 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1447 __func__, (unsigned long long)sh->sector, target, target2);
1448 BUG_ON(target < 0 || target2 < 0);
1449 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1450 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1452 /* we need to open-code set_syndrome_sources to handle the
1453 * slot number conversion for 'faila' and 'failb'
1455 for (i = 0; i < disks ; i++)
1456 blocks[i] = NULL;
1457 count = 0;
1458 i = d0_idx;
1459 do {
1460 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1462 blocks[slot] = sh->dev[i].page;
1464 if (i == target)
1465 faila = slot;
1466 if (i == target2)
1467 failb = slot;
1468 i = raid6_next_disk(i, disks);
1469 } while (i != d0_idx);
1471 BUG_ON(faila == failb);
1472 if (failb < faila)
1473 swap(faila, failb);
1474 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1475 __func__, (unsigned long long)sh->sector, faila, failb);
1477 atomic_inc(&sh->count);
1479 if (failb == syndrome_disks+1) {
1480 /* Q disk is one of the missing disks */
1481 if (faila == syndrome_disks) {
1482 /* Missing P+Q, just recompute */
1483 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1484 ops_complete_compute, sh,
1485 to_addr_conv(sh, percpu, 0));
1486 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1487 STRIPE_SIZE, &submit);
1488 } else {
1489 struct page *dest;
1490 int data_target;
1491 int qd_idx = sh->qd_idx;
1493 /* Missing D+Q: recompute D from P, then recompute Q */
1494 if (target == qd_idx)
1495 data_target = target2;
1496 else
1497 data_target = target;
1499 count = 0;
1500 for (i = disks; i-- ; ) {
1501 if (i == data_target || i == qd_idx)
1502 continue;
1503 blocks[count++] = sh->dev[i].page;
1505 dest = sh->dev[data_target].page;
1506 init_async_submit(&submit,
1507 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1508 NULL, NULL, NULL,
1509 to_addr_conv(sh, percpu, 0));
1510 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1511 &submit);
1513 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1514 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1515 ops_complete_compute, sh,
1516 to_addr_conv(sh, percpu, 0));
1517 return async_gen_syndrome(blocks, 0, count+2,
1518 STRIPE_SIZE, &submit);
1520 } else {
1521 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1522 ops_complete_compute, sh,
1523 to_addr_conv(sh, percpu, 0));
1524 if (failb == syndrome_disks) {
1525 /* We're missing D+P. */
1526 return async_raid6_datap_recov(syndrome_disks+2,
1527 STRIPE_SIZE, faila,
1528 blocks, &submit);
1529 } else {
1530 /* We're missing D+D. */
1531 return async_raid6_2data_recov(syndrome_disks+2,
1532 STRIPE_SIZE, faila, failb,
1533 blocks, &submit);
1538 static void ops_complete_prexor(void *stripe_head_ref)
1540 struct stripe_head *sh = stripe_head_ref;
1542 pr_debug("%s: stripe %llu\n", __func__,
1543 (unsigned long long)sh->sector);
1546 static struct dma_async_tx_descriptor *
1547 ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1548 struct dma_async_tx_descriptor *tx)
1550 int disks = sh->disks;
1551 struct page **xor_srcs = to_addr_page(percpu, 0);
1552 int count = 0, pd_idx = sh->pd_idx, i;
1553 struct async_submit_ctl submit;
1555 /* existing parity data subtracted */
1556 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1558 BUG_ON(sh->batch_head);
1559 pr_debug("%s: stripe %llu\n", __func__,
1560 (unsigned long long)sh->sector);
1562 for (i = disks; i--; ) {
1563 struct r5dev *dev = &sh->dev[i];
1564 /* Only process blocks that are known to be uptodate */
1565 if (test_bit(R5_Wantdrain, &dev->flags))
1566 xor_srcs[count++] = dev->page;
1569 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1570 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1571 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1573 return tx;
1576 static struct dma_async_tx_descriptor *
1577 ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1578 struct dma_async_tx_descriptor *tx)
1580 struct page **blocks = to_addr_page(percpu, 0);
1581 int count;
1582 struct async_submit_ctl submit;
1584 pr_debug("%s: stripe %llu\n", __func__,
1585 (unsigned long long)sh->sector);
1587 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1589 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1590 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1591 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1593 return tx;
1596 static struct dma_async_tx_descriptor *
1597 ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1599 int disks = sh->disks;
1600 int i;
1601 struct stripe_head *head_sh = sh;
1603 pr_debug("%s: stripe %llu\n", __func__,
1604 (unsigned long long)sh->sector);
1606 for (i = disks; i--; ) {
1607 struct r5dev *dev;
1608 struct bio *chosen;
1610 sh = head_sh;
1611 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1612 struct bio *wbi;
1614 again:
1615 dev = &sh->dev[i];
1616 spin_lock_irq(&sh->stripe_lock);
1617 chosen = dev->towrite;
1618 dev->towrite = NULL;
1619 sh->overwrite_disks = 0;
1620 BUG_ON(dev->written);
1621 wbi = dev->written = chosen;
1622 spin_unlock_irq(&sh->stripe_lock);
1623 WARN_ON(dev->page != dev->orig_page);
1625 while (wbi && wbi->bi_iter.bi_sector <
1626 dev->sector + STRIPE_SECTORS) {
1627 if (wbi->bi_rw & REQ_FUA)
1628 set_bit(R5_WantFUA, &dev->flags);
1629 if (wbi->bi_rw & REQ_SYNC)
1630 set_bit(R5_SyncIO, &dev->flags);
1631 if (wbi->bi_rw & REQ_DISCARD)
1632 set_bit(R5_Discard, &dev->flags);
1633 else {
1634 tx = async_copy_data(1, wbi, &dev->page,
1635 dev->sector, tx, sh);
1636 if (dev->page != dev->orig_page) {
1637 set_bit(R5_SkipCopy, &dev->flags);
1638 clear_bit(R5_UPTODATE, &dev->flags);
1639 clear_bit(R5_OVERWRITE, &dev->flags);
1642 wbi = r5_next_bio(wbi, dev->sector);
1645 if (head_sh->batch_head) {
1646 sh = list_first_entry(&sh->batch_list,
1647 struct stripe_head,
1648 batch_list);
1649 if (sh == head_sh)
1650 continue;
1651 goto again;
1656 return tx;
1659 static void ops_complete_reconstruct(void *stripe_head_ref)
1661 struct stripe_head *sh = stripe_head_ref;
1662 int disks = sh->disks;
1663 int pd_idx = sh->pd_idx;
1664 int qd_idx = sh->qd_idx;
1665 int i;
1666 bool fua = false, sync = false, discard = false;
1668 pr_debug("%s: stripe %llu\n", __func__,
1669 (unsigned long long)sh->sector);
1671 for (i = disks; i--; ) {
1672 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1673 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1674 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1677 for (i = disks; i--; ) {
1678 struct r5dev *dev = &sh->dev[i];
1680 if (dev->written || i == pd_idx || i == qd_idx) {
1681 if (!discard && !test_bit(R5_SkipCopy, &dev->flags)) {
1682 set_bit(R5_UPTODATE, &dev->flags);
1683 if (test_bit(STRIPE_EXPAND_READY, &sh->state))
1684 set_bit(R5_Expanded, &dev->flags);
1686 if (fua)
1687 set_bit(R5_WantFUA, &dev->flags);
1688 if (sync)
1689 set_bit(R5_SyncIO, &dev->flags);
1693 if (sh->reconstruct_state == reconstruct_state_drain_run)
1694 sh->reconstruct_state = reconstruct_state_drain_result;
1695 else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1696 sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1697 else {
1698 BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1699 sh->reconstruct_state = reconstruct_state_result;
1702 set_bit(STRIPE_HANDLE, &sh->state);
1703 raid5_release_stripe(sh);
1706 static void
1707 ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1708 struct dma_async_tx_descriptor *tx)
1710 int disks = sh->disks;
1711 struct page **xor_srcs;
1712 struct async_submit_ctl submit;
1713 int count, pd_idx = sh->pd_idx, i;
1714 struct page *xor_dest;
1715 int prexor = 0;
1716 unsigned long flags;
1717 int j = 0;
1718 struct stripe_head *head_sh = sh;
1719 int last_stripe;
1721 pr_debug("%s: stripe %llu\n", __func__,
1722 (unsigned long long)sh->sector);
1724 for (i = 0; i < sh->disks; i++) {
1725 if (pd_idx == i)
1726 continue;
1727 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1728 break;
1730 if (i >= sh->disks) {
1731 atomic_inc(&sh->count);
1732 set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1733 ops_complete_reconstruct(sh);
1734 return;
1736 again:
1737 count = 0;
1738 xor_srcs = to_addr_page(percpu, j);
1739 /* check if prexor is active which means only process blocks
1740 * that are part of a read-modify-write (written)
1742 if (head_sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1743 prexor = 1;
1744 xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1745 for (i = disks; i--; ) {
1746 struct r5dev *dev = &sh->dev[i];
1747 if (head_sh->dev[i].written)
1748 xor_srcs[count++] = dev->page;
1750 } else {
1751 xor_dest = sh->dev[pd_idx].page;
1752 for (i = disks; i--; ) {
1753 struct r5dev *dev = &sh->dev[i];
1754 if (i != pd_idx)
1755 xor_srcs[count++] = dev->page;
1759 /* 1/ if we prexor'd then the dest is reused as a source
1760 * 2/ if we did not prexor then we are redoing the parity
1761 * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1762 * for the synchronous xor case
1764 last_stripe = !head_sh->batch_head ||
1765 list_first_entry(&sh->batch_list,
1766 struct stripe_head, batch_list) == head_sh;
1767 if (last_stripe) {
1768 flags = ASYNC_TX_ACK |
1769 (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1771 atomic_inc(&head_sh->count);
1772 init_async_submit(&submit, flags, tx, ops_complete_reconstruct, head_sh,
1773 to_addr_conv(sh, percpu, j));
1774 } else {
1775 flags = prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST;
1776 init_async_submit(&submit, flags, tx, NULL, NULL,
1777 to_addr_conv(sh, percpu, j));
1780 if (unlikely(count == 1))
1781 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1782 else
1783 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1784 if (!last_stripe) {
1785 j++;
1786 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1787 batch_list);
1788 goto again;
1792 static void
1793 ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1794 struct dma_async_tx_descriptor *tx)
1796 struct async_submit_ctl submit;
1797 struct page **blocks;
1798 int count, i, j = 0;
1799 struct stripe_head *head_sh = sh;
1800 int last_stripe;
1801 int synflags;
1802 unsigned long txflags;
1804 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1806 for (i = 0; i < sh->disks; i++) {
1807 if (sh->pd_idx == i || sh->qd_idx == i)
1808 continue;
1809 if (!test_bit(R5_Discard, &sh->dev[i].flags))
1810 break;
1812 if (i >= sh->disks) {
1813 atomic_inc(&sh->count);
1814 set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1815 set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1816 ops_complete_reconstruct(sh);
1817 return;
1820 again:
1821 blocks = to_addr_page(percpu, j);
1823 if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1824 synflags = SYNDROME_SRC_WRITTEN;
1825 txflags = ASYNC_TX_ACK | ASYNC_TX_PQ_XOR_DST;
1826 } else {
1827 synflags = SYNDROME_SRC_ALL;
1828 txflags = ASYNC_TX_ACK;
1831 count = set_syndrome_sources(blocks, sh, synflags);
1832 last_stripe = !head_sh->batch_head ||
1833 list_first_entry(&sh->batch_list,
1834 struct stripe_head, batch_list) == head_sh;
1836 if (last_stripe) {
1837 atomic_inc(&head_sh->count);
1838 init_async_submit(&submit, txflags, tx, ops_complete_reconstruct,
1839 head_sh, to_addr_conv(sh, percpu, j));
1840 } else
1841 init_async_submit(&submit, 0, tx, NULL, NULL,
1842 to_addr_conv(sh, percpu, j));
1843 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1844 if (!last_stripe) {
1845 j++;
1846 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1847 batch_list);
1848 goto again;
1852 static void ops_complete_check(void *stripe_head_ref)
1854 struct stripe_head *sh = stripe_head_ref;
1856 pr_debug("%s: stripe %llu\n", __func__,
1857 (unsigned long long)sh->sector);
1859 sh->check_state = check_state_check_result;
1860 set_bit(STRIPE_HANDLE, &sh->state);
1861 raid5_release_stripe(sh);
1864 static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1866 int disks = sh->disks;
1867 int pd_idx = sh->pd_idx;
1868 int qd_idx = sh->qd_idx;
1869 struct page *xor_dest;
1870 struct page **xor_srcs = to_addr_page(percpu, 0);
1871 struct dma_async_tx_descriptor *tx;
1872 struct async_submit_ctl submit;
1873 int count;
1874 int i;
1876 pr_debug("%s: stripe %llu\n", __func__,
1877 (unsigned long long)sh->sector);
1879 BUG_ON(sh->batch_head);
1880 count = 0;
1881 xor_dest = sh->dev[pd_idx].page;
1882 xor_srcs[count++] = xor_dest;
1883 for (i = disks; i--; ) {
1884 if (i == pd_idx || i == qd_idx)
1885 continue;
1886 xor_srcs[count++] = sh->dev[i].page;
1889 init_async_submit(&submit, 0, NULL, NULL, NULL,
1890 to_addr_conv(sh, percpu, 0));
1891 tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1892 &sh->ops.zero_sum_result, &submit);
1894 atomic_inc(&sh->count);
1895 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1896 tx = async_trigger_callback(&submit);
1899 static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1901 struct page **srcs = to_addr_page(percpu, 0);
1902 struct async_submit_ctl submit;
1903 int count;
1905 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1906 (unsigned long long)sh->sector, checkp);
1908 BUG_ON(sh->batch_head);
1909 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
1910 if (!checkp)
1911 srcs[count] = NULL;
1913 atomic_inc(&sh->count);
1914 init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1915 sh, to_addr_conv(sh, percpu, 0));
1916 async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1917 &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1920 static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1922 int overlap_clear = 0, i, disks = sh->disks;
1923 struct dma_async_tx_descriptor *tx = NULL;
1924 struct r5conf *conf = sh->raid_conf;
1925 int level = conf->level;
1926 struct raid5_percpu *percpu;
1927 unsigned long cpu;
1929 cpu = get_cpu();
1930 percpu = per_cpu_ptr(conf->percpu, cpu);
1931 if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1932 ops_run_biofill(sh);
1933 overlap_clear++;
1936 if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1937 if (level < 6)
1938 tx = ops_run_compute5(sh, percpu);
1939 else {
1940 if (sh->ops.target2 < 0 || sh->ops.target < 0)
1941 tx = ops_run_compute6_1(sh, percpu);
1942 else
1943 tx = ops_run_compute6_2(sh, percpu);
1945 /* terminate the chain if reconstruct is not set to be run */
1946 if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1947 async_tx_ack(tx);
1950 if (test_bit(STRIPE_OP_PREXOR, &ops_request)) {
1951 if (level < 6)
1952 tx = ops_run_prexor5(sh, percpu, tx);
1953 else
1954 tx = ops_run_prexor6(sh, percpu, tx);
1957 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1958 tx = ops_run_biodrain(sh, tx);
1959 overlap_clear++;
1962 if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1963 if (level < 6)
1964 ops_run_reconstruct5(sh, percpu, tx);
1965 else
1966 ops_run_reconstruct6(sh, percpu, tx);
1969 if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1970 if (sh->check_state == check_state_run)
1971 ops_run_check_p(sh, percpu);
1972 else if (sh->check_state == check_state_run_q)
1973 ops_run_check_pq(sh, percpu, 0);
1974 else if (sh->check_state == check_state_run_pq)
1975 ops_run_check_pq(sh, percpu, 1);
1976 else
1977 BUG();
1980 if (overlap_clear && !sh->batch_head)
1981 for (i = disks; i--; ) {
1982 struct r5dev *dev = &sh->dev[i];
1983 if (test_and_clear_bit(R5_Overlap, &dev->flags))
1984 wake_up(&sh->raid_conf->wait_for_overlap);
1986 put_cpu();
1989 static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp)
1991 struct stripe_head *sh;
1993 sh = kmem_cache_zalloc(sc, gfp);
1994 if (sh) {
1995 spin_lock_init(&sh->stripe_lock);
1996 spin_lock_init(&sh->batch_lock);
1997 INIT_LIST_HEAD(&sh->batch_list);
1998 INIT_LIST_HEAD(&sh->lru);
1999 atomic_set(&sh->count, 1);
2001 return sh;
2003 static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2005 struct stripe_head *sh;
2007 sh = alloc_stripe(conf->slab_cache, gfp);
2008 if (!sh)
2009 return 0;
2011 sh->raid_conf = conf;
2013 if (grow_buffers(sh, gfp)) {
2014 shrink_buffers(sh);
2015 kmem_cache_free(conf->slab_cache, sh);
2016 return 0;
2018 sh->hash_lock_index =
2019 conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS;
2020 /* we just created an active stripe so... */
2021 atomic_inc(&conf->active_stripes);
2023 raid5_release_stripe(sh);
2024 conf->max_nr_stripes++;
2025 return 1;
2028 static int grow_stripes(struct r5conf *conf, int num)
2030 struct kmem_cache *sc;
2031 size_t namelen = sizeof(conf->cache_name[0]);
2032 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2034 if (conf->mddev->gendisk)
2035 snprintf(conf->cache_name[0], namelen,
2036 "raid%d-%s", conf->level, mdname(conf->mddev));
2037 else
2038 snprintf(conf->cache_name[0], namelen,
2039 "raid%d-%p", conf->level, conf->mddev);
2040 snprintf(conf->cache_name[1], namelen, "%.27s-alt", conf->cache_name[0]);
2042 conf->active_name = 0;
2043 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2044 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2045 0, 0, NULL);
2046 if (!sc)
2047 return 1;
2048 conf->slab_cache = sc;
2049 conf->pool_size = devs;
2050 while (num--)
2051 if (!grow_one_stripe(conf, GFP_KERNEL))
2052 return 1;
2054 return 0;
2058 * scribble_len - return the required size of the scribble region
2059 * @num - total number of disks in the array
2061 * The size must be enough to contain:
2062 * 1/ a struct page pointer for each device in the array +2
2063 * 2/ room to convert each entry in (1) to its corresponding dma
2064 * (dma_map_page()) or page (page_address()) address.
2066 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2067 * calculate over all devices (not just the data blocks), using zeros in place
2068 * of the P and Q blocks.
2070 static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2072 struct flex_array *ret;
2073 size_t len;
2075 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2076 ret = flex_array_alloc(len, cnt, flags);
2077 if (!ret)
2078 return NULL;
2079 /* always prealloc all elements, so no locking is required */
2080 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2081 flex_array_free(ret);
2082 return NULL;
2084 return ret;
2087 static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2089 unsigned long cpu;
2090 int err = 0;
2093 * Never shrink. And mddev_suspend() could deadlock if this is called
2094 * from raid5d. In that case, scribble_disks and scribble_sectors
2095 * should equal to new_disks and new_sectors
2097 if (conf->scribble_disks >= new_disks &&
2098 conf->scribble_sectors >= new_sectors)
2099 return 0;
2100 mddev_suspend(conf->mddev);
2101 get_online_cpus();
2102 for_each_present_cpu(cpu) {
2103 struct raid5_percpu *percpu;
2104 struct flex_array *scribble;
2106 percpu = per_cpu_ptr(conf->percpu, cpu);
2107 scribble = scribble_alloc(new_disks,
2108 new_sectors / STRIPE_SECTORS,
2109 GFP_NOIO);
2111 if (scribble) {
2112 flex_array_free(percpu->scribble);
2113 percpu->scribble = scribble;
2114 } else {
2115 err = -ENOMEM;
2116 break;
2119 put_online_cpus();
2120 mddev_resume(conf->mddev);
2121 if (!err) {
2122 conf->scribble_disks = new_disks;
2123 conf->scribble_sectors = new_sectors;
2125 return err;
2128 static int resize_stripes(struct r5conf *conf, int newsize)
2130 /* Make all the stripes able to hold 'newsize' devices.
2131 * New slots in each stripe get 'page' set to a new page.
2133 * This happens in stages:
2134 * 1/ create a new kmem_cache and allocate the required number of
2135 * stripe_heads.
2136 * 2/ gather all the old stripe_heads and transfer the pages across
2137 * to the new stripe_heads. This will have the side effect of
2138 * freezing the array as once all stripe_heads have been collected,
2139 * no IO will be possible. Old stripe heads are freed once their
2140 * pages have been transferred over, and the old kmem_cache is
2141 * freed when all stripes are done.
2142 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2143 * we simple return a failre status - no need to clean anything up.
2144 * 4/ allocate new pages for the new slots in the new stripe_heads.
2145 * If this fails, we don't bother trying the shrink the
2146 * stripe_heads down again, we just leave them as they are.
2147 * As each stripe_head is processed the new one is released into
2148 * active service.
2150 * Once step2 is started, we cannot afford to wait for a write,
2151 * so we use GFP_NOIO allocations.
2153 struct stripe_head *osh, *nsh;
2154 LIST_HEAD(newstripes);
2155 struct disk_info *ndisks;
2156 int err;
2157 struct kmem_cache *sc;
2158 int i;
2159 int hash, cnt;
2161 if (newsize <= conf->pool_size)
2162 return 0; /* never bother to shrink */
2164 err = md_allow_write(conf->mddev);
2165 if (err)
2166 return err;
2168 /* Step 1 */
2169 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2170 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2171 0, 0, NULL);
2172 if (!sc)
2173 return -ENOMEM;
2175 /* Need to ensure auto-resizing doesn't interfere */
2176 mutex_lock(&conf->cache_size_mutex);
2178 for (i = conf->max_nr_stripes; i; i--) {
2179 nsh = alloc_stripe(sc, GFP_KERNEL);
2180 if (!nsh)
2181 break;
2183 nsh->raid_conf = conf;
2184 list_add(&nsh->lru, &newstripes);
2186 if (i) {
2187 /* didn't get enough, give up */
2188 while (!list_empty(&newstripes)) {
2189 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2190 list_del(&nsh->lru);
2191 kmem_cache_free(sc, nsh);
2193 kmem_cache_destroy(sc);
2194 mutex_unlock(&conf->cache_size_mutex);
2195 return -ENOMEM;
2197 /* Step 2 - Must use GFP_NOIO now.
2198 * OK, we have enough stripes, start collecting inactive
2199 * stripes and copying them over
2201 hash = 0;
2202 cnt = 0;
2203 list_for_each_entry(nsh, &newstripes, lru) {
2204 lock_device_hash_lock(conf, hash);
2205 wait_event_cmd(conf->wait_for_stripe,
2206 !list_empty(conf->inactive_list + hash),
2207 unlock_device_hash_lock(conf, hash),
2208 lock_device_hash_lock(conf, hash));
2209 osh = get_free_stripe(conf, hash);
2210 unlock_device_hash_lock(conf, hash);
2212 for(i=0; i<conf->pool_size; i++) {
2213 nsh->dev[i].page = osh->dev[i].page;
2214 nsh->dev[i].orig_page = osh->dev[i].page;
2216 nsh->hash_lock_index = hash;
2217 kmem_cache_free(conf->slab_cache, osh);
2218 cnt++;
2219 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2220 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2221 hash++;
2222 cnt = 0;
2225 kmem_cache_destroy(conf->slab_cache);
2227 /* Step 3.
2228 * At this point, we are holding all the stripes so the array
2229 * is completely stalled, so now is a good time to resize
2230 * conf->disks and the scribble region
2232 ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2233 if (ndisks) {
2234 for (i=0; i<conf->raid_disks; i++)
2235 ndisks[i] = conf->disks[i];
2236 kfree(conf->disks);
2237 conf->disks = ndisks;
2238 } else
2239 err = -ENOMEM;
2241 mutex_unlock(&conf->cache_size_mutex);
2243 conf->slab_cache = sc;
2244 conf->active_name = 1-conf->active_name;
2246 /* Step 4, return new stripes to service */
2247 while(!list_empty(&newstripes)) {
2248 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2249 list_del_init(&nsh->lru);
2251 for (i=conf->raid_disks; i < newsize; i++)
2252 if (nsh->dev[i].page == NULL) {
2253 struct page *p = alloc_page(GFP_NOIO);
2254 nsh->dev[i].page = p;
2255 nsh->dev[i].orig_page = p;
2256 if (!p)
2257 err = -ENOMEM;
2259 raid5_release_stripe(nsh);
2261 /* critical section pass, GFP_NOIO no longer needed */
2263 if (!err)
2264 conf->pool_size = newsize;
2265 return err;
2268 static int drop_one_stripe(struct r5conf *conf)
2270 struct stripe_head *sh;
2271 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2273 spin_lock_irq(conf->hash_locks + hash);
2274 sh = get_free_stripe(conf, hash);
2275 spin_unlock_irq(conf->hash_locks + hash);
2276 if (!sh)
2277 return 0;
2278 BUG_ON(atomic_read(&sh->count));
2279 shrink_buffers(sh);
2280 kmem_cache_free(conf->slab_cache, sh);
2281 atomic_dec(&conf->active_stripes);
2282 conf->max_nr_stripes--;
2283 return 1;
2286 static void shrink_stripes(struct r5conf *conf)
2288 while (conf->max_nr_stripes &&
2289 drop_one_stripe(conf))
2292 kmem_cache_destroy(conf->slab_cache);
2293 conf->slab_cache = NULL;
2296 static void raid5_end_read_request(struct bio * bi)
2298 struct stripe_head *sh = bi->bi_private;
2299 struct r5conf *conf = sh->raid_conf;
2300 int disks = sh->disks, i;
2301 char b[BDEVNAME_SIZE];
2302 struct md_rdev *rdev = NULL;
2303 sector_t s;
2305 for (i=0 ; i<disks; i++)
2306 if (bi == &sh->dev[i].req)
2307 break;
2309 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2310 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2311 bi->bi_error);
2312 if (i == disks) {
2313 BUG();
2314 return;
2316 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2317 /* If replacement finished while this request was outstanding,
2318 * 'replacement' might be NULL already.
2319 * In that case it moved down to 'rdev'.
2320 * rdev is not removed until all requests are finished.
2322 rdev = conf->disks[i].replacement;
2323 if (!rdev)
2324 rdev = conf->disks[i].rdev;
2326 if (use_new_offset(conf, sh))
2327 s = sh->sector + rdev->new_data_offset;
2328 else
2329 s = sh->sector + rdev->data_offset;
2330 if (!bi->bi_error) {
2331 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2332 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2333 /* Note that this cannot happen on a
2334 * replacement device. We just fail those on
2335 * any error
2337 printk_ratelimited(
2338 KERN_INFO
2339 "md/raid:%s: read error corrected"
2340 " (%lu sectors at %llu on %s)\n",
2341 mdname(conf->mddev), STRIPE_SECTORS,
2342 (unsigned long long)s,
2343 bdevname(rdev->bdev, b));
2344 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2345 clear_bit(R5_ReadError, &sh->dev[i].flags);
2346 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2347 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2348 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2350 if (atomic_read(&rdev->read_errors))
2351 atomic_set(&rdev->read_errors, 0);
2352 } else {
2353 const char *bdn = bdevname(rdev->bdev, b);
2354 int retry = 0;
2355 int set_bad = 0;
2357 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2358 atomic_inc(&rdev->read_errors);
2359 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2360 printk_ratelimited(
2361 KERN_WARNING
2362 "md/raid:%s: read error on replacement device "
2363 "(sector %llu on %s).\n",
2364 mdname(conf->mddev),
2365 (unsigned long long)s,
2366 bdn);
2367 else if (conf->mddev->degraded >= conf->max_degraded) {
2368 set_bad = 1;
2369 printk_ratelimited(
2370 KERN_WARNING
2371 "md/raid:%s: read error not correctable "
2372 "(sector %llu on %s).\n",
2373 mdname(conf->mddev),
2374 (unsigned long long)s,
2375 bdn);
2376 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2377 /* Oh, no!!! */
2378 set_bad = 1;
2379 printk_ratelimited(
2380 KERN_WARNING
2381 "md/raid:%s: read error NOT corrected!! "
2382 "(sector %llu on %s).\n",
2383 mdname(conf->mddev),
2384 (unsigned long long)s,
2385 bdn);
2386 } else if (atomic_read(&rdev->read_errors)
2387 > conf->max_nr_stripes)
2388 printk(KERN_WARNING
2389 "md/raid:%s: Too many read errors, failing device %s.\n",
2390 mdname(conf->mddev), bdn);
2391 else
2392 retry = 1;
2393 if (set_bad && test_bit(In_sync, &rdev->flags)
2394 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2395 retry = 1;
2396 if (retry)
2397 if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2398 set_bit(R5_ReadError, &sh->dev[i].flags);
2399 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2400 } else
2401 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2402 else {
2403 clear_bit(R5_ReadError, &sh->dev[i].flags);
2404 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2405 if (!(set_bad
2406 && test_bit(In_sync, &rdev->flags)
2407 && rdev_set_badblocks(
2408 rdev, sh->sector, STRIPE_SECTORS, 0)))
2409 md_error(conf->mddev, rdev);
2412 rdev_dec_pending(rdev, conf->mddev);
2413 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2414 set_bit(STRIPE_HANDLE, &sh->state);
2415 raid5_release_stripe(sh);
2418 static void raid5_end_write_request(struct bio *bi)
2420 struct stripe_head *sh = bi->bi_private;
2421 struct r5conf *conf = sh->raid_conf;
2422 int disks = sh->disks, i;
2423 struct md_rdev *uninitialized_var(rdev);
2424 sector_t first_bad;
2425 int bad_sectors;
2426 int replacement = 0;
2428 for (i = 0 ; i < disks; i++) {
2429 if (bi == &sh->dev[i].req) {
2430 rdev = conf->disks[i].rdev;
2431 break;
2433 if (bi == &sh->dev[i].rreq) {
2434 rdev = conf->disks[i].replacement;
2435 if (rdev)
2436 replacement = 1;
2437 else
2438 /* rdev was removed and 'replacement'
2439 * replaced it. rdev is not removed
2440 * until all requests are finished.
2442 rdev = conf->disks[i].rdev;
2443 break;
2446 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2447 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2448 bi->bi_error);
2449 if (i == disks) {
2450 BUG();
2451 return;
2454 if (replacement) {
2455 if (bi->bi_error)
2456 md_error(conf->mddev, rdev);
2457 else if (is_badblock(rdev, sh->sector,
2458 STRIPE_SECTORS,
2459 &first_bad, &bad_sectors))
2460 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2461 } else {
2462 if (bi->bi_error) {
2463 set_bit(STRIPE_DEGRADED, &sh->state);
2464 set_bit(WriteErrorSeen, &rdev->flags);
2465 set_bit(R5_WriteError, &sh->dev[i].flags);
2466 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2467 set_bit(MD_RECOVERY_NEEDED,
2468 &rdev->mddev->recovery);
2469 } else if (is_badblock(rdev, sh->sector,
2470 STRIPE_SECTORS,
2471 &first_bad, &bad_sectors)) {
2472 set_bit(R5_MadeGood, &sh->dev[i].flags);
2473 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2474 /* That was a successful write so make
2475 * sure it looks like we already did
2476 * a re-write.
2478 set_bit(R5_ReWrite, &sh->dev[i].flags);
2481 rdev_dec_pending(rdev, conf->mddev);
2483 if (sh->batch_head && bi->bi_error && !replacement)
2484 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2486 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2487 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2488 set_bit(STRIPE_HANDLE, &sh->state);
2489 raid5_release_stripe(sh);
2491 if (sh->batch_head && sh != sh->batch_head)
2492 raid5_release_stripe(sh->batch_head);
2495 static void raid5_build_block(struct stripe_head *sh, int i, int previous)
2497 struct r5dev *dev = &sh->dev[i];
2499 bio_init(&dev->req);
2500 dev->req.bi_io_vec = &dev->vec;
2501 dev->req.bi_max_vecs = 1;
2502 dev->req.bi_private = sh;
2504 bio_init(&dev->rreq);
2505 dev->rreq.bi_io_vec = &dev->rvec;
2506 dev->rreq.bi_max_vecs = 1;
2507 dev->rreq.bi_private = sh;
2509 dev->flags = 0;
2510 dev->sector = raid5_compute_blocknr(sh, i, previous);
2513 static void error(struct mddev *mddev, struct md_rdev *rdev)
2515 char b[BDEVNAME_SIZE];
2516 struct r5conf *conf = mddev->private;
2517 unsigned long flags;
2518 pr_debug("raid456: error called\n");
2520 spin_lock_irqsave(&conf->device_lock, flags);
2521 clear_bit(In_sync, &rdev->flags);
2522 mddev->degraded = calc_degraded(conf);
2523 spin_unlock_irqrestore(&conf->device_lock, flags);
2524 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2526 set_bit(Blocked, &rdev->flags);
2527 set_bit(Faulty, &rdev->flags);
2528 set_bit(MD_CHANGE_DEVS, &mddev->flags);
2529 set_bit(MD_CHANGE_PENDING, &mddev->flags);
2530 printk(KERN_ALERT
2531 "md/raid:%s: Disk failure on %s, disabling device.\n"
2532 "md/raid:%s: Operation continuing on %d devices.\n",
2533 mdname(mddev),
2534 bdevname(rdev->bdev, b),
2535 mdname(mddev),
2536 conf->raid_disks - mddev->degraded);
2540 * Input: a 'big' sector number,
2541 * Output: index of the data and parity disk, and the sector # in them.
2543 sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2544 int previous, int *dd_idx,
2545 struct stripe_head *sh)
2547 sector_t stripe, stripe2;
2548 sector_t chunk_number;
2549 unsigned int chunk_offset;
2550 int pd_idx, qd_idx;
2551 int ddf_layout = 0;
2552 sector_t new_sector;
2553 int algorithm = previous ? conf->prev_algo
2554 : conf->algorithm;
2555 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2556 : conf->chunk_sectors;
2557 int raid_disks = previous ? conf->previous_raid_disks
2558 : conf->raid_disks;
2559 int data_disks = raid_disks - conf->max_degraded;
2561 /* First compute the information on this sector */
2564 * Compute the chunk number and the sector offset inside the chunk
2566 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2567 chunk_number = r_sector;
2570 * Compute the stripe number
2572 stripe = chunk_number;
2573 *dd_idx = sector_div(stripe, data_disks);
2574 stripe2 = stripe;
2576 * Select the parity disk based on the user selected algorithm.
2578 pd_idx = qd_idx = -1;
2579 switch(conf->level) {
2580 case 4:
2581 pd_idx = data_disks;
2582 break;
2583 case 5:
2584 switch (algorithm) {
2585 case ALGORITHM_LEFT_ASYMMETRIC:
2586 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2587 if (*dd_idx >= pd_idx)
2588 (*dd_idx)++;
2589 break;
2590 case ALGORITHM_RIGHT_ASYMMETRIC:
2591 pd_idx = sector_div(stripe2, raid_disks);
2592 if (*dd_idx >= pd_idx)
2593 (*dd_idx)++;
2594 break;
2595 case ALGORITHM_LEFT_SYMMETRIC:
2596 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2597 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2598 break;
2599 case ALGORITHM_RIGHT_SYMMETRIC:
2600 pd_idx = sector_div(stripe2, raid_disks);
2601 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2602 break;
2603 case ALGORITHM_PARITY_0:
2604 pd_idx = 0;
2605 (*dd_idx)++;
2606 break;
2607 case ALGORITHM_PARITY_N:
2608 pd_idx = data_disks;
2609 break;
2610 default:
2611 BUG();
2613 break;
2614 case 6:
2616 switch (algorithm) {
2617 case ALGORITHM_LEFT_ASYMMETRIC:
2618 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2619 qd_idx = pd_idx + 1;
2620 if (pd_idx == raid_disks-1) {
2621 (*dd_idx)++; /* Q D D D P */
2622 qd_idx = 0;
2623 } else if (*dd_idx >= pd_idx)
2624 (*dd_idx) += 2; /* D D P Q D */
2625 break;
2626 case ALGORITHM_RIGHT_ASYMMETRIC:
2627 pd_idx = sector_div(stripe2, raid_disks);
2628 qd_idx = pd_idx + 1;
2629 if (pd_idx == raid_disks-1) {
2630 (*dd_idx)++; /* Q D D D P */
2631 qd_idx = 0;
2632 } else if (*dd_idx >= pd_idx)
2633 (*dd_idx) += 2; /* D D P Q D */
2634 break;
2635 case ALGORITHM_LEFT_SYMMETRIC:
2636 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2637 qd_idx = (pd_idx + 1) % raid_disks;
2638 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2639 break;
2640 case ALGORITHM_RIGHT_SYMMETRIC:
2641 pd_idx = sector_div(stripe2, raid_disks);
2642 qd_idx = (pd_idx + 1) % raid_disks;
2643 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2644 break;
2646 case ALGORITHM_PARITY_0:
2647 pd_idx = 0;
2648 qd_idx = 1;
2649 (*dd_idx) += 2;
2650 break;
2651 case ALGORITHM_PARITY_N:
2652 pd_idx = data_disks;
2653 qd_idx = data_disks + 1;
2654 break;
2656 case ALGORITHM_ROTATING_ZERO_RESTART:
2657 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2658 * of blocks for computing Q is different.
2660 pd_idx = sector_div(stripe2, raid_disks);
2661 qd_idx = pd_idx + 1;
2662 if (pd_idx == raid_disks-1) {
2663 (*dd_idx)++; /* Q D D D P */
2664 qd_idx = 0;
2665 } else if (*dd_idx >= pd_idx)
2666 (*dd_idx) += 2; /* D D P Q D */
2667 ddf_layout = 1;
2668 break;
2670 case ALGORITHM_ROTATING_N_RESTART:
2671 /* Same a left_asymmetric, by first stripe is
2672 * D D D P Q rather than
2673 * Q D D D P
2675 stripe2 += 1;
2676 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2677 qd_idx = pd_idx + 1;
2678 if (pd_idx == raid_disks-1) {
2679 (*dd_idx)++; /* Q D D D P */
2680 qd_idx = 0;
2681 } else if (*dd_idx >= pd_idx)
2682 (*dd_idx) += 2; /* D D P Q D */
2683 ddf_layout = 1;
2684 break;
2686 case ALGORITHM_ROTATING_N_CONTINUE:
2687 /* Same as left_symmetric but Q is before P */
2688 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2689 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2690 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2691 ddf_layout = 1;
2692 break;
2694 case ALGORITHM_LEFT_ASYMMETRIC_6:
2695 /* RAID5 left_asymmetric, with Q on last device */
2696 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2697 if (*dd_idx >= pd_idx)
2698 (*dd_idx)++;
2699 qd_idx = raid_disks - 1;
2700 break;
2702 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2703 pd_idx = sector_div(stripe2, raid_disks-1);
2704 if (*dd_idx >= pd_idx)
2705 (*dd_idx)++;
2706 qd_idx = raid_disks - 1;
2707 break;
2709 case ALGORITHM_LEFT_SYMMETRIC_6:
2710 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2711 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2712 qd_idx = raid_disks - 1;
2713 break;
2715 case ALGORITHM_RIGHT_SYMMETRIC_6:
2716 pd_idx = sector_div(stripe2, raid_disks-1);
2717 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2718 qd_idx = raid_disks - 1;
2719 break;
2721 case ALGORITHM_PARITY_0_6:
2722 pd_idx = 0;
2723 (*dd_idx)++;
2724 qd_idx = raid_disks - 1;
2725 break;
2727 default:
2728 BUG();
2730 break;
2733 if (sh) {
2734 sh->pd_idx = pd_idx;
2735 sh->qd_idx = qd_idx;
2736 sh->ddf_layout = ddf_layout;
2739 * Finally, compute the new sector number
2741 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2742 return new_sector;
2745 sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2747 struct r5conf *conf = sh->raid_conf;
2748 int raid_disks = sh->disks;
2749 int data_disks = raid_disks - conf->max_degraded;
2750 sector_t new_sector = sh->sector, check;
2751 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2752 : conf->chunk_sectors;
2753 int algorithm = previous ? conf->prev_algo
2754 : conf->algorithm;
2755 sector_t stripe;
2756 int chunk_offset;
2757 sector_t chunk_number;
2758 int dummy1, dd_idx = i;
2759 sector_t r_sector;
2760 struct stripe_head sh2;
2762 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2763 stripe = new_sector;
2765 if (i == sh->pd_idx)
2766 return 0;
2767 switch(conf->level) {
2768 case 4: break;
2769 case 5:
2770 switch (algorithm) {
2771 case ALGORITHM_LEFT_ASYMMETRIC:
2772 case ALGORITHM_RIGHT_ASYMMETRIC:
2773 if (i > sh->pd_idx)
2774 i--;
2775 break;
2776 case ALGORITHM_LEFT_SYMMETRIC:
2777 case ALGORITHM_RIGHT_SYMMETRIC:
2778 if (i < sh->pd_idx)
2779 i += raid_disks;
2780 i -= (sh->pd_idx + 1);
2781 break;
2782 case ALGORITHM_PARITY_0:
2783 i -= 1;
2784 break;
2785 case ALGORITHM_PARITY_N:
2786 break;
2787 default:
2788 BUG();
2790 break;
2791 case 6:
2792 if (i == sh->qd_idx)
2793 return 0; /* It is the Q disk */
2794 switch (algorithm) {
2795 case ALGORITHM_LEFT_ASYMMETRIC:
2796 case ALGORITHM_RIGHT_ASYMMETRIC:
2797 case ALGORITHM_ROTATING_ZERO_RESTART:
2798 case ALGORITHM_ROTATING_N_RESTART:
2799 if (sh->pd_idx == raid_disks-1)
2800 i--; /* Q D D D P */
2801 else if (i > sh->pd_idx)
2802 i -= 2; /* D D P Q D */
2803 break;
2804 case ALGORITHM_LEFT_SYMMETRIC:
2805 case ALGORITHM_RIGHT_SYMMETRIC:
2806 if (sh->pd_idx == raid_disks-1)
2807 i--; /* Q D D D P */
2808 else {
2809 /* D D P Q D */
2810 if (i < sh->pd_idx)
2811 i += raid_disks;
2812 i -= (sh->pd_idx + 2);
2814 break;
2815 case ALGORITHM_PARITY_0:
2816 i -= 2;
2817 break;
2818 case ALGORITHM_PARITY_N:
2819 break;
2820 case ALGORITHM_ROTATING_N_CONTINUE:
2821 /* Like left_symmetric, but P is before Q */
2822 if (sh->pd_idx == 0)
2823 i--; /* P D D D Q */
2824 else {
2825 /* D D Q P D */
2826 if (i < sh->pd_idx)
2827 i += raid_disks;
2828 i -= (sh->pd_idx + 1);
2830 break;
2831 case ALGORITHM_LEFT_ASYMMETRIC_6:
2832 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2833 if (i > sh->pd_idx)
2834 i--;
2835 break;
2836 case ALGORITHM_LEFT_SYMMETRIC_6:
2837 case ALGORITHM_RIGHT_SYMMETRIC_6:
2838 if (i < sh->pd_idx)
2839 i += data_disks + 1;
2840 i -= (sh->pd_idx + 1);
2841 break;
2842 case ALGORITHM_PARITY_0_6:
2843 i -= 1;
2844 break;
2845 default:
2846 BUG();
2848 break;
2851 chunk_number = stripe * data_disks + i;
2852 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2854 check = raid5_compute_sector(conf, r_sector,
2855 previous, &dummy1, &sh2);
2856 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2857 || sh2.qd_idx != sh->qd_idx) {
2858 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2859 mdname(conf->mddev));
2860 return 0;
2862 return r_sector;
2865 static void
2866 schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2867 int rcw, int expand)
2869 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
2870 struct r5conf *conf = sh->raid_conf;
2871 int level = conf->level;
2873 if (rcw) {
2875 for (i = disks; i--; ) {
2876 struct r5dev *dev = &sh->dev[i];
2878 if (dev->towrite) {
2879 set_bit(R5_LOCKED, &dev->flags);
2880 set_bit(R5_Wantdrain, &dev->flags);
2881 if (!expand)
2882 clear_bit(R5_UPTODATE, &dev->flags);
2883 s->locked++;
2886 /* if we are not expanding this is a proper write request, and
2887 * there will be bios with new data to be drained into the
2888 * stripe cache
2890 if (!expand) {
2891 if (!s->locked)
2892 /* False alarm, nothing to do */
2893 return;
2894 sh->reconstruct_state = reconstruct_state_drain_run;
2895 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2896 } else
2897 sh->reconstruct_state = reconstruct_state_run;
2899 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2901 if (s->locked + conf->max_degraded == disks)
2902 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2903 atomic_inc(&conf->pending_full_writes);
2904 } else {
2905 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2906 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2907 BUG_ON(level == 6 &&
2908 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
2909 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
2911 for (i = disks; i--; ) {
2912 struct r5dev *dev = &sh->dev[i];
2913 if (i == pd_idx || i == qd_idx)
2914 continue;
2916 if (dev->towrite &&
2917 (test_bit(R5_UPTODATE, &dev->flags) ||
2918 test_bit(R5_Wantcompute, &dev->flags))) {
2919 set_bit(R5_Wantdrain, &dev->flags);
2920 set_bit(R5_LOCKED, &dev->flags);
2921 clear_bit(R5_UPTODATE, &dev->flags);
2922 s->locked++;
2925 if (!s->locked)
2926 /* False alarm - nothing to do */
2927 return;
2928 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2929 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2930 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2931 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2934 /* keep the parity disk(s) locked while asynchronous operations
2935 * are in flight
2937 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2938 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2939 s->locked++;
2941 if (level == 6) {
2942 int qd_idx = sh->qd_idx;
2943 struct r5dev *dev = &sh->dev[qd_idx];
2945 set_bit(R5_LOCKED, &dev->flags);
2946 clear_bit(R5_UPTODATE, &dev->flags);
2947 s->locked++;
2950 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2951 __func__, (unsigned long long)sh->sector,
2952 s->locked, s->ops_request);
2956 * Each stripe/dev can have one or more bion attached.
2957 * toread/towrite point to the first in a chain.
2958 * The bi_next chain must be in order.
2960 static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
2961 int forwrite, int previous)
2963 struct bio **bip;
2964 struct r5conf *conf = sh->raid_conf;
2965 int firstwrite=0;
2967 pr_debug("adding bi b#%llu to stripe s#%llu\n",
2968 (unsigned long long)bi->bi_iter.bi_sector,
2969 (unsigned long long)sh->sector);
2972 * If several bio share a stripe. The bio bi_phys_segments acts as a
2973 * reference count to avoid race. The reference count should already be
2974 * increased before this function is called (for example, in
2975 * make_request()), so other bio sharing this stripe will not free the
2976 * stripe. If a stripe is owned by one stripe, the stripe lock will
2977 * protect it.
2979 spin_lock_irq(&sh->stripe_lock);
2980 /* Don't allow new IO added to stripes in batch list */
2981 if (sh->batch_head)
2982 goto overlap;
2983 if (forwrite) {
2984 bip = &sh->dev[dd_idx].towrite;
2985 if (*bip == NULL)
2986 firstwrite = 1;
2987 } else
2988 bip = &sh->dev[dd_idx].toread;
2989 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
2990 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
2991 goto overlap;
2992 bip = & (*bip)->bi_next;
2994 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
2995 goto overlap;
2997 if (!forwrite || previous)
2998 clear_bit(STRIPE_BATCH_READY, &sh->state);
3000 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3001 if (*bip)
3002 bi->bi_next = *bip;
3003 *bip = bi;
3004 raid5_inc_bi_active_stripes(bi);
3006 if (forwrite) {
3007 /* check if page is covered */
3008 sector_t sector = sh->dev[dd_idx].sector;
3009 for (bi=sh->dev[dd_idx].towrite;
3010 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3011 bi && bi->bi_iter.bi_sector <= sector;
3012 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3013 if (bio_end_sector(bi) >= sector)
3014 sector = bio_end_sector(bi);
3016 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3017 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3018 sh->overwrite_disks++;
3021 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3022 (unsigned long long)(*bip)->bi_iter.bi_sector,
3023 (unsigned long long)sh->sector, dd_idx);
3025 if (conf->mddev->bitmap && firstwrite) {
3026 /* Cannot hold spinlock over bitmap_startwrite,
3027 * but must ensure this isn't added to a batch until
3028 * we have added to the bitmap and set bm_seq.
3029 * So set STRIPE_BITMAP_PENDING to prevent
3030 * batching.
3031 * If multiple add_stripe_bio() calls race here they
3032 * much all set STRIPE_BITMAP_PENDING. So only the first one
3033 * to complete "bitmap_startwrite" gets to set
3034 * STRIPE_BIT_DELAY. This is important as once a stripe
3035 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3036 * any more.
3038 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3039 spin_unlock_irq(&sh->stripe_lock);
3040 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3041 STRIPE_SECTORS, 0);
3042 spin_lock_irq(&sh->stripe_lock);
3043 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3044 if (!sh->batch_head) {
3045 sh->bm_seq = conf->seq_flush+1;
3046 set_bit(STRIPE_BIT_DELAY, &sh->state);
3049 spin_unlock_irq(&sh->stripe_lock);
3051 if (stripe_can_batch(sh))
3052 stripe_add_to_batch_list(conf, sh);
3053 return 1;
3055 overlap:
3056 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3057 spin_unlock_irq(&sh->stripe_lock);
3058 return 0;
3061 static void end_reshape(struct r5conf *conf);
3063 static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3064 struct stripe_head *sh)
3066 int sectors_per_chunk =
3067 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3068 int dd_idx;
3069 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3070 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3072 raid5_compute_sector(conf,
3073 stripe * (disks - conf->max_degraded)
3074 *sectors_per_chunk + chunk_offset,
3075 previous,
3076 &dd_idx, sh);
3079 static void
3080 handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3081 struct stripe_head_state *s, int disks,
3082 struct bio_list *return_bi)
3084 int i;
3085 BUG_ON(sh->batch_head);
3086 for (i = disks; i--; ) {
3087 struct bio *bi;
3088 int bitmap_end = 0;
3090 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3091 struct md_rdev *rdev;
3092 rcu_read_lock();
3093 rdev = rcu_dereference(conf->disks[i].rdev);
3094 if (rdev && test_bit(In_sync, &rdev->flags))
3095 atomic_inc(&rdev->nr_pending);
3096 else
3097 rdev = NULL;
3098 rcu_read_unlock();
3099 if (rdev) {
3100 if (!rdev_set_badblocks(
3101 rdev,
3102 sh->sector,
3103 STRIPE_SECTORS, 0))
3104 md_error(conf->mddev, rdev);
3105 rdev_dec_pending(rdev, conf->mddev);
3108 spin_lock_irq(&sh->stripe_lock);
3109 /* fail all writes first */
3110 bi = sh->dev[i].towrite;
3111 sh->dev[i].towrite = NULL;
3112 sh->overwrite_disks = 0;
3113 spin_unlock_irq(&sh->stripe_lock);
3114 if (bi)
3115 bitmap_end = 1;
3117 r5l_stripe_write_finished(sh);
3119 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3120 wake_up(&conf->wait_for_overlap);
3122 while (bi && bi->bi_iter.bi_sector <
3123 sh->dev[i].sector + STRIPE_SECTORS) {
3124 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3126 bi->bi_error = -EIO;
3127 if (!raid5_dec_bi_active_stripes(bi)) {
3128 md_write_end(conf->mddev);
3129 bio_list_add(return_bi, bi);
3131 bi = nextbi;
3133 if (bitmap_end)
3134 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3135 STRIPE_SECTORS, 0, 0);
3136 bitmap_end = 0;
3137 /* and fail all 'written' */
3138 bi = sh->dev[i].written;
3139 sh->dev[i].written = NULL;
3140 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3141 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3142 sh->dev[i].page = sh->dev[i].orig_page;
3145 if (bi) bitmap_end = 1;
3146 while (bi && bi->bi_iter.bi_sector <
3147 sh->dev[i].sector + STRIPE_SECTORS) {
3148 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3150 bi->bi_error = -EIO;
3151 if (!raid5_dec_bi_active_stripes(bi)) {
3152 md_write_end(conf->mddev);
3153 bio_list_add(return_bi, bi);
3155 bi = bi2;
3158 /* fail any reads if this device is non-operational and
3159 * the data has not reached the cache yet.
3161 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3162 s->failed > conf->max_degraded &&
3163 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3164 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3165 spin_lock_irq(&sh->stripe_lock);
3166 bi = sh->dev[i].toread;
3167 sh->dev[i].toread = NULL;
3168 spin_unlock_irq(&sh->stripe_lock);
3169 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3170 wake_up(&conf->wait_for_overlap);
3171 if (bi)
3172 s->to_read--;
3173 while (bi && bi->bi_iter.bi_sector <
3174 sh->dev[i].sector + STRIPE_SECTORS) {
3175 struct bio *nextbi =
3176 r5_next_bio(bi, sh->dev[i].sector);
3178 bi->bi_error = -EIO;
3179 if (!raid5_dec_bi_active_stripes(bi))
3180 bio_list_add(return_bi, bi);
3181 bi = nextbi;
3184 if (bitmap_end)
3185 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3186 STRIPE_SECTORS, 0, 0);
3187 /* If we were in the middle of a write the parity block might
3188 * still be locked - so just clear all R5_LOCKED flags
3190 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3192 s->to_write = 0;
3193 s->written = 0;
3195 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3196 if (atomic_dec_and_test(&conf->pending_full_writes))
3197 md_wakeup_thread(conf->mddev->thread);
3200 static void
3201 handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3202 struct stripe_head_state *s)
3204 int abort = 0;
3205 int i;
3207 BUG_ON(sh->batch_head);
3208 clear_bit(STRIPE_SYNCING, &sh->state);
3209 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3210 wake_up(&conf->wait_for_overlap);
3211 s->syncing = 0;
3212 s->replacing = 0;
3213 /* There is nothing more to do for sync/check/repair.
3214 * Don't even need to abort as that is handled elsewhere
3215 * if needed, and not always wanted e.g. if there is a known
3216 * bad block here.
3217 * For recover/replace we need to record a bad block on all
3218 * non-sync devices, or abort the recovery
3220 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3221 /* During recovery devices cannot be removed, so
3222 * locking and refcounting of rdevs is not needed
3224 for (i = 0; i < conf->raid_disks; i++) {
3225 struct md_rdev *rdev = conf->disks[i].rdev;
3226 if (rdev
3227 && !test_bit(Faulty, &rdev->flags)
3228 && !test_bit(In_sync, &rdev->flags)
3229 && !rdev_set_badblocks(rdev, sh->sector,
3230 STRIPE_SECTORS, 0))
3231 abort = 1;
3232 rdev = conf->disks[i].replacement;
3233 if (rdev
3234 && !test_bit(Faulty, &rdev->flags)
3235 && !test_bit(In_sync, &rdev->flags)
3236 && !rdev_set_badblocks(rdev, sh->sector,
3237 STRIPE_SECTORS, 0))
3238 abort = 1;
3240 if (abort)
3241 conf->recovery_disabled =
3242 conf->mddev->recovery_disabled;
3244 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3247 static int want_replace(struct stripe_head *sh, int disk_idx)
3249 struct md_rdev *rdev;
3250 int rv = 0;
3251 /* Doing recovery so rcu locking not required */
3252 rdev = sh->raid_conf->disks[disk_idx].replacement;
3253 if (rdev
3254 && !test_bit(Faulty, &rdev->flags)
3255 && !test_bit(In_sync, &rdev->flags)
3256 && (rdev->recovery_offset <= sh->sector
3257 || rdev->mddev->recovery_cp <= sh->sector))
3258 rv = 1;
3260 return rv;
3263 /* fetch_block - checks the given member device to see if its data needs
3264 * to be read or computed to satisfy a request.
3266 * Returns 1 when no more member devices need to be checked, otherwise returns
3267 * 0 to tell the loop in handle_stripe_fill to continue
3270 static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3271 int disk_idx, int disks)
3273 struct r5dev *dev = &sh->dev[disk_idx];
3274 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3275 &sh->dev[s->failed_num[1]] };
3276 int i;
3279 if (test_bit(R5_LOCKED, &dev->flags) ||
3280 test_bit(R5_UPTODATE, &dev->flags))
3281 /* No point reading this as we already have it or have
3282 * decided to get it.
3284 return 0;
3286 if (dev->toread ||
3287 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3288 /* We need this block to directly satisfy a request */
3289 return 1;
3291 if (s->syncing || s->expanding ||
3292 (s->replacing && want_replace(sh, disk_idx)))
3293 /* When syncing, or expanding we read everything.
3294 * When replacing, we need the replaced block.
3296 return 1;
3298 if ((s->failed >= 1 && fdev[0]->toread) ||
3299 (s->failed >= 2 && fdev[1]->toread))
3300 /* If we want to read from a failed device, then
3301 * we need to actually read every other device.
3303 return 1;
3305 /* Sometimes neither read-modify-write nor reconstruct-write
3306 * cycles can work. In those cases we read every block we
3307 * can. Then the parity-update is certain to have enough to
3308 * work with.
3309 * This can only be a problem when we need to write something,
3310 * and some device has failed. If either of those tests
3311 * fail we need look no further.
3313 if (!s->failed || !s->to_write)
3314 return 0;
3316 if (test_bit(R5_Insync, &dev->flags) &&
3317 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3318 /* Pre-reads at not permitted until after short delay
3319 * to gather multiple requests. However if this
3320 * device is no Insync, the block could only be be computed
3321 * and there is no need to delay that.
3323 return 0;
3325 for (i = 0; i < s->failed && i < 2; i++) {
3326 if (fdev[i]->towrite &&
3327 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3328 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3329 /* If we have a partial write to a failed
3330 * device, then we will need to reconstruct
3331 * the content of that device, so all other
3332 * devices must be read.
3334 return 1;
3337 /* If we are forced to do a reconstruct-write, either because
3338 * the current RAID6 implementation only supports that, or
3339 * or because parity cannot be trusted and we are currently
3340 * recovering it, there is extra need to be careful.
3341 * If one of the devices that we would need to read, because
3342 * it is not being overwritten (and maybe not written at all)
3343 * is missing/faulty, then we need to read everything we can.
3345 if (sh->raid_conf->level != 6 &&
3346 sh->sector < sh->raid_conf->mddev->recovery_cp)
3347 /* reconstruct-write isn't being forced */
3348 return 0;
3349 for (i = 0; i < s->failed && i < 2; i++) {
3350 if (s->failed_num[i] != sh->pd_idx &&
3351 s->failed_num[i] != sh->qd_idx &&
3352 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3353 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3354 return 1;
3357 return 0;
3360 static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3361 int disk_idx, int disks)
3363 struct r5dev *dev = &sh->dev[disk_idx];
3365 /* is the data in this block needed, and can we get it? */
3366 if (need_this_block(sh, s, disk_idx, disks)) {
3367 /* we would like to get this block, possibly by computing it,
3368 * otherwise read it if the backing disk is insync
3370 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3371 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3372 BUG_ON(sh->batch_head);
3375 * In the raid6 case if the only non-uptodate disk is P
3376 * then we already trusted P to compute the other failed
3377 * drives. It is safe to compute rather than re-read P.
3378 * In other cases we only compute blocks from failed
3379 * devices, otherwise check/repair might fail to detect
3380 * a real inconsistency.
3383 if ((s->uptodate == disks - 1) &&
3384 ((sh->qd_idx >= 0 && sh->pd_idx == disk_idx) ||
3385 (s->failed && (disk_idx == s->failed_num[0] ||
3386 disk_idx == s->failed_num[1])))) {
3387 /* have disk failed, and we're requested to fetch it;
3388 * do compute it
3390 pr_debug("Computing stripe %llu block %d\n",
3391 (unsigned long long)sh->sector, disk_idx);
3392 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3393 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3394 set_bit(R5_Wantcompute, &dev->flags);
3395 sh->ops.target = disk_idx;
3396 sh->ops.target2 = -1; /* no 2nd target */
3397 s->req_compute = 1;
3398 /* Careful: from this point on 'uptodate' is in the eye
3399 * of raid_run_ops which services 'compute' operations
3400 * before writes. R5_Wantcompute flags a block that will
3401 * be R5_UPTODATE by the time it is needed for a
3402 * subsequent operation.
3404 s->uptodate++;
3405 return 1;
3406 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3407 /* Computing 2-failure is *very* expensive; only
3408 * do it if failed >= 2
3410 int other;
3411 for (other = disks; other--; ) {
3412 if (other == disk_idx)
3413 continue;
3414 if (!test_bit(R5_UPTODATE,
3415 &sh->dev[other].flags))
3416 break;
3418 BUG_ON(other < 0);
3419 pr_debug("Computing stripe %llu blocks %d,%d\n",
3420 (unsigned long long)sh->sector,
3421 disk_idx, other);
3422 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3423 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3424 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3425 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3426 sh->ops.target = disk_idx;
3427 sh->ops.target2 = other;
3428 s->uptodate += 2;
3429 s->req_compute = 1;
3430 return 1;
3431 } else if (test_bit(R5_Insync, &dev->flags)) {
3432 set_bit(R5_LOCKED, &dev->flags);
3433 set_bit(R5_Wantread, &dev->flags);
3434 s->locked++;
3435 pr_debug("Reading block %d (sync=%d)\n",
3436 disk_idx, s->syncing);
3440 return 0;
3444 * handle_stripe_fill - read or compute data to satisfy pending requests.
3446 static void handle_stripe_fill(struct stripe_head *sh,
3447 struct stripe_head_state *s,
3448 int disks)
3450 int i;
3452 /* look for blocks to read/compute, skip this if a compute
3453 * is already in flight, or if the stripe contents are in the
3454 * midst of changing due to a write
3456 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3457 !sh->reconstruct_state)
3458 for (i = disks; i--; )
3459 if (fetch_block(sh, s, i, disks))
3460 break;
3461 set_bit(STRIPE_HANDLE, &sh->state);
3464 static void break_stripe_batch_list(struct stripe_head *head_sh,
3465 unsigned long handle_flags);
3466 /* handle_stripe_clean_event
3467 * any written block on an uptodate or failed drive can be returned.
3468 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3469 * never LOCKED, so we don't need to test 'failed' directly.
3471 static void handle_stripe_clean_event(struct r5conf *conf,
3472 struct stripe_head *sh, int disks, struct bio_list *return_bi)
3474 int i;
3475 struct r5dev *dev;
3476 int discard_pending = 0;
3477 struct stripe_head *head_sh = sh;
3478 bool do_endio = false;
3480 for (i = disks; i--; )
3481 if (sh->dev[i].written) {
3482 dev = &sh->dev[i];
3483 if (!test_bit(R5_LOCKED, &dev->flags) &&
3484 (test_bit(R5_UPTODATE, &dev->flags) ||
3485 test_bit(R5_Discard, &dev->flags) ||
3486 test_bit(R5_SkipCopy, &dev->flags))) {
3487 /* We can return any write requests */
3488 struct bio *wbi, *wbi2;
3489 pr_debug("Return write for disc %d\n", i);
3490 if (test_and_clear_bit(R5_Discard, &dev->flags))
3491 clear_bit(R5_UPTODATE, &dev->flags);
3492 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3493 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3495 do_endio = true;
3497 returnbi:
3498 dev->page = dev->orig_page;
3499 wbi = dev->written;
3500 dev->written = NULL;
3501 while (wbi && wbi->bi_iter.bi_sector <
3502 dev->sector + STRIPE_SECTORS) {
3503 wbi2 = r5_next_bio(wbi, dev->sector);
3504 if (!raid5_dec_bi_active_stripes(wbi)) {
3505 md_write_end(conf->mddev);
3506 bio_list_add(return_bi, wbi);
3508 wbi = wbi2;
3510 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3511 STRIPE_SECTORS,
3512 !test_bit(STRIPE_DEGRADED, &sh->state),
3514 if (head_sh->batch_head) {
3515 sh = list_first_entry(&sh->batch_list,
3516 struct stripe_head,
3517 batch_list);
3518 if (sh != head_sh) {
3519 dev = &sh->dev[i];
3520 goto returnbi;
3523 sh = head_sh;
3524 dev = &sh->dev[i];
3525 } else if (test_bit(R5_Discard, &dev->flags))
3526 discard_pending = 1;
3527 WARN_ON(test_bit(R5_SkipCopy, &dev->flags));
3528 WARN_ON(dev->page != dev->orig_page);
3531 r5l_stripe_write_finished(sh);
3533 if (!discard_pending &&
3534 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3535 int hash;
3536 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3537 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3538 if (sh->qd_idx >= 0) {
3539 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3540 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3542 /* now that discard is done we can proceed with any sync */
3543 clear_bit(STRIPE_DISCARD, &sh->state);
3545 * SCSI discard will change some bio fields and the stripe has
3546 * no updated data, so remove it from hash list and the stripe
3547 * will be reinitialized
3549 unhash:
3550 hash = sh->hash_lock_index;
3551 spin_lock_irq(conf->hash_locks + hash);
3552 remove_hash(sh);
3553 spin_unlock_irq(conf->hash_locks + hash);
3554 if (head_sh->batch_head) {
3555 sh = list_first_entry(&sh->batch_list,
3556 struct stripe_head, batch_list);
3557 if (sh != head_sh)
3558 goto unhash;
3560 sh = head_sh;
3562 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3563 set_bit(STRIPE_HANDLE, &sh->state);
3567 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3568 if (atomic_dec_and_test(&conf->pending_full_writes))
3569 md_wakeup_thread(conf->mddev->thread);
3571 if (head_sh->batch_head && do_endio)
3572 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3575 static void handle_stripe_dirtying(struct r5conf *conf,
3576 struct stripe_head *sh,
3577 struct stripe_head_state *s,
3578 int disks)
3580 int rmw = 0, rcw = 0, i;
3581 sector_t recovery_cp = conf->mddev->recovery_cp;
3583 /* Check whether resync is now happening or should start.
3584 * If yes, then the array is dirty (after unclean shutdown or
3585 * initial creation), so parity in some stripes might be inconsistent.
3586 * In this case, we need to always do reconstruct-write, to ensure
3587 * that in case of drive failure or read-error correction, we
3588 * generate correct data from the parity.
3590 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3591 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3592 s->failed == 0)) {
3593 /* Calculate the real rcw later - for now make it
3594 * look like rcw is cheaper
3596 rcw = 1; rmw = 2;
3597 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3598 conf->rmw_level, (unsigned long long)recovery_cp,
3599 (unsigned long long)sh->sector);
3600 } else for (i = disks; i--; ) {
3601 /* would I have to read this buffer for read_modify_write */
3602 struct r5dev *dev = &sh->dev[i];
3603 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3604 !test_bit(R5_LOCKED, &dev->flags) &&
3605 !(test_bit(R5_UPTODATE, &dev->flags) ||
3606 test_bit(R5_Wantcompute, &dev->flags))) {
3607 if (test_bit(R5_Insync, &dev->flags))
3608 rmw++;
3609 else
3610 rmw += 2*disks; /* cannot read it */
3612 /* Would I have to read this buffer for reconstruct_write */
3613 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3614 i != sh->pd_idx && i != sh->qd_idx &&
3615 !test_bit(R5_LOCKED, &dev->flags) &&
3616 !(test_bit(R5_UPTODATE, &dev->flags) ||
3617 test_bit(R5_Wantcompute, &dev->flags))) {
3618 if (test_bit(R5_Insync, &dev->flags))
3619 rcw++;
3620 else
3621 rcw += 2*disks;
3624 pr_debug("for sector %llu, rmw=%d rcw=%d\n",
3625 (unsigned long long)sh->sector, rmw, rcw);
3626 set_bit(STRIPE_HANDLE, &sh->state);
3627 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_ENABLE_RMW)) && rmw > 0) {
3628 /* prefer read-modify-write, but need to get some data */
3629 if (conf->mddev->queue)
3630 blk_add_trace_msg(conf->mddev->queue,
3631 "raid5 rmw %llu %d",
3632 (unsigned long long)sh->sector, rmw);
3633 for (i = disks; i--; ) {
3634 struct r5dev *dev = &sh->dev[i];
3635 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3636 !test_bit(R5_LOCKED, &dev->flags) &&
3637 !(test_bit(R5_UPTODATE, &dev->flags) ||
3638 test_bit(R5_Wantcompute, &dev->flags)) &&
3639 test_bit(R5_Insync, &dev->flags)) {
3640 if (test_bit(STRIPE_PREREAD_ACTIVE,
3641 &sh->state)) {
3642 pr_debug("Read_old block %d for r-m-w\n",
3644 set_bit(R5_LOCKED, &dev->flags);
3645 set_bit(R5_Wantread, &dev->flags);
3646 s->locked++;
3647 } else {
3648 set_bit(STRIPE_DELAYED, &sh->state);
3649 set_bit(STRIPE_HANDLE, &sh->state);
3654 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_ENABLE_RMW)) && rcw > 0) {
3655 /* want reconstruct write, but need to get some data */
3656 int qread =0;
3657 rcw = 0;
3658 for (i = disks; i--; ) {
3659 struct r5dev *dev = &sh->dev[i];
3660 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3661 i != sh->pd_idx && i != sh->qd_idx &&
3662 !test_bit(R5_LOCKED, &dev->flags) &&
3663 !(test_bit(R5_UPTODATE, &dev->flags) ||
3664 test_bit(R5_Wantcompute, &dev->flags))) {
3665 rcw++;
3666 if (test_bit(R5_Insync, &dev->flags) &&
3667 test_bit(STRIPE_PREREAD_ACTIVE,
3668 &sh->state)) {
3669 pr_debug("Read_old block "
3670 "%d for Reconstruct\n", i);
3671 set_bit(R5_LOCKED, &dev->flags);
3672 set_bit(R5_Wantread, &dev->flags);
3673 s->locked++;
3674 qread++;
3675 } else {
3676 set_bit(STRIPE_DELAYED, &sh->state);
3677 set_bit(STRIPE_HANDLE, &sh->state);
3681 if (rcw && conf->mddev->queue)
3682 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
3683 (unsigned long long)sh->sector,
3684 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
3687 if (rcw > disks && rmw > disks &&
3688 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3689 set_bit(STRIPE_DELAYED, &sh->state);
3691 /* now if nothing is locked, and if we have enough data,
3692 * we can start a write request
3694 /* since handle_stripe can be called at any time we need to handle the
3695 * case where a compute block operation has been submitted and then a
3696 * subsequent call wants to start a write request. raid_run_ops only
3697 * handles the case where compute block and reconstruct are requested
3698 * simultaneously. If this is not the case then new writes need to be
3699 * held off until the compute completes.
3701 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
3702 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
3703 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
3704 schedule_reconstruction(sh, s, rcw == 0, 0);
3707 static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
3708 struct stripe_head_state *s, int disks)
3710 struct r5dev *dev = NULL;
3712 BUG_ON(sh->batch_head);
3713 set_bit(STRIPE_HANDLE, &sh->state);
3715 switch (sh->check_state) {
3716 case check_state_idle:
3717 /* start a new check operation if there are no failures */
3718 if (s->failed == 0) {
3719 BUG_ON(s->uptodate != disks);
3720 sh->check_state = check_state_run;
3721 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3722 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3723 s->uptodate--;
3724 break;
3726 dev = &sh->dev[s->failed_num[0]];
3727 /* fall through */
3728 case check_state_compute_result:
3729 sh->check_state = check_state_idle;
3730 if (!dev)
3731 dev = &sh->dev[sh->pd_idx];
3733 /* check that a write has not made the stripe insync */
3734 if (test_bit(STRIPE_INSYNC, &sh->state))
3735 break;
3737 /* either failed parity check, or recovery is happening */
3738 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
3739 BUG_ON(s->uptodate != disks);
3741 set_bit(R5_LOCKED, &dev->flags);
3742 s->locked++;
3743 set_bit(R5_Wantwrite, &dev->flags);
3745 clear_bit(STRIPE_DEGRADED, &sh->state);
3746 set_bit(STRIPE_INSYNC, &sh->state);
3747 break;
3748 case check_state_run:
3749 break; /* we will be called again upon completion */
3750 case check_state_check_result:
3751 sh->check_state = check_state_idle;
3753 /* if a failure occurred during the check operation, leave
3754 * STRIPE_INSYNC not set and let the stripe be handled again
3756 if (s->failed)
3757 break;
3759 /* handle a successful check operation, if parity is correct
3760 * we are done. Otherwise update the mismatch count and repair
3761 * parity if !MD_RECOVERY_CHECK
3763 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
3764 /* parity is correct (on disc,
3765 * not in buffer any more)
3767 set_bit(STRIPE_INSYNC, &sh->state);
3768 else {
3769 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3770 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3771 /* don't try to repair!! */
3772 set_bit(STRIPE_INSYNC, &sh->state);
3773 else {
3774 sh->check_state = check_state_compute_run;
3775 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3776 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3777 set_bit(R5_Wantcompute,
3778 &sh->dev[sh->pd_idx].flags);
3779 sh->ops.target = sh->pd_idx;
3780 sh->ops.target2 = -1;
3781 s->uptodate++;
3784 break;
3785 case check_state_compute_run:
3786 break;
3787 default:
3788 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3789 __func__, sh->check_state,
3790 (unsigned long long) sh->sector);
3791 BUG();
3795 static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3796 struct stripe_head_state *s,
3797 int disks)
3799 int pd_idx = sh->pd_idx;
3800 int qd_idx = sh->qd_idx;
3801 struct r5dev *dev;
3803 BUG_ON(sh->batch_head);
3804 set_bit(STRIPE_HANDLE, &sh->state);
3806 BUG_ON(s->failed > 2);
3808 /* Want to check and possibly repair P and Q.
3809 * However there could be one 'failed' device, in which
3810 * case we can only check one of them, possibly using the
3811 * other to generate missing data
3814 switch (sh->check_state) {
3815 case check_state_idle:
3816 /* start a new check operation if there are < 2 failures */
3817 if (s->failed == s->q_failed) {
3818 /* The only possible failed device holds Q, so it
3819 * makes sense to check P (If anything else were failed,
3820 * we would have used P to recreate it).
3822 sh->check_state = check_state_run;
3824 if (!s->q_failed && s->failed < 2) {
3825 /* Q is not failed, and we didn't use it to generate
3826 * anything, so it makes sense to check it
3828 if (sh->check_state == check_state_run)
3829 sh->check_state = check_state_run_pq;
3830 else
3831 sh->check_state = check_state_run_q;
3834 /* discard potentially stale zero_sum_result */
3835 sh->ops.zero_sum_result = 0;
3837 if (sh->check_state == check_state_run) {
3838 /* async_xor_zero_sum destroys the contents of P */
3839 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3840 s->uptodate--;
3842 if (sh->check_state >= check_state_run &&
3843 sh->check_state <= check_state_run_pq) {
3844 /* async_syndrome_zero_sum preserves P and Q, so
3845 * no need to mark them !uptodate here
3847 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3848 break;
3851 /* we have 2-disk failure */
3852 BUG_ON(s->failed != 2);
3853 /* fall through */
3854 case check_state_compute_result:
3855 sh->check_state = check_state_idle;
3857 /* check that a write has not made the stripe insync */
3858 if (test_bit(STRIPE_INSYNC, &sh->state))
3859 break;
3861 /* now write out any block on a failed drive,
3862 * or P or Q if they were recomputed
3864 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3865 if (s->failed == 2) {
3866 dev = &sh->dev[s->failed_num[1]];
3867 s->locked++;
3868 set_bit(R5_LOCKED, &dev->flags);
3869 set_bit(R5_Wantwrite, &dev->flags);
3871 if (s->failed >= 1) {
3872 dev = &sh->dev[s->failed_num[0]];
3873 s->locked++;
3874 set_bit(R5_LOCKED, &dev->flags);
3875 set_bit(R5_Wantwrite, &dev->flags);
3877 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3878 dev = &sh->dev[pd_idx];
3879 s->locked++;
3880 set_bit(R5_LOCKED, &dev->flags);
3881 set_bit(R5_Wantwrite, &dev->flags);
3883 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3884 dev = &sh->dev[qd_idx];
3885 s->locked++;
3886 set_bit(R5_LOCKED, &dev->flags);
3887 set_bit(R5_Wantwrite, &dev->flags);
3889 clear_bit(STRIPE_DEGRADED, &sh->state);
3891 set_bit(STRIPE_INSYNC, &sh->state);
3892 break;
3893 case check_state_run:
3894 case check_state_run_q:
3895 case check_state_run_pq:
3896 break; /* we will be called again upon completion */
3897 case check_state_check_result:
3898 sh->check_state = check_state_idle;
3900 /* handle a successful check operation, if parity is correct
3901 * we are done. Otherwise update the mismatch count and repair
3902 * parity if !MD_RECOVERY_CHECK
3904 if (sh->ops.zero_sum_result == 0) {
3905 /* both parities are correct */
3906 if (!s->failed)
3907 set_bit(STRIPE_INSYNC, &sh->state);
3908 else {
3909 /* in contrast to the raid5 case we can validate
3910 * parity, but still have a failure to write
3911 * back
3913 sh->check_state = check_state_compute_result;
3914 /* Returning at this point means that we may go
3915 * off and bring p and/or q uptodate again so
3916 * we make sure to check zero_sum_result again
3917 * to verify if p or q need writeback
3920 } else {
3921 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3922 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3923 /* don't try to repair!! */
3924 set_bit(STRIPE_INSYNC, &sh->state);
3925 else {
3926 int *target = &sh->ops.target;
3928 sh->ops.target = -1;
3929 sh->ops.target2 = -1;
3930 sh->check_state = check_state_compute_run;
3931 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3932 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3933 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3934 set_bit(R5_Wantcompute,
3935 &sh->dev[pd_idx].flags);
3936 *target = pd_idx;
3937 target = &sh->ops.target2;
3938 s->uptodate++;
3940 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3941 set_bit(R5_Wantcompute,
3942 &sh->dev[qd_idx].flags);
3943 *target = qd_idx;
3944 s->uptodate++;
3948 break;
3949 case check_state_compute_run:
3950 break;
3951 default:
3952 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3953 __func__, sh->check_state,
3954 (unsigned long long) sh->sector);
3955 BUG();
3959 static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3961 int i;
3963 /* We have read all the blocks in this stripe and now we need to
3964 * copy some of them into a target stripe for expand.
3966 struct dma_async_tx_descriptor *tx = NULL;
3967 BUG_ON(sh->batch_head);
3968 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3969 for (i = 0; i < sh->disks; i++)
3970 if (i != sh->pd_idx && i != sh->qd_idx) {
3971 int dd_idx, j;
3972 struct stripe_head *sh2;
3973 struct async_submit_ctl submit;
3975 sector_t bn = raid5_compute_blocknr(sh, i, 1);
3976 sector_t s = raid5_compute_sector(conf, bn, 0,
3977 &dd_idx, NULL);
3978 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
3979 if (sh2 == NULL)
3980 /* so far only the early blocks of this stripe
3981 * have been requested. When later blocks
3982 * get requested, we will try again
3984 continue;
3985 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3986 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3987 /* must have already done this block */
3988 raid5_release_stripe(sh2);
3989 continue;
3992 /* place all the copies on one channel */
3993 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3994 tx = async_memcpy(sh2->dev[dd_idx].page,
3995 sh->dev[i].page, 0, 0, STRIPE_SIZE,
3996 &submit);
3998 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3999 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
4000 for (j = 0; j < conf->raid_disks; j++)
4001 if (j != sh2->pd_idx &&
4002 j != sh2->qd_idx &&
4003 !test_bit(R5_Expanded, &sh2->dev[j].flags))
4004 break;
4005 if (j == conf->raid_disks) {
4006 set_bit(STRIPE_EXPAND_READY, &sh2->state);
4007 set_bit(STRIPE_HANDLE, &sh2->state);
4009 raid5_release_stripe(sh2);
4012 /* done submitting copies, wait for them to complete */
4013 async_tx_quiesce(&tx);
4017 * handle_stripe - do things to a stripe.
4019 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4020 * state of various bits to see what needs to be done.
4021 * Possible results:
4022 * return some read requests which now have data
4023 * return some write requests which are safely on storage
4024 * schedule a read on some buffers
4025 * schedule a write of some buffers
4026 * return confirmation of parity correctness
4030 static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4032 struct r5conf *conf = sh->raid_conf;
4033 int disks = sh->disks;
4034 struct r5dev *dev;
4035 int i;
4036 int do_recovery = 0;
4038 memset(s, 0, sizeof(*s));
4040 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4041 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4042 s->failed_num[0] = -1;
4043 s->failed_num[1] = -1;
4044 s->log_failed = r5l_log_disk_error(conf);
4046 /* Now to look around and see what can be done */
4047 rcu_read_lock();
4048 for (i=disks; i--; ) {
4049 struct md_rdev *rdev;
4050 sector_t first_bad;
4051 int bad_sectors;
4052 int is_bad = 0;
4054 dev = &sh->dev[i];
4056 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4057 i, dev->flags,
4058 dev->toread, dev->towrite, dev->written);
4059 /* maybe we can reply to a read
4061 * new wantfill requests are only permitted while
4062 * ops_complete_biofill is guaranteed to be inactive
4064 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4065 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4066 set_bit(R5_Wantfill, &dev->flags);
4068 /* now count some things */
4069 if (test_bit(R5_LOCKED, &dev->flags))
4070 s->locked++;
4071 if (test_bit(R5_UPTODATE, &dev->flags))
4072 s->uptodate++;
4073 if (test_bit(R5_Wantcompute, &dev->flags)) {
4074 s->compute++;
4075 BUG_ON(s->compute > 2);
4078 if (test_bit(R5_Wantfill, &dev->flags))
4079 s->to_fill++;
4080 else if (dev->toread)
4081 s->to_read++;
4082 if (dev->towrite) {
4083 s->to_write++;
4084 if (!test_bit(R5_OVERWRITE, &dev->flags))
4085 s->non_overwrite++;
4087 if (dev->written)
4088 s->written++;
4089 /* Prefer to use the replacement for reads, but only
4090 * if it is recovered enough and has no bad blocks.
4092 rdev = rcu_dereference(conf->disks[i].replacement);
4093 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4094 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4095 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4096 &first_bad, &bad_sectors))
4097 set_bit(R5_ReadRepl, &dev->flags);
4098 else {
4099 if (rdev && !test_bit(Faulty, &rdev->flags))
4100 set_bit(R5_NeedReplace, &dev->flags);
4101 else
4102 clear_bit(R5_NeedReplace, &dev->flags);
4103 rdev = rcu_dereference(conf->disks[i].rdev);
4104 clear_bit(R5_ReadRepl, &dev->flags);
4106 if (rdev && test_bit(Faulty, &rdev->flags))
4107 rdev = NULL;
4108 if (rdev) {
4109 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4110 &first_bad, &bad_sectors);
4111 if (s->blocked_rdev == NULL
4112 && (test_bit(Blocked, &rdev->flags)
4113 || is_bad < 0)) {
4114 if (is_bad < 0)
4115 set_bit(BlockedBadBlocks,
4116 &rdev->flags);
4117 s->blocked_rdev = rdev;
4118 atomic_inc(&rdev->nr_pending);
4121 clear_bit(R5_Insync, &dev->flags);
4122 if (!rdev)
4123 /* Not in-sync */;
4124 else if (is_bad) {
4125 /* also not in-sync */
4126 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4127 test_bit(R5_UPTODATE, &dev->flags)) {
4128 /* treat as in-sync, but with a read error
4129 * which we can now try to correct
4131 set_bit(R5_Insync, &dev->flags);
4132 set_bit(R5_ReadError, &dev->flags);
4134 } else if (test_bit(In_sync, &rdev->flags))
4135 set_bit(R5_Insync, &dev->flags);
4136 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4137 /* in sync if before recovery_offset */
4138 set_bit(R5_Insync, &dev->flags);
4139 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4140 test_bit(R5_Expanded, &dev->flags))
4141 /* If we've reshaped into here, we assume it is Insync.
4142 * We will shortly update recovery_offset to make
4143 * it official.
4145 set_bit(R5_Insync, &dev->flags);
4147 if (test_bit(R5_WriteError, &dev->flags)) {
4148 /* This flag does not apply to '.replacement'
4149 * only to .rdev, so make sure to check that*/
4150 struct md_rdev *rdev2 = rcu_dereference(
4151 conf->disks[i].rdev);
4152 if (rdev2 == rdev)
4153 clear_bit(R5_Insync, &dev->flags);
4154 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4155 s->handle_bad_blocks = 1;
4156 atomic_inc(&rdev2->nr_pending);
4157 } else
4158 clear_bit(R5_WriteError, &dev->flags);
4160 if (test_bit(R5_MadeGood, &dev->flags)) {
4161 /* This flag does not apply to '.replacement'
4162 * only to .rdev, so make sure to check that*/
4163 struct md_rdev *rdev2 = rcu_dereference(
4164 conf->disks[i].rdev);
4165 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4166 s->handle_bad_blocks = 1;
4167 atomic_inc(&rdev2->nr_pending);
4168 } else
4169 clear_bit(R5_MadeGood, &dev->flags);
4171 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4172 struct md_rdev *rdev2 = rcu_dereference(
4173 conf->disks[i].replacement);
4174 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4175 s->handle_bad_blocks = 1;
4176 atomic_inc(&rdev2->nr_pending);
4177 } else
4178 clear_bit(R5_MadeGoodRepl, &dev->flags);
4180 if (!test_bit(R5_Insync, &dev->flags)) {
4181 /* The ReadError flag will just be confusing now */
4182 clear_bit(R5_ReadError, &dev->flags);
4183 clear_bit(R5_ReWrite, &dev->flags);
4185 if (test_bit(R5_ReadError, &dev->flags))
4186 clear_bit(R5_Insync, &dev->flags);
4187 if (!test_bit(R5_Insync, &dev->flags)) {
4188 if (s->failed < 2)
4189 s->failed_num[s->failed] = i;
4190 s->failed++;
4191 if (rdev && !test_bit(Faulty, &rdev->flags))
4192 do_recovery = 1;
4193 else if (!rdev) {
4194 rdev = rcu_dereference(
4195 conf->disks[i].replacement);
4196 if (rdev && !test_bit(Faulty, &rdev->flags))
4197 do_recovery = 1;
4201 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4202 /* If there is a failed device being replaced,
4203 * we must be recovering.
4204 * else if we are after recovery_cp, we must be syncing
4205 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4206 * else we can only be replacing
4207 * sync and recovery both need to read all devices, and so
4208 * use the same flag.
4210 if (do_recovery ||
4211 sh->sector >= conf->mddev->recovery_cp ||
4212 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4213 s->syncing = 1;
4214 else
4215 s->replacing = 1;
4217 rcu_read_unlock();
4220 static int clear_batch_ready(struct stripe_head *sh)
4222 /* Return '1' if this is a member of batch, or
4223 * '0' if it is a lone stripe or a head which can now be
4224 * handled.
4226 struct stripe_head *tmp;
4227 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4228 return (sh->batch_head && sh->batch_head != sh);
4229 spin_lock(&sh->stripe_lock);
4230 if (!sh->batch_head) {
4231 spin_unlock(&sh->stripe_lock);
4232 return 0;
4236 * this stripe could be added to a batch list before we check
4237 * BATCH_READY, skips it
4239 if (sh->batch_head != sh) {
4240 spin_unlock(&sh->stripe_lock);
4241 return 1;
4243 spin_lock(&sh->batch_lock);
4244 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4245 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4246 spin_unlock(&sh->batch_lock);
4247 spin_unlock(&sh->stripe_lock);
4250 * BATCH_READY is cleared, no new stripes can be added.
4251 * batch_list can be accessed without lock
4253 return 0;
4256 static void break_stripe_batch_list(struct stripe_head *head_sh,
4257 unsigned long handle_flags)
4259 struct stripe_head *sh, *next;
4260 int i;
4261 int do_wakeup = 0;
4263 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4265 list_del_init(&sh->batch_list);
4267 WARN_ON_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4268 (1 << STRIPE_SYNCING) |
4269 (1 << STRIPE_REPLACED) |
4270 (1 << STRIPE_DELAYED) |
4271 (1 << STRIPE_BIT_DELAY) |
4272 (1 << STRIPE_FULL_WRITE) |
4273 (1 << STRIPE_BIOFILL_RUN) |
4274 (1 << STRIPE_COMPUTE_RUN) |
4275 (1 << STRIPE_OPS_REQ_PENDING) |
4276 (1 << STRIPE_DISCARD) |
4277 (1 << STRIPE_BATCH_READY) |
4278 (1 << STRIPE_BATCH_ERR) |
4279 (1 << STRIPE_BITMAP_PENDING)));
4280 WARN_ON_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4281 (1 << STRIPE_REPLACED)));
4283 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4284 (1 << STRIPE_PREREAD_ACTIVE) |
4285 (1 << STRIPE_DEGRADED) |
4286 (1 << STRIPE_ON_UNPLUG_LIST)),
4287 head_sh->state & (1 << STRIPE_INSYNC));
4289 sh->check_state = head_sh->check_state;
4290 sh->reconstruct_state = head_sh->reconstruct_state;
4291 for (i = 0; i < sh->disks; i++) {
4292 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4293 do_wakeup = 1;
4294 sh->dev[i].flags = head_sh->dev[i].flags &
4295 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4297 spin_lock_irq(&sh->stripe_lock);
4298 sh->batch_head = NULL;
4299 spin_unlock_irq(&sh->stripe_lock);
4300 if (handle_flags == 0 ||
4301 sh->state & handle_flags)
4302 set_bit(STRIPE_HANDLE, &sh->state);
4303 raid5_release_stripe(sh);
4305 spin_lock_irq(&head_sh->stripe_lock);
4306 head_sh->batch_head = NULL;
4307 spin_unlock_irq(&head_sh->stripe_lock);
4308 for (i = 0; i < head_sh->disks; i++)
4309 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4310 do_wakeup = 1;
4311 if (head_sh->state & handle_flags)
4312 set_bit(STRIPE_HANDLE, &head_sh->state);
4314 if (do_wakeup)
4315 wake_up(&head_sh->raid_conf->wait_for_overlap);
4318 static void handle_stripe(struct stripe_head *sh)
4320 struct stripe_head_state s;
4321 struct r5conf *conf = sh->raid_conf;
4322 int i;
4323 int prexor;
4324 int disks = sh->disks;
4325 struct r5dev *pdev, *qdev;
4327 clear_bit(STRIPE_HANDLE, &sh->state);
4328 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4329 /* already being handled, ensure it gets handled
4330 * again when current action finishes */
4331 set_bit(STRIPE_HANDLE, &sh->state);
4332 return;
4335 if (clear_batch_ready(sh) ) {
4336 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4337 return;
4340 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4341 break_stripe_batch_list(sh, 0);
4343 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4344 spin_lock(&sh->stripe_lock);
4345 /* Cannot process 'sync' concurrently with 'discard' */
4346 if (!test_bit(STRIPE_DISCARD, &sh->state) &&
4347 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4348 set_bit(STRIPE_SYNCING, &sh->state);
4349 clear_bit(STRIPE_INSYNC, &sh->state);
4350 clear_bit(STRIPE_REPLACED, &sh->state);
4352 spin_unlock(&sh->stripe_lock);
4354 clear_bit(STRIPE_DELAYED, &sh->state);
4356 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4357 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4358 (unsigned long long)sh->sector, sh->state,
4359 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4360 sh->check_state, sh->reconstruct_state);
4362 analyse_stripe(sh, &s);
4364 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4365 goto finish;
4367 if (s.handle_bad_blocks) {
4368 set_bit(STRIPE_HANDLE, &sh->state);
4369 goto finish;
4372 if (unlikely(s.blocked_rdev)) {
4373 if (s.syncing || s.expanding || s.expanded ||
4374 s.replacing || s.to_write || s.written) {
4375 set_bit(STRIPE_HANDLE, &sh->state);
4376 goto finish;
4378 /* There is nothing for the blocked_rdev to block */
4379 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4380 s.blocked_rdev = NULL;
4383 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4384 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4385 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4388 pr_debug("locked=%d uptodate=%d to_read=%d"
4389 " to_write=%d failed=%d failed_num=%d,%d\n",
4390 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4391 s.failed_num[0], s.failed_num[1]);
4392 /* check if the array has lost more than max_degraded devices and,
4393 * if so, some requests might need to be failed.
4395 if (s.failed > conf->max_degraded || s.log_failed) {
4396 sh->check_state = 0;
4397 sh->reconstruct_state = 0;
4398 break_stripe_batch_list(sh, 0);
4399 if (s.to_read+s.to_write+s.written)
4400 handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
4401 if (s.syncing + s.replacing)
4402 handle_failed_sync(conf, sh, &s);
4405 /* Now we check to see if any write operations have recently
4406 * completed
4408 prexor = 0;
4409 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4410 prexor = 1;
4411 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4412 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4413 sh->reconstruct_state = reconstruct_state_idle;
4415 /* All the 'written' buffers and the parity block are ready to
4416 * be written back to disk
4418 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4419 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4420 BUG_ON(sh->qd_idx >= 0 &&
4421 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4422 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4423 for (i = disks; i--; ) {
4424 struct r5dev *dev = &sh->dev[i];
4425 if (test_bit(R5_LOCKED, &dev->flags) &&
4426 (i == sh->pd_idx || i == sh->qd_idx ||
4427 dev->written)) {
4428 pr_debug("Writing block %d\n", i);
4429 set_bit(R5_Wantwrite, &dev->flags);
4430 if (prexor)
4431 continue;
4432 if (s.failed > 1)
4433 continue;
4434 if (!test_bit(R5_Insync, &dev->flags) ||
4435 ((i == sh->pd_idx || i == sh->qd_idx) &&
4436 s.failed == 0))
4437 set_bit(STRIPE_INSYNC, &sh->state);
4440 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4441 s.dec_preread_active = 1;
4445 * might be able to return some write requests if the parity blocks
4446 * are safe, or on a failed drive
4448 pdev = &sh->dev[sh->pd_idx];
4449 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4450 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4451 qdev = &sh->dev[sh->qd_idx];
4452 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4453 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4454 || conf->level < 6;
4456 if (s.written &&
4457 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4458 && !test_bit(R5_LOCKED, &pdev->flags)
4459 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4460 test_bit(R5_Discard, &pdev->flags))))) &&
4461 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4462 && !test_bit(R5_LOCKED, &qdev->flags)
4463 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4464 test_bit(R5_Discard, &qdev->flags))))))
4465 handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
4467 /* Now we might consider reading some blocks, either to check/generate
4468 * parity, or to satisfy requests
4469 * or to load a block that is being partially written.
4471 if (s.to_read || s.non_overwrite
4472 || (conf->level == 6 && s.to_write && s.failed)
4473 || (s.syncing && (s.uptodate + s.compute < disks))
4474 || s.replacing
4475 || s.expanding)
4476 handle_stripe_fill(sh, &s, disks);
4478 /* Now to consider new write requests and what else, if anything
4479 * should be read. We do not handle new writes when:
4480 * 1/ A 'write' operation (copy+xor) is already in flight.
4481 * 2/ A 'check' operation is in flight, as it may clobber the parity
4482 * block.
4484 if (s.to_write && !sh->reconstruct_state && !sh->check_state)
4485 handle_stripe_dirtying(conf, sh, &s, disks);
4487 /* maybe we need to check and possibly fix the parity for this stripe
4488 * Any reads will already have been scheduled, so we just see if enough
4489 * data is available. The parity check is held off while parity
4490 * dependent operations are in flight.
4492 if (sh->check_state ||
4493 (s.syncing && s.locked == 0 &&
4494 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4495 !test_bit(STRIPE_INSYNC, &sh->state))) {
4496 if (conf->level == 6)
4497 handle_parity_checks6(conf, sh, &s, disks);
4498 else
4499 handle_parity_checks5(conf, sh, &s, disks);
4502 if ((s.replacing || s.syncing) && s.locked == 0
4503 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4504 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4505 /* Write out to replacement devices where possible */
4506 for (i = 0; i < conf->raid_disks; i++)
4507 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4508 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4509 set_bit(R5_WantReplace, &sh->dev[i].flags);
4510 set_bit(R5_LOCKED, &sh->dev[i].flags);
4511 s.locked++;
4513 if (s.replacing)
4514 set_bit(STRIPE_INSYNC, &sh->state);
4515 set_bit(STRIPE_REPLACED, &sh->state);
4517 if ((s.syncing || s.replacing) && s.locked == 0 &&
4518 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4519 test_bit(STRIPE_INSYNC, &sh->state)) {
4520 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4521 clear_bit(STRIPE_SYNCING, &sh->state);
4522 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4523 wake_up(&conf->wait_for_overlap);
4526 /* If the failed drives are just a ReadError, then we might need
4527 * to progress the repair/check process
4529 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4530 for (i = 0; i < s.failed; i++) {
4531 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4532 if (test_bit(R5_ReadError, &dev->flags)
4533 && !test_bit(R5_LOCKED, &dev->flags)
4534 && test_bit(R5_UPTODATE, &dev->flags)
4536 if (!test_bit(R5_ReWrite, &dev->flags)) {
4537 set_bit(R5_Wantwrite, &dev->flags);
4538 set_bit(R5_ReWrite, &dev->flags);
4539 set_bit(R5_LOCKED, &dev->flags);
4540 s.locked++;
4541 } else {
4542 /* let's read it back */
4543 set_bit(R5_Wantread, &dev->flags);
4544 set_bit(R5_LOCKED, &dev->flags);
4545 s.locked++;
4550 /* Finish reconstruct operations initiated by the expansion process */
4551 if (sh->reconstruct_state == reconstruct_state_result) {
4552 struct stripe_head *sh_src
4553 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4554 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4555 /* sh cannot be written until sh_src has been read.
4556 * so arrange for sh to be delayed a little
4558 set_bit(STRIPE_DELAYED, &sh->state);
4559 set_bit(STRIPE_HANDLE, &sh->state);
4560 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4561 &sh_src->state))
4562 atomic_inc(&conf->preread_active_stripes);
4563 raid5_release_stripe(sh_src);
4564 goto finish;
4566 if (sh_src)
4567 raid5_release_stripe(sh_src);
4569 sh->reconstruct_state = reconstruct_state_idle;
4570 clear_bit(STRIPE_EXPANDING, &sh->state);
4571 for (i = conf->raid_disks; i--; ) {
4572 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4573 set_bit(R5_LOCKED, &sh->dev[i].flags);
4574 s.locked++;
4578 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4579 !sh->reconstruct_state) {
4580 /* Need to write out all blocks after computing parity */
4581 sh->disks = conf->raid_disks;
4582 stripe_set_idx(sh->sector, conf, 0, sh);
4583 schedule_reconstruction(sh, &s, 1, 1);
4584 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4585 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4586 atomic_dec(&conf->reshape_stripes);
4587 wake_up(&conf->wait_for_overlap);
4588 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4591 if (s.expanding && s.locked == 0 &&
4592 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4593 handle_stripe_expansion(conf, sh);
4595 finish:
4596 /* wait for this device to become unblocked */
4597 if (unlikely(s.blocked_rdev)) {
4598 if (conf->mddev->external)
4599 md_wait_for_blocked_rdev(s.blocked_rdev,
4600 conf->mddev);
4601 else
4602 /* Internal metadata will immediately
4603 * be written by raid5d, so we don't
4604 * need to wait here.
4606 rdev_dec_pending(s.blocked_rdev,
4607 conf->mddev);
4610 if (s.handle_bad_blocks)
4611 for (i = disks; i--; ) {
4612 struct md_rdev *rdev;
4613 struct r5dev *dev = &sh->dev[i];
4614 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
4615 /* We own a safe reference to the rdev */
4616 rdev = conf->disks[i].rdev;
4617 if (!rdev_set_badblocks(rdev, sh->sector,
4618 STRIPE_SECTORS, 0))
4619 md_error(conf->mddev, rdev);
4620 rdev_dec_pending(rdev, conf->mddev);
4622 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
4623 rdev = conf->disks[i].rdev;
4624 rdev_clear_badblocks(rdev, sh->sector,
4625 STRIPE_SECTORS, 0);
4626 rdev_dec_pending(rdev, conf->mddev);
4628 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
4629 rdev = conf->disks[i].replacement;
4630 if (!rdev)
4631 /* rdev have been moved down */
4632 rdev = conf->disks[i].rdev;
4633 rdev_clear_badblocks(rdev, sh->sector,
4634 STRIPE_SECTORS, 0);
4635 rdev_dec_pending(rdev, conf->mddev);
4639 if (s.ops_request)
4640 raid_run_ops(sh, s.ops_request);
4642 ops_run_io(sh, &s);
4644 if (s.dec_preread_active) {
4645 /* We delay this until after ops_run_io so that if make_request
4646 * is waiting on a flush, it won't continue until the writes
4647 * have actually been submitted.
4649 atomic_dec(&conf->preread_active_stripes);
4650 if (atomic_read(&conf->preread_active_stripes) <
4651 IO_THRESHOLD)
4652 md_wakeup_thread(conf->mddev->thread);
4655 if (!bio_list_empty(&s.return_bi)) {
4656 if (test_bit(MD_CHANGE_PENDING, &conf->mddev->flags)) {
4657 spin_lock_irq(&conf->device_lock);
4658 bio_list_merge(&conf->return_bi, &s.return_bi);
4659 spin_unlock_irq(&conf->device_lock);
4660 md_wakeup_thread(conf->mddev->thread);
4661 } else
4662 return_io(&s.return_bi);
4665 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4668 static void raid5_activate_delayed(struct r5conf *conf)
4670 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
4671 while (!list_empty(&conf->delayed_list)) {
4672 struct list_head *l = conf->delayed_list.next;
4673 struct stripe_head *sh;
4674 sh = list_entry(l, struct stripe_head, lru);
4675 list_del_init(l);
4676 clear_bit(STRIPE_DELAYED, &sh->state);
4677 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4678 atomic_inc(&conf->preread_active_stripes);
4679 list_add_tail(&sh->lru, &conf->hold_list);
4680 raid5_wakeup_stripe_thread(sh);
4685 static void activate_bit_delay(struct r5conf *conf,
4686 struct list_head *temp_inactive_list)
4688 /* device_lock is held */
4689 struct list_head head;
4690 list_add(&head, &conf->bitmap_list);
4691 list_del_init(&conf->bitmap_list);
4692 while (!list_empty(&head)) {
4693 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
4694 int hash;
4695 list_del_init(&sh->lru);
4696 atomic_inc(&sh->count);
4697 hash = sh->hash_lock_index;
4698 __release_stripe(conf, sh, &temp_inactive_list[hash]);
4702 static int raid5_congested(struct mddev *mddev, int bits)
4704 struct r5conf *conf = mddev->private;
4706 /* No difference between reads and writes. Just check
4707 * how busy the stripe_cache is
4710 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
4711 return 1;
4712 if (conf->quiesce)
4713 return 1;
4714 if (atomic_read(&conf->empty_inactive_list_nr))
4715 return 1;
4717 return 0;
4720 static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
4722 struct r5conf *conf = mddev->private;
4723 sector_t sector = bio->bi_iter.bi_sector + get_start_sect(bio->bi_bdev);
4724 unsigned int chunk_sectors;
4725 unsigned int bio_sectors = bio_sectors(bio);
4727 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
4728 return chunk_sectors >=
4729 ((sector & (chunk_sectors - 1)) + bio_sectors);
4733 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
4734 * later sampled by raid5d.
4736 static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
4738 unsigned long flags;
4740 spin_lock_irqsave(&conf->device_lock, flags);
4742 bi->bi_next = conf->retry_read_aligned_list;
4743 conf->retry_read_aligned_list = bi;
4745 spin_unlock_irqrestore(&conf->device_lock, flags);
4746 md_wakeup_thread(conf->mddev->thread);
4749 static struct bio *remove_bio_from_retry(struct r5conf *conf)
4751 struct bio *bi;
4753 bi = conf->retry_read_aligned;
4754 if (bi) {
4755 conf->retry_read_aligned = NULL;
4756 return bi;
4758 bi = conf->retry_read_aligned_list;
4759 if(bi) {
4760 conf->retry_read_aligned_list = bi->bi_next;
4761 bi->bi_next = NULL;
4763 * this sets the active strip count to 1 and the processed
4764 * strip count to zero (upper 8 bits)
4766 raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
4769 return bi;
4773 * The "raid5_align_endio" should check if the read succeeded and if it
4774 * did, call bio_endio on the original bio (having bio_put the new bio
4775 * first).
4776 * If the read failed..
4778 static void raid5_align_endio(struct bio *bi)
4780 struct bio* raid_bi = bi->bi_private;
4781 struct mddev *mddev;
4782 struct r5conf *conf;
4783 struct md_rdev *rdev;
4784 int error = bi->bi_error;
4786 bio_put(bi);
4788 rdev = (void*)raid_bi->bi_next;
4789 raid_bi->bi_next = NULL;
4790 mddev = rdev->mddev;
4791 conf = mddev->private;
4793 rdev_dec_pending(rdev, conf->mddev);
4795 if (!error) {
4796 trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
4797 raid_bi, 0);
4798 bio_endio(raid_bi);
4799 if (atomic_dec_and_test(&conf->active_aligned_reads))
4800 wake_up(&conf->wait_for_quiescent);
4801 return;
4804 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
4806 add_bio_to_retry(raid_bi, conf);
4809 static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
4811 struct r5conf *conf = mddev->private;
4812 int dd_idx;
4813 struct bio* align_bi;
4814 struct md_rdev *rdev;
4815 sector_t end_sector;
4817 if (!in_chunk_boundary(mddev, raid_bio)) {
4818 pr_debug("%s: non aligned\n", __func__);
4819 return 0;
4822 * use bio_clone_mddev to make a copy of the bio
4824 align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
4825 if (!align_bi)
4826 return 0;
4828 * set bi_end_io to a new function, and set bi_private to the
4829 * original bio.
4831 align_bi->bi_end_io = raid5_align_endio;
4832 align_bi->bi_private = raid_bio;
4834 * compute position
4836 align_bi->bi_iter.bi_sector =
4837 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
4838 0, &dd_idx, NULL);
4840 end_sector = bio_end_sector(align_bi);
4841 rcu_read_lock();
4842 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
4843 if (!rdev || test_bit(Faulty, &rdev->flags) ||
4844 rdev->recovery_offset < end_sector) {
4845 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
4846 if (rdev &&
4847 (test_bit(Faulty, &rdev->flags) ||
4848 !(test_bit(In_sync, &rdev->flags) ||
4849 rdev->recovery_offset >= end_sector)))
4850 rdev = NULL;
4852 if (rdev) {
4853 sector_t first_bad;
4854 int bad_sectors;
4856 atomic_inc(&rdev->nr_pending);
4857 rcu_read_unlock();
4858 raid_bio->bi_next = (void*)rdev;
4859 align_bi->bi_bdev = rdev->bdev;
4860 bio_clear_flag(align_bi, BIO_SEG_VALID);
4862 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
4863 bio_sectors(align_bi),
4864 &first_bad, &bad_sectors)) {
4865 bio_put(align_bi);
4866 rdev_dec_pending(rdev, mddev);
4867 return 0;
4870 /* No reshape active, so we can trust rdev->data_offset */
4871 align_bi->bi_iter.bi_sector += rdev->data_offset;
4873 spin_lock_irq(&conf->device_lock);
4874 wait_event_lock_irq(conf->wait_for_quiescent,
4875 conf->quiesce == 0,
4876 conf->device_lock);
4877 atomic_inc(&conf->active_aligned_reads);
4878 spin_unlock_irq(&conf->device_lock);
4880 if (mddev->gendisk)
4881 trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4882 align_bi, disk_devt(mddev->gendisk),
4883 raid_bio->bi_iter.bi_sector);
4884 generic_make_request(align_bi);
4885 return 1;
4886 } else {
4887 rcu_read_unlock();
4888 bio_put(align_bi);
4889 return 0;
4893 static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
4895 struct bio *split;
4897 do {
4898 sector_t sector = raid_bio->bi_iter.bi_sector;
4899 unsigned chunk_sects = mddev->chunk_sectors;
4900 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
4902 if (sectors < bio_sectors(raid_bio)) {
4903 split = bio_split(raid_bio, sectors, GFP_NOIO, fs_bio_set);
4904 bio_chain(split, raid_bio);
4905 } else
4906 split = raid_bio;
4908 if (!raid5_read_one_chunk(mddev, split)) {
4909 if (split != raid_bio)
4910 generic_make_request(raid_bio);
4911 return split;
4913 } while (split != raid_bio);
4915 return NULL;
4918 /* __get_priority_stripe - get the next stripe to process
4920 * Full stripe writes are allowed to pass preread active stripes up until
4921 * the bypass_threshold is exceeded. In general the bypass_count
4922 * increments when the handle_list is handled before the hold_list; however, it
4923 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4924 * stripe with in flight i/o. The bypass_count will be reset when the
4925 * head of the hold_list has changed, i.e. the head was promoted to the
4926 * handle_list.
4928 static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
4930 struct stripe_head *sh = NULL, *tmp;
4931 struct list_head *handle_list = NULL;
4932 struct r5worker_group *wg = NULL;
4934 if (conf->worker_cnt_per_group == 0) {
4935 handle_list = &conf->handle_list;
4936 } else if (group != ANY_GROUP) {
4937 handle_list = &conf->worker_groups[group].handle_list;
4938 wg = &conf->worker_groups[group];
4939 } else {
4940 int i;
4941 for (i = 0; i < conf->group_cnt; i++) {
4942 handle_list = &conf->worker_groups[i].handle_list;
4943 wg = &conf->worker_groups[i];
4944 if (!list_empty(handle_list))
4945 break;
4949 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4950 __func__,
4951 list_empty(handle_list) ? "empty" : "busy",
4952 list_empty(&conf->hold_list) ? "empty" : "busy",
4953 atomic_read(&conf->pending_full_writes), conf->bypass_count);
4955 if (!list_empty(handle_list)) {
4956 sh = list_entry(handle_list->next, typeof(*sh), lru);
4958 if (list_empty(&conf->hold_list))
4959 conf->bypass_count = 0;
4960 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4961 if (conf->hold_list.next == conf->last_hold)
4962 conf->bypass_count++;
4963 else {
4964 conf->last_hold = conf->hold_list.next;
4965 conf->bypass_count -= conf->bypass_threshold;
4966 if (conf->bypass_count < 0)
4967 conf->bypass_count = 0;
4970 } else if (!list_empty(&conf->hold_list) &&
4971 ((conf->bypass_threshold &&
4972 conf->bypass_count > conf->bypass_threshold) ||
4973 atomic_read(&conf->pending_full_writes) == 0)) {
4975 list_for_each_entry(tmp, &conf->hold_list, lru) {
4976 if (conf->worker_cnt_per_group == 0 ||
4977 group == ANY_GROUP ||
4978 !cpu_online(tmp->cpu) ||
4979 cpu_to_group(tmp->cpu) == group) {
4980 sh = tmp;
4981 break;
4985 if (sh) {
4986 conf->bypass_count -= conf->bypass_threshold;
4987 if (conf->bypass_count < 0)
4988 conf->bypass_count = 0;
4990 wg = NULL;
4993 if (!sh)
4994 return NULL;
4996 if (wg) {
4997 wg->stripes_cnt--;
4998 sh->group = NULL;
5000 list_del_init(&sh->lru);
5001 BUG_ON(atomic_inc_return(&sh->count) != 1);
5002 return sh;
5005 struct raid5_plug_cb {
5006 struct blk_plug_cb cb;
5007 struct list_head list;
5008 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
5011 static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
5013 struct raid5_plug_cb *cb = container_of(
5014 blk_cb, struct raid5_plug_cb, cb);
5015 struct stripe_head *sh;
5016 struct mddev *mddev = cb->cb.data;
5017 struct r5conf *conf = mddev->private;
5018 int cnt = 0;
5019 int hash;
5021 if (cb->list.next && !list_empty(&cb->list)) {
5022 spin_lock_irq(&conf->device_lock);
5023 while (!list_empty(&cb->list)) {
5024 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5025 list_del_init(&sh->lru);
5027 * avoid race release_stripe_plug() sees
5028 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5029 * is still in our list
5031 smp_mb__before_atomic();
5032 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5034 * STRIPE_ON_RELEASE_LIST could be set here. In that
5035 * case, the count is always > 1 here
5037 hash = sh->hash_lock_index;
5038 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5039 cnt++;
5041 spin_unlock_irq(&conf->device_lock);
5043 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5044 NR_STRIPE_HASH_LOCKS);
5045 if (mddev->queue)
5046 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5047 kfree(cb);
5050 static void release_stripe_plug(struct mddev *mddev,
5051 struct stripe_head *sh)
5053 struct blk_plug_cb *blk_cb = blk_check_plugged(
5054 raid5_unplug, mddev,
5055 sizeof(struct raid5_plug_cb));
5056 struct raid5_plug_cb *cb;
5058 if (!blk_cb) {
5059 raid5_release_stripe(sh);
5060 return;
5063 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5065 if (cb->list.next == NULL) {
5066 int i;
5067 INIT_LIST_HEAD(&cb->list);
5068 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5069 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5072 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5073 list_add_tail(&sh->lru, &cb->list);
5074 else
5075 raid5_release_stripe(sh);
5078 static void make_discard_request(struct mddev *mddev, struct bio *bi)
5080 struct r5conf *conf = mddev->private;
5081 sector_t logical_sector, last_sector;
5082 struct stripe_head *sh;
5083 int remaining;
5084 int stripe_sectors;
5086 if (mddev->reshape_position != MaxSector)
5087 /* Skip discard while reshape is happening */
5088 return;
5090 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5091 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5093 bi->bi_next = NULL;
5094 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5096 stripe_sectors = conf->chunk_sectors *
5097 (conf->raid_disks - conf->max_degraded);
5098 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5099 stripe_sectors);
5100 sector_div(last_sector, stripe_sectors);
5102 logical_sector *= conf->chunk_sectors;
5103 last_sector *= conf->chunk_sectors;
5105 for (; logical_sector < last_sector;
5106 logical_sector += STRIPE_SECTORS) {
5107 DEFINE_WAIT(w);
5108 int d;
5109 again:
5110 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5111 prepare_to_wait(&conf->wait_for_overlap, &w,
5112 TASK_UNINTERRUPTIBLE);
5113 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5114 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5115 raid5_release_stripe(sh);
5116 schedule();
5117 goto again;
5119 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5120 spin_lock_irq(&sh->stripe_lock);
5121 for (d = 0; d < conf->raid_disks; d++) {
5122 if (d == sh->pd_idx || d == sh->qd_idx)
5123 continue;
5124 if (sh->dev[d].towrite || sh->dev[d].toread) {
5125 set_bit(R5_Overlap, &sh->dev[d].flags);
5126 spin_unlock_irq(&sh->stripe_lock);
5127 raid5_release_stripe(sh);
5128 schedule();
5129 goto again;
5132 set_bit(STRIPE_DISCARD, &sh->state);
5133 finish_wait(&conf->wait_for_overlap, &w);
5134 sh->overwrite_disks = 0;
5135 for (d = 0; d < conf->raid_disks; d++) {
5136 if (d == sh->pd_idx || d == sh->qd_idx)
5137 continue;
5138 sh->dev[d].towrite = bi;
5139 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5140 raid5_inc_bi_active_stripes(bi);
5141 sh->overwrite_disks++;
5143 spin_unlock_irq(&sh->stripe_lock);
5144 if (conf->mddev->bitmap) {
5145 for (d = 0;
5146 d < conf->raid_disks - conf->max_degraded;
5147 d++)
5148 bitmap_startwrite(mddev->bitmap,
5149 sh->sector,
5150 STRIPE_SECTORS,
5152 sh->bm_seq = conf->seq_flush + 1;
5153 set_bit(STRIPE_BIT_DELAY, &sh->state);
5156 set_bit(STRIPE_HANDLE, &sh->state);
5157 clear_bit(STRIPE_DELAYED, &sh->state);
5158 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5159 atomic_inc(&conf->preread_active_stripes);
5160 release_stripe_plug(mddev, sh);
5163 remaining = raid5_dec_bi_active_stripes(bi);
5164 if (remaining == 0) {
5165 md_write_end(mddev);
5166 bio_endio(bi);
5170 static void make_request(struct mddev *mddev, struct bio * bi)
5172 struct r5conf *conf = mddev->private;
5173 int dd_idx;
5174 sector_t new_sector;
5175 sector_t logical_sector, last_sector;
5176 struct stripe_head *sh;
5177 const int rw = bio_data_dir(bi);
5178 int remaining;
5179 DEFINE_WAIT(w);
5180 bool do_prepare;
5182 if (unlikely(bi->bi_rw & REQ_FLUSH)) {
5183 int ret = r5l_handle_flush_request(conf->log, bi);
5185 if (ret == 0)
5186 return;
5187 if (ret == -ENODEV) {
5188 md_flush_request(mddev, bi);
5189 return;
5191 /* ret == -EAGAIN, fallback */
5194 md_write_start(mddev, bi);
5197 * If array is degraded, better not do chunk aligned read because
5198 * later we might have to read it again in order to reconstruct
5199 * data on failed drives.
5201 if (rw == READ && mddev->degraded == 0 &&
5202 mddev->reshape_position == MaxSector) {
5203 bi = chunk_aligned_read(mddev, bi);
5204 if (!bi)
5205 return;
5208 if (unlikely(bi->bi_rw & REQ_DISCARD)) {
5209 make_discard_request(mddev, bi);
5210 return;
5213 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5214 last_sector = bio_end_sector(bi);
5215 bi->bi_next = NULL;
5216 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5218 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5219 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5220 int previous;
5221 int seq;
5223 do_prepare = false;
5224 retry:
5225 seq = read_seqcount_begin(&conf->gen_lock);
5226 previous = 0;
5227 if (do_prepare)
5228 prepare_to_wait(&conf->wait_for_overlap, &w,
5229 TASK_UNINTERRUPTIBLE);
5230 if (unlikely(conf->reshape_progress != MaxSector)) {
5231 /* spinlock is needed as reshape_progress may be
5232 * 64bit on a 32bit platform, and so it might be
5233 * possible to see a half-updated value
5234 * Of course reshape_progress could change after
5235 * the lock is dropped, so once we get a reference
5236 * to the stripe that we think it is, we will have
5237 * to check again.
5239 spin_lock_irq(&conf->device_lock);
5240 if (mddev->reshape_backwards
5241 ? logical_sector < conf->reshape_progress
5242 : logical_sector >= conf->reshape_progress) {
5243 previous = 1;
5244 } else {
5245 if (mddev->reshape_backwards
5246 ? logical_sector < conf->reshape_safe
5247 : logical_sector >= conf->reshape_safe) {
5248 spin_unlock_irq(&conf->device_lock);
5249 schedule();
5250 do_prepare = true;
5251 goto retry;
5254 spin_unlock_irq(&conf->device_lock);
5257 new_sector = raid5_compute_sector(conf, logical_sector,
5258 previous,
5259 &dd_idx, NULL);
5260 pr_debug("raid456: make_request, sector %llu logical %llu\n",
5261 (unsigned long long)new_sector,
5262 (unsigned long long)logical_sector);
5264 sh = raid5_get_active_stripe(conf, new_sector, previous,
5265 (bi->bi_rw&RWA_MASK), 0);
5266 if (sh) {
5267 if (unlikely(previous)) {
5268 /* expansion might have moved on while waiting for a
5269 * stripe, so we must do the range check again.
5270 * Expansion could still move past after this
5271 * test, but as we are holding a reference to
5272 * 'sh', we know that if that happens,
5273 * STRIPE_EXPANDING will get set and the expansion
5274 * won't proceed until we finish with the stripe.
5276 int must_retry = 0;
5277 spin_lock_irq(&conf->device_lock);
5278 if (mddev->reshape_backwards
5279 ? logical_sector >= conf->reshape_progress
5280 : logical_sector < conf->reshape_progress)
5281 /* mismatch, need to try again */
5282 must_retry = 1;
5283 spin_unlock_irq(&conf->device_lock);
5284 if (must_retry) {
5285 raid5_release_stripe(sh);
5286 schedule();
5287 do_prepare = true;
5288 goto retry;
5291 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5292 /* Might have got the wrong stripe_head
5293 * by accident
5295 raid5_release_stripe(sh);
5296 goto retry;
5299 if (rw == WRITE &&
5300 logical_sector >= mddev->suspend_lo &&
5301 logical_sector < mddev->suspend_hi) {
5302 raid5_release_stripe(sh);
5303 /* As the suspend_* range is controlled by
5304 * userspace, we want an interruptible
5305 * wait.
5307 prepare_to_wait(&conf->wait_for_overlap,
5308 &w, TASK_INTERRUPTIBLE);
5309 if (logical_sector >= mddev->suspend_lo &&
5310 logical_sector < mddev->suspend_hi) {
5311 sigset_t full, old;
5312 sigfillset(&full);
5313 sigprocmask(SIG_BLOCK, &full, &old);
5314 schedule();
5315 sigprocmask(SIG_SETMASK, &old, NULL);
5316 do_prepare = true;
5318 goto retry;
5321 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5322 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5323 /* Stripe is busy expanding or
5324 * add failed due to overlap. Flush everything
5325 * and wait a while
5327 md_wakeup_thread(mddev->thread);
5328 raid5_release_stripe(sh);
5329 schedule();
5330 do_prepare = true;
5331 goto retry;
5333 set_bit(STRIPE_HANDLE, &sh->state);
5334 clear_bit(STRIPE_DELAYED, &sh->state);
5335 if ((!sh->batch_head || sh == sh->batch_head) &&
5336 (bi->bi_rw & REQ_SYNC) &&
5337 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5338 atomic_inc(&conf->preread_active_stripes);
5339 release_stripe_plug(mddev, sh);
5340 } else {
5341 /* cannot get stripe for read-ahead, just give-up */
5342 bi->bi_error = -EIO;
5343 break;
5346 finish_wait(&conf->wait_for_overlap, &w);
5348 remaining = raid5_dec_bi_active_stripes(bi);
5349 if (remaining == 0) {
5351 if ( rw == WRITE )
5352 md_write_end(mddev);
5354 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
5355 bi, 0);
5356 bio_endio(bi);
5360 static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5362 static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5364 /* reshaping is quite different to recovery/resync so it is
5365 * handled quite separately ... here.
5367 * On each call to sync_request, we gather one chunk worth of
5368 * destination stripes and flag them as expanding.
5369 * Then we find all the source stripes and request reads.
5370 * As the reads complete, handle_stripe will copy the data
5371 * into the destination stripe and release that stripe.
5373 struct r5conf *conf = mddev->private;
5374 struct stripe_head *sh;
5375 sector_t first_sector, last_sector;
5376 int raid_disks = conf->previous_raid_disks;
5377 int data_disks = raid_disks - conf->max_degraded;
5378 int new_data_disks = conf->raid_disks - conf->max_degraded;
5379 int i;
5380 int dd_idx;
5381 sector_t writepos, readpos, safepos;
5382 sector_t stripe_addr;
5383 int reshape_sectors;
5384 struct list_head stripes;
5385 sector_t retn;
5387 if (sector_nr == 0) {
5388 /* If restarting in the middle, skip the initial sectors */
5389 if (mddev->reshape_backwards &&
5390 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5391 sector_nr = raid5_size(mddev, 0, 0)
5392 - conf->reshape_progress;
5393 } else if (mddev->reshape_backwards &&
5394 conf->reshape_progress == MaxSector) {
5395 /* shouldn't happen, but just in case, finish up.*/
5396 sector_nr = MaxSector;
5397 } else if (!mddev->reshape_backwards &&
5398 conf->reshape_progress > 0)
5399 sector_nr = conf->reshape_progress;
5400 sector_div(sector_nr, new_data_disks);
5401 if (sector_nr) {
5402 mddev->curr_resync_completed = sector_nr;
5403 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5404 *skipped = 1;
5405 retn = sector_nr;
5406 goto finish;
5410 /* We need to process a full chunk at a time.
5411 * If old and new chunk sizes differ, we need to process the
5412 * largest of these
5415 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5417 /* We update the metadata at least every 10 seconds, or when
5418 * the data about to be copied would over-write the source of
5419 * the data at the front of the range. i.e. one new_stripe
5420 * along from reshape_progress new_maps to after where
5421 * reshape_safe old_maps to
5423 writepos = conf->reshape_progress;
5424 sector_div(writepos, new_data_disks);
5425 readpos = conf->reshape_progress;
5426 sector_div(readpos, data_disks);
5427 safepos = conf->reshape_safe;
5428 sector_div(safepos, data_disks);
5429 if (mddev->reshape_backwards) {
5430 BUG_ON(writepos < reshape_sectors);
5431 writepos -= reshape_sectors;
5432 readpos += reshape_sectors;
5433 safepos += reshape_sectors;
5434 } else {
5435 writepos += reshape_sectors;
5436 /* readpos and safepos are worst-case calculations.
5437 * A negative number is overly pessimistic, and causes
5438 * obvious problems for unsigned storage. So clip to 0.
5440 readpos -= min_t(sector_t, reshape_sectors, readpos);
5441 safepos -= min_t(sector_t, reshape_sectors, safepos);
5444 /* Having calculated the 'writepos' possibly use it
5445 * to set 'stripe_addr' which is where we will write to.
5447 if (mddev->reshape_backwards) {
5448 BUG_ON(conf->reshape_progress == 0);
5449 stripe_addr = writepos;
5450 BUG_ON((mddev->dev_sectors &
5451 ~((sector_t)reshape_sectors - 1))
5452 - reshape_sectors - stripe_addr
5453 != sector_nr);
5454 } else {
5455 BUG_ON(writepos != sector_nr + reshape_sectors);
5456 stripe_addr = sector_nr;
5459 /* 'writepos' is the most advanced device address we might write.
5460 * 'readpos' is the least advanced device address we might read.
5461 * 'safepos' is the least address recorded in the metadata as having
5462 * been reshaped.
5463 * If there is a min_offset_diff, these are adjusted either by
5464 * increasing the safepos/readpos if diff is negative, or
5465 * increasing writepos if diff is positive.
5466 * If 'readpos' is then behind 'writepos', there is no way that we can
5467 * ensure safety in the face of a crash - that must be done by userspace
5468 * making a backup of the data. So in that case there is no particular
5469 * rush to update metadata.
5470 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5471 * update the metadata to advance 'safepos' to match 'readpos' so that
5472 * we can be safe in the event of a crash.
5473 * So we insist on updating metadata if safepos is behind writepos and
5474 * readpos is beyond writepos.
5475 * In any case, update the metadata every 10 seconds.
5476 * Maybe that number should be configurable, but I'm not sure it is
5477 * worth it.... maybe it could be a multiple of safemode_delay???
5479 if (conf->min_offset_diff < 0) {
5480 safepos += -conf->min_offset_diff;
5481 readpos += -conf->min_offset_diff;
5482 } else
5483 writepos += conf->min_offset_diff;
5485 if ((mddev->reshape_backwards
5486 ? (safepos > writepos && readpos < writepos)
5487 : (safepos < writepos && readpos > writepos)) ||
5488 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5489 /* Cannot proceed until we've updated the superblock... */
5490 wait_event(conf->wait_for_overlap,
5491 atomic_read(&conf->reshape_stripes)==0
5492 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5493 if (atomic_read(&conf->reshape_stripes) != 0)
5494 return 0;
5495 mddev->reshape_position = conf->reshape_progress;
5496 mddev->curr_resync_completed = sector_nr;
5497 conf->reshape_checkpoint = jiffies;
5498 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5499 md_wakeup_thread(mddev->thread);
5500 wait_event(mddev->sb_wait, mddev->flags == 0 ||
5501 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5502 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5503 return 0;
5504 spin_lock_irq(&conf->device_lock);
5505 conf->reshape_safe = mddev->reshape_position;
5506 spin_unlock_irq(&conf->device_lock);
5507 wake_up(&conf->wait_for_overlap);
5508 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5511 INIT_LIST_HEAD(&stripes);
5512 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5513 int j;
5514 int skipped_disk = 0;
5515 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5516 set_bit(STRIPE_EXPANDING, &sh->state);
5517 atomic_inc(&conf->reshape_stripes);
5518 /* If any of this stripe is beyond the end of the old
5519 * array, then we need to zero those blocks
5521 for (j=sh->disks; j--;) {
5522 sector_t s;
5523 if (j == sh->pd_idx)
5524 continue;
5525 if (conf->level == 6 &&
5526 j == sh->qd_idx)
5527 continue;
5528 s = raid5_compute_blocknr(sh, j, 0);
5529 if (s < raid5_size(mddev, 0, 0)) {
5530 skipped_disk = 1;
5531 continue;
5533 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5534 set_bit(R5_Expanded, &sh->dev[j].flags);
5535 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5537 if (!skipped_disk) {
5538 set_bit(STRIPE_EXPAND_READY, &sh->state);
5539 set_bit(STRIPE_HANDLE, &sh->state);
5541 list_add(&sh->lru, &stripes);
5543 spin_lock_irq(&conf->device_lock);
5544 if (mddev->reshape_backwards)
5545 conf->reshape_progress -= reshape_sectors * new_data_disks;
5546 else
5547 conf->reshape_progress += reshape_sectors * new_data_disks;
5548 spin_unlock_irq(&conf->device_lock);
5549 /* Ok, those stripe are ready. We can start scheduling
5550 * reads on the source stripes.
5551 * The source stripes are determined by mapping the first and last
5552 * block on the destination stripes.
5554 first_sector =
5555 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5556 1, &dd_idx, NULL);
5557 last_sector =
5558 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5559 * new_data_disks - 1),
5560 1, &dd_idx, NULL);
5561 if (last_sector >= mddev->dev_sectors)
5562 last_sector = mddev->dev_sectors - 1;
5563 while (first_sector <= last_sector) {
5564 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5565 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5566 set_bit(STRIPE_HANDLE, &sh->state);
5567 raid5_release_stripe(sh);
5568 first_sector += STRIPE_SECTORS;
5570 /* Now that the sources are clearly marked, we can release
5571 * the destination stripes
5573 while (!list_empty(&stripes)) {
5574 sh = list_entry(stripes.next, struct stripe_head, lru);
5575 list_del_init(&sh->lru);
5576 raid5_release_stripe(sh);
5578 /* If this takes us to the resync_max point where we have to pause,
5579 * then we need to write out the superblock.
5581 sector_nr += reshape_sectors;
5582 retn = reshape_sectors;
5583 finish:
5584 if (mddev->curr_resync_completed > mddev->resync_max ||
5585 (sector_nr - mddev->curr_resync_completed) * 2
5586 >= mddev->resync_max - mddev->curr_resync_completed) {
5587 /* Cannot proceed until we've updated the superblock... */
5588 wait_event(conf->wait_for_overlap,
5589 atomic_read(&conf->reshape_stripes) == 0
5590 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5591 if (atomic_read(&conf->reshape_stripes) != 0)
5592 goto ret;
5593 mddev->reshape_position = conf->reshape_progress;
5594 mddev->curr_resync_completed = sector_nr;
5595 conf->reshape_checkpoint = jiffies;
5596 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5597 md_wakeup_thread(mddev->thread);
5598 wait_event(mddev->sb_wait,
5599 !test_bit(MD_CHANGE_DEVS, &mddev->flags)
5600 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5601 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5602 goto ret;
5603 spin_lock_irq(&conf->device_lock);
5604 conf->reshape_safe = mddev->reshape_position;
5605 spin_unlock_irq(&conf->device_lock);
5606 wake_up(&conf->wait_for_overlap);
5607 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5609 ret:
5610 return retn;
5613 static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5615 struct r5conf *conf = mddev->private;
5616 struct stripe_head *sh;
5617 sector_t max_sector = mddev->dev_sectors;
5618 sector_t sync_blocks;
5619 int still_degraded = 0;
5620 int i;
5622 if (sector_nr >= max_sector) {
5623 /* just being told to finish up .. nothing much to do */
5625 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
5626 end_reshape(conf);
5627 return 0;
5630 if (mddev->curr_resync < max_sector) /* aborted */
5631 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
5632 &sync_blocks, 1);
5633 else /* completed sync */
5634 conf->fullsync = 0;
5635 bitmap_close_sync(mddev->bitmap);
5637 return 0;
5640 /* Allow raid5_quiesce to complete */
5641 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
5643 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5644 return reshape_request(mddev, sector_nr, skipped);
5646 /* No need to check resync_max as we never do more than one
5647 * stripe, and as resync_max will always be on a chunk boundary,
5648 * if the check in md_do_sync didn't fire, there is no chance
5649 * of overstepping resync_max here
5652 /* if there is too many failed drives and we are trying
5653 * to resync, then assert that we are finished, because there is
5654 * nothing we can do.
5656 if (mddev->degraded >= conf->max_degraded &&
5657 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5658 sector_t rv = mddev->dev_sectors - sector_nr;
5659 *skipped = 1;
5660 return rv;
5662 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
5663 !conf->fullsync &&
5664 !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
5665 sync_blocks >= STRIPE_SECTORS) {
5666 /* we can skip this block, and probably more */
5667 sync_blocks /= STRIPE_SECTORS;
5668 *skipped = 1;
5669 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
5672 bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
5674 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
5675 if (sh == NULL) {
5676 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
5677 /* make sure we don't swamp the stripe cache if someone else
5678 * is trying to get access
5680 schedule_timeout_uninterruptible(1);
5682 /* Need to check if array will still be degraded after recovery/resync
5683 * Note in case of > 1 drive failures it's possible we're rebuilding
5684 * one drive while leaving another faulty drive in array.
5686 rcu_read_lock();
5687 for (i = 0; i < conf->raid_disks; i++) {
5688 struct md_rdev *rdev = ACCESS_ONCE(conf->disks[i].rdev);
5690 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
5691 still_degraded = 1;
5693 rcu_read_unlock();
5695 bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
5697 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
5698 set_bit(STRIPE_HANDLE, &sh->state);
5700 raid5_release_stripe(sh);
5702 return STRIPE_SECTORS;
5705 static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
5707 /* We may not be able to submit a whole bio at once as there
5708 * may not be enough stripe_heads available.
5709 * We cannot pre-allocate enough stripe_heads as we may need
5710 * more than exist in the cache (if we allow ever large chunks).
5711 * So we do one stripe head at a time and record in
5712 * ->bi_hw_segments how many have been done.
5714 * We *know* that this entire raid_bio is in one chunk, so
5715 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
5717 struct stripe_head *sh;
5718 int dd_idx;
5719 sector_t sector, logical_sector, last_sector;
5720 int scnt = 0;
5721 int remaining;
5722 int handled = 0;
5724 logical_sector = raid_bio->bi_iter.bi_sector &
5725 ~((sector_t)STRIPE_SECTORS-1);
5726 sector = raid5_compute_sector(conf, logical_sector,
5727 0, &dd_idx, NULL);
5728 last_sector = bio_end_sector(raid_bio);
5730 for (; logical_sector < last_sector;
5731 logical_sector += STRIPE_SECTORS,
5732 sector += STRIPE_SECTORS,
5733 scnt++) {
5735 if (scnt < raid5_bi_processed_stripes(raid_bio))
5736 /* already done this stripe */
5737 continue;
5739 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
5741 if (!sh) {
5742 /* failed to get a stripe - must wait */
5743 raid5_set_bi_processed_stripes(raid_bio, scnt);
5744 conf->retry_read_aligned = raid_bio;
5745 return handled;
5748 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
5749 raid5_release_stripe(sh);
5750 raid5_set_bi_processed_stripes(raid_bio, scnt);
5751 conf->retry_read_aligned = raid_bio;
5752 return handled;
5755 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
5756 handle_stripe(sh);
5757 raid5_release_stripe(sh);
5758 handled++;
5760 remaining = raid5_dec_bi_active_stripes(raid_bio);
5761 if (remaining == 0) {
5762 trace_block_bio_complete(bdev_get_queue(raid_bio->bi_bdev),
5763 raid_bio, 0);
5764 bio_endio(raid_bio);
5766 if (atomic_dec_and_test(&conf->active_aligned_reads))
5767 wake_up(&conf->wait_for_quiescent);
5768 return handled;
5771 static int handle_active_stripes(struct r5conf *conf, int group,
5772 struct r5worker *worker,
5773 struct list_head *temp_inactive_list)
5775 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
5776 int i, batch_size = 0, hash;
5777 bool release_inactive = false;
5779 while (batch_size < MAX_STRIPE_BATCH &&
5780 (sh = __get_priority_stripe(conf, group)) != NULL)
5781 batch[batch_size++] = sh;
5783 if (batch_size == 0) {
5784 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5785 if (!list_empty(temp_inactive_list + i))
5786 break;
5787 if (i == NR_STRIPE_HASH_LOCKS) {
5788 spin_unlock_irq(&conf->device_lock);
5789 r5l_flush_stripe_to_raid(conf->log);
5790 spin_lock_irq(&conf->device_lock);
5791 return batch_size;
5793 release_inactive = true;
5795 spin_unlock_irq(&conf->device_lock);
5797 release_inactive_stripe_list(conf, temp_inactive_list,
5798 NR_STRIPE_HASH_LOCKS);
5800 r5l_flush_stripe_to_raid(conf->log);
5801 if (release_inactive) {
5802 spin_lock_irq(&conf->device_lock);
5803 return 0;
5806 for (i = 0; i < batch_size; i++)
5807 handle_stripe(batch[i]);
5808 r5l_write_stripe_run(conf->log);
5810 cond_resched();
5812 spin_lock_irq(&conf->device_lock);
5813 for (i = 0; i < batch_size; i++) {
5814 hash = batch[i]->hash_lock_index;
5815 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
5817 return batch_size;
5820 static void raid5_do_work(struct work_struct *work)
5822 struct r5worker *worker = container_of(work, struct r5worker, work);
5823 struct r5worker_group *group = worker->group;
5824 struct r5conf *conf = group->conf;
5825 int group_id = group - conf->worker_groups;
5826 int handled;
5827 struct blk_plug plug;
5829 pr_debug("+++ raid5worker active\n");
5831 blk_start_plug(&plug);
5832 handled = 0;
5833 spin_lock_irq(&conf->device_lock);
5834 while (1) {
5835 int batch_size, released;
5837 released = release_stripe_list(conf, worker->temp_inactive_list);
5839 batch_size = handle_active_stripes(conf, group_id, worker,
5840 worker->temp_inactive_list);
5841 worker->working = false;
5842 if (!batch_size && !released)
5843 break;
5844 handled += batch_size;
5846 pr_debug("%d stripes handled\n", handled);
5848 spin_unlock_irq(&conf->device_lock);
5850 r5l_flush_stripe_to_raid(conf->log);
5852 async_tx_issue_pending_all();
5853 blk_finish_plug(&plug);
5855 pr_debug("--- raid5worker inactive\n");
5859 * This is our raid5 kernel thread.
5861 * We scan the hash table for stripes which can be handled now.
5862 * During the scan, completed stripes are saved for us by the interrupt
5863 * handler, so that they will not have to wait for our next wakeup.
5865 static void raid5d(struct md_thread *thread)
5867 struct mddev *mddev = thread->mddev;
5868 struct r5conf *conf = mddev->private;
5869 int handled;
5870 struct blk_plug plug;
5872 pr_debug("+++ raid5d active\n");
5874 md_check_recovery(mddev);
5876 if (!bio_list_empty(&conf->return_bi) &&
5877 !test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5878 struct bio_list tmp = BIO_EMPTY_LIST;
5879 spin_lock_irq(&conf->device_lock);
5880 if (!test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5881 bio_list_merge(&tmp, &conf->return_bi);
5882 bio_list_init(&conf->return_bi);
5884 spin_unlock_irq(&conf->device_lock);
5885 return_io(&tmp);
5888 blk_start_plug(&plug);
5889 handled = 0;
5890 spin_lock_irq(&conf->device_lock);
5891 while (1) {
5892 struct bio *bio;
5893 int batch_size, released;
5895 released = release_stripe_list(conf, conf->temp_inactive_list);
5896 if (released)
5897 clear_bit(R5_DID_ALLOC, &conf->cache_state);
5899 if (
5900 !list_empty(&conf->bitmap_list)) {
5901 /* Now is a good time to flush some bitmap updates */
5902 conf->seq_flush++;
5903 spin_unlock_irq(&conf->device_lock);
5904 bitmap_unplug(mddev->bitmap);
5905 spin_lock_irq(&conf->device_lock);
5906 conf->seq_write = conf->seq_flush;
5907 activate_bit_delay(conf, conf->temp_inactive_list);
5909 raid5_activate_delayed(conf);
5911 while ((bio = remove_bio_from_retry(conf))) {
5912 int ok;
5913 spin_unlock_irq(&conf->device_lock);
5914 ok = retry_aligned_read(conf, bio);
5915 spin_lock_irq(&conf->device_lock);
5916 if (!ok)
5917 break;
5918 handled++;
5921 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
5922 conf->temp_inactive_list);
5923 if (!batch_size && !released)
5924 break;
5925 handled += batch_size;
5927 if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
5928 spin_unlock_irq(&conf->device_lock);
5929 md_check_recovery(mddev);
5930 spin_lock_irq(&conf->device_lock);
5933 pr_debug("%d stripes handled\n", handled);
5935 spin_unlock_irq(&conf->device_lock);
5936 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
5937 mutex_trylock(&conf->cache_size_mutex)) {
5938 grow_one_stripe(conf, __GFP_NOWARN);
5939 /* Set flag even if allocation failed. This helps
5940 * slow down allocation requests when mem is short
5942 set_bit(R5_DID_ALLOC, &conf->cache_state);
5943 mutex_unlock(&conf->cache_size_mutex);
5946 r5l_flush_stripe_to_raid(conf->log);
5948 async_tx_issue_pending_all();
5949 blk_finish_plug(&plug);
5951 pr_debug("--- raid5d inactive\n");
5954 static ssize_t
5955 raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
5957 struct r5conf *conf;
5958 int ret = 0;
5959 spin_lock(&mddev->lock);
5960 conf = mddev->private;
5961 if (conf)
5962 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
5963 spin_unlock(&mddev->lock);
5964 return ret;
5968 raid5_set_cache_size(struct mddev *mddev, int size)
5970 struct r5conf *conf = mddev->private;
5971 int err;
5973 if (size <= 16 || size > 32768)
5974 return -EINVAL;
5976 conf->min_nr_stripes = size;
5977 mutex_lock(&conf->cache_size_mutex);
5978 while (size < conf->max_nr_stripes &&
5979 drop_one_stripe(conf))
5981 mutex_unlock(&conf->cache_size_mutex);
5984 err = md_allow_write(mddev);
5985 if (err)
5986 return err;
5988 mutex_lock(&conf->cache_size_mutex);
5989 while (size > conf->max_nr_stripes)
5990 if (!grow_one_stripe(conf, GFP_KERNEL))
5991 break;
5992 mutex_unlock(&conf->cache_size_mutex);
5994 return 0;
5996 EXPORT_SYMBOL(raid5_set_cache_size);
5998 static ssize_t
5999 raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
6001 struct r5conf *conf;
6002 unsigned long new;
6003 int err;
6005 if (len >= PAGE_SIZE)
6006 return -EINVAL;
6007 if (kstrtoul(page, 10, &new))
6008 return -EINVAL;
6009 err = mddev_lock(mddev);
6010 if (err)
6011 return err;
6012 conf = mddev->private;
6013 if (!conf)
6014 err = -ENODEV;
6015 else
6016 err = raid5_set_cache_size(mddev, new);
6017 mddev_unlock(mddev);
6019 return err ?: len;
6022 static struct md_sysfs_entry
6023 raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6024 raid5_show_stripe_cache_size,
6025 raid5_store_stripe_cache_size);
6027 static ssize_t
6028 raid5_show_rmw_level(struct mddev *mddev, char *page)
6030 struct r5conf *conf = mddev->private;
6031 if (conf)
6032 return sprintf(page, "%d\n", conf->rmw_level);
6033 else
6034 return 0;
6037 static ssize_t
6038 raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6040 struct r5conf *conf = mddev->private;
6041 unsigned long new;
6043 if (!conf)
6044 return -ENODEV;
6046 if (len >= PAGE_SIZE)
6047 return -EINVAL;
6049 if (kstrtoul(page, 10, &new))
6050 return -EINVAL;
6052 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6053 return -EINVAL;
6055 if (new != PARITY_DISABLE_RMW &&
6056 new != PARITY_ENABLE_RMW &&
6057 new != PARITY_PREFER_RMW)
6058 return -EINVAL;
6060 conf->rmw_level = new;
6061 return len;
6064 static struct md_sysfs_entry
6065 raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6066 raid5_show_rmw_level,
6067 raid5_store_rmw_level);
6070 static ssize_t
6071 raid5_show_preread_threshold(struct mddev *mddev, char *page)
6073 struct r5conf *conf;
6074 int ret = 0;
6075 spin_lock(&mddev->lock);
6076 conf = mddev->private;
6077 if (conf)
6078 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6079 spin_unlock(&mddev->lock);
6080 return ret;
6083 static ssize_t
6084 raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6086 struct r5conf *conf;
6087 unsigned long new;
6088 int err;
6090 if (len >= PAGE_SIZE)
6091 return -EINVAL;
6092 if (kstrtoul(page, 10, &new))
6093 return -EINVAL;
6095 err = mddev_lock(mddev);
6096 if (err)
6097 return err;
6098 conf = mddev->private;
6099 if (!conf)
6100 err = -ENODEV;
6101 else if (new > conf->min_nr_stripes)
6102 err = -EINVAL;
6103 else
6104 conf->bypass_threshold = new;
6105 mddev_unlock(mddev);
6106 return err ?: len;
6109 static struct md_sysfs_entry
6110 raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6111 S_IRUGO | S_IWUSR,
6112 raid5_show_preread_threshold,
6113 raid5_store_preread_threshold);
6115 static ssize_t
6116 raid5_show_skip_copy(struct mddev *mddev, char *page)
6118 struct r5conf *conf;
6119 int ret = 0;
6120 spin_lock(&mddev->lock);
6121 conf = mddev->private;
6122 if (conf)
6123 ret = sprintf(page, "%d\n", conf->skip_copy);
6124 spin_unlock(&mddev->lock);
6125 return ret;
6128 static ssize_t
6129 raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6131 struct r5conf *conf;
6132 unsigned long new;
6133 int err;
6135 if (len >= PAGE_SIZE)
6136 return -EINVAL;
6137 if (kstrtoul(page, 10, &new))
6138 return -EINVAL;
6139 new = !!new;
6141 err = mddev_lock(mddev);
6142 if (err)
6143 return err;
6144 conf = mddev->private;
6145 if (!conf)
6146 err = -ENODEV;
6147 else if (new != conf->skip_copy) {
6148 mddev_suspend(mddev);
6149 conf->skip_copy = new;
6150 if (new)
6151 mddev->queue->backing_dev_info.capabilities |=
6152 BDI_CAP_STABLE_WRITES;
6153 else
6154 mddev->queue->backing_dev_info.capabilities &=
6155 ~BDI_CAP_STABLE_WRITES;
6156 mddev_resume(mddev);
6158 mddev_unlock(mddev);
6159 return err ?: len;
6162 static struct md_sysfs_entry
6163 raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6164 raid5_show_skip_copy,
6165 raid5_store_skip_copy);
6167 static ssize_t
6168 stripe_cache_active_show(struct mddev *mddev, char *page)
6170 struct r5conf *conf = mddev->private;
6171 if (conf)
6172 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6173 else
6174 return 0;
6177 static struct md_sysfs_entry
6178 raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6180 static ssize_t
6181 raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6183 struct r5conf *conf;
6184 int ret = 0;
6185 spin_lock(&mddev->lock);
6186 conf = mddev->private;
6187 if (conf)
6188 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6189 spin_unlock(&mddev->lock);
6190 return ret;
6193 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6194 int *group_cnt,
6195 int *worker_cnt_per_group,
6196 struct r5worker_group **worker_groups);
6197 static ssize_t
6198 raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6200 struct r5conf *conf;
6201 unsigned long new;
6202 int err;
6203 struct r5worker_group *new_groups, *old_groups;
6204 int group_cnt, worker_cnt_per_group;
6206 if (len >= PAGE_SIZE)
6207 return -EINVAL;
6208 if (kstrtoul(page, 10, &new))
6209 return -EINVAL;
6211 err = mddev_lock(mddev);
6212 if (err)
6213 return err;
6214 conf = mddev->private;
6215 if (!conf)
6216 err = -ENODEV;
6217 else if (new != conf->worker_cnt_per_group) {
6218 mddev_suspend(mddev);
6220 old_groups = conf->worker_groups;
6221 if (old_groups)
6222 flush_workqueue(raid5_wq);
6224 err = alloc_thread_groups(conf, new,
6225 &group_cnt, &worker_cnt_per_group,
6226 &new_groups);
6227 if (!err) {
6228 spin_lock_irq(&conf->device_lock);
6229 conf->group_cnt = group_cnt;
6230 conf->worker_cnt_per_group = worker_cnt_per_group;
6231 conf->worker_groups = new_groups;
6232 spin_unlock_irq(&conf->device_lock);
6234 if (old_groups)
6235 kfree(old_groups[0].workers);
6236 kfree(old_groups);
6238 mddev_resume(mddev);
6240 mddev_unlock(mddev);
6242 return err ?: len;
6245 static struct md_sysfs_entry
6246 raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6247 raid5_show_group_thread_cnt,
6248 raid5_store_group_thread_cnt);
6250 static struct attribute *raid5_attrs[] = {
6251 &raid5_stripecache_size.attr,
6252 &raid5_stripecache_active.attr,
6253 &raid5_preread_bypass_threshold.attr,
6254 &raid5_group_thread_cnt.attr,
6255 &raid5_skip_copy.attr,
6256 &raid5_rmw_level.attr,
6257 NULL,
6259 static struct attribute_group raid5_attrs_group = {
6260 .name = NULL,
6261 .attrs = raid5_attrs,
6264 static int alloc_thread_groups(struct r5conf *conf, int cnt,
6265 int *group_cnt,
6266 int *worker_cnt_per_group,
6267 struct r5worker_group **worker_groups)
6269 int i, j, k;
6270 ssize_t size;
6271 struct r5worker *workers;
6273 *worker_cnt_per_group = cnt;
6274 if (cnt == 0) {
6275 *group_cnt = 0;
6276 *worker_groups = NULL;
6277 return 0;
6279 *group_cnt = num_possible_nodes();
6280 size = sizeof(struct r5worker) * cnt;
6281 workers = kzalloc(size * *group_cnt, GFP_NOIO);
6282 *worker_groups = kzalloc(sizeof(struct r5worker_group) *
6283 *group_cnt, GFP_NOIO);
6284 if (!*worker_groups || !workers) {
6285 kfree(workers);
6286 kfree(*worker_groups);
6287 return -ENOMEM;
6290 for (i = 0; i < *group_cnt; i++) {
6291 struct r5worker_group *group;
6293 group = &(*worker_groups)[i];
6294 INIT_LIST_HEAD(&group->handle_list);
6295 group->conf = conf;
6296 group->workers = workers + i * cnt;
6298 for (j = 0; j < cnt; j++) {
6299 struct r5worker *worker = group->workers + j;
6300 worker->group = group;
6301 INIT_WORK(&worker->work, raid5_do_work);
6303 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6304 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6308 return 0;
6311 static void free_thread_groups(struct r5conf *conf)
6313 if (conf->worker_groups)
6314 kfree(conf->worker_groups[0].workers);
6315 kfree(conf->worker_groups);
6316 conf->worker_groups = NULL;
6319 static sector_t
6320 raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6322 struct r5conf *conf = mddev->private;
6324 if (!sectors)
6325 sectors = mddev->dev_sectors;
6326 if (!raid_disks)
6327 /* size is defined by the smallest of previous and new size */
6328 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6330 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6331 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6332 return sectors * (raid_disks - conf->max_degraded);
6335 static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6337 safe_put_page(percpu->spare_page);
6338 if (percpu->scribble)
6339 flex_array_free(percpu->scribble);
6340 percpu->spare_page = NULL;
6341 percpu->scribble = NULL;
6344 static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6346 if (conf->level == 6 && !percpu->spare_page)
6347 percpu->spare_page = alloc_page(GFP_KERNEL);
6348 if (!percpu->scribble)
6349 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6350 conf->previous_raid_disks),
6351 max(conf->chunk_sectors,
6352 conf->prev_chunk_sectors)
6353 / STRIPE_SECTORS,
6354 GFP_KERNEL);
6356 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6357 free_scratch_buffer(conf, percpu);
6358 return -ENOMEM;
6361 return 0;
6364 static void raid5_free_percpu(struct r5conf *conf)
6366 unsigned long cpu;
6368 if (!conf->percpu)
6369 return;
6371 #ifdef CONFIG_HOTPLUG_CPU
6372 unregister_cpu_notifier(&conf->cpu_notify);
6373 #endif
6375 get_online_cpus();
6376 for_each_possible_cpu(cpu)
6377 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6378 put_online_cpus();
6380 free_percpu(conf->percpu);
6383 static void free_conf(struct r5conf *conf)
6385 if (conf->log)
6386 r5l_exit_log(conf->log);
6387 if (conf->shrinker.seeks)
6388 unregister_shrinker(&conf->shrinker);
6390 free_thread_groups(conf);
6391 shrink_stripes(conf);
6392 raid5_free_percpu(conf);
6393 kfree(conf->disks);
6394 kfree(conf->stripe_hashtbl);
6395 kfree(conf);
6398 #ifdef CONFIG_HOTPLUG_CPU
6399 static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
6400 void *hcpu)
6402 struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
6403 long cpu = (long)hcpu;
6404 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6406 switch (action) {
6407 case CPU_UP_PREPARE:
6408 case CPU_UP_PREPARE_FROZEN:
6409 if (alloc_scratch_buffer(conf, percpu)) {
6410 pr_err("%s: failed memory allocation for cpu%ld\n",
6411 __func__, cpu);
6412 return notifier_from_errno(-ENOMEM);
6414 break;
6415 case CPU_DEAD:
6416 case CPU_DEAD_FROZEN:
6417 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6418 break;
6419 default:
6420 break;
6422 return NOTIFY_OK;
6424 #endif
6426 static int raid5_alloc_percpu(struct r5conf *conf)
6428 unsigned long cpu;
6429 int err = 0;
6431 conf->percpu = alloc_percpu(struct raid5_percpu);
6432 if (!conf->percpu)
6433 return -ENOMEM;
6435 #ifdef CONFIG_HOTPLUG_CPU
6436 conf->cpu_notify.notifier_call = raid456_cpu_notify;
6437 conf->cpu_notify.priority = 0;
6438 err = register_cpu_notifier(&conf->cpu_notify);
6439 if (err)
6440 return err;
6441 #endif
6443 get_online_cpus();
6444 for_each_present_cpu(cpu) {
6445 err = alloc_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6446 if (err) {
6447 pr_err("%s: failed memory allocation for cpu%ld\n",
6448 __func__, cpu);
6449 break;
6452 put_online_cpus();
6454 if (!err) {
6455 conf->scribble_disks = max(conf->raid_disks,
6456 conf->previous_raid_disks);
6457 conf->scribble_sectors = max(conf->chunk_sectors,
6458 conf->prev_chunk_sectors);
6460 return err;
6463 static unsigned long raid5_cache_scan(struct shrinker *shrink,
6464 struct shrink_control *sc)
6466 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6467 unsigned long ret = SHRINK_STOP;
6469 if (mutex_trylock(&conf->cache_size_mutex)) {
6470 ret= 0;
6471 while (ret < sc->nr_to_scan &&
6472 conf->max_nr_stripes > conf->min_nr_stripes) {
6473 if (drop_one_stripe(conf) == 0) {
6474 ret = SHRINK_STOP;
6475 break;
6477 ret++;
6479 mutex_unlock(&conf->cache_size_mutex);
6481 return ret;
6484 static unsigned long raid5_cache_count(struct shrinker *shrink,
6485 struct shrink_control *sc)
6487 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6489 if (conf->max_nr_stripes < conf->min_nr_stripes)
6490 /* unlikely, but not impossible */
6491 return 0;
6492 return conf->max_nr_stripes - conf->min_nr_stripes;
6495 static struct r5conf *setup_conf(struct mddev *mddev)
6497 struct r5conf *conf;
6498 int raid_disk, memory, max_disks;
6499 struct md_rdev *rdev;
6500 struct disk_info *disk;
6501 char pers_name[6];
6502 int i;
6503 int group_cnt, worker_cnt_per_group;
6504 struct r5worker_group *new_group;
6506 if (mddev->new_level != 5
6507 && mddev->new_level != 4
6508 && mddev->new_level != 6) {
6509 printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6510 mdname(mddev), mddev->new_level);
6511 return ERR_PTR(-EIO);
6513 if ((mddev->new_level == 5
6514 && !algorithm_valid_raid5(mddev->new_layout)) ||
6515 (mddev->new_level == 6
6516 && !algorithm_valid_raid6(mddev->new_layout))) {
6517 printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
6518 mdname(mddev), mddev->new_layout);
6519 return ERR_PTR(-EIO);
6521 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6522 printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6523 mdname(mddev), mddev->raid_disks);
6524 return ERR_PTR(-EINVAL);
6527 if (!mddev->new_chunk_sectors ||
6528 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6529 !is_power_of_2(mddev->new_chunk_sectors)) {
6530 printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
6531 mdname(mddev), mddev->new_chunk_sectors << 9);
6532 return ERR_PTR(-EINVAL);
6535 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6536 if (conf == NULL)
6537 goto abort;
6538 /* Don't enable multi-threading by default*/
6539 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6540 &new_group)) {
6541 conf->group_cnt = group_cnt;
6542 conf->worker_cnt_per_group = worker_cnt_per_group;
6543 conf->worker_groups = new_group;
6544 } else
6545 goto abort;
6546 spin_lock_init(&conf->device_lock);
6547 seqcount_init(&conf->gen_lock);
6548 mutex_init(&conf->cache_size_mutex);
6549 init_waitqueue_head(&conf->wait_for_quiescent);
6550 init_waitqueue_head(&conf->wait_for_stripe);
6551 init_waitqueue_head(&conf->wait_for_overlap);
6552 INIT_LIST_HEAD(&conf->handle_list);
6553 INIT_LIST_HEAD(&conf->hold_list);
6554 INIT_LIST_HEAD(&conf->delayed_list);
6555 INIT_LIST_HEAD(&conf->bitmap_list);
6556 bio_list_init(&conf->return_bi);
6557 init_llist_head(&conf->released_stripes);
6558 atomic_set(&conf->active_stripes, 0);
6559 atomic_set(&conf->preread_active_stripes, 0);
6560 atomic_set(&conf->active_aligned_reads, 0);
6561 conf->bypass_threshold = BYPASS_THRESHOLD;
6562 conf->recovery_disabled = mddev->recovery_disabled - 1;
6564 conf->raid_disks = mddev->raid_disks;
6565 if (mddev->reshape_position == MaxSector)
6566 conf->previous_raid_disks = mddev->raid_disks;
6567 else
6568 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6569 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6571 conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
6572 GFP_KERNEL);
6573 if (!conf->disks)
6574 goto abort;
6576 conf->mddev = mddev;
6578 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
6579 goto abort;
6581 /* We init hash_locks[0] separately to that it can be used
6582 * as the reference lock in the spin_lock_nest_lock() call
6583 * in lock_all_device_hash_locks_irq in order to convince
6584 * lockdep that we know what we are doing.
6586 spin_lock_init(conf->hash_locks);
6587 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
6588 spin_lock_init(conf->hash_locks + i);
6590 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6591 INIT_LIST_HEAD(conf->inactive_list + i);
6593 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6594 INIT_LIST_HEAD(conf->temp_inactive_list + i);
6596 conf->level = mddev->new_level;
6597 conf->chunk_sectors = mddev->new_chunk_sectors;
6598 if (raid5_alloc_percpu(conf) != 0)
6599 goto abort;
6601 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
6603 rdev_for_each(rdev, mddev) {
6604 raid_disk = rdev->raid_disk;
6605 if (raid_disk >= max_disks
6606 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
6607 continue;
6608 disk = conf->disks + raid_disk;
6610 if (test_bit(Replacement, &rdev->flags)) {
6611 if (disk->replacement)
6612 goto abort;
6613 disk->replacement = rdev;
6614 } else {
6615 if (disk->rdev)
6616 goto abort;
6617 disk->rdev = rdev;
6620 if (test_bit(In_sync, &rdev->flags)) {
6621 char b[BDEVNAME_SIZE];
6622 printk(KERN_INFO "md/raid:%s: device %s operational as raid"
6623 " disk %d\n",
6624 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
6625 } else if (rdev->saved_raid_disk != raid_disk)
6626 /* Cannot rely on bitmap to complete recovery */
6627 conf->fullsync = 1;
6630 conf->level = mddev->new_level;
6631 if (conf->level == 6) {
6632 conf->max_degraded = 2;
6633 if (raid6_call.xor_syndrome)
6634 conf->rmw_level = PARITY_ENABLE_RMW;
6635 else
6636 conf->rmw_level = PARITY_DISABLE_RMW;
6637 } else {
6638 conf->max_degraded = 1;
6639 conf->rmw_level = PARITY_ENABLE_RMW;
6641 conf->algorithm = mddev->new_layout;
6642 conf->reshape_progress = mddev->reshape_position;
6643 if (conf->reshape_progress != MaxSector) {
6644 conf->prev_chunk_sectors = mddev->chunk_sectors;
6645 conf->prev_algo = mddev->layout;
6646 } else {
6647 conf->prev_chunk_sectors = conf->chunk_sectors;
6648 conf->prev_algo = conf->algorithm;
6651 conf->min_nr_stripes = NR_STRIPES;
6652 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
6653 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
6654 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
6655 if (grow_stripes(conf, conf->min_nr_stripes)) {
6656 printk(KERN_ERR
6657 "md/raid:%s: couldn't allocate %dkB for buffers\n",
6658 mdname(mddev), memory);
6659 goto abort;
6660 } else
6661 printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
6662 mdname(mddev), memory);
6664 * Losing a stripe head costs more than the time to refill it,
6665 * it reduces the queue depth and so can hurt throughput.
6666 * So set it rather large, scaled by number of devices.
6668 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
6669 conf->shrinker.scan_objects = raid5_cache_scan;
6670 conf->shrinker.count_objects = raid5_cache_count;
6671 conf->shrinker.batch = 128;
6672 conf->shrinker.flags = 0;
6673 register_shrinker(&conf->shrinker);
6675 sprintf(pers_name, "raid%d", mddev->new_level);
6676 conf->thread = md_register_thread(raid5d, mddev, pers_name);
6677 if (!conf->thread) {
6678 printk(KERN_ERR
6679 "md/raid:%s: couldn't allocate thread.\n",
6680 mdname(mddev));
6681 goto abort;
6684 return conf;
6686 abort:
6687 if (conf) {
6688 free_conf(conf);
6689 return ERR_PTR(-EIO);
6690 } else
6691 return ERR_PTR(-ENOMEM);
6694 static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
6696 switch (algo) {
6697 case ALGORITHM_PARITY_0:
6698 if (raid_disk < max_degraded)
6699 return 1;
6700 break;
6701 case ALGORITHM_PARITY_N:
6702 if (raid_disk >= raid_disks - max_degraded)
6703 return 1;
6704 break;
6705 case ALGORITHM_PARITY_0_6:
6706 if (raid_disk == 0 ||
6707 raid_disk == raid_disks - 1)
6708 return 1;
6709 break;
6710 case ALGORITHM_LEFT_ASYMMETRIC_6:
6711 case ALGORITHM_RIGHT_ASYMMETRIC_6:
6712 case ALGORITHM_LEFT_SYMMETRIC_6:
6713 case ALGORITHM_RIGHT_SYMMETRIC_6:
6714 if (raid_disk == raid_disks - 1)
6715 return 1;
6717 return 0;
6720 static int run(struct mddev *mddev)
6722 struct r5conf *conf;
6723 int working_disks = 0;
6724 int dirty_parity_disks = 0;
6725 struct md_rdev *rdev;
6726 struct md_rdev *journal_dev = NULL;
6727 sector_t reshape_offset = 0;
6728 int i;
6729 long long min_offset_diff = 0;
6730 int first = 1;
6732 if (mddev->recovery_cp != MaxSector)
6733 printk(KERN_NOTICE "md/raid:%s: not clean"
6734 " -- starting background reconstruction\n",
6735 mdname(mddev));
6737 rdev_for_each(rdev, mddev) {
6738 long long diff;
6740 if (test_bit(Journal, &rdev->flags)) {
6741 journal_dev = rdev;
6742 continue;
6744 if (rdev->raid_disk < 0)
6745 continue;
6746 diff = (rdev->new_data_offset - rdev->data_offset);
6747 if (first) {
6748 min_offset_diff = diff;
6749 first = 0;
6750 } else if (mddev->reshape_backwards &&
6751 diff < min_offset_diff)
6752 min_offset_diff = diff;
6753 else if (!mddev->reshape_backwards &&
6754 diff > min_offset_diff)
6755 min_offset_diff = diff;
6758 if (mddev->reshape_position != MaxSector) {
6759 /* Check that we can continue the reshape.
6760 * Difficulties arise if the stripe we would write to
6761 * next is at or after the stripe we would read from next.
6762 * For a reshape that changes the number of devices, this
6763 * is only possible for a very short time, and mdadm makes
6764 * sure that time appears to have past before assembling
6765 * the array. So we fail if that time hasn't passed.
6766 * For a reshape that keeps the number of devices the same
6767 * mdadm must be monitoring the reshape can keeping the
6768 * critical areas read-only and backed up. It will start
6769 * the array in read-only mode, so we check for that.
6771 sector_t here_new, here_old;
6772 int old_disks;
6773 int max_degraded = (mddev->level == 6 ? 2 : 1);
6774 int chunk_sectors;
6775 int new_data_disks;
6777 if (journal_dev) {
6778 printk(KERN_ERR "md/raid:%s: don't support reshape with journal - aborting.\n",
6779 mdname(mddev));
6780 return -EINVAL;
6783 if (mddev->new_level != mddev->level) {
6784 printk(KERN_ERR "md/raid:%s: unsupported reshape "
6785 "required - aborting.\n",
6786 mdname(mddev));
6787 return -EINVAL;
6789 old_disks = mddev->raid_disks - mddev->delta_disks;
6790 /* reshape_position must be on a new-stripe boundary, and one
6791 * further up in new geometry must map after here in old
6792 * geometry.
6793 * If the chunk sizes are different, then as we perform reshape
6794 * in units of the largest of the two, reshape_position needs
6795 * be a multiple of the largest chunk size times new data disks.
6797 here_new = mddev->reshape_position;
6798 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
6799 new_data_disks = mddev->raid_disks - max_degraded;
6800 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
6801 printk(KERN_ERR "md/raid:%s: reshape_position not "
6802 "on a stripe boundary\n", mdname(mddev));
6803 return -EINVAL;
6805 reshape_offset = here_new * chunk_sectors;
6806 /* here_new is the stripe we will write to */
6807 here_old = mddev->reshape_position;
6808 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
6809 /* here_old is the first stripe that we might need to read
6810 * from */
6811 if (mddev->delta_disks == 0) {
6812 /* We cannot be sure it is safe to start an in-place
6813 * reshape. It is only safe if user-space is monitoring
6814 * and taking constant backups.
6815 * mdadm always starts a situation like this in
6816 * readonly mode so it can take control before
6817 * allowing any writes. So just check for that.
6819 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
6820 abs(min_offset_diff) >= mddev->new_chunk_sectors)
6821 /* not really in-place - so OK */;
6822 else if (mddev->ro == 0) {
6823 printk(KERN_ERR "md/raid:%s: in-place reshape "
6824 "must be started in read-only mode "
6825 "- aborting\n",
6826 mdname(mddev));
6827 return -EINVAL;
6829 } else if (mddev->reshape_backwards
6830 ? (here_new * chunk_sectors + min_offset_diff <=
6831 here_old * chunk_sectors)
6832 : (here_new * chunk_sectors >=
6833 here_old * chunk_sectors + (-min_offset_diff))) {
6834 /* Reading from the same stripe as writing to - bad */
6835 printk(KERN_ERR "md/raid:%s: reshape_position too early for "
6836 "auto-recovery - aborting.\n",
6837 mdname(mddev));
6838 return -EINVAL;
6840 printk(KERN_INFO "md/raid:%s: reshape will continue\n",
6841 mdname(mddev));
6842 /* OK, we should be able to continue; */
6843 } else {
6844 BUG_ON(mddev->level != mddev->new_level);
6845 BUG_ON(mddev->layout != mddev->new_layout);
6846 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
6847 BUG_ON(mddev->delta_disks != 0);
6850 if (mddev->private == NULL)
6851 conf = setup_conf(mddev);
6852 else
6853 conf = mddev->private;
6855 if (IS_ERR(conf))
6856 return PTR_ERR(conf);
6858 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !journal_dev) {
6859 printk(KERN_ERR "md/raid:%s: journal disk is missing, force array readonly\n",
6860 mdname(mddev));
6861 mddev->ro = 1;
6862 set_disk_ro(mddev->gendisk, 1);
6865 conf->min_offset_diff = min_offset_diff;
6866 mddev->thread = conf->thread;
6867 conf->thread = NULL;
6868 mddev->private = conf;
6870 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
6871 i++) {
6872 rdev = conf->disks[i].rdev;
6873 if (!rdev && conf->disks[i].replacement) {
6874 /* The replacement is all we have yet */
6875 rdev = conf->disks[i].replacement;
6876 conf->disks[i].replacement = NULL;
6877 clear_bit(Replacement, &rdev->flags);
6878 conf->disks[i].rdev = rdev;
6880 if (!rdev)
6881 continue;
6882 if (conf->disks[i].replacement &&
6883 conf->reshape_progress != MaxSector) {
6884 /* replacements and reshape simply do not mix. */
6885 printk(KERN_ERR "md: cannot handle concurrent "
6886 "replacement and reshape.\n");
6887 goto abort;
6889 if (test_bit(In_sync, &rdev->flags)) {
6890 working_disks++;
6891 continue;
6893 /* This disc is not fully in-sync. However if it
6894 * just stored parity (beyond the recovery_offset),
6895 * when we don't need to be concerned about the
6896 * array being dirty.
6897 * When reshape goes 'backwards', we never have
6898 * partially completed devices, so we only need
6899 * to worry about reshape going forwards.
6901 /* Hack because v0.91 doesn't store recovery_offset properly. */
6902 if (mddev->major_version == 0 &&
6903 mddev->minor_version > 90)
6904 rdev->recovery_offset = reshape_offset;
6906 if (rdev->recovery_offset < reshape_offset) {
6907 /* We need to check old and new layout */
6908 if (!only_parity(rdev->raid_disk,
6909 conf->algorithm,
6910 conf->raid_disks,
6911 conf->max_degraded))
6912 continue;
6914 if (!only_parity(rdev->raid_disk,
6915 conf->prev_algo,
6916 conf->previous_raid_disks,
6917 conf->max_degraded))
6918 continue;
6919 dirty_parity_disks++;
6923 * 0 for a fully functional array, 1 or 2 for a degraded array.
6925 mddev->degraded = calc_degraded(conf);
6927 if (has_failed(conf)) {
6928 printk(KERN_ERR "md/raid:%s: not enough operational devices"
6929 " (%d/%d failed)\n",
6930 mdname(mddev), mddev->degraded, conf->raid_disks);
6931 goto abort;
6934 /* device size must be a multiple of chunk size */
6935 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
6936 mddev->resync_max_sectors = mddev->dev_sectors;
6938 if (mddev->degraded > dirty_parity_disks &&
6939 mddev->recovery_cp != MaxSector) {
6940 if (mddev->ok_start_degraded)
6941 printk(KERN_WARNING
6942 "md/raid:%s: starting dirty degraded array"
6943 " - data corruption possible.\n",
6944 mdname(mddev));
6945 else {
6946 printk(KERN_ERR
6947 "md/raid:%s: cannot start dirty degraded array.\n",
6948 mdname(mddev));
6949 goto abort;
6953 if (mddev->degraded == 0)
6954 printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
6955 " devices, algorithm %d\n", mdname(mddev), conf->level,
6956 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
6957 mddev->new_layout);
6958 else
6959 printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
6960 " out of %d devices, algorithm %d\n",
6961 mdname(mddev), conf->level,
6962 mddev->raid_disks - mddev->degraded,
6963 mddev->raid_disks, mddev->new_layout);
6965 print_raid5_conf(conf);
6967 if (conf->reshape_progress != MaxSector) {
6968 conf->reshape_safe = conf->reshape_progress;
6969 atomic_set(&conf->reshape_stripes, 0);
6970 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6971 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6972 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6973 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6974 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6975 "reshape");
6978 /* Ok, everything is just fine now */
6979 if (mddev->to_remove == &raid5_attrs_group)
6980 mddev->to_remove = NULL;
6981 else if (mddev->kobj.sd &&
6982 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
6983 printk(KERN_WARNING
6984 "raid5: failed to create sysfs attributes for %s\n",
6985 mdname(mddev));
6986 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6988 if (mddev->queue) {
6989 int chunk_size;
6990 bool discard_supported = true;
6991 /* read-ahead size must cover two whole stripes, which
6992 * is 2 * (datadisks) * chunksize where 'n' is the
6993 * number of raid devices
6995 int data_disks = conf->previous_raid_disks - conf->max_degraded;
6996 int stripe = data_disks *
6997 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
6998 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6999 mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
7001 chunk_size = mddev->chunk_sectors << 9;
7002 blk_queue_io_min(mddev->queue, chunk_size);
7003 blk_queue_io_opt(mddev->queue, chunk_size *
7004 (conf->raid_disks - conf->max_degraded));
7005 mddev->queue->limits.raid_partial_stripes_expensive = 1;
7007 * We can only discard a whole stripe. It doesn't make sense to
7008 * discard data disk but write parity disk
7010 stripe = stripe * PAGE_SIZE;
7011 /* Round up to power of 2, as discard handling
7012 * currently assumes that */
7013 while ((stripe-1) & stripe)
7014 stripe = (stripe | (stripe-1)) + 1;
7015 mddev->queue->limits.discard_alignment = stripe;
7016 mddev->queue->limits.discard_granularity = stripe;
7019 * We use 16-bit counter of active stripes in bi_phys_segments
7020 * (minus one for over-loaded initialization)
7022 blk_queue_max_hw_sectors(mddev->queue, 0xfffe * STRIPE_SECTORS);
7023 blk_queue_max_discard_sectors(mddev->queue,
7024 0xfffe * STRIPE_SECTORS);
7027 * unaligned part of discard request will be ignored, so can't
7028 * guarantee discard_zeroes_data
7030 mddev->queue->limits.discard_zeroes_data = 0;
7032 blk_queue_max_write_same_sectors(mddev->queue, 0);
7034 rdev_for_each(rdev, mddev) {
7035 disk_stack_limits(mddev->gendisk, rdev->bdev,
7036 rdev->data_offset << 9);
7037 disk_stack_limits(mddev->gendisk, rdev->bdev,
7038 rdev->new_data_offset << 9);
7040 * discard_zeroes_data is required, otherwise data
7041 * could be lost. Consider a scenario: discard a stripe
7042 * (the stripe could be inconsistent if
7043 * discard_zeroes_data is 0); write one disk of the
7044 * stripe (the stripe could be inconsistent again
7045 * depending on which disks are used to calculate
7046 * parity); the disk is broken; The stripe data of this
7047 * disk is lost.
7049 if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
7050 !bdev_get_queue(rdev->bdev)->
7051 limits.discard_zeroes_data)
7052 discard_supported = false;
7053 /* Unfortunately, discard_zeroes_data is not currently
7054 * a guarantee - just a hint. So we only allow DISCARD
7055 * if the sysadmin has confirmed that only safe devices
7056 * are in use by setting a module parameter.
7058 if (!devices_handle_discard_safely) {
7059 if (discard_supported) {
7060 pr_info("md/raid456: discard support disabled due to uncertainty.\n");
7061 pr_info("Set raid456.devices_handle_discard_safely=Y to override.\n");
7063 discard_supported = false;
7067 if (discard_supported &&
7068 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7069 mddev->queue->limits.discard_granularity >= stripe)
7070 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
7071 mddev->queue);
7072 else
7073 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
7074 mddev->queue);
7077 if (journal_dev) {
7078 char b[BDEVNAME_SIZE];
7080 printk(KERN_INFO"md/raid:%s: using device %s as journal\n",
7081 mdname(mddev), bdevname(journal_dev->bdev, b));
7082 r5l_init_log(conf, journal_dev);
7085 return 0;
7086 abort:
7087 md_unregister_thread(&mddev->thread);
7088 print_raid5_conf(conf);
7089 free_conf(conf);
7090 mddev->private = NULL;
7091 printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
7092 return -EIO;
7095 static void raid5_free(struct mddev *mddev, void *priv)
7097 struct r5conf *conf = priv;
7099 free_conf(conf);
7100 mddev->to_remove = &raid5_attrs_group;
7103 static void status(struct seq_file *seq, struct mddev *mddev)
7105 struct r5conf *conf = mddev->private;
7106 int i;
7108 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7109 conf->chunk_sectors / 2, mddev->layout);
7110 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7111 for (i = 0; i < conf->raid_disks; i++)
7112 seq_printf (seq, "%s",
7113 conf->disks[i].rdev &&
7114 test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
7115 seq_printf (seq, "]");
7118 static void print_raid5_conf (struct r5conf *conf)
7120 int i;
7121 struct disk_info *tmp;
7123 printk(KERN_DEBUG "RAID conf printout:\n");
7124 if (!conf) {
7125 printk("(conf==NULL)\n");
7126 return;
7128 printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
7129 conf->raid_disks,
7130 conf->raid_disks - conf->mddev->degraded);
7132 for (i = 0; i < conf->raid_disks; i++) {
7133 char b[BDEVNAME_SIZE];
7134 tmp = conf->disks + i;
7135 if (tmp->rdev)
7136 printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
7137 i, !test_bit(Faulty, &tmp->rdev->flags),
7138 bdevname(tmp->rdev->bdev, b));
7142 static int raid5_spare_active(struct mddev *mddev)
7144 int i;
7145 struct r5conf *conf = mddev->private;
7146 struct disk_info *tmp;
7147 int count = 0;
7148 unsigned long flags;
7150 for (i = 0; i < conf->raid_disks; i++) {
7151 tmp = conf->disks + i;
7152 if (tmp->replacement
7153 && tmp->replacement->recovery_offset == MaxSector
7154 && !test_bit(Faulty, &tmp->replacement->flags)
7155 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7156 /* Replacement has just become active. */
7157 if (!tmp->rdev
7158 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7159 count++;
7160 if (tmp->rdev) {
7161 /* Replaced device not technically faulty,
7162 * but we need to be sure it gets removed
7163 * and never re-added.
7165 set_bit(Faulty, &tmp->rdev->flags);
7166 sysfs_notify_dirent_safe(
7167 tmp->rdev->sysfs_state);
7169 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7170 } else if (tmp->rdev
7171 && tmp->rdev->recovery_offset == MaxSector
7172 && !test_bit(Faulty, &tmp->rdev->flags)
7173 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7174 count++;
7175 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7178 spin_lock_irqsave(&conf->device_lock, flags);
7179 mddev->degraded = calc_degraded(conf);
7180 spin_unlock_irqrestore(&conf->device_lock, flags);
7181 print_raid5_conf(conf);
7182 return count;
7185 static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7187 struct r5conf *conf = mddev->private;
7188 int err = 0;
7189 int number = rdev->raid_disk;
7190 struct md_rdev **rdevp;
7191 struct disk_info *p = conf->disks + number;
7193 print_raid5_conf(conf);
7194 if (test_bit(Journal, &rdev->flags)) {
7196 * journal disk is not removable, but we need give a chance to
7197 * update superblock of other disks. Otherwise journal disk
7198 * will be considered as 'fresh'
7200 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7201 return -EINVAL;
7203 if (rdev == p->rdev)
7204 rdevp = &p->rdev;
7205 else if (rdev == p->replacement)
7206 rdevp = &p->replacement;
7207 else
7208 return 0;
7210 if (number >= conf->raid_disks &&
7211 conf->reshape_progress == MaxSector)
7212 clear_bit(In_sync, &rdev->flags);
7214 if (test_bit(In_sync, &rdev->flags) ||
7215 atomic_read(&rdev->nr_pending)) {
7216 err = -EBUSY;
7217 goto abort;
7219 /* Only remove non-faulty devices if recovery
7220 * isn't possible.
7222 if (!test_bit(Faulty, &rdev->flags) &&
7223 mddev->recovery_disabled != conf->recovery_disabled &&
7224 !has_failed(conf) &&
7225 (!p->replacement || p->replacement == rdev) &&
7226 number < conf->raid_disks) {
7227 err = -EBUSY;
7228 goto abort;
7230 *rdevp = NULL;
7231 synchronize_rcu();
7232 if (atomic_read(&rdev->nr_pending)) {
7233 /* lost the race, try later */
7234 err = -EBUSY;
7235 *rdevp = rdev;
7236 } else if (p->replacement) {
7237 /* We must have just cleared 'rdev' */
7238 p->rdev = p->replacement;
7239 clear_bit(Replacement, &p->replacement->flags);
7240 smp_mb(); /* Make sure other CPUs may see both as identical
7241 * but will never see neither - if they are careful
7243 p->replacement = NULL;
7244 clear_bit(WantReplacement, &rdev->flags);
7245 } else
7246 /* We might have just removed the Replacement as faulty-
7247 * clear the bit just in case
7249 clear_bit(WantReplacement, &rdev->flags);
7250 abort:
7252 print_raid5_conf(conf);
7253 return err;
7256 static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7258 struct r5conf *conf = mddev->private;
7259 int err = -EEXIST;
7260 int disk;
7261 struct disk_info *p;
7262 int first = 0;
7263 int last = conf->raid_disks - 1;
7265 if (test_bit(Journal, &rdev->flags))
7266 return -EINVAL;
7267 if (mddev->recovery_disabled == conf->recovery_disabled)
7268 return -EBUSY;
7270 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7271 /* no point adding a device */
7272 return -EINVAL;
7274 if (rdev->raid_disk >= 0)
7275 first = last = rdev->raid_disk;
7278 * find the disk ... but prefer rdev->saved_raid_disk
7279 * if possible.
7281 if (rdev->saved_raid_disk >= 0 &&
7282 rdev->saved_raid_disk >= first &&
7283 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7284 first = rdev->saved_raid_disk;
7286 for (disk = first; disk <= last; disk++) {
7287 p = conf->disks + disk;
7288 if (p->rdev == NULL) {
7289 clear_bit(In_sync, &rdev->flags);
7290 rdev->raid_disk = disk;
7291 err = 0;
7292 if (rdev->saved_raid_disk != disk)
7293 conf->fullsync = 1;
7294 rcu_assign_pointer(p->rdev, rdev);
7295 goto out;
7298 for (disk = first; disk <= last; disk++) {
7299 p = conf->disks + disk;
7300 if (test_bit(WantReplacement, &p->rdev->flags) &&
7301 p->replacement == NULL) {
7302 clear_bit(In_sync, &rdev->flags);
7303 set_bit(Replacement, &rdev->flags);
7304 rdev->raid_disk = disk;
7305 err = 0;
7306 conf->fullsync = 1;
7307 rcu_assign_pointer(p->replacement, rdev);
7308 break;
7311 out:
7312 print_raid5_conf(conf);
7313 return err;
7316 static int raid5_resize(struct mddev *mddev, sector_t sectors)
7318 /* no resync is happening, and there is enough space
7319 * on all devices, so we can resize.
7320 * We need to make sure resync covers any new space.
7321 * If the array is shrinking we should possibly wait until
7322 * any io in the removed space completes, but it hardly seems
7323 * worth it.
7325 sector_t newsize;
7326 struct r5conf *conf = mddev->private;
7328 if (conf->log)
7329 return -EINVAL;
7330 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7331 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7332 if (mddev->external_size &&
7333 mddev->array_sectors > newsize)
7334 return -EINVAL;
7335 if (mddev->bitmap) {
7336 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
7337 if (ret)
7338 return ret;
7340 md_set_array_sectors(mddev, newsize);
7341 set_capacity(mddev->gendisk, mddev->array_sectors);
7342 revalidate_disk(mddev->gendisk);
7343 if (sectors > mddev->dev_sectors &&
7344 mddev->recovery_cp > mddev->dev_sectors) {
7345 mddev->recovery_cp = mddev->dev_sectors;
7346 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7348 mddev->dev_sectors = sectors;
7349 mddev->resync_max_sectors = sectors;
7350 return 0;
7353 static int check_stripe_cache(struct mddev *mddev)
7355 /* Can only proceed if there are plenty of stripe_heads.
7356 * We need a minimum of one full stripe,, and for sensible progress
7357 * it is best to have about 4 times that.
7358 * If we require 4 times, then the default 256 4K stripe_heads will
7359 * allow for chunk sizes up to 256K, which is probably OK.
7360 * If the chunk size is greater, user-space should request more
7361 * stripe_heads first.
7363 struct r5conf *conf = mddev->private;
7364 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7365 > conf->min_nr_stripes ||
7366 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7367 > conf->min_nr_stripes) {
7368 printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7369 mdname(mddev),
7370 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7371 / STRIPE_SIZE)*4);
7372 return 0;
7374 return 1;
7377 static int check_reshape(struct mddev *mddev)
7379 struct r5conf *conf = mddev->private;
7381 if (conf->log)
7382 return -EINVAL;
7383 if (mddev->delta_disks == 0 &&
7384 mddev->new_layout == mddev->layout &&
7385 mddev->new_chunk_sectors == mddev->chunk_sectors)
7386 return 0; /* nothing to do */
7387 if (has_failed(conf))
7388 return -EINVAL;
7389 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7390 /* We might be able to shrink, but the devices must
7391 * be made bigger first.
7392 * For raid6, 4 is the minimum size.
7393 * Otherwise 2 is the minimum
7395 int min = 2;
7396 if (mddev->level == 6)
7397 min = 4;
7398 if (mddev->raid_disks + mddev->delta_disks < min)
7399 return -EINVAL;
7402 if (!check_stripe_cache(mddev))
7403 return -ENOSPC;
7405 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7406 mddev->delta_disks > 0)
7407 if (resize_chunks(conf,
7408 conf->previous_raid_disks
7409 + max(0, mddev->delta_disks),
7410 max(mddev->new_chunk_sectors,
7411 mddev->chunk_sectors)
7412 ) < 0)
7413 return -ENOMEM;
7414 return resize_stripes(conf, (conf->previous_raid_disks
7415 + mddev->delta_disks));
7418 static int raid5_start_reshape(struct mddev *mddev)
7420 struct r5conf *conf = mddev->private;
7421 struct md_rdev *rdev;
7422 int spares = 0;
7423 unsigned long flags;
7425 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7426 return -EBUSY;
7428 if (!check_stripe_cache(mddev))
7429 return -ENOSPC;
7431 if (has_failed(conf))
7432 return -EINVAL;
7434 rdev_for_each(rdev, mddev) {
7435 if (!test_bit(In_sync, &rdev->flags)
7436 && !test_bit(Faulty, &rdev->flags))
7437 spares++;
7440 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7441 /* Not enough devices even to make a degraded array
7442 * of that size
7444 return -EINVAL;
7446 /* Refuse to reduce size of the array. Any reductions in
7447 * array size must be through explicit setting of array_size
7448 * attribute.
7450 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7451 < mddev->array_sectors) {
7452 printk(KERN_ERR "md/raid:%s: array size must be reduced "
7453 "before number of disks\n", mdname(mddev));
7454 return -EINVAL;
7457 atomic_set(&conf->reshape_stripes, 0);
7458 spin_lock_irq(&conf->device_lock);
7459 write_seqcount_begin(&conf->gen_lock);
7460 conf->previous_raid_disks = conf->raid_disks;
7461 conf->raid_disks += mddev->delta_disks;
7462 conf->prev_chunk_sectors = conf->chunk_sectors;
7463 conf->chunk_sectors = mddev->new_chunk_sectors;
7464 conf->prev_algo = conf->algorithm;
7465 conf->algorithm = mddev->new_layout;
7466 conf->generation++;
7467 /* Code that selects data_offset needs to see the generation update
7468 * if reshape_progress has been set - so a memory barrier needed.
7470 smp_mb();
7471 if (mddev->reshape_backwards)
7472 conf->reshape_progress = raid5_size(mddev, 0, 0);
7473 else
7474 conf->reshape_progress = 0;
7475 conf->reshape_safe = conf->reshape_progress;
7476 write_seqcount_end(&conf->gen_lock);
7477 spin_unlock_irq(&conf->device_lock);
7479 /* Now make sure any requests that proceeded on the assumption
7480 * the reshape wasn't running - like Discard or Read - have
7481 * completed.
7483 mddev_suspend(mddev);
7484 mddev_resume(mddev);
7486 /* Add some new drives, as many as will fit.
7487 * We know there are enough to make the newly sized array work.
7488 * Don't add devices if we are reducing the number of
7489 * devices in the array. This is because it is not possible
7490 * to correctly record the "partially reconstructed" state of
7491 * such devices during the reshape and confusion could result.
7493 if (mddev->delta_disks >= 0) {
7494 rdev_for_each(rdev, mddev)
7495 if (rdev->raid_disk < 0 &&
7496 !test_bit(Faulty, &rdev->flags)) {
7497 if (raid5_add_disk(mddev, rdev) == 0) {
7498 if (rdev->raid_disk
7499 >= conf->previous_raid_disks)
7500 set_bit(In_sync, &rdev->flags);
7501 else
7502 rdev->recovery_offset = 0;
7504 if (sysfs_link_rdev(mddev, rdev))
7505 /* Failure here is OK */;
7507 } else if (rdev->raid_disk >= conf->previous_raid_disks
7508 && !test_bit(Faulty, &rdev->flags)) {
7509 /* This is a spare that was manually added */
7510 set_bit(In_sync, &rdev->flags);
7513 /* When a reshape changes the number of devices,
7514 * ->degraded is measured against the larger of the
7515 * pre and post number of devices.
7517 spin_lock_irqsave(&conf->device_lock, flags);
7518 mddev->degraded = calc_degraded(conf);
7519 spin_unlock_irqrestore(&conf->device_lock, flags);
7521 mddev->raid_disks = conf->raid_disks;
7522 mddev->reshape_position = conf->reshape_progress;
7523 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7525 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7526 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7527 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7528 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7529 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7530 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7531 "reshape");
7532 if (!mddev->sync_thread) {
7533 mddev->recovery = 0;
7534 spin_lock_irq(&conf->device_lock);
7535 write_seqcount_begin(&conf->gen_lock);
7536 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7537 mddev->new_chunk_sectors =
7538 conf->chunk_sectors = conf->prev_chunk_sectors;
7539 mddev->new_layout = conf->algorithm = conf->prev_algo;
7540 rdev_for_each(rdev, mddev)
7541 rdev->new_data_offset = rdev->data_offset;
7542 smp_wmb();
7543 conf->generation --;
7544 conf->reshape_progress = MaxSector;
7545 mddev->reshape_position = MaxSector;
7546 write_seqcount_end(&conf->gen_lock);
7547 spin_unlock_irq(&conf->device_lock);
7548 return -EAGAIN;
7550 conf->reshape_checkpoint = jiffies;
7551 md_wakeup_thread(mddev->sync_thread);
7552 md_new_event(mddev);
7553 return 0;
7556 /* This is called from the reshape thread and should make any
7557 * changes needed in 'conf'
7559 static void end_reshape(struct r5conf *conf)
7562 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
7564 spin_lock_irq(&conf->device_lock);
7565 conf->previous_raid_disks = conf->raid_disks;
7566 md_finish_reshape(conf->mddev);
7567 smp_wmb();
7568 conf->reshape_progress = MaxSector;
7569 conf->mddev->reshape_position = MaxSector;
7570 spin_unlock_irq(&conf->device_lock);
7571 wake_up(&conf->wait_for_overlap);
7573 /* read-ahead size must cover two whole stripes, which is
7574 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
7576 if (conf->mddev->queue) {
7577 int data_disks = conf->raid_disks - conf->max_degraded;
7578 int stripe = data_disks * ((conf->chunk_sectors << 9)
7579 / PAGE_SIZE);
7580 if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
7581 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
7586 /* This is called from the raid5d thread with mddev_lock held.
7587 * It makes config changes to the device.
7589 static void raid5_finish_reshape(struct mddev *mddev)
7591 struct r5conf *conf = mddev->private;
7593 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7595 if (mddev->delta_disks > 0) {
7596 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7597 set_capacity(mddev->gendisk, mddev->array_sectors);
7598 revalidate_disk(mddev->gendisk);
7599 } else {
7600 int d;
7601 spin_lock_irq(&conf->device_lock);
7602 mddev->degraded = calc_degraded(conf);
7603 spin_unlock_irq(&conf->device_lock);
7604 for (d = conf->raid_disks ;
7605 d < conf->raid_disks - mddev->delta_disks;
7606 d++) {
7607 struct md_rdev *rdev = conf->disks[d].rdev;
7608 if (rdev)
7609 clear_bit(In_sync, &rdev->flags);
7610 rdev = conf->disks[d].replacement;
7611 if (rdev)
7612 clear_bit(In_sync, &rdev->flags);
7615 mddev->layout = conf->algorithm;
7616 mddev->chunk_sectors = conf->chunk_sectors;
7617 mddev->reshape_position = MaxSector;
7618 mddev->delta_disks = 0;
7619 mddev->reshape_backwards = 0;
7623 static void raid5_quiesce(struct mddev *mddev, int state)
7625 struct r5conf *conf = mddev->private;
7627 switch(state) {
7628 case 2: /* resume for a suspend */
7629 wake_up(&conf->wait_for_overlap);
7630 break;
7632 case 1: /* stop all writes */
7633 lock_all_device_hash_locks_irq(conf);
7634 /* '2' tells resync/reshape to pause so that all
7635 * active stripes can drain
7637 conf->quiesce = 2;
7638 wait_event_cmd(conf->wait_for_quiescent,
7639 atomic_read(&conf->active_stripes) == 0 &&
7640 atomic_read(&conf->active_aligned_reads) == 0,
7641 unlock_all_device_hash_locks_irq(conf),
7642 lock_all_device_hash_locks_irq(conf));
7643 conf->quiesce = 1;
7644 unlock_all_device_hash_locks_irq(conf);
7645 /* allow reshape to continue */
7646 wake_up(&conf->wait_for_overlap);
7647 break;
7649 case 0: /* re-enable writes */
7650 lock_all_device_hash_locks_irq(conf);
7651 conf->quiesce = 0;
7652 wake_up(&conf->wait_for_quiescent);
7653 wake_up(&conf->wait_for_overlap);
7654 unlock_all_device_hash_locks_irq(conf);
7655 break;
7657 r5l_quiesce(conf->log, state);
7660 static void *raid45_takeover_raid0(struct mddev *mddev, int level)
7662 struct r0conf *raid0_conf = mddev->private;
7663 sector_t sectors;
7665 /* for raid0 takeover only one zone is supported */
7666 if (raid0_conf->nr_strip_zones > 1) {
7667 printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
7668 mdname(mddev));
7669 return ERR_PTR(-EINVAL);
7672 sectors = raid0_conf->strip_zone[0].zone_end;
7673 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
7674 mddev->dev_sectors = sectors;
7675 mddev->new_level = level;
7676 mddev->new_layout = ALGORITHM_PARITY_N;
7677 mddev->new_chunk_sectors = mddev->chunk_sectors;
7678 mddev->raid_disks += 1;
7679 mddev->delta_disks = 1;
7680 /* make sure it will be not marked as dirty */
7681 mddev->recovery_cp = MaxSector;
7683 return setup_conf(mddev);
7686 static void *raid5_takeover_raid1(struct mddev *mddev)
7688 int chunksect;
7690 if (mddev->raid_disks != 2 ||
7691 mddev->degraded > 1)
7692 return ERR_PTR(-EINVAL);
7694 /* Should check if there are write-behind devices? */
7696 chunksect = 64*2; /* 64K by default */
7698 /* The array must be an exact multiple of chunksize */
7699 while (chunksect && (mddev->array_sectors & (chunksect-1)))
7700 chunksect >>= 1;
7702 if ((chunksect<<9) < STRIPE_SIZE)
7703 /* array size does not allow a suitable chunk size */
7704 return ERR_PTR(-EINVAL);
7706 mddev->new_level = 5;
7707 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
7708 mddev->new_chunk_sectors = chunksect;
7710 return setup_conf(mddev);
7713 static void *raid5_takeover_raid6(struct mddev *mddev)
7715 int new_layout;
7717 switch (mddev->layout) {
7718 case ALGORITHM_LEFT_ASYMMETRIC_6:
7719 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
7720 break;
7721 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7722 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
7723 break;
7724 case ALGORITHM_LEFT_SYMMETRIC_6:
7725 new_layout = ALGORITHM_LEFT_SYMMETRIC;
7726 break;
7727 case ALGORITHM_RIGHT_SYMMETRIC_6:
7728 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
7729 break;
7730 case ALGORITHM_PARITY_0_6:
7731 new_layout = ALGORITHM_PARITY_0;
7732 break;
7733 case ALGORITHM_PARITY_N:
7734 new_layout = ALGORITHM_PARITY_N;
7735 break;
7736 default:
7737 return ERR_PTR(-EINVAL);
7739 mddev->new_level = 5;
7740 mddev->new_layout = new_layout;
7741 mddev->delta_disks = -1;
7742 mddev->raid_disks -= 1;
7743 return setup_conf(mddev);
7746 static int raid5_check_reshape(struct mddev *mddev)
7748 /* For a 2-drive array, the layout and chunk size can be changed
7749 * immediately as not restriping is needed.
7750 * For larger arrays we record the new value - after validation
7751 * to be used by a reshape pass.
7753 struct r5conf *conf = mddev->private;
7754 int new_chunk = mddev->new_chunk_sectors;
7756 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
7757 return -EINVAL;
7758 if (new_chunk > 0) {
7759 if (!is_power_of_2(new_chunk))
7760 return -EINVAL;
7761 if (new_chunk < (PAGE_SIZE>>9))
7762 return -EINVAL;
7763 if (mddev->array_sectors & (new_chunk-1))
7764 /* not factor of array size */
7765 return -EINVAL;
7768 /* They look valid */
7770 if (mddev->raid_disks == 2) {
7771 /* can make the change immediately */
7772 if (mddev->new_layout >= 0) {
7773 conf->algorithm = mddev->new_layout;
7774 mddev->layout = mddev->new_layout;
7776 if (new_chunk > 0) {
7777 conf->chunk_sectors = new_chunk ;
7778 mddev->chunk_sectors = new_chunk;
7780 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7781 md_wakeup_thread(mddev->thread);
7783 return check_reshape(mddev);
7786 static int raid6_check_reshape(struct mddev *mddev)
7788 int new_chunk = mddev->new_chunk_sectors;
7790 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
7791 return -EINVAL;
7792 if (new_chunk > 0) {
7793 if (!is_power_of_2(new_chunk))
7794 return -EINVAL;
7795 if (new_chunk < (PAGE_SIZE >> 9))
7796 return -EINVAL;
7797 if (mddev->array_sectors & (new_chunk-1))
7798 /* not factor of array size */
7799 return -EINVAL;
7802 /* They look valid */
7803 return check_reshape(mddev);
7806 static void *raid5_takeover(struct mddev *mddev)
7808 /* raid5 can take over:
7809 * raid0 - if there is only one strip zone - make it a raid4 layout
7810 * raid1 - if there are two drives. We need to know the chunk size
7811 * raid4 - trivial - just use a raid4 layout.
7812 * raid6 - Providing it is a *_6 layout
7814 if (mddev->level == 0)
7815 return raid45_takeover_raid0(mddev, 5);
7816 if (mddev->level == 1)
7817 return raid5_takeover_raid1(mddev);
7818 if (mddev->level == 4) {
7819 mddev->new_layout = ALGORITHM_PARITY_N;
7820 mddev->new_level = 5;
7821 return setup_conf(mddev);
7823 if (mddev->level == 6)
7824 return raid5_takeover_raid6(mddev);
7826 return ERR_PTR(-EINVAL);
7829 static void *raid4_takeover(struct mddev *mddev)
7831 /* raid4 can take over:
7832 * raid0 - if there is only one strip zone
7833 * raid5 - if layout is right
7835 if (mddev->level == 0)
7836 return raid45_takeover_raid0(mddev, 4);
7837 if (mddev->level == 5 &&
7838 mddev->layout == ALGORITHM_PARITY_N) {
7839 mddev->new_layout = 0;
7840 mddev->new_level = 4;
7841 return setup_conf(mddev);
7843 return ERR_PTR(-EINVAL);
7846 static struct md_personality raid5_personality;
7848 static void *raid6_takeover(struct mddev *mddev)
7850 /* Currently can only take over a raid5. We map the
7851 * personality to an equivalent raid6 personality
7852 * with the Q block at the end.
7854 int new_layout;
7856 if (mddev->pers != &raid5_personality)
7857 return ERR_PTR(-EINVAL);
7858 if (mddev->degraded > 1)
7859 return ERR_PTR(-EINVAL);
7860 if (mddev->raid_disks > 253)
7861 return ERR_PTR(-EINVAL);
7862 if (mddev->raid_disks < 3)
7863 return ERR_PTR(-EINVAL);
7865 switch (mddev->layout) {
7866 case ALGORITHM_LEFT_ASYMMETRIC:
7867 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
7868 break;
7869 case ALGORITHM_RIGHT_ASYMMETRIC:
7870 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
7871 break;
7872 case ALGORITHM_LEFT_SYMMETRIC:
7873 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
7874 break;
7875 case ALGORITHM_RIGHT_SYMMETRIC:
7876 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
7877 break;
7878 case ALGORITHM_PARITY_0:
7879 new_layout = ALGORITHM_PARITY_0_6;
7880 break;
7881 case ALGORITHM_PARITY_N:
7882 new_layout = ALGORITHM_PARITY_N;
7883 break;
7884 default:
7885 return ERR_PTR(-EINVAL);
7887 mddev->new_level = 6;
7888 mddev->new_layout = new_layout;
7889 mddev->delta_disks = 1;
7890 mddev->raid_disks += 1;
7891 return setup_conf(mddev);
7894 static struct md_personality raid6_personality =
7896 .name = "raid6",
7897 .level = 6,
7898 .owner = THIS_MODULE,
7899 .make_request = make_request,
7900 .run = run,
7901 .free = raid5_free,
7902 .status = status,
7903 .error_handler = error,
7904 .hot_add_disk = raid5_add_disk,
7905 .hot_remove_disk= raid5_remove_disk,
7906 .spare_active = raid5_spare_active,
7907 .sync_request = sync_request,
7908 .resize = raid5_resize,
7909 .size = raid5_size,
7910 .check_reshape = raid6_check_reshape,
7911 .start_reshape = raid5_start_reshape,
7912 .finish_reshape = raid5_finish_reshape,
7913 .quiesce = raid5_quiesce,
7914 .takeover = raid6_takeover,
7915 .congested = raid5_congested,
7917 static struct md_personality raid5_personality =
7919 .name = "raid5",
7920 .level = 5,
7921 .owner = THIS_MODULE,
7922 .make_request = make_request,
7923 .run = run,
7924 .free = raid5_free,
7925 .status = status,
7926 .error_handler = error,
7927 .hot_add_disk = raid5_add_disk,
7928 .hot_remove_disk= raid5_remove_disk,
7929 .spare_active = raid5_spare_active,
7930 .sync_request = sync_request,
7931 .resize = raid5_resize,
7932 .size = raid5_size,
7933 .check_reshape = raid5_check_reshape,
7934 .start_reshape = raid5_start_reshape,
7935 .finish_reshape = raid5_finish_reshape,
7936 .quiesce = raid5_quiesce,
7937 .takeover = raid5_takeover,
7938 .congested = raid5_congested,
7941 static struct md_personality raid4_personality =
7943 .name = "raid4",
7944 .level = 4,
7945 .owner = THIS_MODULE,
7946 .make_request = make_request,
7947 .run = run,
7948 .free = raid5_free,
7949 .status = status,
7950 .error_handler = error,
7951 .hot_add_disk = raid5_add_disk,
7952 .hot_remove_disk= raid5_remove_disk,
7953 .spare_active = raid5_spare_active,
7954 .sync_request = sync_request,
7955 .resize = raid5_resize,
7956 .size = raid5_size,
7957 .check_reshape = raid5_check_reshape,
7958 .start_reshape = raid5_start_reshape,
7959 .finish_reshape = raid5_finish_reshape,
7960 .quiesce = raid5_quiesce,
7961 .takeover = raid4_takeover,
7962 .congested = raid5_congested,
7965 static int __init raid5_init(void)
7967 raid5_wq = alloc_workqueue("raid5wq",
7968 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
7969 if (!raid5_wq)
7970 return -ENOMEM;
7971 register_md_personality(&raid6_personality);
7972 register_md_personality(&raid5_personality);
7973 register_md_personality(&raid4_personality);
7974 return 0;
7977 static void raid5_exit(void)
7979 unregister_md_personality(&raid6_personality);
7980 unregister_md_personality(&raid5_personality);
7981 unregister_md_personality(&raid4_personality);
7982 destroy_workqueue(raid5_wq);
7985 module_init(raid5_init);
7986 module_exit(raid5_exit);
7987 MODULE_LICENSE("GPL");
7988 MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
7989 MODULE_ALIAS("md-personality-4"); /* RAID5 */
7990 MODULE_ALIAS("md-raid5");
7991 MODULE_ALIAS("md-raid4");
7992 MODULE_ALIAS("md-level-5");
7993 MODULE_ALIAS("md-level-4");
7994 MODULE_ALIAS("md-personality-8"); /* RAID6 */
7995 MODULE_ALIAS("md-raid6");
7996 MODULE_ALIAS("md-level-6");
7998 /* This used to be two separate modules, they were: */
7999 MODULE_ALIAS("raid5");
8000 MODULE_ALIAS("raid6");