blob: d55bf85b76ce587cb9473b23a6c6a8fb82b54097 [file] [log] [blame]
Kyle Swenson8d8f6542021-03-15 11:02:55 -06001/*
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
6 *
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!
10 *
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.
15 *
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.
19 */
20
21/*
22 * BITMAP UNPLUGGING:
23 *
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.
27 *
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.
44 */
45
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>
59
60#include "md.h"
61#include "raid5.h"
62#include "raid0.h"
63#include "bitmap.h"
64
65#define cpu_to_group(cpu) cpu_to_node(cpu)
66#define ANY_GROUP NUMA_NO_NODE
67
68static bool devices_handle_discard_safely = false;
69module_param(devices_handle_discard_safely, bool, 0644);
70MODULE_PARM_DESC(devices_handle_discard_safely,
71 "Set to Y if all devices in each array reliably return zeroes on reads from discarded regions");
72static struct workqueue_struct *raid5_wq;
73/*
74 * Stripe cache
75 */
76
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
86
87static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
88{
89 int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
90 return &conf->stripe_hashtbl[hash];
91}
92
93static inline int stripe_hash_locks_hash(sector_t sect)
94{
95 return (sect >> STRIPE_SHIFT) & STRIPE_HASH_LOCKS_MASK;
96}
97
98static inline void lock_device_hash_lock(struct r5conf *conf, int hash)
99{
100 spin_lock_irq(conf->hash_locks + hash);
101 spin_lock(&conf->device_lock);
102}
103
104static inline void unlock_device_hash_lock(struct r5conf *conf, int hash)
105{
106 spin_unlock(&conf->device_lock);
107 spin_unlock_irq(conf->hash_locks + hash);
108}
109
110static inline void lock_all_device_hash_locks_irq(struct r5conf *conf)
111{
112 int i;
113 local_irq_disable();
114 spin_lock(conf->hash_locks);
115 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
116 spin_lock_nest_lock(conf->hash_locks + i, conf->hash_locks);
117 spin_lock(&conf->device_lock);
118}
119
120static inline void unlock_all_device_hash_locks_irq(struct r5conf *conf)
121{
122 int i;
123 spin_unlock(&conf->device_lock);
124 for (i = NR_STRIPE_HASH_LOCKS; i; i--)
125 spin_unlock(conf->hash_locks + i - 1);
126 local_irq_enable();
127}
128
129/* bio's attached to a stripe+device for I/O are linked together in bi_sector
130 * order without overlap. There may be several bio's per stripe+device, and
131 * a bio could span several devices.
132 * When walking this list for a particular stripe+device, we must never proceed
133 * beyond a bio that extends past this device, as the next bio might no longer
134 * be valid.
135 * This function is used to determine the 'next' bio in the list, given the sector
136 * of the current stripe+device
137 */
138static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
139{
140 int sectors = bio_sectors(bio);
141 if (bio->bi_iter.bi_sector + sectors < sector + STRIPE_SECTORS)
142 return bio->bi_next;
143 else
144 return NULL;
145}
146
147/*
148 * We maintain a biased count of active stripes in the bottom 16 bits of
149 * bi_phys_segments, and a count of processed stripes in the upper 16 bits
150 */
151static inline int raid5_bi_processed_stripes(struct bio *bio)
152{
153 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
154 return (atomic_read(segments) >> 16) & 0xffff;
155}
156
157static inline int raid5_dec_bi_active_stripes(struct bio *bio)
158{
159 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
160 return atomic_sub_return(1, segments) & 0xffff;
161}
162
163static inline void raid5_inc_bi_active_stripes(struct bio *bio)
164{
165 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
166 atomic_inc(segments);
167}
168
169static inline void raid5_set_bi_processed_stripes(struct bio *bio,
170 unsigned int cnt)
171{
172 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
173 int old, new;
174
175 do {
176 old = atomic_read(segments);
177 new = (old & 0xffff) | (cnt << 16);
178 } while (atomic_cmpxchg(segments, old, new) != old);
179}
180
181static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
182{
183 atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
184 atomic_set(segments, cnt);
185}
186
187/* Find first data disk in a raid6 stripe */
188static inline int raid6_d0(struct stripe_head *sh)
189{
190 if (sh->ddf_layout)
191 /* ddf always start from first device */
192 return 0;
193 /* md starts just after Q block */
194 if (sh->qd_idx == sh->disks - 1)
195 return 0;
196 else
197 return sh->qd_idx + 1;
198}
199static inline int raid6_next_disk(int disk, int raid_disks)
200{
201 disk++;
202 return (disk < raid_disks) ? disk : 0;
203}
204
205/* When walking through the disks in a raid5, starting at raid6_d0,
206 * We need to map each disk to a 'slot', where the data disks are slot
207 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
208 * is raid_disks-1. This help does that mapping.
209 */
210static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
211 int *count, int syndrome_disks)
212{
213 int slot = *count;
214
215 if (sh->ddf_layout)
216 (*count)++;
217 if (idx == sh->pd_idx)
218 return syndrome_disks;
219 if (idx == sh->qd_idx)
220 return syndrome_disks + 1;
221 if (!sh->ddf_layout)
222 (*count)++;
223 return slot;
224}
225
226static void return_io(struct bio_list *return_bi)
227{
228 struct bio *bi;
229 while ((bi = bio_list_pop(return_bi)) != NULL) {
230 bi->bi_iter.bi_size = 0;
231 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
232 bi, 0);
233 bio_endio(bi);
234 }
235}
236
237static void print_raid5_conf (struct r5conf *conf);
238
239static int stripe_operations_active(struct stripe_head *sh)
240{
241 return sh->check_state || sh->reconstruct_state ||
242 test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
243 test_bit(STRIPE_COMPUTE_RUN, &sh->state);
244}
245
246static void raid5_wakeup_stripe_thread(struct stripe_head *sh)
247{
248 struct r5conf *conf = sh->raid_conf;
249 struct r5worker_group *group;
250 int thread_cnt;
251 int i, cpu = sh->cpu;
252
253 if (!cpu_online(cpu)) {
254 cpu = cpumask_any(cpu_online_mask);
255 sh->cpu = cpu;
256 }
257
258 if (list_empty(&sh->lru)) {
259 struct r5worker_group *group;
260 group = conf->worker_groups + cpu_to_group(cpu);
261 list_add_tail(&sh->lru, &group->handle_list);
262 group->stripes_cnt++;
263 sh->group = group;
264 }
265
266 if (conf->worker_cnt_per_group == 0) {
267 md_wakeup_thread(conf->mddev->thread);
268 return;
269 }
270
271 group = conf->worker_groups + cpu_to_group(sh->cpu);
272
273 group->workers[0].working = true;
274 /* at least one worker should run to avoid race */
275 queue_work_on(sh->cpu, raid5_wq, &group->workers[0].work);
276
277 thread_cnt = group->stripes_cnt / MAX_STRIPE_BATCH - 1;
278 /* wakeup more workers */
279 for (i = 1; i < conf->worker_cnt_per_group && thread_cnt > 0; i++) {
280 if (group->workers[i].working == false) {
281 group->workers[i].working = true;
282 queue_work_on(sh->cpu, raid5_wq,
283 &group->workers[i].work);
284 thread_cnt--;
285 }
286 }
287}
288
289static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh,
290 struct list_head *temp_inactive_list)
291{
292 BUG_ON(!list_empty(&sh->lru));
293 BUG_ON(atomic_read(&conf->active_stripes)==0);
294 if (test_bit(STRIPE_HANDLE, &sh->state)) {
295 if (test_bit(STRIPE_DELAYED, &sh->state) &&
296 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
297 list_add_tail(&sh->lru, &conf->delayed_list);
298 else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
299 sh->bm_seq - conf->seq_write > 0)
300 list_add_tail(&sh->lru, &conf->bitmap_list);
301 else {
302 clear_bit(STRIPE_DELAYED, &sh->state);
303 clear_bit(STRIPE_BIT_DELAY, &sh->state);
304 if (conf->worker_cnt_per_group == 0) {
305 list_add_tail(&sh->lru, &conf->handle_list);
306 } else {
307 raid5_wakeup_stripe_thread(sh);
308 return;
309 }
310 }
311 md_wakeup_thread(conf->mddev->thread);
312 } else {
313 BUG_ON(stripe_operations_active(sh));
314 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
315 if (atomic_dec_return(&conf->preread_active_stripes)
316 < IO_THRESHOLD)
317 md_wakeup_thread(conf->mddev->thread);
318 atomic_dec(&conf->active_stripes);
319 if (!test_bit(STRIPE_EXPANDING, &sh->state))
320 list_add_tail(&sh->lru, temp_inactive_list);
321 }
322}
323
324static void __release_stripe(struct r5conf *conf, struct stripe_head *sh,
325 struct list_head *temp_inactive_list)
326{
327 if (atomic_dec_and_test(&sh->count))
328 do_release_stripe(conf, sh, temp_inactive_list);
329}
330
331/*
332 * @hash could be NR_STRIPE_HASH_LOCKS, then we have a list of inactive_list
333 *
334 * Be careful: Only one task can add/delete stripes from temp_inactive_list at
335 * given time. Adding stripes only takes device lock, while deleting stripes
336 * only takes hash lock.
337 */
338static void release_inactive_stripe_list(struct r5conf *conf,
339 struct list_head *temp_inactive_list,
340 int hash)
341{
342 int size;
343 bool do_wakeup = false;
344 unsigned long flags;
345
346 if (hash == NR_STRIPE_HASH_LOCKS) {
347 size = NR_STRIPE_HASH_LOCKS;
348 hash = NR_STRIPE_HASH_LOCKS - 1;
349 } else
350 size = 1;
351 while (size) {
352 struct list_head *list = &temp_inactive_list[size - 1];
353
354 /*
355 * We don't hold any lock here yet, raid5_get_active_stripe() might
356 * remove stripes from the list
357 */
358 if (!list_empty_careful(list)) {
359 spin_lock_irqsave(conf->hash_locks + hash, flags);
360 if (list_empty(conf->inactive_list + hash) &&
361 !list_empty(list))
362 atomic_dec(&conf->empty_inactive_list_nr);
363 list_splice_tail_init(list, conf->inactive_list + hash);
364 do_wakeup = true;
365 spin_unlock_irqrestore(conf->hash_locks + hash, flags);
366 }
367 size--;
368 hash--;
369 }
370
371 if (do_wakeup) {
372 wake_up(&conf->wait_for_stripe);
373 if (atomic_read(&conf->active_stripes) == 0)
374 wake_up(&conf->wait_for_quiescent);
375 if (conf->retry_read_aligned)
376 md_wakeup_thread(conf->mddev->thread);
377 }
378}
379
380/* should hold conf->device_lock already */
381static int release_stripe_list(struct r5conf *conf,
382 struct list_head *temp_inactive_list)
383{
384 struct stripe_head *sh;
385 int count = 0;
386 struct llist_node *head;
387
388 head = llist_del_all(&conf->released_stripes);
389 head = llist_reverse_order(head);
390 while (head) {
391 int hash;
392
393 sh = llist_entry(head, struct stripe_head, release_list);
394 head = llist_next(head);
395 /* sh could be readded after STRIPE_ON_RELEASE_LIST is cleard */
396 smp_mb();
397 clear_bit(STRIPE_ON_RELEASE_LIST, &sh->state);
398 /*
399 * Don't worry the bit is set here, because if the bit is set
400 * again, the count is always > 1. This is true for
401 * STRIPE_ON_UNPLUG_LIST bit too.
402 */
403 hash = sh->hash_lock_index;
404 __release_stripe(conf, sh, &temp_inactive_list[hash]);
405 count++;
406 }
407
408 return count;
409}
410
411void raid5_release_stripe(struct stripe_head *sh)
412{
413 struct r5conf *conf = sh->raid_conf;
414 unsigned long flags;
415 struct list_head list;
416 int hash;
417 bool wakeup;
418
419 /* Avoid release_list until the last reference.
420 */
421 if (atomic_add_unless(&sh->count, -1, 1))
422 return;
423
424 if (unlikely(!conf->mddev->thread) ||
425 test_and_set_bit(STRIPE_ON_RELEASE_LIST, &sh->state))
426 goto slow_path;
427 wakeup = llist_add(&sh->release_list, &conf->released_stripes);
428 if (wakeup)
429 md_wakeup_thread(conf->mddev->thread);
430 return;
431slow_path:
432 local_irq_save(flags);
433 /* we are ok here if STRIPE_ON_RELEASE_LIST is set or not */
434 if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
435 INIT_LIST_HEAD(&list);
436 hash = sh->hash_lock_index;
437 do_release_stripe(conf, sh, &list);
438 spin_unlock(&conf->device_lock);
439 release_inactive_stripe_list(conf, &list, hash);
440 }
441 local_irq_restore(flags);
442}
443
444static inline void remove_hash(struct stripe_head *sh)
445{
446 pr_debug("remove_hash(), stripe %llu\n",
447 (unsigned long long)sh->sector);
448
449 hlist_del_init(&sh->hash);
450}
451
452static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
453{
454 struct hlist_head *hp = stripe_hash(conf, sh->sector);
455
456 pr_debug("insert_hash(), stripe %llu\n",
457 (unsigned long long)sh->sector);
458
459 hlist_add_head(&sh->hash, hp);
460}
461
462/* find an idle stripe, make sure it is unhashed, and return it. */
463static struct stripe_head *get_free_stripe(struct r5conf *conf, int hash)
464{
465 struct stripe_head *sh = NULL;
466 struct list_head *first;
467
468 if (list_empty(conf->inactive_list + hash))
469 goto out;
470 first = (conf->inactive_list + hash)->next;
471 sh = list_entry(first, struct stripe_head, lru);
472 list_del_init(first);
473 remove_hash(sh);
474 atomic_inc(&conf->active_stripes);
475 BUG_ON(hash != sh->hash_lock_index);
476 if (list_empty(conf->inactive_list + hash))
477 atomic_inc(&conf->empty_inactive_list_nr);
478out:
479 return sh;
480}
481
482static void shrink_buffers(struct stripe_head *sh)
483{
484 struct page *p;
485 int i;
486 int num = sh->raid_conf->pool_size;
487
488 for (i = 0; i < num ; i++) {
489 WARN_ON(sh->dev[i].page != sh->dev[i].orig_page);
490 p = sh->dev[i].page;
491 if (!p)
492 continue;
493 sh->dev[i].page = NULL;
494 put_page(p);
495 }
496}
497
498static int grow_buffers(struct stripe_head *sh, gfp_t gfp)
499{
500 int i;
501 int num = sh->raid_conf->pool_size;
502
503 for (i = 0; i < num; i++) {
504 struct page *page;
505
506 if (!(page = alloc_page(gfp))) {
507 return 1;
508 }
509 sh->dev[i].page = page;
510 sh->dev[i].orig_page = page;
511 }
512 return 0;
513}
514
515static void raid5_build_block(struct stripe_head *sh, int i, int previous);
516static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
517 struct stripe_head *sh);
518
519static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
520{
521 struct r5conf *conf = sh->raid_conf;
522 int i, seq;
523
524 BUG_ON(atomic_read(&sh->count) != 0);
525 BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
526 BUG_ON(stripe_operations_active(sh));
527 BUG_ON(sh->batch_head);
528
529 pr_debug("init_stripe called, stripe %llu\n",
530 (unsigned long long)sector);
531retry:
532 seq = read_seqcount_begin(&conf->gen_lock);
533 sh->generation = conf->generation - previous;
534 sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
535 sh->sector = sector;
536 stripe_set_idx(sector, conf, previous, sh);
537 sh->state = 0;
538
539 for (i = sh->disks; i--; ) {
540 struct r5dev *dev = &sh->dev[i];
541
542 if (dev->toread || dev->read || dev->towrite || dev->written ||
543 test_bit(R5_LOCKED, &dev->flags)) {
544 printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
545 (unsigned long long)sh->sector, i, dev->toread,
546 dev->read, dev->towrite, dev->written,
547 test_bit(R5_LOCKED, &dev->flags));
548 WARN_ON(1);
549 }
550 dev->flags = 0;
551 raid5_build_block(sh, i, previous);
552 }
553 if (read_seqcount_retry(&conf->gen_lock, seq))
554 goto retry;
555 sh->overwrite_disks = 0;
556 insert_hash(conf, sh);
557 sh->cpu = smp_processor_id();
558 set_bit(STRIPE_BATCH_READY, &sh->state);
559}
560
561static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
562 short generation)
563{
564 struct stripe_head *sh;
565
566 pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
567 hlist_for_each_entry(sh, stripe_hash(conf, sector), hash)
568 if (sh->sector == sector && sh->generation == generation)
569 return sh;
570 pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
571 return NULL;
572}
573
574/*
575 * Need to check if array has failed when deciding whether to:
576 * - start an array
577 * - remove non-faulty devices
578 * - add a spare
579 * - allow a reshape
580 * This determination is simple when no reshape is happening.
581 * However if there is a reshape, we need to carefully check
582 * both the before and after sections.
583 * This is because some failed devices may only affect one
584 * of the two sections, and some non-in_sync devices may
585 * be insync in the section most affected by failed devices.
586 */
587static int calc_degraded(struct r5conf *conf)
588{
589 int degraded, degraded2;
590 int i;
591
592 rcu_read_lock();
593 degraded = 0;
594 for (i = 0; i < conf->previous_raid_disks; i++) {
595 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
596 if (rdev && test_bit(Faulty, &rdev->flags))
597 rdev = rcu_dereference(conf->disks[i].replacement);
598 if (!rdev || test_bit(Faulty, &rdev->flags))
599 degraded++;
600 else if (test_bit(In_sync, &rdev->flags))
601 ;
602 else
603 /* not in-sync or faulty.
604 * If the reshape increases the number of devices,
605 * this is being recovered by the reshape, so
606 * this 'previous' section is not in_sync.
607 * If the number of devices is being reduced however,
608 * the device can only be part of the array if
609 * we are reverting a reshape, so this section will
610 * be in-sync.
611 */
612 if (conf->raid_disks >= conf->previous_raid_disks)
613 degraded++;
614 }
615 rcu_read_unlock();
616 if (conf->raid_disks == conf->previous_raid_disks)
617 return degraded;
618 rcu_read_lock();
619 degraded2 = 0;
620 for (i = 0; i < conf->raid_disks; i++) {
621 struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
622 if (rdev && test_bit(Faulty, &rdev->flags))
623 rdev = rcu_dereference(conf->disks[i].replacement);
624 if (!rdev || test_bit(Faulty, &rdev->flags))
625 degraded2++;
626 else if (test_bit(In_sync, &rdev->flags))
627 ;
628 else
629 /* not in-sync or faulty.
630 * If reshape increases the number of devices, this
631 * section has already been recovered, else it
632 * almost certainly hasn't.
633 */
634 if (conf->raid_disks <= conf->previous_raid_disks)
635 degraded2++;
636 }
637 rcu_read_unlock();
638 if (degraded2 > degraded)
639 return degraded2;
640 return degraded;
641}
642
643static int has_failed(struct r5conf *conf)
644{
645 int degraded;
646
647 if (conf->mddev->reshape_position == MaxSector)
648 return conf->mddev->degraded > conf->max_degraded;
649
650 degraded = calc_degraded(conf);
651 if (degraded > conf->max_degraded)
652 return 1;
653 return 0;
654}
655
656struct stripe_head *
657raid5_get_active_stripe(struct r5conf *conf, sector_t sector,
658 int previous, int noblock, int noquiesce)
659{
660 struct stripe_head *sh;
661 int hash = stripe_hash_locks_hash(sector);
662
663 pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
664
665 spin_lock_irq(conf->hash_locks + hash);
666
667 do {
668 wait_event_lock_irq(conf->wait_for_quiescent,
669 conf->quiesce == 0 || noquiesce,
670 *(conf->hash_locks + hash));
671 sh = __find_stripe(conf, sector, conf->generation - previous);
672 if (!sh) {
673 if (!test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state)) {
674 sh = get_free_stripe(conf, hash);
675 if (!sh && !test_bit(R5_DID_ALLOC,
676 &conf->cache_state))
677 set_bit(R5_ALLOC_MORE,
678 &conf->cache_state);
679 }
680 if (noblock && sh == NULL)
681 break;
682 if (!sh) {
683 set_bit(R5_INACTIVE_BLOCKED,
684 &conf->cache_state);
685 wait_event_lock_irq(
686 conf->wait_for_stripe,
687 !list_empty(conf->inactive_list + hash) &&
688 (atomic_read(&conf->active_stripes)
689 < (conf->max_nr_stripes * 3 / 4)
690 || !test_bit(R5_INACTIVE_BLOCKED,
691 &conf->cache_state)),
692 *(conf->hash_locks + hash));
693 clear_bit(R5_INACTIVE_BLOCKED,
694 &conf->cache_state);
695 } else {
696 init_stripe(sh, sector, previous);
697 atomic_inc(&sh->count);
698 }
699 } else if (!atomic_inc_not_zero(&sh->count)) {
700 spin_lock(&conf->device_lock);
701 if (!atomic_read(&sh->count)) {
702 if (!test_bit(STRIPE_HANDLE, &sh->state))
703 atomic_inc(&conf->active_stripes);
704 BUG_ON(list_empty(&sh->lru) &&
705 !test_bit(STRIPE_EXPANDING, &sh->state));
706 list_del_init(&sh->lru);
707 if (sh->group) {
708 sh->group->stripes_cnt--;
709 sh->group = NULL;
710 }
711 }
712 atomic_inc(&sh->count);
713 spin_unlock(&conf->device_lock);
714 }
715 } while (sh == NULL);
716
717 spin_unlock_irq(conf->hash_locks + hash);
718 return sh;
719}
720
721static bool is_full_stripe_write(struct stripe_head *sh)
722{
723 BUG_ON(sh->overwrite_disks > (sh->disks - sh->raid_conf->max_degraded));
724 return sh->overwrite_disks == (sh->disks - sh->raid_conf->max_degraded);
725}
726
727static void lock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
728{
729 local_irq_disable();
730 if (sh1 > sh2) {
731 spin_lock(&sh2->stripe_lock);
732 spin_lock_nested(&sh1->stripe_lock, 1);
733 } else {
734 spin_lock(&sh1->stripe_lock);
735 spin_lock_nested(&sh2->stripe_lock, 1);
736 }
737}
738
739static void unlock_two_stripes(struct stripe_head *sh1, struct stripe_head *sh2)
740{
741 spin_unlock(&sh1->stripe_lock);
742 spin_unlock(&sh2->stripe_lock);
743 local_irq_enable();
744}
745
746/* Only freshly new full stripe normal write stripe can be added to a batch list */
747static bool stripe_can_batch(struct stripe_head *sh)
748{
749 struct r5conf *conf = sh->raid_conf;
750
751 if (conf->log)
752 return false;
753 return test_bit(STRIPE_BATCH_READY, &sh->state) &&
754 !test_bit(STRIPE_BITMAP_PENDING, &sh->state) &&
755 is_full_stripe_write(sh);
756}
757
758/* we only do back search */
759static void stripe_add_to_batch_list(struct r5conf *conf, struct stripe_head *sh)
760{
761 struct stripe_head *head;
762 sector_t head_sector, tmp_sec;
763 int hash;
764 int dd_idx;
765
766 if (!stripe_can_batch(sh))
767 return;
768 /* Don't cross chunks, so stripe pd_idx/qd_idx is the same */
769 tmp_sec = sh->sector;
770 if (!sector_div(tmp_sec, conf->chunk_sectors))
771 return;
772 head_sector = sh->sector - STRIPE_SECTORS;
773
774 hash = stripe_hash_locks_hash(head_sector);
775 spin_lock_irq(conf->hash_locks + hash);
776 head = __find_stripe(conf, head_sector, conf->generation);
777 if (head && !atomic_inc_not_zero(&head->count)) {
778 spin_lock(&conf->device_lock);
779 if (!atomic_read(&head->count)) {
780 if (!test_bit(STRIPE_HANDLE, &head->state))
781 atomic_inc(&conf->active_stripes);
782 BUG_ON(list_empty(&head->lru) &&
783 !test_bit(STRIPE_EXPANDING, &head->state));
784 list_del_init(&head->lru);
785 if (head->group) {
786 head->group->stripes_cnt--;
787 head->group = NULL;
788 }
789 }
790 atomic_inc(&head->count);
791 spin_unlock(&conf->device_lock);
792 }
793 spin_unlock_irq(conf->hash_locks + hash);
794
795 if (!head)
796 return;
797 if (!stripe_can_batch(head))
798 goto out;
799
800 lock_two_stripes(head, sh);
801 /* clear_batch_ready clear the flag */
802 if (!stripe_can_batch(head) || !stripe_can_batch(sh))
803 goto unlock_out;
804
805 if (sh->batch_head)
806 goto unlock_out;
807
808 dd_idx = 0;
809 while (dd_idx == sh->pd_idx || dd_idx == sh->qd_idx)
810 dd_idx++;
811 if (head->dev[dd_idx].towrite->bi_rw != sh->dev[dd_idx].towrite->bi_rw)
812 goto unlock_out;
813
814 if (head->batch_head) {
815 spin_lock(&head->batch_head->batch_lock);
816 /* This batch list is already running */
817 if (!stripe_can_batch(head)) {
818 spin_unlock(&head->batch_head->batch_lock);
819 goto unlock_out;
820 }
821 /*
822 * We must assign batch_head of this stripe within the
823 * batch_lock, otherwise clear_batch_ready of batch head
824 * stripe could clear BATCH_READY bit of this stripe and
825 * this stripe->batch_head doesn't get assigned, which
826 * could confuse clear_batch_ready for this stripe
827 */
828 sh->batch_head = head->batch_head;
829
830 /*
831 * at this point, head's BATCH_READY could be cleared, but we
832 * can still add the stripe to batch list
833 */
834 list_add(&sh->batch_list, &head->batch_list);
835 spin_unlock(&head->batch_head->batch_lock);
836 } else {
837 head->batch_head = head;
838 sh->batch_head = head->batch_head;
839 spin_lock(&head->batch_lock);
840 list_add_tail(&sh->batch_list, &head->batch_list);
841 spin_unlock(&head->batch_lock);
842 }
843
844 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
845 if (atomic_dec_return(&conf->preread_active_stripes)
846 < IO_THRESHOLD)
847 md_wakeup_thread(conf->mddev->thread);
848
849 if (test_and_clear_bit(STRIPE_BIT_DELAY, &sh->state)) {
850 int seq = sh->bm_seq;
851 if (test_bit(STRIPE_BIT_DELAY, &sh->batch_head->state) &&
852 sh->batch_head->bm_seq > seq)
853 seq = sh->batch_head->bm_seq;
854 set_bit(STRIPE_BIT_DELAY, &sh->batch_head->state);
855 sh->batch_head->bm_seq = seq;
856 }
857
858 atomic_inc(&sh->count);
859unlock_out:
860 unlock_two_stripes(head, sh);
861out:
862 raid5_release_stripe(head);
863}
864
865/* Determine if 'data_offset' or 'new_data_offset' should be used
866 * in this stripe_head.
867 */
868static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
869{
870 sector_t progress = conf->reshape_progress;
871 /* Need a memory barrier to make sure we see the value
872 * of conf->generation, or ->data_offset that was set before
873 * reshape_progress was updated.
874 */
875 smp_rmb();
876 if (progress == MaxSector)
877 return 0;
878 if (sh->generation == conf->generation - 1)
879 return 0;
880 /* We are in a reshape, and this is a new-generation stripe,
881 * so use new_data_offset.
882 */
883 return 1;
884}
885
886static void
887raid5_end_read_request(struct bio *bi);
888static void
889raid5_end_write_request(struct bio *bi);
890
891static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
892{
893 struct r5conf *conf = sh->raid_conf;
894 int i, disks = sh->disks;
895 struct stripe_head *head_sh = sh;
896
897 might_sleep();
898
899 if (r5l_write_stripe(conf->log, sh) == 0)
900 return;
901 for (i = disks; i--; ) {
902 int rw;
903 int replace_only = 0;
904 struct bio *bi, *rbi;
905 struct md_rdev *rdev, *rrdev = NULL;
906
907 sh = head_sh;
908 if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
909 if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
910 rw = WRITE_FUA;
911 else
912 rw = WRITE;
913 if (test_bit(R5_Discard, &sh->dev[i].flags))
914 rw |= REQ_DISCARD;
915 } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
916 rw = READ;
917 else if (test_and_clear_bit(R5_WantReplace,
918 &sh->dev[i].flags)) {
919 rw = WRITE;
920 replace_only = 1;
921 } else
922 continue;
923 if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
924 rw |= REQ_SYNC;
925
926again:
927 bi = &sh->dev[i].req;
928 rbi = &sh->dev[i].rreq; /* For writing to replacement */
929
930 rcu_read_lock();
931 rrdev = rcu_dereference(conf->disks[i].replacement);
932 smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
933 rdev = rcu_dereference(conf->disks[i].rdev);
934 if (!rdev) {
935 rdev = rrdev;
936 rrdev = NULL;
937 }
938 if (rw & WRITE) {
939 if (replace_only)
940 rdev = NULL;
941 if (rdev == rrdev)
942 /* We raced and saw duplicates */
943 rrdev = NULL;
944 } else {
945 if (test_bit(R5_ReadRepl, &head_sh->dev[i].flags) && rrdev)
946 rdev = rrdev;
947 rrdev = NULL;
948 }
949
950 if (rdev && test_bit(Faulty, &rdev->flags))
951 rdev = NULL;
952 if (rdev)
953 atomic_inc(&rdev->nr_pending);
954 if (rrdev && test_bit(Faulty, &rrdev->flags))
955 rrdev = NULL;
956 if (rrdev)
957 atomic_inc(&rrdev->nr_pending);
958 rcu_read_unlock();
959
960 /* We have already checked bad blocks for reads. Now
961 * need to check for writes. We never accept write errors
962 * on the replacement, so we don't to check rrdev.
963 */
964 while ((rw & WRITE) && rdev &&
965 test_bit(WriteErrorSeen, &rdev->flags)) {
966 sector_t first_bad;
967 int bad_sectors;
968 int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
969 &first_bad, &bad_sectors);
970 if (!bad)
971 break;
972
973 if (bad < 0) {
974 set_bit(BlockedBadBlocks, &rdev->flags);
975 if (!conf->mddev->external &&
976 conf->mddev->flags) {
977 /* It is very unlikely, but we might
978 * still need to write out the
979 * bad block log - better give it
980 * a chance*/
981 md_check_recovery(conf->mddev);
982 }
983 /*
984 * Because md_wait_for_blocked_rdev
985 * will dec nr_pending, we must
986 * increment it first.
987 */
988 atomic_inc(&rdev->nr_pending);
989 md_wait_for_blocked_rdev(rdev, conf->mddev);
990 } else {
991 /* Acknowledged bad block - skip the write */
992 rdev_dec_pending(rdev, conf->mddev);
993 rdev = NULL;
994 }
995 }
996
997 if (rdev) {
998 if (s->syncing || s->expanding || s->expanded
999 || s->replacing)
1000 md_sync_acct(rdev->bdev, STRIPE_SECTORS);
1001
1002 set_bit(STRIPE_IO_STARTED, &sh->state);
1003
1004 bio_reset(bi);
1005 bi->bi_bdev = rdev->bdev;
1006 bi->bi_rw = rw;
1007 bi->bi_end_io = (rw & WRITE)
1008 ? raid5_end_write_request
1009 : raid5_end_read_request;
1010 bi->bi_private = sh;
1011
1012 pr_debug("%s: for %llu schedule op %ld on disc %d\n",
1013 __func__, (unsigned long long)sh->sector,
1014 bi->bi_rw, i);
1015 atomic_inc(&sh->count);
1016 if (sh != head_sh)
1017 atomic_inc(&head_sh->count);
1018 if (use_new_offset(conf, sh))
1019 bi->bi_iter.bi_sector = (sh->sector
1020 + rdev->new_data_offset);
1021 else
1022 bi->bi_iter.bi_sector = (sh->sector
1023 + rdev->data_offset);
1024 if (test_bit(R5_ReadNoMerge, &head_sh->dev[i].flags))
1025 bi->bi_rw |= REQ_NOMERGE;
1026
1027 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1028 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1029 sh->dev[i].vec.bv_page = sh->dev[i].page;
1030 bi->bi_vcnt = 1;
1031 bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1032 bi->bi_io_vec[0].bv_offset = 0;
1033 bi->bi_iter.bi_size = STRIPE_SIZE;
1034 /*
1035 * If this is discard request, set bi_vcnt 0. We don't
1036 * want to confuse SCSI because SCSI will replace payload
1037 */
1038 if (rw & REQ_DISCARD)
1039 bi->bi_vcnt = 0;
1040 if (rrdev)
1041 set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
1042
1043 if (conf->mddev->gendisk)
1044 trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
1045 bi, disk_devt(conf->mddev->gendisk),
1046 sh->dev[i].sector);
1047 generic_make_request(bi);
1048 }
1049 if (rrdev) {
1050 if (s->syncing || s->expanding || s->expanded
1051 || s->replacing)
1052 md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
1053
1054 set_bit(STRIPE_IO_STARTED, &sh->state);
1055
1056 bio_reset(rbi);
1057 rbi->bi_bdev = rrdev->bdev;
1058 rbi->bi_rw = rw;
1059 BUG_ON(!(rw & WRITE));
1060 rbi->bi_end_io = raid5_end_write_request;
1061 rbi->bi_private = sh;
1062
1063 pr_debug("%s: for %llu schedule op %ld on "
1064 "replacement disc %d\n",
1065 __func__, (unsigned long long)sh->sector,
1066 rbi->bi_rw, i);
1067 atomic_inc(&sh->count);
1068 if (sh != head_sh)
1069 atomic_inc(&head_sh->count);
1070 if (use_new_offset(conf, sh))
1071 rbi->bi_iter.bi_sector = (sh->sector
1072 + rrdev->new_data_offset);
1073 else
1074 rbi->bi_iter.bi_sector = (sh->sector
1075 + rrdev->data_offset);
1076 if (test_bit(R5_SkipCopy, &sh->dev[i].flags))
1077 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
1078 sh->dev[i].rvec.bv_page = sh->dev[i].page;
1079 rbi->bi_vcnt = 1;
1080 rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
1081 rbi->bi_io_vec[0].bv_offset = 0;
1082 rbi->bi_iter.bi_size = STRIPE_SIZE;
1083 /*
1084 * If this is discard request, set bi_vcnt 0. We don't
1085 * want to confuse SCSI because SCSI will replace payload
1086 */
1087 if (rw & REQ_DISCARD)
1088 rbi->bi_vcnt = 0;
1089 if (conf->mddev->gendisk)
1090 trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
1091 rbi, disk_devt(conf->mddev->gendisk),
1092 sh->dev[i].sector);
1093 generic_make_request(rbi);
1094 }
1095 if (!rdev && !rrdev) {
1096 if (rw & WRITE)
1097 set_bit(STRIPE_DEGRADED, &sh->state);
1098 pr_debug("skip op %ld on disc %d for sector %llu\n",
1099 bi->bi_rw, i, (unsigned long long)sh->sector);
1100 clear_bit(R5_LOCKED, &sh->dev[i].flags);
1101 set_bit(STRIPE_HANDLE, &sh->state);
1102 }
1103
1104 if (!head_sh->batch_head)
1105 continue;
1106 sh = list_first_entry(&sh->batch_list, struct stripe_head,
1107 batch_list);
1108 if (sh != head_sh)
1109 goto again;
1110 }
1111}
1112
1113static struct dma_async_tx_descriptor *
1114async_copy_data(int frombio, struct bio *bio, struct page **page,
1115 sector_t sector, struct dma_async_tx_descriptor *tx,
1116 struct stripe_head *sh)
1117{
1118 struct bio_vec bvl;
1119 struct bvec_iter iter;
1120 struct page *bio_page;
1121 int page_offset;
1122 struct async_submit_ctl submit;
1123 enum async_tx_flags flags = 0;
1124
1125 if (bio->bi_iter.bi_sector >= sector)
1126 page_offset = (signed)(bio->bi_iter.bi_sector - sector) * 512;
1127 else
1128 page_offset = (signed)(sector - bio->bi_iter.bi_sector) * -512;
1129
1130 if (frombio)
1131 flags |= ASYNC_TX_FENCE;
1132 init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
1133
1134 bio_for_each_segment(bvl, bio, iter) {
1135 int len = bvl.bv_len;
1136 int clen;
1137 int b_offset = 0;
1138
1139 if (page_offset < 0) {
1140 b_offset = -page_offset;
1141 page_offset += b_offset;
1142 len -= b_offset;
1143 }
1144
1145 if (len > 0 && page_offset + len > STRIPE_SIZE)
1146 clen = STRIPE_SIZE - page_offset;
1147 else
1148 clen = len;
1149
1150 if (clen > 0) {
1151 b_offset += bvl.bv_offset;
1152 bio_page = bvl.bv_page;
1153 if (frombio) {
1154 if (sh->raid_conf->skip_copy &&
1155 b_offset == 0 && page_offset == 0 &&
1156 clen == STRIPE_SIZE)
1157 *page = bio_page;
1158 else
1159 tx = async_memcpy(*page, bio_page, page_offset,
1160 b_offset, clen, &submit);
1161 } else
1162 tx = async_memcpy(bio_page, *page, b_offset,
1163 page_offset, clen, &submit);
1164 }
1165 /* chain the operations */
1166 submit.depend_tx = tx;
1167
1168 if (clen < len) /* hit end of page */
1169 break;
1170 page_offset += len;
1171 }
1172
1173 return tx;
1174}
1175
1176static void ops_complete_biofill(void *stripe_head_ref)
1177{
1178 struct stripe_head *sh = stripe_head_ref;
1179 struct bio_list return_bi = BIO_EMPTY_LIST;
1180 int i;
1181
1182 pr_debug("%s: stripe %llu\n", __func__,
1183 (unsigned long long)sh->sector);
1184
1185 /* clear completed biofills */
1186 for (i = sh->disks; i--; ) {
1187 struct r5dev *dev = &sh->dev[i];
1188
1189 /* acknowledge completion of a biofill operation */
1190 /* and check if we need to reply to a read request,
1191 * new R5_Wantfill requests are held off until
1192 * !STRIPE_BIOFILL_RUN
1193 */
1194 if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
1195 struct bio *rbi, *rbi2;
1196
1197 BUG_ON(!dev->read);
1198 rbi = dev->read;
1199 dev->read = NULL;
1200 while (rbi && rbi->bi_iter.bi_sector <
1201 dev->sector + STRIPE_SECTORS) {
1202 rbi2 = r5_next_bio(rbi, dev->sector);
1203 if (!raid5_dec_bi_active_stripes(rbi))
1204 bio_list_add(&return_bi, rbi);
1205 rbi = rbi2;
1206 }
1207 }
1208 }
1209 clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
1210
1211 return_io(&return_bi);
1212
1213 set_bit(STRIPE_HANDLE, &sh->state);
1214 raid5_release_stripe(sh);
1215}
1216
1217static void ops_run_biofill(struct stripe_head *sh)
1218{
1219 struct dma_async_tx_descriptor *tx = NULL;
1220 struct async_submit_ctl submit;
1221 int i;
1222
1223 BUG_ON(sh->batch_head);
1224 pr_debug("%s: stripe %llu\n", __func__,
1225 (unsigned long long)sh->sector);
1226
1227 for (i = sh->disks; i--; ) {
1228 struct r5dev *dev = &sh->dev[i];
1229 if (test_bit(R5_Wantfill, &dev->flags)) {
1230 struct bio *rbi;
1231 spin_lock_irq(&sh->stripe_lock);
1232 dev->read = rbi = dev->toread;
1233 dev->toread = NULL;
1234 spin_unlock_irq(&sh->stripe_lock);
1235 while (rbi && rbi->bi_iter.bi_sector <
1236 dev->sector + STRIPE_SECTORS) {
1237 tx = async_copy_data(0, rbi, &dev->page,
1238 dev->sector, tx, sh);
1239 rbi = r5_next_bio(rbi, dev->sector);
1240 }
1241 }
1242 }
1243
1244 atomic_inc(&sh->count);
1245 init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
1246 async_trigger_callback(&submit);
1247}
1248
1249static void mark_target_uptodate(struct stripe_head *sh, int target)
1250{
1251 struct r5dev *tgt;
1252
1253 if (target < 0)
1254 return;
1255
1256 tgt = &sh->dev[target];
1257 set_bit(R5_UPTODATE, &tgt->flags);
1258 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1259 clear_bit(R5_Wantcompute, &tgt->flags);
1260}
1261
1262static void ops_complete_compute(void *stripe_head_ref)
1263{
1264 struct stripe_head *sh = stripe_head_ref;
1265
1266 pr_debug("%s: stripe %llu\n", __func__,
1267 (unsigned long long)sh->sector);
1268
1269 /* mark the computed target(s) as uptodate */
1270 mark_target_uptodate(sh, sh->ops.target);
1271 mark_target_uptodate(sh, sh->ops.target2);
1272
1273 clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
1274 if (sh->check_state == check_state_compute_run)
1275 sh->check_state = check_state_compute_result;
1276 set_bit(STRIPE_HANDLE, &sh->state);
1277 raid5_release_stripe(sh);
1278}
1279
1280/* return a pointer to the address conversion region of the scribble buffer */
1281static addr_conv_t *to_addr_conv(struct stripe_head *sh,
1282 struct raid5_percpu *percpu, int i)
1283{
1284 void *addr;
1285
1286 addr = flex_array_get(percpu->scribble, i);
1287 return addr + sizeof(struct page *) * (sh->disks + 2);
1288}
1289
1290/* return a pointer to the address conversion region of the scribble buffer */
1291static struct page **to_addr_page(struct raid5_percpu *percpu, int i)
1292{
1293 void *addr;
1294
1295 addr = flex_array_get(percpu->scribble, i);
1296 return addr;
1297}
1298
1299static struct dma_async_tx_descriptor *
1300ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
1301{
1302 int disks = sh->disks;
1303 struct page **xor_srcs = to_addr_page(percpu, 0);
1304 int target = sh->ops.target;
1305 struct r5dev *tgt = &sh->dev[target];
1306 struct page *xor_dest = tgt->page;
1307 int count = 0;
1308 struct dma_async_tx_descriptor *tx;
1309 struct async_submit_ctl submit;
1310 int i;
1311
1312 BUG_ON(sh->batch_head);
1313
1314 pr_debug("%s: stripe %llu block: %d\n",
1315 __func__, (unsigned long long)sh->sector, target);
1316 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1317
1318 for (i = disks; i--; )
1319 if (i != target)
1320 xor_srcs[count++] = sh->dev[i].page;
1321
1322 atomic_inc(&sh->count);
1323
1324 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
1325 ops_complete_compute, sh, to_addr_conv(sh, percpu, 0));
1326 if (unlikely(count == 1))
1327 tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1328 else
1329 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1330
1331 return tx;
1332}
1333
1334/* set_syndrome_sources - populate source buffers for gen_syndrome
1335 * @srcs - (struct page *) array of size sh->disks
1336 * @sh - stripe_head to parse
1337 *
1338 * Populates srcs in proper layout order for the stripe and returns the
1339 * 'count' of sources to be used in a call to async_gen_syndrome. The P
1340 * destination buffer is recorded in srcs[count] and the Q destination
1341 * is recorded in srcs[count+1]].
1342 */
1343static int set_syndrome_sources(struct page **srcs,
1344 struct stripe_head *sh,
1345 int srctype)
1346{
1347 int disks = sh->disks;
1348 int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
1349 int d0_idx = raid6_d0(sh);
1350 int count;
1351 int i;
1352
1353 for (i = 0; i < disks; i++)
1354 srcs[i] = NULL;
1355
1356 count = 0;
1357 i = d0_idx;
1358 do {
1359 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1360 struct r5dev *dev = &sh->dev[i];
1361
1362 if (i == sh->qd_idx || i == sh->pd_idx ||
1363 (srctype == SYNDROME_SRC_ALL) ||
1364 (srctype == SYNDROME_SRC_WANT_DRAIN &&
1365 test_bit(R5_Wantdrain, &dev->flags)) ||
1366 (srctype == SYNDROME_SRC_WRITTEN &&
1367 dev->written))
1368 srcs[slot] = sh->dev[i].page;
1369 i = raid6_next_disk(i, disks);
1370 } while (i != d0_idx);
1371
1372 return syndrome_disks;
1373}
1374
1375static struct dma_async_tx_descriptor *
1376ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
1377{
1378 int disks = sh->disks;
1379 struct page **blocks = to_addr_page(percpu, 0);
1380 int target;
1381 int qd_idx = sh->qd_idx;
1382 struct dma_async_tx_descriptor *tx;
1383 struct async_submit_ctl submit;
1384 struct r5dev *tgt;
1385 struct page *dest;
1386 int i;
1387 int count;
1388
1389 BUG_ON(sh->batch_head);
1390 if (sh->ops.target < 0)
1391 target = sh->ops.target2;
1392 else if (sh->ops.target2 < 0)
1393 target = sh->ops.target;
1394 else
1395 /* we should only have one valid target */
1396 BUG();
1397 BUG_ON(target < 0);
1398 pr_debug("%s: stripe %llu block: %d\n",
1399 __func__, (unsigned long long)sh->sector, target);
1400
1401 tgt = &sh->dev[target];
1402 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1403 dest = tgt->page;
1404
1405 atomic_inc(&sh->count);
1406
1407 if (target == qd_idx) {
1408 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1409 blocks[count] = NULL; /* regenerating p is not necessary */
1410 BUG_ON(blocks[count+1] != dest); /* q should already be set */
1411 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1412 ops_complete_compute, sh,
1413 to_addr_conv(sh, percpu, 0));
1414 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1415 } else {
1416 /* Compute any data- or p-drive using XOR */
1417 count = 0;
1418 for (i = disks; i-- ; ) {
1419 if (i == target || i == qd_idx)
1420 continue;
1421 blocks[count++] = sh->dev[i].page;
1422 }
1423
1424 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1425 NULL, ops_complete_compute, sh,
1426 to_addr_conv(sh, percpu, 0));
1427 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1428 }
1429
1430 return tx;
1431}
1432
1433static struct dma_async_tx_descriptor *
1434ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1435{
1436 int i, count, disks = sh->disks;
1437 int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1438 int d0_idx = raid6_d0(sh);
1439 int faila = -1, failb = -1;
1440 int target = sh->ops.target;
1441 int target2 = sh->ops.target2;
1442 struct r5dev *tgt = &sh->dev[target];
1443 struct r5dev *tgt2 = &sh->dev[target2];
1444 struct dma_async_tx_descriptor *tx;
1445 struct page **blocks = to_addr_page(percpu, 0);
1446 struct async_submit_ctl submit;
1447
1448 BUG_ON(sh->batch_head);
1449 pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1450 __func__, (unsigned long long)sh->sector, target, target2);
1451 BUG_ON(target < 0 || target2 < 0);
1452 BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1453 BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1454
1455 /* we need to open-code set_syndrome_sources to handle the
1456 * slot number conversion for 'faila' and 'failb'
1457 */
1458 for (i = 0; i < disks ; i++)
1459 blocks[i] = NULL;
1460 count = 0;
1461 i = d0_idx;
1462 do {
1463 int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1464
1465 blocks[slot] = sh->dev[i].page;
1466
1467 if (i == target)
1468 faila = slot;
1469 if (i == target2)
1470 failb = slot;
1471 i = raid6_next_disk(i, disks);
1472 } while (i != d0_idx);
1473
1474 BUG_ON(faila == failb);
1475 if (failb < faila)
1476 swap(faila, failb);
1477 pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1478 __func__, (unsigned long long)sh->sector, faila, failb);
1479
1480 atomic_inc(&sh->count);
1481
1482 if (failb == syndrome_disks+1) {
1483 /* Q disk is one of the missing disks */
1484 if (faila == syndrome_disks) {
1485 /* Missing P+Q, just recompute */
1486 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1487 ops_complete_compute, sh,
1488 to_addr_conv(sh, percpu, 0));
1489 return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1490 STRIPE_SIZE, &submit);
1491 } else {
1492 struct page *dest;
1493 int data_target;
1494 int qd_idx = sh->qd_idx;
1495
1496 /* Missing D+Q: recompute D from P, then recompute Q */
1497 if (target == qd_idx)
1498 data_target = target2;
1499 else
1500 data_target = target;
1501
1502 count = 0;
1503 for (i = disks; i-- ; ) {
1504 if (i == data_target || i == qd_idx)
1505 continue;
1506 blocks[count++] = sh->dev[i].page;
1507 }
1508 dest = sh->dev[data_target].page;
1509 init_async_submit(&submit,
1510 ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1511 NULL, NULL, NULL,
1512 to_addr_conv(sh, percpu, 0));
1513 tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1514 &submit);
1515
1516 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_ALL);
1517 init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1518 ops_complete_compute, sh,
1519 to_addr_conv(sh, percpu, 0));
1520 return async_gen_syndrome(blocks, 0, count+2,
1521 STRIPE_SIZE, &submit);
1522 }
1523 } else {
1524 init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1525 ops_complete_compute, sh,
1526 to_addr_conv(sh, percpu, 0));
1527 if (failb == syndrome_disks) {
1528 /* We're missing D+P. */
1529 return async_raid6_datap_recov(syndrome_disks+2,
1530 STRIPE_SIZE, faila,
1531 blocks, &submit);
1532 } else {
1533 /* We're missing D+D. */
1534 return async_raid6_2data_recov(syndrome_disks+2,
1535 STRIPE_SIZE, faila, failb,
1536 blocks, &submit);
1537 }
1538 }
1539}
1540
1541static void ops_complete_prexor(void *stripe_head_ref)
1542{
1543 struct stripe_head *sh = stripe_head_ref;
1544
1545 pr_debug("%s: stripe %llu\n", __func__,
1546 (unsigned long long)sh->sector);
1547}
1548
1549static struct dma_async_tx_descriptor *
1550ops_run_prexor5(struct stripe_head *sh, struct raid5_percpu *percpu,
1551 struct dma_async_tx_descriptor *tx)
1552{
1553 int disks = sh->disks;
1554 struct page **xor_srcs = to_addr_page(percpu, 0);
1555 int count = 0, pd_idx = sh->pd_idx, i;
1556 struct async_submit_ctl submit;
1557
1558 /* existing parity data subtracted */
1559 struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1560
1561 BUG_ON(sh->batch_head);
1562 pr_debug("%s: stripe %llu\n", __func__,
1563 (unsigned long long)sh->sector);
1564
1565 for (i = disks; i--; ) {
1566 struct r5dev *dev = &sh->dev[i];
1567 /* Only process blocks that are known to be uptodate */
1568 if (test_bit(R5_Wantdrain, &dev->flags))
1569 xor_srcs[count++] = dev->page;
1570 }
1571
1572 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1573 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1574 tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1575
1576 return tx;
1577}
1578
1579static struct dma_async_tx_descriptor *
1580ops_run_prexor6(struct stripe_head *sh, struct raid5_percpu *percpu,
1581 struct dma_async_tx_descriptor *tx)
1582{
1583 struct page **blocks = to_addr_page(percpu, 0);
1584 int count;
1585 struct async_submit_ctl submit;
1586
1587 pr_debug("%s: stripe %llu\n", __func__,
1588 (unsigned long long)sh->sector);
1589
1590 count = set_syndrome_sources(blocks, sh, SYNDROME_SRC_WANT_DRAIN);
1591
1592 init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_PQ_XOR_DST, tx,
1593 ops_complete_prexor, sh, to_addr_conv(sh, percpu, 0));
1594 tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
1595
1596 return tx;
1597}
1598
1599static struct dma_async_tx_descriptor *
1600ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1601{
1602 int disks = sh->disks;
1603 int i;
1604 struct stripe_head *head_sh = sh;
1605
1606 pr_debug("%s: stripe %llu\n", __func__,
1607 (unsigned long long)sh->sector);
1608
1609 for (i = disks; i--; ) {
1610 struct r5dev *dev;
1611 struct bio *chosen;
1612
1613 sh = head_sh;
1614 if (test_and_clear_bit(R5_Wantdrain, &head_sh->dev[i].flags)) {
1615 struct bio *wbi;
1616
1617again:
1618 dev = &sh->dev[i];
1619 spin_lock_irq(&sh->stripe_lock);
1620 chosen = dev->towrite;
1621 dev->towrite = NULL;
1622 sh->overwrite_disks = 0;
1623 BUG_ON(dev->written);
1624 wbi = dev->written = chosen;
1625 spin_unlock_irq(&sh->stripe_lock);
1626 WARN_ON(dev->page != dev->orig_page);
1627
1628 while (wbi && wbi->bi_iter.bi_sector <
1629 dev->sector + STRIPE_SECTORS) {
1630 if (wbi->bi_rw & REQ_FUA)
1631 set_bit(R5_WantFUA, &dev->flags);
1632 if (wbi->bi_rw & REQ_SYNC)
1633 set_bit(R5_SyncIO, &dev->flags);
1634 if (wbi->bi_rw & REQ_DISCARD)
1635 set_bit(R5_Discard, &dev->flags);
1636 else {
1637 tx = async_copy_data(1, wbi, &dev->page,
1638 dev->sector, tx, sh);
1639 if (dev->page != dev->orig_page) {
1640 set_bit(R5_SkipCopy, &dev->flags);
1641 clear_bit(R5_UPTODATE, &dev->flags);
1642 clear_bit(R5_OVERWRITE, &dev->flags);
1643 }
1644 }
1645 wbi = r5_next_bio(wbi, dev->sector);
1646 }
1647
1648 if (head_sh->batch_head) {
1649 sh = list_first_entry(&sh->batch_list,
1650 struct stripe_head,
1651 batch_list);
1652 if (sh == head_sh)
1653 continue;
1654 goto again;
1655 }
1656 }
1657 }
1658
1659 return tx;
1660}
1661
1662static void ops_complete_reconstruct(void *stripe_head_ref)
1663{
1664 struct stripe_head *sh = stripe_head_ref;
1665 int disks = sh->disks;
1666 int pd_idx = sh->pd_idx;
1667 int qd_idx = sh->qd_idx;
1668 int i;
1669 bool fua = false, sync = false, discard = false;
1670
1671 pr_debug("%s: stripe %llu\n", __func__,
1672 (unsigned long long)sh->sector);
1673
1674 for (i = disks; i--; ) {
1675 fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1676 sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1677 discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1678 }
1679
1680 for (i = disks; i--; ) {
1681 struct r5dev *dev = &sh->dev[i];
1682
1683 if (dev->written || i == pd_idx || i == qd_idx) {
1684 if (!discard && !test_bit(R5_SkipCopy, &dev->flags))
1685 set_bit(R5_UPTODATE, &dev->flags);
1686 if (fua)
1687 set_bit(R5_WantFUA, &dev->flags);
1688 if (sync)
1689 set_bit(R5_SyncIO, &dev->flags);
1690 }
1691 }
1692
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;
1700 }
1701
1702 set_bit(STRIPE_HANDLE, &sh->state);
1703 raid5_release_stripe(sh);
1704}
1705
1706static void
1707ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1708 struct dma_async_tx_descriptor *tx)
1709{
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;
1720
1721 pr_debug("%s: stripe %llu\n", __func__,
1722 (unsigned long long)sh->sector);
1723
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;
1729 }
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;
1735 }
1736again:
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)
1741 */
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;
1749 }
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;
1756 }
1757 }
1758
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
1763 */
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);
1770
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));
1778 }
1779
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;
1789 }
1790}
1791
1792static void
1793ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1794 struct dma_async_tx_descriptor *tx)
1795{
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;
1803
1804 pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1805
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;
1811 }
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;
1818 }
1819
1820again:
1821 blocks = to_addr_page(percpu, j);
1822
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;
1829 }
1830
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;
1835
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;
1849 }
1850}
1851
1852static void ops_complete_check(void *stripe_head_ref)
1853{
1854 struct stripe_head *sh = stripe_head_ref;
1855
1856 pr_debug("%s: stripe %llu\n", __func__,
1857 (unsigned long long)sh->sector);
1858
1859 sh->check_state = check_state_check_result;
1860 set_bit(STRIPE_HANDLE, &sh->state);
1861 raid5_release_stripe(sh);
1862}
1863
1864static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1865{
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;
1875
1876 pr_debug("%s: stripe %llu\n", __func__,
1877 (unsigned long long)sh->sector);
1878
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;
1887 }
1888
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);
1893
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);
1897}
1898
1899static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1900{
1901 struct page **srcs = to_addr_page(percpu, 0);
1902 struct async_submit_ctl submit;
1903 int count;
1904
1905 pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1906 (unsigned long long)sh->sector, checkp);
1907
1908 BUG_ON(sh->batch_head);
1909 count = set_syndrome_sources(srcs, sh, SYNDROME_SRC_ALL);
1910 if (!checkp)
1911 srcs[count] = NULL;
1912
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);
1918}
1919
1920static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1921{
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;
1928
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++;
1934 }
1935
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);
1944 }
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);
1948 }
1949
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);
1955 }
1956
1957 if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1958 tx = ops_run_biodrain(sh, tx);
1959 overlap_clear++;
1960 }
1961
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);
1967 }
1968
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();
1978 }
1979
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);
1985 }
1986 put_cpu();
1987}
1988
1989static struct stripe_head *alloc_stripe(struct kmem_cache *sc, gfp_t gfp)
1990{
1991 struct stripe_head *sh;
1992
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);
2000 }
2001 return sh;
2002}
2003static int grow_one_stripe(struct r5conf *conf, gfp_t gfp)
2004{
2005 struct stripe_head *sh;
2006
2007 sh = alloc_stripe(conf->slab_cache, gfp);
2008 if (!sh)
2009 return 0;
2010
2011 sh->raid_conf = conf;
2012
2013 if (grow_buffers(sh, gfp)) {
2014 shrink_buffers(sh);
2015 kmem_cache_free(conf->slab_cache, sh);
2016 return 0;
2017 }
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);
2022
2023 raid5_release_stripe(sh);
2024 conf->max_nr_stripes++;
2025 return 1;
2026}
2027
2028static int grow_stripes(struct r5conf *conf, int num)
2029{
2030 struct kmem_cache *sc;
2031 int devs = max(conf->raid_disks, conf->previous_raid_disks);
2032
2033 if (conf->mddev->gendisk)
2034 sprintf(conf->cache_name[0],
2035 "raid%d-%s", conf->level, mdname(conf->mddev));
2036 else
2037 sprintf(conf->cache_name[0],
2038 "raid%d-%p", conf->level, conf->mddev);
2039 sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
2040
2041 conf->active_name = 0;
2042 sc = kmem_cache_create(conf->cache_name[conf->active_name],
2043 sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
2044 0, 0, NULL);
2045 if (!sc)
2046 return 1;
2047 conf->slab_cache = sc;
2048 conf->pool_size = devs;
2049 while (num--)
2050 if (!grow_one_stripe(conf, GFP_KERNEL))
2051 return 1;
2052
2053 return 0;
2054}
2055
2056/**
2057 * scribble_len - return the required size of the scribble region
2058 * @num - total number of disks in the array
2059 *
2060 * The size must be enough to contain:
2061 * 1/ a struct page pointer for each device in the array +2
2062 * 2/ room to convert each entry in (1) to its corresponding dma
2063 * (dma_map_page()) or page (page_address()) address.
2064 *
2065 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
2066 * calculate over all devices (not just the data blocks), using zeros in place
2067 * of the P and Q blocks.
2068 */
2069static struct flex_array *scribble_alloc(int num, int cnt, gfp_t flags)
2070{
2071 struct flex_array *ret;
2072 size_t len;
2073
2074 len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
2075 ret = flex_array_alloc(len, cnt, flags);
2076 if (!ret)
2077 return NULL;
2078 /* always prealloc all elements, so no locking is required */
2079 if (flex_array_prealloc(ret, 0, cnt, flags)) {
2080 flex_array_free(ret);
2081 return NULL;
2082 }
2083 return ret;
2084}
2085
2086static int resize_chunks(struct r5conf *conf, int new_disks, int new_sectors)
2087{
2088 unsigned long cpu;
2089 int err = 0;
2090
2091 /*
2092 * Never shrink. And mddev_suspend() could deadlock if this is called
2093 * from raid5d. In that case, scribble_disks and scribble_sectors
2094 * should equal to new_disks and new_sectors
2095 */
2096 if (conf->scribble_disks >= new_disks &&
2097 conf->scribble_sectors >= new_sectors)
2098 return 0;
2099 mddev_suspend(conf->mddev);
2100 get_online_cpus();
2101 for_each_present_cpu(cpu) {
2102 struct raid5_percpu *percpu;
2103 struct flex_array *scribble;
2104
2105 percpu = per_cpu_ptr(conf->percpu, cpu);
2106 scribble = scribble_alloc(new_disks,
2107 new_sectors / STRIPE_SECTORS,
2108 GFP_NOIO);
2109
2110 if (scribble) {
2111 flex_array_free(percpu->scribble);
2112 percpu->scribble = scribble;
2113 } else {
2114 err = -ENOMEM;
2115 break;
2116 }
2117 }
2118 put_online_cpus();
2119 mddev_resume(conf->mddev);
2120 if (!err) {
2121 conf->scribble_disks = new_disks;
2122 conf->scribble_sectors = new_sectors;
2123 }
2124 return err;
2125}
2126
2127static int resize_stripes(struct r5conf *conf, int newsize)
2128{
2129 /* Make all the stripes able to hold 'newsize' devices.
2130 * New slots in each stripe get 'page' set to a new page.
2131 *
2132 * This happens in stages:
2133 * 1/ create a new kmem_cache and allocate the required number of
2134 * stripe_heads.
2135 * 2/ gather all the old stripe_heads and transfer the pages across
2136 * to the new stripe_heads. This will have the side effect of
2137 * freezing the array as once all stripe_heads have been collected,
2138 * no IO will be possible. Old stripe heads are freed once their
2139 * pages have been transferred over, and the old kmem_cache is
2140 * freed when all stripes are done.
2141 * 3/ reallocate conf->disks to be suitable bigger. If this fails,
2142 * we simple return a failre status - no need to clean anything up.
2143 * 4/ allocate new pages for the new slots in the new stripe_heads.
2144 * If this fails, we don't bother trying the shrink the
2145 * stripe_heads down again, we just leave them as they are.
2146 * As each stripe_head is processed the new one is released into
2147 * active service.
2148 *
2149 * Once step2 is started, we cannot afford to wait for a write,
2150 * so we use GFP_NOIO allocations.
2151 */
2152 struct stripe_head *osh, *nsh;
2153 LIST_HEAD(newstripes);
2154 struct disk_info *ndisks;
2155 int err;
2156 struct kmem_cache *sc;
2157 int i;
2158 int hash, cnt;
2159
2160 if (newsize <= conf->pool_size)
2161 return 0; /* never bother to shrink */
2162
2163 err = md_allow_write(conf->mddev);
2164 if (err)
2165 return err;
2166
2167 /* Step 1 */
2168 sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
2169 sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
2170 0, 0, NULL);
2171 if (!sc)
2172 return -ENOMEM;
2173
2174 /* Need to ensure auto-resizing doesn't interfere */
2175 mutex_lock(&conf->cache_size_mutex);
2176
2177 for (i = conf->max_nr_stripes; i; i--) {
2178 nsh = alloc_stripe(sc, GFP_KERNEL);
2179 if (!nsh)
2180 break;
2181
2182 nsh->raid_conf = conf;
2183 list_add(&nsh->lru, &newstripes);
2184 }
2185 if (i) {
2186 /* didn't get enough, give up */
2187 while (!list_empty(&newstripes)) {
2188 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2189 list_del(&nsh->lru);
2190 kmem_cache_free(sc, nsh);
2191 }
2192 kmem_cache_destroy(sc);
2193 mutex_unlock(&conf->cache_size_mutex);
2194 return -ENOMEM;
2195 }
2196 /* Step 2 - Must use GFP_NOIO now.
2197 * OK, we have enough stripes, start collecting inactive
2198 * stripes and copying them over
2199 */
2200 hash = 0;
2201 cnt = 0;
2202 list_for_each_entry(nsh, &newstripes, lru) {
2203 lock_device_hash_lock(conf, hash);
2204 wait_event_cmd(conf->wait_for_stripe,
2205 !list_empty(conf->inactive_list + hash),
2206 unlock_device_hash_lock(conf, hash),
2207 lock_device_hash_lock(conf, hash));
2208 osh = get_free_stripe(conf, hash);
2209 unlock_device_hash_lock(conf, hash);
2210
2211 for(i=0; i<conf->pool_size; i++) {
2212 nsh->dev[i].page = osh->dev[i].page;
2213 nsh->dev[i].orig_page = osh->dev[i].page;
2214 }
2215 nsh->hash_lock_index = hash;
2216 kmem_cache_free(conf->slab_cache, osh);
2217 cnt++;
2218 if (cnt >= conf->max_nr_stripes / NR_STRIPE_HASH_LOCKS +
2219 !!((conf->max_nr_stripes % NR_STRIPE_HASH_LOCKS) > hash)) {
2220 hash++;
2221 cnt = 0;
2222 }
2223 }
2224 kmem_cache_destroy(conf->slab_cache);
2225
2226 /* Step 3.
2227 * At this point, we are holding all the stripes so the array
2228 * is completely stalled, so now is a good time to resize
2229 * conf->disks and the scribble region
2230 */
2231 ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
2232 if (ndisks) {
2233 for (i=0; i<conf->raid_disks; i++)
2234 ndisks[i] = conf->disks[i];
2235 kfree(conf->disks);
2236 conf->disks = ndisks;
2237 } else
2238 err = -ENOMEM;
2239
2240 mutex_unlock(&conf->cache_size_mutex);
2241
2242 conf->slab_cache = sc;
2243 conf->active_name = 1-conf->active_name;
2244
2245 /* Step 4, return new stripes to service */
2246 while(!list_empty(&newstripes)) {
2247 nsh = list_entry(newstripes.next, struct stripe_head, lru);
2248 list_del_init(&nsh->lru);
2249
2250 for (i=conf->raid_disks; i < newsize; i++)
2251 if (nsh->dev[i].page == NULL) {
2252 struct page *p = alloc_page(GFP_NOIO);
2253 nsh->dev[i].page = p;
2254 nsh->dev[i].orig_page = p;
2255 if (!p)
2256 err = -ENOMEM;
2257 }
2258 raid5_release_stripe(nsh);
2259 }
2260 /* critical section pass, GFP_NOIO no longer needed */
2261
2262 if (!err)
2263 conf->pool_size = newsize;
2264 return err;
2265}
2266
2267static int drop_one_stripe(struct r5conf *conf)
2268{
2269 struct stripe_head *sh;
2270 int hash = (conf->max_nr_stripes - 1) & STRIPE_HASH_LOCKS_MASK;
2271
2272 spin_lock_irq(conf->hash_locks + hash);
2273 sh = get_free_stripe(conf, hash);
2274 spin_unlock_irq(conf->hash_locks + hash);
2275 if (!sh)
2276 return 0;
2277 BUG_ON(atomic_read(&sh->count));
2278 shrink_buffers(sh);
2279 kmem_cache_free(conf->slab_cache, sh);
2280 atomic_dec(&conf->active_stripes);
2281 conf->max_nr_stripes--;
2282 return 1;
2283}
2284
2285static void shrink_stripes(struct r5conf *conf)
2286{
2287 while (conf->max_nr_stripes &&
2288 drop_one_stripe(conf))
2289 ;
2290
2291 kmem_cache_destroy(conf->slab_cache);
2292 conf->slab_cache = NULL;
2293}
2294
2295static void raid5_end_read_request(struct bio * bi)
2296{
2297 struct stripe_head *sh = bi->bi_private;
2298 struct r5conf *conf = sh->raid_conf;
2299 int disks = sh->disks, i;
2300 char b[BDEVNAME_SIZE];
2301 struct md_rdev *rdev = NULL;
2302 sector_t s;
2303
2304 for (i=0 ; i<disks; i++)
2305 if (bi == &sh->dev[i].req)
2306 break;
2307
2308 pr_debug("end_read_request %llu/%d, count: %d, error %d.\n",
2309 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2310 bi->bi_error);
2311 if (i == disks) {
2312 BUG();
2313 return;
2314 }
2315 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2316 /* If replacement finished while this request was outstanding,
2317 * 'replacement' might be NULL already.
2318 * In that case it moved down to 'rdev'.
2319 * rdev is not removed until all requests are finished.
2320 */
2321 rdev = conf->disks[i].replacement;
2322 if (!rdev)
2323 rdev = conf->disks[i].rdev;
2324
2325 if (use_new_offset(conf, sh))
2326 s = sh->sector + rdev->new_data_offset;
2327 else
2328 s = sh->sector + rdev->data_offset;
2329 if (!bi->bi_error) {
2330 set_bit(R5_UPTODATE, &sh->dev[i].flags);
2331 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2332 /* Note that this cannot happen on a
2333 * replacement device. We just fail those on
2334 * any error
2335 */
2336 printk_ratelimited(
2337 KERN_INFO
2338 "md/raid:%s: read error corrected"
2339 " (%lu sectors at %llu on %s)\n",
2340 mdname(conf->mddev), STRIPE_SECTORS,
2341 (unsigned long long)s,
2342 bdevname(rdev->bdev, b));
2343 atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
2344 clear_bit(R5_ReadError, &sh->dev[i].flags);
2345 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2346 } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2347 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2348
2349 if (atomic_read(&rdev->read_errors))
2350 atomic_set(&rdev->read_errors, 0);
2351 } else {
2352 const char *bdn = bdevname(rdev->bdev, b);
2353 int retry = 0;
2354 int set_bad = 0;
2355
2356 clear_bit(R5_UPTODATE, &sh->dev[i].flags);
2357 atomic_inc(&rdev->read_errors);
2358 if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
2359 printk_ratelimited(
2360 KERN_WARNING
2361 "md/raid:%s: read error on replacement device "
2362 "(sector %llu on %s).\n",
2363 mdname(conf->mddev),
2364 (unsigned long long)s,
2365 bdn);
2366 else if (conf->mddev->degraded >= conf->max_degraded) {
2367 set_bad = 1;
2368 printk_ratelimited(
2369 KERN_WARNING
2370 "md/raid:%s: read error not correctable "
2371 "(sector %llu on %s).\n",
2372 mdname(conf->mddev),
2373 (unsigned long long)s,
2374 bdn);
2375 } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
2376 /* Oh, no!!! */
2377 set_bad = 1;
2378 printk_ratelimited(
2379 KERN_WARNING
2380 "md/raid:%s: read error NOT corrected!! "
2381 "(sector %llu on %s).\n",
2382 mdname(conf->mddev),
2383 (unsigned long long)s,
2384 bdn);
2385 } else if (atomic_read(&rdev->read_errors)
2386 > conf->max_nr_stripes)
2387 printk(KERN_WARNING
2388 "md/raid:%s: Too many read errors, failing device %s.\n",
2389 mdname(conf->mddev), bdn);
2390 else
2391 retry = 1;
2392 if (set_bad && test_bit(In_sync, &rdev->flags)
2393 && !test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
2394 retry = 1;
2395 if (retry)
2396 if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
2397 set_bit(R5_ReadError, &sh->dev[i].flags);
2398 clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2399 } else
2400 set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
2401 else {
2402 clear_bit(R5_ReadError, &sh->dev[i].flags);
2403 clear_bit(R5_ReWrite, &sh->dev[i].flags);
2404 if (!(set_bad
2405 && test_bit(In_sync, &rdev->flags)
2406 && rdev_set_badblocks(
2407 rdev, sh->sector, STRIPE_SECTORS, 0)))
2408 md_error(conf->mddev, rdev);
2409 }
2410 }
2411 rdev_dec_pending(rdev, conf->mddev);
2412 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2413 set_bit(STRIPE_HANDLE, &sh->state);
2414 raid5_release_stripe(sh);
2415}
2416
2417static void raid5_end_write_request(struct bio *bi)
2418{
2419 struct stripe_head *sh = bi->bi_private;
2420 struct r5conf *conf = sh->raid_conf;
2421 int disks = sh->disks, i;
2422 struct md_rdev *uninitialized_var(rdev);
2423 sector_t first_bad;
2424 int bad_sectors;
2425 int replacement = 0;
2426
2427 for (i = 0 ; i < disks; i++) {
2428 if (bi == &sh->dev[i].req) {
2429 rdev = conf->disks[i].rdev;
2430 break;
2431 }
2432 if (bi == &sh->dev[i].rreq) {
2433 rdev = conf->disks[i].replacement;
2434 if (rdev)
2435 replacement = 1;
2436 else
2437 /* rdev was removed and 'replacement'
2438 * replaced it. rdev is not removed
2439 * until all requests are finished.
2440 */
2441 rdev = conf->disks[i].rdev;
2442 break;
2443 }
2444 }
2445 pr_debug("end_write_request %llu/%d, count %d, error: %d.\n",
2446 (unsigned long long)sh->sector, i, atomic_read(&sh->count),
2447 bi->bi_error);
2448 if (i == disks) {
2449 BUG();
2450 return;
2451 }
2452
2453 if (replacement) {
2454 if (bi->bi_error)
2455 md_error(conf->mddev, rdev);
2456 else if (is_badblock(rdev, sh->sector,
2457 STRIPE_SECTORS,
2458 &first_bad, &bad_sectors))
2459 set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
2460 } else {
2461 if (bi->bi_error) {
2462 set_bit(STRIPE_DEGRADED, &sh->state);
2463 set_bit(WriteErrorSeen, &rdev->flags);
2464 set_bit(R5_WriteError, &sh->dev[i].flags);
2465 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2466 set_bit(MD_RECOVERY_NEEDED,
2467 &rdev->mddev->recovery);
2468 } else if (is_badblock(rdev, sh->sector,
2469 STRIPE_SECTORS,
2470 &first_bad, &bad_sectors)) {
2471 set_bit(R5_MadeGood, &sh->dev[i].flags);
2472 if (test_bit(R5_ReadError, &sh->dev[i].flags))
2473 /* That was a successful write so make
2474 * sure it looks like we already did
2475 * a re-write.
2476 */
2477 set_bit(R5_ReWrite, &sh->dev[i].flags);
2478 }
2479 }
2480 rdev_dec_pending(rdev, conf->mddev);
2481
2482 if (sh->batch_head && bi->bi_error && !replacement)
2483 set_bit(STRIPE_BATCH_ERR, &sh->batch_head->state);
2484
2485 if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
2486 clear_bit(R5_LOCKED, &sh->dev[i].flags);
2487 set_bit(STRIPE_HANDLE, &sh->state);
2488 raid5_release_stripe(sh);
2489
2490 if (sh->batch_head && sh != sh->batch_head)
2491 raid5_release_stripe(sh->batch_head);
2492}
2493
2494static void raid5_build_block(struct stripe_head *sh, int i, int previous)
2495{
2496 struct r5dev *dev = &sh->dev[i];
2497
2498 bio_init(&dev->req);
2499 dev->req.bi_io_vec = &dev->vec;
2500 dev->req.bi_max_vecs = 1;
2501 dev->req.bi_private = sh;
2502
2503 bio_init(&dev->rreq);
2504 dev->rreq.bi_io_vec = &dev->rvec;
2505 dev->rreq.bi_max_vecs = 1;
2506 dev->rreq.bi_private = sh;
2507
2508 dev->flags = 0;
2509 dev->sector = raid5_compute_blocknr(sh, i, previous);
2510}
2511
2512static void error(struct mddev *mddev, struct md_rdev *rdev)
2513{
2514 char b[BDEVNAME_SIZE];
2515 struct r5conf *conf = mddev->private;
2516 unsigned long flags;
2517 pr_debug("raid456: error called\n");
2518
2519 spin_lock_irqsave(&conf->device_lock, flags);
2520 clear_bit(In_sync, &rdev->flags);
2521 mddev->degraded = calc_degraded(conf);
2522 spin_unlock_irqrestore(&conf->device_lock, flags);
2523 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
2524
2525 set_bit(Blocked, &rdev->flags);
2526 set_bit(Faulty, &rdev->flags);
2527 set_bit(MD_CHANGE_DEVS, &mddev->flags);
2528 set_bit(MD_CHANGE_PENDING, &mddev->flags);
2529 printk(KERN_ALERT
2530 "md/raid:%s: Disk failure on %s, disabling device.\n"
2531 "md/raid:%s: Operation continuing on %d devices.\n",
2532 mdname(mddev),
2533 bdevname(rdev->bdev, b),
2534 mdname(mddev),
2535 conf->raid_disks - mddev->degraded);
2536}
2537
2538/*
2539 * Input: a 'big' sector number,
2540 * Output: index of the data and parity disk, and the sector # in them.
2541 */
2542sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
2543 int previous, int *dd_idx,
2544 struct stripe_head *sh)
2545{
2546 sector_t stripe, stripe2;
2547 sector_t chunk_number;
2548 unsigned int chunk_offset;
2549 int pd_idx, qd_idx;
2550 int ddf_layout = 0;
2551 sector_t new_sector;
2552 int algorithm = previous ? conf->prev_algo
2553 : conf->algorithm;
2554 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2555 : conf->chunk_sectors;
2556 int raid_disks = previous ? conf->previous_raid_disks
2557 : conf->raid_disks;
2558 int data_disks = raid_disks - conf->max_degraded;
2559
2560 /* First compute the information on this sector */
2561
2562 /*
2563 * Compute the chunk number and the sector offset inside the chunk
2564 */
2565 chunk_offset = sector_div(r_sector, sectors_per_chunk);
2566 chunk_number = r_sector;
2567
2568 /*
2569 * Compute the stripe number
2570 */
2571 stripe = chunk_number;
2572 *dd_idx = sector_div(stripe, data_disks);
2573 stripe2 = stripe;
2574 /*
2575 * Select the parity disk based on the user selected algorithm.
2576 */
2577 pd_idx = qd_idx = -1;
2578 switch(conf->level) {
2579 case 4:
2580 pd_idx = data_disks;
2581 break;
2582 case 5:
2583 switch (algorithm) {
2584 case ALGORITHM_LEFT_ASYMMETRIC:
2585 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2586 if (*dd_idx >= pd_idx)
2587 (*dd_idx)++;
2588 break;
2589 case ALGORITHM_RIGHT_ASYMMETRIC:
2590 pd_idx = sector_div(stripe2, raid_disks);
2591 if (*dd_idx >= pd_idx)
2592 (*dd_idx)++;
2593 break;
2594 case ALGORITHM_LEFT_SYMMETRIC:
2595 pd_idx = data_disks - sector_div(stripe2, raid_disks);
2596 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2597 break;
2598 case ALGORITHM_RIGHT_SYMMETRIC:
2599 pd_idx = sector_div(stripe2, raid_disks);
2600 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2601 break;
2602 case ALGORITHM_PARITY_0:
2603 pd_idx = 0;
2604 (*dd_idx)++;
2605 break;
2606 case ALGORITHM_PARITY_N:
2607 pd_idx = data_disks;
2608 break;
2609 default:
2610 BUG();
2611 }
2612 break;
2613 case 6:
2614
2615 switch (algorithm) {
2616 case ALGORITHM_LEFT_ASYMMETRIC:
2617 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2618 qd_idx = pd_idx + 1;
2619 if (pd_idx == raid_disks-1) {
2620 (*dd_idx)++; /* Q D D D P */
2621 qd_idx = 0;
2622 } else if (*dd_idx >= pd_idx)
2623 (*dd_idx) += 2; /* D D P Q D */
2624 break;
2625 case ALGORITHM_RIGHT_ASYMMETRIC:
2626 pd_idx = sector_div(stripe2, raid_disks);
2627 qd_idx = pd_idx + 1;
2628 if (pd_idx == raid_disks-1) {
2629 (*dd_idx)++; /* Q D D D P */
2630 qd_idx = 0;
2631 } else if (*dd_idx >= pd_idx)
2632 (*dd_idx) += 2; /* D D P Q D */
2633 break;
2634 case ALGORITHM_LEFT_SYMMETRIC:
2635 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2636 qd_idx = (pd_idx + 1) % raid_disks;
2637 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2638 break;
2639 case ALGORITHM_RIGHT_SYMMETRIC:
2640 pd_idx = sector_div(stripe2, raid_disks);
2641 qd_idx = (pd_idx + 1) % raid_disks;
2642 *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2643 break;
2644
2645 case ALGORITHM_PARITY_0:
2646 pd_idx = 0;
2647 qd_idx = 1;
2648 (*dd_idx) += 2;
2649 break;
2650 case ALGORITHM_PARITY_N:
2651 pd_idx = data_disks;
2652 qd_idx = data_disks + 1;
2653 break;
2654
2655 case ALGORITHM_ROTATING_ZERO_RESTART:
2656 /* Exactly the same as RIGHT_ASYMMETRIC, but or
2657 * of blocks for computing Q is different.
2658 */
2659 pd_idx = sector_div(stripe2, raid_disks);
2660 qd_idx = pd_idx + 1;
2661 if (pd_idx == raid_disks-1) {
2662 (*dd_idx)++; /* Q D D D P */
2663 qd_idx = 0;
2664 } else if (*dd_idx >= pd_idx)
2665 (*dd_idx) += 2; /* D D P Q D */
2666 ddf_layout = 1;
2667 break;
2668
2669 case ALGORITHM_ROTATING_N_RESTART:
2670 /* Same a left_asymmetric, by first stripe is
2671 * D D D P Q rather than
2672 * Q D D D P
2673 */
2674 stripe2 += 1;
2675 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2676 qd_idx = pd_idx + 1;
2677 if (pd_idx == raid_disks-1) {
2678 (*dd_idx)++; /* Q D D D P */
2679 qd_idx = 0;
2680 } else if (*dd_idx >= pd_idx)
2681 (*dd_idx) += 2; /* D D P Q D */
2682 ddf_layout = 1;
2683 break;
2684
2685 case ALGORITHM_ROTATING_N_CONTINUE:
2686 /* Same as left_symmetric but Q is before P */
2687 pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2688 qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2689 *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2690 ddf_layout = 1;
2691 break;
2692
2693 case ALGORITHM_LEFT_ASYMMETRIC_6:
2694 /* RAID5 left_asymmetric, with Q on last device */
2695 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2696 if (*dd_idx >= pd_idx)
2697 (*dd_idx)++;
2698 qd_idx = raid_disks - 1;
2699 break;
2700
2701 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2702 pd_idx = sector_div(stripe2, raid_disks-1);
2703 if (*dd_idx >= pd_idx)
2704 (*dd_idx)++;
2705 qd_idx = raid_disks - 1;
2706 break;
2707
2708 case ALGORITHM_LEFT_SYMMETRIC_6:
2709 pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2710 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2711 qd_idx = raid_disks - 1;
2712 break;
2713
2714 case ALGORITHM_RIGHT_SYMMETRIC_6:
2715 pd_idx = sector_div(stripe2, raid_disks-1);
2716 *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2717 qd_idx = raid_disks - 1;
2718 break;
2719
2720 case ALGORITHM_PARITY_0_6:
2721 pd_idx = 0;
2722 (*dd_idx)++;
2723 qd_idx = raid_disks - 1;
2724 break;
2725
2726 default:
2727 BUG();
2728 }
2729 break;
2730 }
2731
2732 if (sh) {
2733 sh->pd_idx = pd_idx;
2734 sh->qd_idx = qd_idx;
2735 sh->ddf_layout = ddf_layout;
2736 }
2737 /*
2738 * Finally, compute the new sector number
2739 */
2740 new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2741 return new_sector;
2742}
2743
2744sector_t raid5_compute_blocknr(struct stripe_head *sh, int i, int previous)
2745{
2746 struct r5conf *conf = sh->raid_conf;
2747 int raid_disks = sh->disks;
2748 int data_disks = raid_disks - conf->max_degraded;
2749 sector_t new_sector = sh->sector, check;
2750 int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2751 : conf->chunk_sectors;
2752 int algorithm = previous ? conf->prev_algo
2753 : conf->algorithm;
2754 sector_t stripe;
2755 int chunk_offset;
2756 sector_t chunk_number;
2757 int dummy1, dd_idx = i;
2758 sector_t r_sector;
2759 struct stripe_head sh2;
2760
2761 chunk_offset = sector_div(new_sector, sectors_per_chunk);
2762 stripe = new_sector;
2763
2764 if (i == sh->pd_idx)
2765 return 0;
2766 switch(conf->level) {
2767 case 4: break;
2768 case 5:
2769 switch (algorithm) {
2770 case ALGORITHM_LEFT_ASYMMETRIC:
2771 case ALGORITHM_RIGHT_ASYMMETRIC:
2772 if (i > sh->pd_idx)
2773 i--;
2774 break;
2775 case ALGORITHM_LEFT_SYMMETRIC:
2776 case ALGORITHM_RIGHT_SYMMETRIC:
2777 if (i < sh->pd_idx)
2778 i += raid_disks;
2779 i -= (sh->pd_idx + 1);
2780 break;
2781 case ALGORITHM_PARITY_0:
2782 i -= 1;
2783 break;
2784 case ALGORITHM_PARITY_N:
2785 break;
2786 default:
2787 BUG();
2788 }
2789 break;
2790 case 6:
2791 if (i == sh->qd_idx)
2792 return 0; /* It is the Q disk */
2793 switch (algorithm) {
2794 case ALGORITHM_LEFT_ASYMMETRIC:
2795 case ALGORITHM_RIGHT_ASYMMETRIC:
2796 case ALGORITHM_ROTATING_ZERO_RESTART:
2797 case ALGORITHM_ROTATING_N_RESTART:
2798 if (sh->pd_idx == raid_disks-1)
2799 i--; /* Q D D D P */
2800 else if (i > sh->pd_idx)
2801 i -= 2; /* D D P Q D */
2802 break;
2803 case ALGORITHM_LEFT_SYMMETRIC:
2804 case ALGORITHM_RIGHT_SYMMETRIC:
2805 if (sh->pd_idx == raid_disks-1)
2806 i--; /* Q D D D P */
2807 else {
2808 /* D D P Q D */
2809 if (i < sh->pd_idx)
2810 i += raid_disks;
2811 i -= (sh->pd_idx + 2);
2812 }
2813 break;
2814 case ALGORITHM_PARITY_0:
2815 i -= 2;
2816 break;
2817 case ALGORITHM_PARITY_N:
2818 break;
2819 case ALGORITHM_ROTATING_N_CONTINUE:
2820 /* Like left_symmetric, but P is before Q */
2821 if (sh->pd_idx == 0)
2822 i--; /* P D D D Q */
2823 else {
2824 /* D D Q P D */
2825 if (i < sh->pd_idx)
2826 i += raid_disks;
2827 i -= (sh->pd_idx + 1);
2828 }
2829 break;
2830 case ALGORITHM_LEFT_ASYMMETRIC_6:
2831 case ALGORITHM_RIGHT_ASYMMETRIC_6:
2832 if (i > sh->pd_idx)
2833 i--;
2834 break;
2835 case ALGORITHM_LEFT_SYMMETRIC_6:
2836 case ALGORITHM_RIGHT_SYMMETRIC_6:
2837 if (i < sh->pd_idx)
2838 i += data_disks + 1;
2839 i -= (sh->pd_idx + 1);
2840 break;
2841 case ALGORITHM_PARITY_0_6:
2842 i -= 1;
2843 break;
2844 default:
2845 BUG();
2846 }
2847 break;
2848 }
2849
2850 chunk_number = stripe * data_disks + i;
2851 r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2852
2853 check = raid5_compute_sector(conf, r_sector,
2854 previous, &dummy1, &sh2);
2855 if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2856 || sh2.qd_idx != sh->qd_idx) {
2857 printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2858 mdname(conf->mddev));
2859 return 0;
2860 }
2861 return r_sector;
2862}
2863
2864static void
2865schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2866 int rcw, int expand)
2867{
2868 int i, pd_idx = sh->pd_idx, qd_idx = sh->qd_idx, disks = sh->disks;
2869 struct r5conf *conf = sh->raid_conf;
2870 int level = conf->level;
2871
2872 if (rcw) {
2873
2874 for (i = disks; i--; ) {
2875 struct r5dev *dev = &sh->dev[i];
2876
2877 if (dev->towrite) {
2878 set_bit(R5_LOCKED, &dev->flags);
2879 set_bit(R5_Wantdrain, &dev->flags);
2880 if (!expand)
2881 clear_bit(R5_UPTODATE, &dev->flags);
2882 s->locked++;
2883 }
2884 }
2885 /* if we are not expanding this is a proper write request, and
2886 * there will be bios with new data to be drained into the
2887 * stripe cache
2888 */
2889 if (!expand) {
2890 if (!s->locked)
2891 /* False alarm, nothing to do */
2892 return;
2893 sh->reconstruct_state = reconstruct_state_drain_run;
2894 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2895 } else
2896 sh->reconstruct_state = reconstruct_state_run;
2897
2898 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2899
2900 if (s->locked + conf->max_degraded == disks)
2901 if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2902 atomic_inc(&conf->pending_full_writes);
2903 } else {
2904 BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2905 test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2906 BUG_ON(level == 6 &&
2907 (!(test_bit(R5_UPTODATE, &sh->dev[qd_idx].flags) ||
2908 test_bit(R5_Wantcompute, &sh->dev[qd_idx].flags))));
2909
2910 for (i = disks; i--; ) {
2911 struct r5dev *dev = &sh->dev[i];
2912 if (i == pd_idx || i == qd_idx)
2913 continue;
2914
2915 if (dev->towrite &&
2916 (test_bit(R5_UPTODATE, &dev->flags) ||
2917 test_bit(R5_Wantcompute, &dev->flags))) {
2918 set_bit(R5_Wantdrain, &dev->flags);
2919 set_bit(R5_LOCKED, &dev->flags);
2920 clear_bit(R5_UPTODATE, &dev->flags);
2921 s->locked++;
2922 }
2923 }
2924 if (!s->locked)
2925 /* False alarm - nothing to do */
2926 return;
2927 sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2928 set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2929 set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2930 set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2931 }
2932
2933 /* keep the parity disk(s) locked while asynchronous operations
2934 * are in flight
2935 */
2936 set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2937 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2938 s->locked++;
2939
2940 if (level == 6) {
2941 int qd_idx = sh->qd_idx;
2942 struct r5dev *dev = &sh->dev[qd_idx];
2943
2944 set_bit(R5_LOCKED, &dev->flags);
2945 clear_bit(R5_UPTODATE, &dev->flags);
2946 s->locked++;
2947 }
2948
2949 pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2950 __func__, (unsigned long long)sh->sector,
2951 s->locked, s->ops_request);
2952}
2953
2954/*
2955 * Each stripe/dev can have one or more bion attached.
2956 * toread/towrite point to the first in a chain.
2957 * The bi_next chain must be in order.
2958 */
2959static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx,
2960 int forwrite, int previous)
2961{
2962 struct bio **bip;
2963 struct r5conf *conf = sh->raid_conf;
2964 int firstwrite=0;
2965
2966 pr_debug("adding bi b#%llu to stripe s#%llu\n",
2967 (unsigned long long)bi->bi_iter.bi_sector,
2968 (unsigned long long)sh->sector);
2969
2970 /*
2971 * If several bio share a stripe. The bio bi_phys_segments acts as a
2972 * reference count to avoid race. The reference count should already be
2973 * increased before this function is called (for example, in
2974 * make_request()), so other bio sharing this stripe will not free the
2975 * stripe. If a stripe is owned by one stripe, the stripe lock will
2976 * protect it.
2977 */
2978 spin_lock_irq(&sh->stripe_lock);
2979 /* Don't allow new IO added to stripes in batch list */
2980 if (sh->batch_head)
2981 goto overlap;
2982 if (forwrite) {
2983 bip = &sh->dev[dd_idx].towrite;
2984 if (*bip == NULL)
2985 firstwrite = 1;
2986 } else
2987 bip = &sh->dev[dd_idx].toread;
2988 while (*bip && (*bip)->bi_iter.bi_sector < bi->bi_iter.bi_sector) {
2989 if (bio_end_sector(*bip) > bi->bi_iter.bi_sector)
2990 goto overlap;
2991 bip = & (*bip)->bi_next;
2992 }
2993 if (*bip && (*bip)->bi_iter.bi_sector < bio_end_sector(bi))
2994 goto overlap;
2995
2996 if (!forwrite || previous)
2997 clear_bit(STRIPE_BATCH_READY, &sh->state);
2998
2999 BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
3000 if (*bip)
3001 bi->bi_next = *bip;
3002 *bip = bi;
3003 raid5_inc_bi_active_stripes(bi);
3004
3005 if (forwrite) {
3006 /* check if page is covered */
3007 sector_t sector = sh->dev[dd_idx].sector;
3008 for (bi=sh->dev[dd_idx].towrite;
3009 sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
3010 bi && bi->bi_iter.bi_sector <= sector;
3011 bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
3012 if (bio_end_sector(bi) >= sector)
3013 sector = bio_end_sector(bi);
3014 }
3015 if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
3016 if (!test_and_set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags))
3017 sh->overwrite_disks++;
3018 }
3019
3020 pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
3021 (unsigned long long)(*bip)->bi_iter.bi_sector,
3022 (unsigned long long)sh->sector, dd_idx);
3023
3024 if (conf->mddev->bitmap && firstwrite) {
3025 /* Cannot hold spinlock over bitmap_startwrite,
3026 * but must ensure this isn't added to a batch until
3027 * we have added to the bitmap and set bm_seq.
3028 * So set STRIPE_BITMAP_PENDING to prevent
3029 * batching.
3030 * If multiple add_stripe_bio() calls race here they
3031 * much all set STRIPE_BITMAP_PENDING. So only the first one
3032 * to complete "bitmap_startwrite" gets to set
3033 * STRIPE_BIT_DELAY. This is important as once a stripe
3034 * is added to a batch, STRIPE_BIT_DELAY cannot be changed
3035 * any more.
3036 */
3037 set_bit(STRIPE_BITMAP_PENDING, &sh->state);
3038 spin_unlock_irq(&sh->stripe_lock);
3039 bitmap_startwrite(conf->mddev->bitmap, sh->sector,
3040 STRIPE_SECTORS, 0);
3041 spin_lock_irq(&sh->stripe_lock);
3042 clear_bit(STRIPE_BITMAP_PENDING, &sh->state);
3043 if (!sh->batch_head) {
3044 sh->bm_seq = conf->seq_flush+1;
3045 set_bit(STRIPE_BIT_DELAY, &sh->state);
3046 }
3047 }
3048 spin_unlock_irq(&sh->stripe_lock);
3049
3050 if (stripe_can_batch(sh))
3051 stripe_add_to_batch_list(conf, sh);
3052 return 1;
3053
3054 overlap:
3055 set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
3056 spin_unlock_irq(&sh->stripe_lock);
3057 return 0;
3058}
3059
3060static void end_reshape(struct r5conf *conf);
3061
3062static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
3063 struct stripe_head *sh)
3064{
3065 int sectors_per_chunk =
3066 previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
3067 int dd_idx;
3068 int chunk_offset = sector_div(stripe, sectors_per_chunk);
3069 int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
3070
3071 raid5_compute_sector(conf,
3072 stripe * (disks - conf->max_degraded)
3073 *sectors_per_chunk + chunk_offset,
3074 previous,
3075 &dd_idx, sh);
3076}
3077
3078static void
3079handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
3080 struct stripe_head_state *s, int disks,
3081 struct bio_list *return_bi)
3082{
3083 int i;
3084 BUG_ON(sh->batch_head);
3085 for (i = disks; i--; ) {
3086 struct bio *bi;
3087 int bitmap_end = 0;
3088
3089 if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
3090 struct md_rdev *rdev;
3091 rcu_read_lock();
3092 rdev = rcu_dereference(conf->disks[i].rdev);
3093 if (rdev && test_bit(In_sync, &rdev->flags))
3094 atomic_inc(&rdev->nr_pending);
3095 else
3096 rdev = NULL;
3097 rcu_read_unlock();
3098 if (rdev) {
3099 if (!rdev_set_badblocks(
3100 rdev,
3101 sh->sector,
3102 STRIPE_SECTORS, 0))
3103 md_error(conf->mddev, rdev);
3104 rdev_dec_pending(rdev, conf->mddev);
3105 }
3106 }
3107 spin_lock_irq(&sh->stripe_lock);
3108 /* fail all writes first */
3109 bi = sh->dev[i].towrite;
3110 sh->dev[i].towrite = NULL;
3111 sh->overwrite_disks = 0;
3112 spin_unlock_irq(&sh->stripe_lock);
3113 if (bi)
3114 bitmap_end = 1;
3115
3116 r5l_stripe_write_finished(sh);
3117
3118 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3119 wake_up(&conf->wait_for_overlap);
3120
3121 while (bi && bi->bi_iter.bi_sector <
3122 sh->dev[i].sector + STRIPE_SECTORS) {
3123 struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
3124
3125 bi->bi_error = -EIO;
3126 if (!raid5_dec_bi_active_stripes(bi)) {
3127 md_write_end(conf->mddev);
3128 bio_list_add(return_bi, bi);
3129 }
3130 bi = nextbi;
3131 }
3132 if (bitmap_end)
3133 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3134 STRIPE_SECTORS, 0, 0);
3135 bitmap_end = 0;
3136 /* and fail all 'written' */
3137 bi = sh->dev[i].written;
3138 sh->dev[i].written = NULL;
3139 if (test_and_clear_bit(R5_SkipCopy, &sh->dev[i].flags)) {
3140 WARN_ON(test_bit(R5_UPTODATE, &sh->dev[i].flags));
3141 sh->dev[i].page = sh->dev[i].orig_page;
3142 }
3143
3144 if (bi) bitmap_end = 1;
3145 while (bi && bi->bi_iter.bi_sector <
3146 sh->dev[i].sector + STRIPE_SECTORS) {
3147 struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
3148
3149 bi->bi_error = -EIO;
3150 if (!raid5_dec_bi_active_stripes(bi)) {
3151 md_write_end(conf->mddev);
3152 bio_list_add(return_bi, bi);
3153 }
3154 bi = bi2;
3155 }
3156
3157 /* fail any reads if this device is non-operational and
3158 * the data has not reached the cache yet.
3159 */
3160 if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
3161 s->failed > conf->max_degraded &&
3162 (!test_bit(R5_Insync, &sh->dev[i].flags) ||
3163 test_bit(R5_ReadError, &sh->dev[i].flags))) {
3164 spin_lock_irq(&sh->stripe_lock);
3165 bi = sh->dev[i].toread;
3166 sh->dev[i].toread = NULL;
3167 spin_unlock_irq(&sh->stripe_lock);
3168 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
3169 wake_up(&conf->wait_for_overlap);
3170 if (bi)
3171 s->to_read--;
3172 while (bi && bi->bi_iter.bi_sector <
3173 sh->dev[i].sector + STRIPE_SECTORS) {
3174 struct bio *nextbi =
3175 r5_next_bio(bi, sh->dev[i].sector);
3176
3177 bi->bi_error = -EIO;
3178 if (!raid5_dec_bi_active_stripes(bi))
3179 bio_list_add(return_bi, bi);
3180 bi = nextbi;
3181 }
3182 }
3183 if (bitmap_end)
3184 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3185 STRIPE_SECTORS, 0, 0);
3186 /* If we were in the middle of a write the parity block might
3187 * still be locked - so just clear all R5_LOCKED flags
3188 */
3189 clear_bit(R5_LOCKED, &sh->dev[i].flags);
3190 }
3191 s->to_write = 0;
3192 s->written = 0;
3193
3194 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3195 if (atomic_dec_and_test(&conf->pending_full_writes))
3196 md_wakeup_thread(conf->mddev->thread);
3197}
3198
3199static void
3200handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
3201 struct stripe_head_state *s)
3202{
3203 int abort = 0;
3204 int i;
3205
3206 BUG_ON(sh->batch_head);
3207 clear_bit(STRIPE_SYNCING, &sh->state);
3208 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3209 wake_up(&conf->wait_for_overlap);
3210 s->syncing = 0;
3211 s->replacing = 0;
3212 /* There is nothing more to do for sync/check/repair.
3213 * Don't even need to abort as that is handled elsewhere
3214 * if needed, and not always wanted e.g. if there is a known
3215 * bad block here.
3216 * For recover/replace we need to record a bad block on all
3217 * non-sync devices, or abort the recovery
3218 */
3219 if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
3220 /* During recovery devices cannot be removed, so
3221 * locking and refcounting of rdevs is not needed
3222 */
3223 for (i = 0; i < conf->raid_disks; i++) {
3224 struct md_rdev *rdev = conf->disks[i].rdev;
3225 if (rdev
3226 && !test_bit(Faulty, &rdev->flags)
3227 && !test_bit(In_sync, &rdev->flags)
3228 && !rdev_set_badblocks(rdev, sh->sector,
3229 STRIPE_SECTORS, 0))
3230 abort = 1;
3231 rdev = conf->disks[i].replacement;
3232 if (rdev
3233 && !test_bit(Faulty, &rdev->flags)
3234 && !test_bit(In_sync, &rdev->flags)
3235 && !rdev_set_badblocks(rdev, sh->sector,
3236 STRIPE_SECTORS, 0))
3237 abort = 1;
3238 }
3239 if (abort)
3240 conf->recovery_disabled =
3241 conf->mddev->recovery_disabled;
3242 }
3243 md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
3244}
3245
3246static int want_replace(struct stripe_head *sh, int disk_idx)
3247{
3248 struct md_rdev *rdev;
3249 int rv = 0;
3250 /* Doing recovery so rcu locking not required */
3251 rdev = sh->raid_conf->disks[disk_idx].replacement;
3252 if (rdev
3253 && !test_bit(Faulty, &rdev->flags)
3254 && !test_bit(In_sync, &rdev->flags)
3255 && (rdev->recovery_offset <= sh->sector
3256 || rdev->mddev->recovery_cp <= sh->sector))
3257 rv = 1;
3258
3259 return rv;
3260}
3261
3262/* fetch_block - checks the given member device to see if its data needs
3263 * to be read or computed to satisfy a request.
3264 *
3265 * Returns 1 when no more member devices need to be checked, otherwise returns
3266 * 0 to tell the loop in handle_stripe_fill to continue
3267 */
3268
3269static int need_this_block(struct stripe_head *sh, struct stripe_head_state *s,
3270 int disk_idx, int disks)
3271{
3272 struct r5dev *dev = &sh->dev[disk_idx];
3273 struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
3274 &sh->dev[s->failed_num[1]] };
3275 int i;
3276
3277
3278 if (test_bit(R5_LOCKED, &dev->flags) ||
3279 test_bit(R5_UPTODATE, &dev->flags))
3280 /* No point reading this as we already have it or have
3281 * decided to get it.
3282 */
3283 return 0;
3284
3285 if (dev->toread ||
3286 (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)))
3287 /* We need this block to directly satisfy a request */
3288 return 1;
3289
3290 if (s->syncing || s->expanding ||
3291 (s->replacing && want_replace(sh, disk_idx)))
3292 /* When syncing, or expanding we read everything.
3293 * When replacing, we need the replaced block.
3294 */
3295 return 1;
3296
3297 if ((s->failed >= 1 && fdev[0]->toread) ||
3298 (s->failed >= 2 && fdev[1]->toread))
3299 /* If we want to read from a failed device, then
3300 * we need to actually read every other device.
3301 */
3302 return 1;
3303
3304 /* Sometimes neither read-modify-write nor reconstruct-write
3305 * cycles can work. In those cases we read every block we
3306 * can. Then the parity-update is certain to have enough to
3307 * work with.
3308 * This can only be a problem when we need to write something,
3309 * and some device has failed. If either of those tests
3310 * fail we need look no further.
3311 */
3312 if (!s->failed || !s->to_write)
3313 return 0;
3314
3315 if (test_bit(R5_Insync, &dev->flags) &&
3316 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3317 /* Pre-reads at not permitted until after short delay
3318 * to gather multiple requests. However if this
3319 * device is no Insync, the block could only be be computed
3320 * and there is no need to delay that.
3321 */
3322 return 0;
3323
3324 for (i = 0; i < s->failed && i < 2; i++) {
3325 if (fdev[i]->towrite &&
3326 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3327 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3328 /* If we have a partial write to a failed
3329 * device, then we will need to reconstruct
3330 * the content of that device, so all other
3331 * devices must be read.
3332 */
3333 return 1;
3334 }
3335
3336 /* If we are forced to do a reconstruct-write, either because
3337 * the current RAID6 implementation only supports that, or
3338 * or because parity cannot be trusted and we are currently
3339 * recovering it, there is extra need to be careful.
3340 * If one of the devices that we would need to read, because
3341 * it is not being overwritten (and maybe not written at all)
3342 * is missing/faulty, then we need to read everything we can.
3343 */
3344 if (sh->raid_conf->level != 6 &&
3345 sh->sector < sh->raid_conf->mddev->recovery_cp)
3346 /* reconstruct-write isn't being forced */
3347 return 0;
3348 for (i = 0; i < s->failed && i < 2; i++) {
3349 if (s->failed_num[i] != sh->pd_idx &&
3350 s->failed_num[i] != sh->qd_idx &&
3351 !test_bit(R5_UPTODATE, &fdev[i]->flags) &&
3352 !test_bit(R5_OVERWRITE, &fdev[i]->flags))
3353 return 1;
3354 }
3355
3356 return 0;
3357}
3358
3359static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
3360 int disk_idx, int disks)
3361{
3362 struct r5dev *dev = &sh->dev[disk_idx];
3363
3364 /* is the data in this block needed, and can we get it? */
3365 if (need_this_block(sh, s, disk_idx, disks)) {
3366 /* we would like to get this block, possibly by computing it,
3367 * otherwise read it if the backing disk is insync
3368 */
3369 BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
3370 BUG_ON(test_bit(R5_Wantread, &dev->flags));
3371 BUG_ON(sh->batch_head);
3372 if ((s->uptodate == disks - 1) &&
3373 (s->failed && (disk_idx == s->failed_num[0] ||
3374 disk_idx == s->failed_num[1]))) {
3375 /* have disk failed, and we're requested to fetch it;
3376 * do compute it
3377 */
3378 pr_debug("Computing stripe %llu block %d\n",
3379 (unsigned long long)sh->sector, disk_idx);
3380 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3381 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3382 set_bit(R5_Wantcompute, &dev->flags);
3383 sh->ops.target = disk_idx;
3384 sh->ops.target2 = -1; /* no 2nd target */
3385 s->req_compute = 1;
3386 /* Careful: from this point on 'uptodate' is in the eye
3387 * of raid_run_ops which services 'compute' operations
3388 * before writes. R5_Wantcompute flags a block that will
3389 * be R5_UPTODATE by the time it is needed for a
3390 * subsequent operation.
3391 */
3392 s->uptodate++;
3393 return 1;
3394 } else if (s->uptodate == disks-2 && s->failed >= 2) {
3395 /* Computing 2-failure is *very* expensive; only
3396 * do it if failed >= 2
3397 */
3398 int other;
3399 for (other = disks; other--; ) {
3400 if (other == disk_idx)
3401 continue;
3402 if (!test_bit(R5_UPTODATE,
3403 &sh->dev[other].flags))
3404 break;
3405 }
3406 BUG_ON(other < 0);
3407 pr_debug("Computing stripe %llu blocks %d,%d\n",
3408 (unsigned long long)sh->sector,
3409 disk_idx, other);
3410 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3411 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3412 set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
3413 set_bit(R5_Wantcompute, &sh->dev[other].flags);
3414 sh->ops.target = disk_idx;
3415 sh->ops.target2 = other;
3416 s->uptodate += 2;
3417 s->req_compute = 1;
3418 return 1;
3419 } else if (test_bit(R5_Insync, &dev->flags)) {
3420 set_bit(R5_LOCKED, &dev->flags);
3421 set_bit(R5_Wantread, &dev->flags);
3422 s->locked++;
3423 pr_debug("Reading block %d (sync=%d)\n",
3424 disk_idx, s->syncing);
3425 }
3426 }
3427
3428 return 0;
3429}
3430
3431/**
3432 * handle_stripe_fill - read or compute data to satisfy pending requests.
3433 */
3434static void handle_stripe_fill(struct stripe_head *sh,
3435 struct stripe_head_state *s,
3436 int disks)
3437{
3438 int i;
3439
3440 /* look for blocks to read/compute, skip this if a compute
3441 * is already in flight, or if the stripe contents are in the
3442 * midst of changing due to a write
3443 */
3444 if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
3445 !sh->reconstruct_state)
3446 for (i = disks; i--; )
3447 if (fetch_block(sh, s, i, disks))
3448 break;
3449 set_bit(STRIPE_HANDLE, &sh->state);
3450}
3451
3452static void break_stripe_batch_list(struct stripe_head *head_sh,
3453 unsigned long handle_flags);
3454/* handle_stripe_clean_event
3455 * any written block on an uptodate or failed drive can be returned.
3456 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
3457 * never LOCKED, so we don't need to test 'failed' directly.
3458 */
3459static void handle_stripe_clean_event(struct r5conf *conf,
3460 struct stripe_head *sh, int disks, struct bio_list *return_bi)
3461{
3462 int i;
3463 struct r5dev *dev;
3464 int discard_pending = 0;
3465 struct stripe_head *head_sh = sh;
3466 bool do_endio = false;
3467
3468 for (i = disks; i--; )
3469 if (sh->dev[i].written) {
3470 dev = &sh->dev[i];
3471 if (!test_bit(R5_LOCKED, &dev->flags) &&
3472 (test_bit(R5_UPTODATE, &dev->flags) ||
3473 test_bit(R5_Discard, &dev->flags) ||
3474 test_bit(R5_SkipCopy, &dev->flags))) {
3475 /* We can return any write requests */
3476 struct bio *wbi, *wbi2;
3477 pr_debug("Return write for disc %d\n", i);
3478 if (test_and_clear_bit(R5_Discard, &dev->flags))
3479 clear_bit(R5_UPTODATE, &dev->flags);
3480 if (test_and_clear_bit(R5_SkipCopy, &dev->flags)) {
3481 WARN_ON(test_bit(R5_UPTODATE, &dev->flags));
3482 }
3483 do_endio = true;
3484
3485returnbi:
3486 dev->page = dev->orig_page;
3487 wbi = dev->written;
3488 dev->written = NULL;
3489 while (wbi && wbi->bi_iter.bi_sector <
3490 dev->sector + STRIPE_SECTORS) {
3491 wbi2 = r5_next_bio(wbi, dev->sector);
3492 if (!raid5_dec_bi_active_stripes(wbi)) {
3493 md_write_end(conf->mddev);
3494 bio_list_add(return_bi, wbi);
3495 }
3496 wbi = wbi2;
3497 }
3498 bitmap_endwrite(conf->mddev->bitmap, sh->sector,
3499 STRIPE_SECTORS,
3500 !test_bit(STRIPE_DEGRADED, &sh->state),
3501 0);
3502 if (head_sh->batch_head) {
3503 sh = list_first_entry(&sh->batch_list,
3504 struct stripe_head,
3505 batch_list);
3506 if (sh != head_sh) {
3507 dev = &sh->dev[i];
3508 goto returnbi;
3509 }
3510 }
3511 sh = head_sh;
3512 dev = &sh->dev[i];
3513 } else if (test_bit(R5_Discard, &dev->flags))
3514 discard_pending = 1;
3515 WARN_ON(test_bit(R5_SkipCopy, &dev->flags));
3516 WARN_ON(dev->page != dev->orig_page);
3517 }
3518
3519 r5l_stripe_write_finished(sh);
3520
3521 if (!discard_pending &&
3522 test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
3523 int hash;
3524 clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
3525 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3526 if (sh->qd_idx >= 0) {
3527 clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
3528 clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
3529 }
3530 /* now that discard is done we can proceed with any sync */
3531 clear_bit(STRIPE_DISCARD, &sh->state);
3532 /*
3533 * SCSI discard will change some bio fields and the stripe has
3534 * no updated data, so remove it from hash list and the stripe
3535 * will be reinitialized
3536 */
3537unhash:
3538 hash = sh->hash_lock_index;
3539 spin_lock_irq(conf->hash_locks + hash);
3540 remove_hash(sh);
3541 spin_unlock_irq(conf->hash_locks + hash);
3542 if (head_sh->batch_head) {
3543 sh = list_first_entry(&sh->batch_list,
3544 struct stripe_head, batch_list);
3545 if (sh != head_sh)
3546 goto unhash;
3547 }
3548 sh = head_sh;
3549
3550 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
3551 set_bit(STRIPE_HANDLE, &sh->state);
3552
3553 }
3554
3555 if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
3556 if (atomic_dec_and_test(&conf->pending_full_writes))
3557 md_wakeup_thread(conf->mddev->thread);
3558
3559 if (head_sh->batch_head && do_endio)
3560 break_stripe_batch_list(head_sh, STRIPE_EXPAND_SYNC_FLAGS);
3561}
3562
3563static void handle_stripe_dirtying(struct r5conf *conf,
3564 struct stripe_head *sh,
3565 struct stripe_head_state *s,
3566 int disks)
3567{
3568 int rmw = 0, rcw = 0, i;
3569 sector_t recovery_cp = conf->mddev->recovery_cp;
3570
3571 /* Check whether resync is now happening or should start.
3572 * If yes, then the array is dirty (after unclean shutdown or
3573 * initial creation), so parity in some stripes might be inconsistent.
3574 * In this case, we need to always do reconstruct-write, to ensure
3575 * that in case of drive failure or read-error correction, we
3576 * generate correct data from the parity.
3577 */
3578 if (conf->rmw_level == PARITY_DISABLE_RMW ||
3579 (recovery_cp < MaxSector && sh->sector >= recovery_cp &&
3580 s->failed == 0)) {
3581 /* Calculate the real rcw later - for now make it
3582 * look like rcw is cheaper
3583 */
3584 rcw = 1; rmw = 2;
3585 pr_debug("force RCW rmw_level=%u, recovery_cp=%llu sh->sector=%llu\n",
3586 conf->rmw_level, (unsigned long long)recovery_cp,
3587 (unsigned long long)sh->sector);
3588 } else for (i = disks; i--; ) {
3589 /* would I have to read this buffer for read_modify_write */
3590 struct r5dev *dev = &sh->dev[i];
3591 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3592 !test_bit(R5_LOCKED, &dev->flags) &&
3593 !(test_bit(R5_UPTODATE, &dev->flags) ||
3594 test_bit(R5_Wantcompute, &dev->flags))) {
3595 if (test_bit(R5_Insync, &dev->flags))
3596 rmw++;
3597 else
3598 rmw += 2*disks; /* cannot read it */
3599 }
3600 /* Would I have to read this buffer for reconstruct_write */
3601 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3602 i != sh->pd_idx && i != sh->qd_idx &&
3603 !test_bit(R5_LOCKED, &dev->flags) &&
3604 !(test_bit(R5_UPTODATE, &dev->flags) ||
3605 test_bit(R5_Wantcompute, &dev->flags))) {
3606 if (test_bit(R5_Insync, &dev->flags))
3607 rcw++;
3608 else
3609 rcw += 2*disks;
3610 }
3611 }
3612 pr_debug("for sector %llu, rmw=%d rcw=%d\n",
3613 (unsigned long long)sh->sector, rmw, rcw);
3614 set_bit(STRIPE_HANDLE, &sh->state);
3615 if ((rmw < rcw || (rmw == rcw && conf->rmw_level == PARITY_ENABLE_RMW)) && rmw > 0) {
3616 /* prefer read-modify-write, but need to get some data */
3617 if (conf->mddev->queue)
3618 blk_add_trace_msg(conf->mddev->queue,
3619 "raid5 rmw %llu %d",
3620 (unsigned long long)sh->sector, rmw);
3621 for (i = disks; i--; ) {
3622 struct r5dev *dev = &sh->dev[i];
3623 if ((dev->towrite || i == sh->pd_idx || i == sh->qd_idx) &&
3624 !test_bit(R5_LOCKED, &dev->flags) &&
3625 !(test_bit(R5_UPTODATE, &dev->flags) ||
3626 test_bit(R5_Wantcompute, &dev->flags)) &&
3627 test_bit(R5_Insync, &dev->flags)) {
3628 if (test_bit(STRIPE_PREREAD_ACTIVE,
3629 &sh->state)) {
3630 pr_debug("Read_old block %d for r-m-w\n",
3631 i);
3632 set_bit(R5_LOCKED, &dev->flags);
3633 set_bit(R5_Wantread, &dev->flags);
3634 s->locked++;
3635 } else {
3636 set_bit(STRIPE_DELAYED, &sh->state);
3637 set_bit(STRIPE_HANDLE, &sh->state);
3638 }
3639 }
3640 }
3641 }
3642 if ((rcw < rmw || (rcw == rmw && conf->rmw_level != PARITY_ENABLE_RMW)) && rcw > 0) {
3643 /* want reconstruct write, but need to get some data */
3644 int qread =0;
3645 rcw = 0;
3646 for (i = disks; i--; ) {
3647 struct r5dev *dev = &sh->dev[i];
3648 if (!test_bit(R5_OVERWRITE, &dev->flags) &&
3649 i != sh->pd_idx && i != sh->qd_idx &&
3650 !test_bit(R5_LOCKED, &dev->flags) &&
3651 !(test_bit(R5_UPTODATE, &dev->flags) ||
3652 test_bit(R5_Wantcompute, &dev->flags))) {
3653 rcw++;
3654 if (test_bit(R5_Insync, &dev->flags) &&
3655 test_bit(STRIPE_PREREAD_ACTIVE,
3656 &sh->state)) {
3657 pr_debug("Read_old block "
3658 "%d for Reconstruct\n", i);
3659 set_bit(R5_LOCKED, &dev->flags);
3660 set_bit(R5_Wantread, &dev->flags);
3661 s->locked++;
3662 qread++;
3663 } else {
3664 set_bit(STRIPE_DELAYED, &sh->state);
3665 set_bit(STRIPE_HANDLE, &sh->state);
3666 }
3667 }
3668 }
3669 if (rcw && conf->mddev->queue)
3670 blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
3671 (unsigned long long)sh->sector,
3672 rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
3673 }
3674
3675 if (rcw > disks && rmw > disks &&
3676 !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3677 set_bit(STRIPE_DELAYED, &sh->state);
3678
3679 /* now if nothing is locked, and if we have enough data,
3680 * we can start a write request
3681 */
3682 /* since handle_stripe can be called at any time we need to handle the
3683 * case where a compute block operation has been submitted and then a
3684 * subsequent call wants to start a write request. raid_run_ops only
3685 * handles the case where compute block and reconstruct are requested
3686 * simultaneously. If this is not the case then new writes need to be
3687 * held off until the compute completes.
3688 */
3689 if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
3690 (s->locked == 0 && (rcw == 0 || rmw == 0) &&
3691 !test_bit(STRIPE_BIT_DELAY, &sh->state)))
3692 schedule_reconstruction(sh, s, rcw == 0, 0);
3693}
3694
3695static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
3696 struct stripe_head_state *s, int disks)
3697{
3698 struct r5dev *dev = NULL;
3699
3700 BUG_ON(sh->batch_head);
3701 set_bit(STRIPE_HANDLE, &sh->state);
3702
3703 switch (sh->check_state) {
3704 case check_state_idle:
3705 /* start a new check operation if there are no failures */
3706 if (s->failed == 0) {
3707 BUG_ON(s->uptodate != disks);
3708 sh->check_state = check_state_run;
3709 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3710 clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
3711 s->uptodate--;
3712 break;
3713 }
3714 dev = &sh->dev[s->failed_num[0]];
3715 /* fall through */
3716 case check_state_compute_result:
3717 sh->check_state = check_state_idle;
3718 if (!dev)
3719 dev = &sh->dev[sh->pd_idx];
3720
3721 /* check that a write has not made the stripe insync */
3722 if (test_bit(STRIPE_INSYNC, &sh->state))
3723 break;
3724
3725 /* either failed parity check, or recovery is happening */
3726 BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
3727 BUG_ON(s->uptodate != disks);
3728
3729 set_bit(R5_LOCKED, &dev->flags);
3730 s->locked++;
3731 set_bit(R5_Wantwrite, &dev->flags);
3732
3733 clear_bit(STRIPE_DEGRADED, &sh->state);
3734 set_bit(STRIPE_INSYNC, &sh->state);
3735 break;
3736 case check_state_run:
3737 break; /* we will be called again upon completion */
3738 case check_state_check_result:
3739 sh->check_state = check_state_idle;
3740
3741 /* if a failure occurred during the check operation, leave
3742 * STRIPE_INSYNC not set and let the stripe be handled again
3743 */
3744 if (s->failed)
3745 break;
3746
3747 /* handle a successful check operation, if parity is correct
3748 * we are done. Otherwise update the mismatch count and repair
3749 * parity if !MD_RECOVERY_CHECK
3750 */
3751 if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
3752 /* parity is correct (on disc,
3753 * not in buffer any more)
3754 */
3755 set_bit(STRIPE_INSYNC, &sh->state);
3756 else {
3757 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3758 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3759 /* don't try to repair!! */
3760 set_bit(STRIPE_INSYNC, &sh->state);
3761 else {
3762 sh->check_state = check_state_compute_run;
3763 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3764 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3765 set_bit(R5_Wantcompute,
3766 &sh->dev[sh->pd_idx].flags);
3767 sh->ops.target = sh->pd_idx;
3768 sh->ops.target2 = -1;
3769 s->uptodate++;
3770 }
3771 }
3772 break;
3773 case check_state_compute_run:
3774 break;
3775 default:
3776 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3777 __func__, sh->check_state,
3778 (unsigned long long) sh->sector);
3779 BUG();
3780 }
3781}
3782
3783static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3784 struct stripe_head_state *s,
3785 int disks)
3786{
3787 int pd_idx = sh->pd_idx;
3788 int qd_idx = sh->qd_idx;
3789 struct r5dev *dev;
3790
3791 BUG_ON(sh->batch_head);
3792 set_bit(STRIPE_HANDLE, &sh->state);
3793
3794 BUG_ON(s->failed > 2);
3795
3796 /* Want to check and possibly repair P and Q.
3797 * However there could be one 'failed' device, in which
3798 * case we can only check one of them, possibly using the
3799 * other to generate missing data
3800 */
3801
3802 switch (sh->check_state) {
3803 case check_state_idle:
3804 /* start a new check operation if there are < 2 failures */
3805 if (s->failed == s->q_failed) {
3806 /* The only possible failed device holds Q, so it
3807 * makes sense to check P (If anything else were failed,
3808 * we would have used P to recreate it).
3809 */
3810 sh->check_state = check_state_run;
3811 }
3812 if (!s->q_failed && s->failed < 2) {
3813 /* Q is not failed, and we didn't use it to generate
3814 * anything, so it makes sense to check it
3815 */
3816 if (sh->check_state == check_state_run)
3817 sh->check_state = check_state_run_pq;
3818 else
3819 sh->check_state = check_state_run_q;
3820 }
3821
3822 /* discard potentially stale zero_sum_result */
3823 sh->ops.zero_sum_result = 0;
3824
3825 if (sh->check_state == check_state_run) {
3826 /* async_xor_zero_sum destroys the contents of P */
3827 clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3828 s->uptodate--;
3829 }
3830 if (sh->check_state >= check_state_run &&
3831 sh->check_state <= check_state_run_pq) {
3832 /* async_syndrome_zero_sum preserves P and Q, so
3833 * no need to mark them !uptodate here
3834 */
3835 set_bit(STRIPE_OP_CHECK, &s->ops_request);
3836 break;
3837 }
3838
3839 /* we have 2-disk failure */
3840 BUG_ON(s->failed != 2);
3841 /* fall through */
3842 case check_state_compute_result:
3843 sh->check_state = check_state_idle;
3844
3845 /* check that a write has not made the stripe insync */
3846 if (test_bit(STRIPE_INSYNC, &sh->state))
3847 break;
3848
3849 /* now write out any block on a failed drive,
3850 * or P or Q if they were recomputed
3851 */
3852 BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3853 if (s->failed == 2) {
3854 dev = &sh->dev[s->failed_num[1]];
3855 s->locked++;
3856 set_bit(R5_LOCKED, &dev->flags);
3857 set_bit(R5_Wantwrite, &dev->flags);
3858 }
3859 if (s->failed >= 1) {
3860 dev = &sh->dev[s->failed_num[0]];
3861 s->locked++;
3862 set_bit(R5_LOCKED, &dev->flags);
3863 set_bit(R5_Wantwrite, &dev->flags);
3864 }
3865 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3866 dev = &sh->dev[pd_idx];
3867 s->locked++;
3868 set_bit(R5_LOCKED, &dev->flags);
3869 set_bit(R5_Wantwrite, &dev->flags);
3870 }
3871 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3872 dev = &sh->dev[qd_idx];
3873 s->locked++;
3874 set_bit(R5_LOCKED, &dev->flags);
3875 set_bit(R5_Wantwrite, &dev->flags);
3876 }
3877 clear_bit(STRIPE_DEGRADED, &sh->state);
3878
3879 set_bit(STRIPE_INSYNC, &sh->state);
3880 break;
3881 case check_state_run:
3882 case check_state_run_q:
3883 case check_state_run_pq:
3884 break; /* we will be called again upon completion */
3885 case check_state_check_result:
3886 sh->check_state = check_state_idle;
3887
3888 /* handle a successful check operation, if parity is correct
3889 * we are done. Otherwise update the mismatch count and repair
3890 * parity if !MD_RECOVERY_CHECK
3891 */
3892 if (sh->ops.zero_sum_result == 0) {
3893 /* both parities are correct */
3894 if (!s->failed)
3895 set_bit(STRIPE_INSYNC, &sh->state);
3896 else {
3897 /* in contrast to the raid5 case we can validate
3898 * parity, but still have a failure to write
3899 * back
3900 */
3901 sh->check_state = check_state_compute_result;
3902 /* Returning at this point means that we may go
3903 * off and bring p and/or q uptodate again so
3904 * we make sure to check zero_sum_result again
3905 * to verify if p or q need writeback
3906 */
3907 }
3908 } else {
3909 atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3910 if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3911 /* don't try to repair!! */
3912 set_bit(STRIPE_INSYNC, &sh->state);
3913 else {
3914 int *target = &sh->ops.target;
3915
3916 sh->ops.target = -1;
3917 sh->ops.target2 = -1;
3918 sh->check_state = check_state_compute_run;
3919 set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3920 set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3921 if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3922 set_bit(R5_Wantcompute,
3923 &sh->dev[pd_idx].flags);
3924 *target = pd_idx;
3925 target = &sh->ops.target2;
3926 s->uptodate++;
3927 }
3928 if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3929 set_bit(R5_Wantcompute,
3930 &sh->dev[qd_idx].flags);
3931 *target = qd_idx;
3932 s->uptodate++;
3933 }
3934 }
3935 }
3936 break;
3937 case check_state_compute_run:
3938 break;
3939 default:
3940 printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3941 __func__, sh->check_state,
3942 (unsigned long long) sh->sector);
3943 BUG();
3944 }
3945}
3946
3947static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3948{
3949 int i;
3950
3951 /* We have read all the blocks in this stripe and now we need to
3952 * copy some of them into a target stripe for expand.
3953 */
3954 struct dma_async_tx_descriptor *tx = NULL;
3955 BUG_ON(sh->batch_head);
3956 clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3957 for (i = 0; i < sh->disks; i++)
3958 if (i != sh->pd_idx && i != sh->qd_idx) {
3959 int dd_idx, j;
3960 struct stripe_head *sh2;
3961 struct async_submit_ctl submit;
3962
3963 sector_t bn = raid5_compute_blocknr(sh, i, 1);
3964 sector_t s = raid5_compute_sector(conf, bn, 0,
3965 &dd_idx, NULL);
3966 sh2 = raid5_get_active_stripe(conf, s, 0, 1, 1);
3967 if (sh2 == NULL)
3968 /* so far only the early blocks of this stripe
3969 * have been requested. When later blocks
3970 * get requested, we will try again
3971 */
3972 continue;
3973 if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3974 test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3975 /* must have already done this block */
3976 raid5_release_stripe(sh2);
3977 continue;
3978 }
3979
3980 /* place all the copies on one channel */
3981 init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3982 tx = async_memcpy(sh2->dev[dd_idx].page,
3983 sh->dev[i].page, 0, 0, STRIPE_SIZE,
3984 &submit);
3985
3986 set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3987 set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
3988 for (j = 0; j < conf->raid_disks; j++)
3989 if (j != sh2->pd_idx &&
3990 j != sh2->qd_idx &&
3991 !test_bit(R5_Expanded, &sh2->dev[j].flags))
3992 break;
3993 if (j == conf->raid_disks) {
3994 set_bit(STRIPE_EXPAND_READY, &sh2->state);
3995 set_bit(STRIPE_HANDLE, &sh2->state);
3996 }
3997 raid5_release_stripe(sh2);
3998
3999 }
4000 /* done submitting copies, wait for them to complete */
4001 async_tx_quiesce(&tx);
4002}
4003
4004/*
4005 * handle_stripe - do things to a stripe.
4006 *
4007 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
4008 * state of various bits to see what needs to be done.
4009 * Possible results:
4010 * return some read requests which now have data
4011 * return some write requests which are safely on storage
4012 * schedule a read on some buffers
4013 * schedule a write of some buffers
4014 * return confirmation of parity correctness
4015 *
4016 */
4017
4018static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
4019{
4020 struct r5conf *conf = sh->raid_conf;
4021 int disks = sh->disks;
4022 struct r5dev *dev;
4023 int i;
4024 int do_recovery = 0;
4025
4026 memset(s, 0, sizeof(*s));
4027
4028 s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state) && !sh->batch_head;
4029 s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state) && !sh->batch_head;
4030 s->failed_num[0] = -1;
4031 s->failed_num[1] = -1;
4032 s->log_failed = r5l_log_disk_error(conf);
4033
4034 /* Now to look around and see what can be done */
4035 rcu_read_lock();
4036 for (i=disks; i--; ) {
4037 struct md_rdev *rdev;
4038 sector_t first_bad;
4039 int bad_sectors;
4040 int is_bad = 0;
4041
4042 dev = &sh->dev[i];
4043
4044 pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
4045 i, dev->flags,
4046 dev->toread, dev->towrite, dev->written);
4047 /* maybe we can reply to a read
4048 *
4049 * new wantfill requests are only permitted while
4050 * ops_complete_biofill is guaranteed to be inactive
4051 */
4052 if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
4053 !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
4054 set_bit(R5_Wantfill, &dev->flags);
4055
4056 /* now count some things */
4057 if (test_bit(R5_LOCKED, &dev->flags))
4058 s->locked++;
4059 if (test_bit(R5_UPTODATE, &dev->flags))
4060 s->uptodate++;
4061 if (test_bit(R5_Wantcompute, &dev->flags)) {
4062 s->compute++;
4063 BUG_ON(s->compute > 2);
4064 }
4065
4066 if (test_bit(R5_Wantfill, &dev->flags))
4067 s->to_fill++;
4068 else if (dev->toread)
4069 s->to_read++;
4070 if (dev->towrite) {
4071 s->to_write++;
4072 if (!test_bit(R5_OVERWRITE, &dev->flags))
4073 s->non_overwrite++;
4074 }
4075 if (dev->written)
4076 s->written++;
4077 /* Prefer to use the replacement for reads, but only
4078 * if it is recovered enough and has no bad blocks.
4079 */
4080 rdev = rcu_dereference(conf->disks[i].replacement);
4081 if (rdev && !test_bit(Faulty, &rdev->flags) &&
4082 rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
4083 !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4084 &first_bad, &bad_sectors))
4085 set_bit(R5_ReadRepl, &dev->flags);
4086 else {
4087 if (rdev && !test_bit(Faulty, &rdev->flags))
4088 set_bit(R5_NeedReplace, &dev->flags);
4089 else
4090 clear_bit(R5_NeedReplace, &dev->flags);
4091 rdev = rcu_dereference(conf->disks[i].rdev);
4092 clear_bit(R5_ReadRepl, &dev->flags);
4093 }
4094 if (rdev && test_bit(Faulty, &rdev->flags))
4095 rdev = NULL;
4096 if (rdev) {
4097 is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
4098 &first_bad, &bad_sectors);
4099 if (s->blocked_rdev == NULL
4100 && (test_bit(Blocked, &rdev->flags)
4101 || is_bad < 0)) {
4102 if (is_bad < 0)
4103 set_bit(BlockedBadBlocks,
4104 &rdev->flags);
4105 s->blocked_rdev = rdev;
4106 atomic_inc(&rdev->nr_pending);
4107 }
4108 }
4109 clear_bit(R5_Insync, &dev->flags);
4110 if (!rdev)
4111 /* Not in-sync */;
4112 else if (is_bad) {
4113 /* also not in-sync */
4114 if (!test_bit(WriteErrorSeen, &rdev->flags) &&
4115 test_bit(R5_UPTODATE, &dev->flags)) {
4116 /* treat as in-sync, but with a read error
4117 * which we can now try to correct
4118 */
4119 set_bit(R5_Insync, &dev->flags);
4120 set_bit(R5_ReadError, &dev->flags);
4121 }
4122 } else if (test_bit(In_sync, &rdev->flags))
4123 set_bit(R5_Insync, &dev->flags);
4124 else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
4125 /* in sync if before recovery_offset */
4126 set_bit(R5_Insync, &dev->flags);
4127 else if (test_bit(R5_UPTODATE, &dev->flags) &&
4128 test_bit(R5_Expanded, &dev->flags))
4129 /* If we've reshaped into here, we assume it is Insync.
4130 * We will shortly update recovery_offset to make
4131 * it official.
4132 */
4133 set_bit(R5_Insync, &dev->flags);
4134
4135 if (test_bit(R5_WriteError, &dev->flags)) {
4136 /* This flag does not apply to '.replacement'
4137 * only to .rdev, so make sure to check that*/
4138 struct md_rdev *rdev2 = rcu_dereference(
4139 conf->disks[i].rdev);
4140 if (rdev2 == rdev)
4141 clear_bit(R5_Insync, &dev->flags);
4142 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4143 s->handle_bad_blocks = 1;
4144 atomic_inc(&rdev2->nr_pending);
4145 } else
4146 clear_bit(R5_WriteError, &dev->flags);
4147 }
4148 if (test_bit(R5_MadeGood, &dev->flags)) {
4149 /* This flag does not apply to '.replacement'
4150 * only to .rdev, so make sure to check that*/
4151 struct md_rdev *rdev2 = rcu_dereference(
4152 conf->disks[i].rdev);
4153 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4154 s->handle_bad_blocks = 1;
4155 atomic_inc(&rdev2->nr_pending);
4156 } else
4157 clear_bit(R5_MadeGood, &dev->flags);
4158 }
4159 if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
4160 struct md_rdev *rdev2 = rcu_dereference(
4161 conf->disks[i].replacement);
4162 if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
4163 s->handle_bad_blocks = 1;
4164 atomic_inc(&rdev2->nr_pending);
4165 } else
4166 clear_bit(R5_MadeGoodRepl, &dev->flags);
4167 }
4168 if (!test_bit(R5_Insync, &dev->flags)) {
4169 /* The ReadError flag will just be confusing now */
4170 clear_bit(R5_ReadError, &dev->flags);
4171 clear_bit(R5_ReWrite, &dev->flags);
4172 }
4173 if (test_bit(R5_ReadError, &dev->flags))
4174 clear_bit(R5_Insync, &dev->flags);
4175 if (!test_bit(R5_Insync, &dev->flags)) {
4176 if (s->failed < 2)
4177 s->failed_num[s->failed] = i;
4178 s->failed++;
4179 if (rdev && !test_bit(Faulty, &rdev->flags))
4180 do_recovery = 1;
4181 }
4182 }
4183 if (test_bit(STRIPE_SYNCING, &sh->state)) {
4184 /* If there is a failed device being replaced,
4185 * we must be recovering.
4186 * else if we are after recovery_cp, we must be syncing
4187 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
4188 * else we can only be replacing
4189 * sync and recovery both need to read all devices, and so
4190 * use the same flag.
4191 */
4192 if (do_recovery ||
4193 sh->sector >= conf->mddev->recovery_cp ||
4194 test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
4195 s->syncing = 1;
4196 else
4197 s->replacing = 1;
4198 }
4199 rcu_read_unlock();
4200}
4201
4202static int clear_batch_ready(struct stripe_head *sh)
4203{
4204 /* Return '1' if this is a member of batch, or
4205 * '0' if it is a lone stripe or a head which can now be
4206 * handled.
4207 */
4208 struct stripe_head *tmp;
4209 if (!test_and_clear_bit(STRIPE_BATCH_READY, &sh->state))
4210 return (sh->batch_head && sh->batch_head != sh);
4211 spin_lock(&sh->stripe_lock);
4212 if (!sh->batch_head) {
4213 spin_unlock(&sh->stripe_lock);
4214 return 0;
4215 }
4216
4217 /*
4218 * this stripe could be added to a batch list before we check
4219 * BATCH_READY, skips it
4220 */
4221 if (sh->batch_head != sh) {
4222 spin_unlock(&sh->stripe_lock);
4223 return 1;
4224 }
4225 spin_lock(&sh->batch_lock);
4226 list_for_each_entry(tmp, &sh->batch_list, batch_list)
4227 clear_bit(STRIPE_BATCH_READY, &tmp->state);
4228 spin_unlock(&sh->batch_lock);
4229 spin_unlock(&sh->stripe_lock);
4230
4231 /*
4232 * BATCH_READY is cleared, no new stripes can be added.
4233 * batch_list can be accessed without lock
4234 */
4235 return 0;
4236}
4237
4238static void break_stripe_batch_list(struct stripe_head *head_sh,
4239 unsigned long handle_flags)
4240{
4241 struct stripe_head *sh, *next;
4242 int i;
4243 int do_wakeup = 0;
4244
4245 list_for_each_entry_safe(sh, next, &head_sh->batch_list, batch_list) {
4246
4247 list_del_init(&sh->batch_list);
4248
4249 WARN_ON_ONCE(sh->state & ((1 << STRIPE_ACTIVE) |
4250 (1 << STRIPE_SYNCING) |
4251 (1 << STRIPE_REPLACED) |
4252 (1 << STRIPE_DELAYED) |
4253 (1 << STRIPE_BIT_DELAY) |
4254 (1 << STRIPE_FULL_WRITE) |
4255 (1 << STRIPE_BIOFILL_RUN) |
4256 (1 << STRIPE_COMPUTE_RUN) |
4257 (1 << STRIPE_OPS_REQ_PENDING) |
4258 (1 << STRIPE_DISCARD) |
4259 (1 << STRIPE_BATCH_READY) |
4260 (1 << STRIPE_BATCH_ERR) |
4261 (1 << STRIPE_BITMAP_PENDING)));
4262 WARN_ON_ONCE(head_sh->state & ((1 << STRIPE_DISCARD) |
4263 (1 << STRIPE_REPLACED)));
4264
4265 set_mask_bits(&sh->state, ~(STRIPE_EXPAND_SYNC_FLAGS |
4266 (1 << STRIPE_PREREAD_ACTIVE) |
4267 (1 << STRIPE_DEGRADED) |
4268 (1 << STRIPE_ON_UNPLUG_LIST)),
4269 head_sh->state & (1 << STRIPE_INSYNC));
4270
4271 sh->check_state = head_sh->check_state;
4272 sh->reconstruct_state = head_sh->reconstruct_state;
4273 for (i = 0; i < sh->disks; i++) {
4274 if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
4275 do_wakeup = 1;
4276 sh->dev[i].flags = head_sh->dev[i].flags &
4277 (~((1 << R5_WriteError) | (1 << R5_Overlap)));
4278 }
4279 spin_lock_irq(&sh->stripe_lock);
4280 sh->batch_head = NULL;
4281 spin_unlock_irq(&sh->stripe_lock);
4282 if (handle_flags == 0 ||
4283 sh->state & handle_flags)
4284 set_bit(STRIPE_HANDLE, &sh->state);
4285 raid5_release_stripe(sh);
4286 }
4287 spin_lock_irq(&head_sh->stripe_lock);
4288 head_sh->batch_head = NULL;
4289 spin_unlock_irq(&head_sh->stripe_lock);
4290 for (i = 0; i < head_sh->disks; i++)
4291 if (test_and_clear_bit(R5_Overlap, &head_sh->dev[i].flags))
4292 do_wakeup = 1;
4293 if (head_sh->state & handle_flags)
4294 set_bit(STRIPE_HANDLE, &head_sh->state);
4295
4296 if (do_wakeup)
4297 wake_up(&head_sh->raid_conf->wait_for_overlap);
4298}
4299
4300static void handle_stripe(struct stripe_head *sh)
4301{
4302 struct stripe_head_state s;
4303 struct r5conf *conf = sh->raid_conf;
4304 int i;
4305 int prexor;
4306 int disks = sh->disks;
4307 struct r5dev *pdev, *qdev;
4308
4309 clear_bit(STRIPE_HANDLE, &sh->state);
4310 if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
4311 /* already being handled, ensure it gets handled
4312 * again when current action finishes */
4313 set_bit(STRIPE_HANDLE, &sh->state);
4314 return;
4315 }
4316
4317 if (clear_batch_ready(sh) ) {
4318 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4319 return;
4320 }
4321
4322 if (test_and_clear_bit(STRIPE_BATCH_ERR, &sh->state))
4323 break_stripe_batch_list(sh, 0);
4324
4325 if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state) && !sh->batch_head) {
4326 spin_lock(&sh->stripe_lock);
4327 /* Cannot process 'sync' concurrently with 'discard' */
4328 if (!test_bit(STRIPE_DISCARD, &sh->state) &&
4329 test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
4330 set_bit(STRIPE_SYNCING, &sh->state);
4331 clear_bit(STRIPE_INSYNC, &sh->state);
4332 clear_bit(STRIPE_REPLACED, &sh->state);
4333 }
4334 spin_unlock(&sh->stripe_lock);
4335 }
4336 clear_bit(STRIPE_DELAYED, &sh->state);
4337
4338 pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
4339 "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
4340 (unsigned long long)sh->sector, sh->state,
4341 atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
4342 sh->check_state, sh->reconstruct_state);
4343
4344 analyse_stripe(sh, &s);
4345
4346 if (test_bit(STRIPE_LOG_TRAPPED, &sh->state))
4347 goto finish;
4348
4349 if (s.handle_bad_blocks) {
4350 set_bit(STRIPE_HANDLE, &sh->state);
4351 goto finish;
4352 }
4353
4354 if (unlikely(s.blocked_rdev)) {
4355 if (s.syncing || s.expanding || s.expanded ||
4356 s.replacing || s.to_write || s.written) {
4357 set_bit(STRIPE_HANDLE, &sh->state);
4358 goto finish;
4359 }
4360 /* There is nothing for the blocked_rdev to block */
4361 rdev_dec_pending(s.blocked_rdev, conf->mddev);
4362 s.blocked_rdev = NULL;
4363 }
4364
4365 if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
4366 set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
4367 set_bit(STRIPE_BIOFILL_RUN, &sh->state);
4368 }
4369
4370 pr_debug("locked=%d uptodate=%d to_read=%d"
4371 " to_write=%d failed=%d failed_num=%d,%d\n",
4372 s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
4373 s.failed_num[0], s.failed_num[1]);
4374 /* check if the array has lost more than max_degraded devices and,
4375 * if so, some requests might need to be failed.
4376 */
4377 if (s.failed > conf->max_degraded || s.log_failed) {
4378 sh->check_state = 0;
4379 sh->reconstruct_state = 0;
4380 break_stripe_batch_list(sh, 0);
4381 if (s.to_read+s.to_write+s.written)
4382 handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
4383 if (s.syncing + s.replacing)
4384 handle_failed_sync(conf, sh, &s);
4385 }
4386
4387 /* Now we check to see if any write operations have recently
4388 * completed
4389 */
4390 prexor = 0;
4391 if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
4392 prexor = 1;
4393 if (sh->reconstruct_state == reconstruct_state_drain_result ||
4394 sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
4395 sh->reconstruct_state = reconstruct_state_idle;
4396
4397 /* All the 'written' buffers and the parity block are ready to
4398 * be written back to disk
4399 */
4400 BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
4401 !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
4402 BUG_ON(sh->qd_idx >= 0 &&
4403 !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
4404 !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
4405 for (i = disks; i--; ) {
4406 struct r5dev *dev = &sh->dev[i];
4407 if (test_bit(R5_LOCKED, &dev->flags) &&
4408 (i == sh->pd_idx || i == sh->qd_idx ||
4409 dev->written)) {
4410 pr_debug("Writing block %d\n", i);
4411 set_bit(R5_Wantwrite, &dev->flags);
4412 if (prexor)
4413 continue;
4414 if (s.failed > 1)
4415 continue;
4416 if (!test_bit(R5_Insync, &dev->flags) ||
4417 ((i == sh->pd_idx || i == sh->qd_idx) &&
4418 s.failed == 0))
4419 set_bit(STRIPE_INSYNC, &sh->state);
4420 }
4421 }
4422 if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4423 s.dec_preread_active = 1;
4424 }
4425
4426 /*
4427 * might be able to return some write requests if the parity blocks
4428 * are safe, or on a failed drive
4429 */
4430 pdev = &sh->dev[sh->pd_idx];
4431 s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
4432 || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
4433 qdev = &sh->dev[sh->qd_idx];
4434 s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
4435 || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
4436 || conf->level < 6;
4437
4438 if (s.written &&
4439 (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
4440 && !test_bit(R5_LOCKED, &pdev->flags)
4441 && (test_bit(R5_UPTODATE, &pdev->flags) ||
4442 test_bit(R5_Discard, &pdev->flags))))) &&
4443 (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
4444 && !test_bit(R5_LOCKED, &qdev->flags)
4445 && (test_bit(R5_UPTODATE, &qdev->flags) ||
4446 test_bit(R5_Discard, &qdev->flags))))))
4447 handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
4448
4449 /* Now we might consider reading some blocks, either to check/generate
4450 * parity, or to satisfy requests
4451 * or to load a block that is being partially written.
4452 */
4453 if (s.to_read || s.non_overwrite
4454 || (conf->level == 6 && s.to_write && s.failed)
4455 || (s.syncing && (s.uptodate + s.compute < disks))
4456 || s.replacing
4457 || s.expanding)
4458 handle_stripe_fill(sh, &s, disks);
4459
4460 /* Now to consider new write requests and what else, if anything
4461 * should be read. We do not handle new writes when:
4462 * 1/ A 'write' operation (copy+xor) is already in flight.
4463 * 2/ A 'check' operation is in flight, as it may clobber the parity
4464 * block.
4465 */
4466 if (s.to_write && !sh->reconstruct_state && !sh->check_state)
4467 handle_stripe_dirtying(conf, sh, &s, disks);
4468
4469 /* maybe we need to check and possibly fix the parity for this stripe
4470 * Any reads will already have been scheduled, so we just see if enough
4471 * data is available. The parity check is held off while parity
4472 * dependent operations are in flight.
4473 */
4474 if (sh->check_state ||
4475 (s.syncing && s.locked == 0 &&
4476 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4477 !test_bit(STRIPE_INSYNC, &sh->state))) {
4478 if (conf->level == 6)
4479 handle_parity_checks6(conf, sh, &s, disks);
4480 else
4481 handle_parity_checks5(conf, sh, &s, disks);
4482 }
4483
4484 if ((s.replacing || s.syncing) && s.locked == 0
4485 && !test_bit(STRIPE_COMPUTE_RUN, &sh->state)
4486 && !test_bit(STRIPE_REPLACED, &sh->state)) {
4487 /* Write out to replacement devices where possible */
4488 for (i = 0; i < conf->raid_disks; i++)
4489 if (test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
4490 WARN_ON(!test_bit(R5_UPTODATE, &sh->dev[i].flags));
4491 set_bit(R5_WantReplace, &sh->dev[i].flags);
4492 set_bit(R5_LOCKED, &sh->dev[i].flags);
4493 s.locked++;
4494 }
4495 if (s.replacing)
4496 set_bit(STRIPE_INSYNC, &sh->state);
4497 set_bit(STRIPE_REPLACED, &sh->state);
4498 }
4499 if ((s.syncing || s.replacing) && s.locked == 0 &&
4500 !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
4501 test_bit(STRIPE_INSYNC, &sh->state)) {
4502 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4503 clear_bit(STRIPE_SYNCING, &sh->state);
4504 if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
4505 wake_up(&conf->wait_for_overlap);
4506 }
4507
4508 /* If the failed drives are just a ReadError, then we might need
4509 * to progress the repair/check process
4510 */
4511 if (s.failed <= conf->max_degraded && !conf->mddev->ro)
4512 for (i = 0; i < s.failed; i++) {
4513 struct r5dev *dev = &sh->dev[s.failed_num[i]];
4514 if (test_bit(R5_ReadError, &dev->flags)
4515 && !test_bit(R5_LOCKED, &dev->flags)
4516 && test_bit(R5_UPTODATE, &dev->flags)
4517 ) {
4518 if (!test_bit(R5_ReWrite, &dev->flags)) {
4519 set_bit(R5_Wantwrite, &dev->flags);
4520 set_bit(R5_ReWrite, &dev->flags);
4521 set_bit(R5_LOCKED, &dev->flags);
4522 s.locked++;
4523 } else {
4524 /* let's read it back */
4525 set_bit(R5_Wantread, &dev->flags);
4526 set_bit(R5_LOCKED, &dev->flags);
4527 s.locked++;
4528 }
4529 }
4530 }
4531
4532 /* Finish reconstruct operations initiated by the expansion process */
4533 if (sh->reconstruct_state == reconstruct_state_result) {
4534 struct stripe_head *sh_src
4535 = raid5_get_active_stripe(conf, sh->sector, 1, 1, 1);
4536 if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
4537 /* sh cannot be written until sh_src has been read.
4538 * so arrange for sh to be delayed a little
4539 */
4540 set_bit(STRIPE_DELAYED, &sh->state);
4541 set_bit(STRIPE_HANDLE, &sh->state);
4542 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
4543 &sh_src->state))
4544 atomic_inc(&conf->preread_active_stripes);
4545 raid5_release_stripe(sh_src);
4546 goto finish;
4547 }
4548 if (sh_src)
4549 raid5_release_stripe(sh_src);
4550
4551 sh->reconstruct_state = reconstruct_state_idle;
4552 clear_bit(STRIPE_EXPANDING, &sh->state);
4553 for (i = conf->raid_disks; i--; ) {
4554 set_bit(R5_Wantwrite, &sh->dev[i].flags);
4555 set_bit(R5_LOCKED, &sh->dev[i].flags);
4556 s.locked++;
4557 }
4558 }
4559
4560 if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
4561 !sh->reconstruct_state) {
4562 /* Need to write out all blocks after computing parity */
4563 sh->disks = conf->raid_disks;
4564 stripe_set_idx(sh->sector, conf, 0, sh);
4565 schedule_reconstruction(sh, &s, 1, 1);
4566 } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
4567 clear_bit(STRIPE_EXPAND_READY, &sh->state);
4568 atomic_dec(&conf->reshape_stripes);
4569 wake_up(&conf->wait_for_overlap);
4570 md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
4571 }
4572
4573 if (s.expanding && s.locked == 0 &&
4574 !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
4575 handle_stripe_expansion(conf, sh);
4576
4577finish:
4578 /* wait for this device to become unblocked */
4579 if (unlikely(s.blocked_rdev)) {
4580 if (conf->mddev->external)
4581 md_wait_for_blocked_rdev(s.blocked_rdev,
4582 conf->mddev);
4583 else
4584 /* Internal metadata will immediately
4585 * be written by raid5d, so we don't
4586 * need to wait here.
4587 */
4588 rdev_dec_pending(s.blocked_rdev,
4589 conf->mddev);
4590 }
4591
4592 if (s.handle_bad_blocks)
4593 for (i = disks; i--; ) {
4594 struct md_rdev *rdev;
4595 struct r5dev *dev = &sh->dev[i];
4596 if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
4597 /* We own a safe reference to the rdev */
4598 rdev = conf->disks[i].rdev;
4599 if (!rdev_set_badblocks(rdev, sh->sector,
4600 STRIPE_SECTORS, 0))
4601 md_error(conf->mddev, rdev);
4602 rdev_dec_pending(rdev, conf->mddev);
4603 }
4604 if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
4605 rdev = conf->disks[i].rdev;
4606 rdev_clear_badblocks(rdev, sh->sector,
4607 STRIPE_SECTORS, 0);
4608 rdev_dec_pending(rdev, conf->mddev);
4609 }
4610 if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
4611 rdev = conf->disks[i].replacement;
4612 if (!rdev)
4613 /* rdev have been moved down */
4614 rdev = conf->disks[i].rdev;
4615 rdev_clear_badblocks(rdev, sh->sector,
4616 STRIPE_SECTORS, 0);
4617 rdev_dec_pending(rdev, conf->mddev);
4618 }
4619 }
4620
4621 if (s.ops_request)
4622 raid_run_ops(sh, s.ops_request);
4623
4624 ops_run_io(sh, &s);
4625
4626 if (s.dec_preread_active) {
4627 /* We delay this until after ops_run_io so that if make_request
4628 * is waiting on a flush, it won't continue until the writes
4629 * have actually been submitted.
4630 */
4631 atomic_dec(&conf->preread_active_stripes);
4632 if (atomic_read(&conf->preread_active_stripes) <
4633 IO_THRESHOLD)
4634 md_wakeup_thread(conf->mddev->thread);
4635 }
4636
4637 if (!bio_list_empty(&s.return_bi)) {
4638 if (test_bit(MD_CHANGE_PENDING, &conf->mddev->flags)) {
4639 spin_lock_irq(&conf->device_lock);
4640 bio_list_merge(&conf->return_bi, &s.return_bi);
4641 spin_unlock_irq(&conf->device_lock);
4642 md_wakeup_thread(conf->mddev->thread);
4643 } else
4644 return_io(&s.return_bi);
4645 }
4646
4647 clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
4648}
4649
4650static void raid5_activate_delayed(struct r5conf *conf)
4651{
4652 if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
4653 while (!list_empty(&conf->delayed_list)) {
4654 struct list_head *l = conf->delayed_list.next;
4655 struct stripe_head *sh;
4656 sh = list_entry(l, struct stripe_head, lru);
4657 list_del_init(l);
4658 clear_bit(STRIPE_DELAYED, &sh->state);
4659 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4660 atomic_inc(&conf->preread_active_stripes);
4661 list_add_tail(&sh->lru, &conf->hold_list);
4662 raid5_wakeup_stripe_thread(sh);
4663 }
4664 }
4665}
4666
4667static void activate_bit_delay(struct r5conf *conf,
4668 struct list_head *temp_inactive_list)
4669{
4670 /* device_lock is held */
4671 struct list_head head;
4672 list_add(&head, &conf->bitmap_list);
4673 list_del_init(&conf->bitmap_list);
4674 while (!list_empty(&head)) {
4675 struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
4676 int hash;
4677 list_del_init(&sh->lru);
4678 atomic_inc(&sh->count);
4679 hash = sh->hash_lock_index;
4680 __release_stripe(conf, sh, &temp_inactive_list[hash]);
4681 }
4682}
4683
4684static int raid5_congested(struct mddev *mddev, int bits)
4685{
4686 struct r5conf *conf = mddev->private;
4687
4688 /* No difference between reads and writes. Just check
4689 * how busy the stripe_cache is
4690 */
4691
4692 if (test_bit(R5_INACTIVE_BLOCKED, &conf->cache_state))
4693 return 1;
4694 if (conf->quiesce)
4695 return 1;
4696 if (atomic_read(&conf->empty_inactive_list_nr))
4697 return 1;
4698
4699 return 0;
4700}
4701
4702static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
4703{
4704 struct r5conf *conf = mddev->private;
4705 sector_t sector = bio->bi_iter.bi_sector + get_start_sect(bio->bi_bdev);
4706 unsigned int chunk_sectors;
4707 unsigned int bio_sectors = bio_sectors(bio);
4708
4709 chunk_sectors = min(conf->chunk_sectors, conf->prev_chunk_sectors);
4710 return chunk_sectors >=
4711 ((sector & (chunk_sectors - 1)) + bio_sectors);
4712}
4713
4714/*
4715 * add bio to the retry LIFO ( in O(1) ... we are in interrupt )
4716 * later sampled by raid5d.
4717 */
4718static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
4719{
4720 unsigned long flags;
4721
4722 spin_lock_irqsave(&conf->device_lock, flags);
4723
4724 bi->bi_next = conf->retry_read_aligned_list;
4725 conf->retry_read_aligned_list = bi;
4726
4727 spin_unlock_irqrestore(&conf->device_lock, flags);
4728 md_wakeup_thread(conf->mddev->thread);
4729}
4730
4731static struct bio *remove_bio_from_retry(struct r5conf *conf)
4732{
4733 struct bio *bi;
4734
4735 bi = conf->retry_read_aligned;
4736 if (bi) {
4737 conf->retry_read_aligned = NULL;
4738 return bi;
4739 }
4740 bi = conf->retry_read_aligned_list;
4741 if(bi) {
4742 conf->retry_read_aligned_list = bi->bi_next;
4743 bi->bi_next = NULL;
4744 /*
4745 * this sets the active strip count to 1 and the processed
4746 * strip count to zero (upper 8 bits)
4747 */
4748 raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
4749 }
4750
4751 return bi;
4752}
4753
4754/*
4755 * The "raid5_align_endio" should check if the read succeeded and if it
4756 * did, call bio_endio on the original bio (having bio_put the new bio
4757 * first).
4758 * If the read failed..
4759 */
4760static void raid5_align_endio(struct bio *bi)
4761{
4762 struct bio* raid_bi = bi->bi_private;
4763 struct mddev *mddev;
4764 struct r5conf *conf;
4765 struct md_rdev *rdev;
4766 int error = bi->bi_error;
4767
4768 bio_put(bi);
4769
4770 rdev = (void*)raid_bi->bi_next;
4771 raid_bi->bi_next = NULL;
4772 mddev = rdev->mddev;
4773 conf = mddev->private;
4774
4775 rdev_dec_pending(rdev, conf->mddev);
4776
4777 if (!error) {
4778 trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
4779 raid_bi, 0);
4780 bio_endio(raid_bi);
4781 if (atomic_dec_and_test(&conf->active_aligned_reads))
4782 wake_up(&conf->wait_for_quiescent);
4783 return;
4784 }
4785
4786 pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
4787
4788 add_bio_to_retry(raid_bi, conf);
4789}
4790
4791static int raid5_read_one_chunk(struct mddev *mddev, struct bio *raid_bio)
4792{
4793 struct r5conf *conf = mddev->private;
4794 int dd_idx;
4795 struct bio* align_bi;
4796 struct md_rdev *rdev;
4797 sector_t end_sector;
4798
4799 if (!in_chunk_boundary(mddev, raid_bio)) {
4800 pr_debug("%s: non aligned\n", __func__);
4801 return 0;
4802 }
4803 /*
4804 * use bio_clone_mddev to make a copy of the bio
4805 */
4806 align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
4807 if (!align_bi)
4808 return 0;
4809 /*
4810 * set bi_end_io to a new function, and set bi_private to the
4811 * original bio.
4812 */
4813 align_bi->bi_end_io = raid5_align_endio;
4814 align_bi->bi_private = raid_bio;
4815 /*
4816 * compute position
4817 */
4818 align_bi->bi_iter.bi_sector =
4819 raid5_compute_sector(conf, raid_bio->bi_iter.bi_sector,
4820 0, &dd_idx, NULL);
4821
4822 end_sector = bio_end_sector(align_bi);
4823 rcu_read_lock();
4824 rdev = rcu_dereference(conf->disks[dd_idx].replacement);
4825 if (!rdev || test_bit(Faulty, &rdev->flags) ||
4826 rdev->recovery_offset < end_sector) {
4827 rdev = rcu_dereference(conf->disks[dd_idx].rdev);
4828 if (rdev &&
4829 (test_bit(Faulty, &rdev->flags) ||
4830 !(test_bit(In_sync, &rdev->flags) ||
4831 rdev->recovery_offset >= end_sector)))
4832 rdev = NULL;
4833 }
4834 if (rdev) {
4835 sector_t first_bad;
4836 int bad_sectors;
4837
4838 atomic_inc(&rdev->nr_pending);
4839 rcu_read_unlock();
4840 raid_bio->bi_next = (void*)rdev;
4841 align_bi->bi_bdev = rdev->bdev;
4842 bio_clear_flag(align_bi, BIO_SEG_VALID);
4843
4844 if (is_badblock(rdev, align_bi->bi_iter.bi_sector,
4845 bio_sectors(align_bi),
4846 &first_bad, &bad_sectors)) {
4847 bio_put(align_bi);
4848 rdev_dec_pending(rdev, mddev);
4849 return 0;
4850 }
4851
4852 /* No reshape active, so we can trust rdev->data_offset */
4853 align_bi->bi_iter.bi_sector += rdev->data_offset;
4854
4855 spin_lock_irq(&conf->device_lock);
4856 wait_event_lock_irq(conf->wait_for_quiescent,
4857 conf->quiesce == 0,
4858 conf->device_lock);
4859 atomic_inc(&conf->active_aligned_reads);
4860 spin_unlock_irq(&conf->device_lock);
4861
4862 if (mddev->gendisk)
4863 trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4864 align_bi, disk_devt(mddev->gendisk),
4865 raid_bio->bi_iter.bi_sector);
4866 generic_make_request(align_bi);
4867 return 1;
4868 } else {
4869 rcu_read_unlock();
4870 bio_put(align_bi);
4871 return 0;
4872 }
4873}
4874
4875static struct bio *chunk_aligned_read(struct mddev *mddev, struct bio *raid_bio)
4876{
4877 struct bio *split;
4878
4879 do {
4880 sector_t sector = raid_bio->bi_iter.bi_sector;
4881 unsigned chunk_sects = mddev->chunk_sectors;
4882 unsigned sectors = chunk_sects - (sector & (chunk_sects-1));
4883
4884 if (sectors < bio_sectors(raid_bio)) {
4885 split = bio_split(raid_bio, sectors, GFP_NOIO, fs_bio_set);
4886 bio_chain(split, raid_bio);
4887 } else
4888 split = raid_bio;
4889
4890 if (!raid5_read_one_chunk(mddev, split)) {
4891 if (split != raid_bio)
4892 generic_make_request(raid_bio);
4893 return split;
4894 }
4895 } while (split != raid_bio);
4896
4897 return NULL;
4898}
4899
4900/* __get_priority_stripe - get the next stripe to process
4901 *
4902 * Full stripe writes are allowed to pass preread active stripes up until
4903 * the bypass_threshold is exceeded. In general the bypass_count
4904 * increments when the handle_list is handled before the hold_list; however, it
4905 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4906 * stripe with in flight i/o. The bypass_count will be reset when the
4907 * head of the hold_list has changed, i.e. the head was promoted to the
4908 * handle_list.
4909 */
4910static struct stripe_head *__get_priority_stripe(struct r5conf *conf, int group)
4911{
4912 struct stripe_head *sh = NULL, *tmp;
4913 struct list_head *handle_list = NULL;
4914 struct r5worker_group *wg = NULL;
4915
4916 if (conf->worker_cnt_per_group == 0) {
4917 handle_list = &conf->handle_list;
4918 } else if (group != ANY_GROUP) {
4919 handle_list = &conf->worker_groups[group].handle_list;
4920 wg = &conf->worker_groups[group];
4921 } else {
4922 int i;
4923 for (i = 0; i < conf->group_cnt; i++) {
4924 handle_list = &conf->worker_groups[i].handle_list;
4925 wg = &conf->worker_groups[i];
4926 if (!list_empty(handle_list))
4927 break;
4928 }
4929 }
4930
4931 pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4932 __func__,
4933 list_empty(handle_list) ? "empty" : "busy",
4934 list_empty(&conf->hold_list) ? "empty" : "busy",
4935 atomic_read(&conf->pending_full_writes), conf->bypass_count);
4936
4937 if (!list_empty(handle_list)) {
4938 sh = list_entry(handle_list->next, typeof(*sh), lru);
4939
4940 if (list_empty(&conf->hold_list))
4941 conf->bypass_count = 0;
4942 else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4943 if (conf->hold_list.next == conf->last_hold)
4944 conf->bypass_count++;
4945 else {
4946 conf->last_hold = conf->hold_list.next;
4947 conf->bypass_count -= conf->bypass_threshold;
4948 if (conf->bypass_count < 0)
4949 conf->bypass_count = 0;
4950 }
4951 }
4952 } else if (!list_empty(&conf->hold_list) &&
4953 ((conf->bypass_threshold &&
4954 conf->bypass_count > conf->bypass_threshold) ||
4955 atomic_read(&conf->pending_full_writes) == 0)) {
4956
4957 list_for_each_entry(tmp, &conf->hold_list, lru) {
4958 if (conf->worker_cnt_per_group == 0 ||
4959 group == ANY_GROUP ||
4960 !cpu_online(tmp->cpu) ||
4961 cpu_to_group(tmp->cpu) == group) {
4962 sh = tmp;
4963 break;
4964 }
4965 }
4966
4967 if (sh) {
4968 conf->bypass_count -= conf->bypass_threshold;
4969 if (conf->bypass_count < 0)
4970 conf->bypass_count = 0;
4971 }
4972 wg = NULL;
4973 }
4974
4975 if (!sh)
4976 return NULL;
4977
4978 if (wg) {
4979 wg->stripes_cnt--;
4980 sh->group = NULL;
4981 }
4982 list_del_init(&sh->lru);
4983 BUG_ON(atomic_inc_return(&sh->count) != 1);
4984 return sh;
4985}
4986
4987struct raid5_plug_cb {
4988 struct blk_plug_cb cb;
4989 struct list_head list;
4990 struct list_head temp_inactive_list[NR_STRIPE_HASH_LOCKS];
4991};
4992
4993static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
4994{
4995 struct raid5_plug_cb *cb = container_of(
4996 blk_cb, struct raid5_plug_cb, cb);
4997 struct stripe_head *sh;
4998 struct mddev *mddev = cb->cb.data;
4999 struct r5conf *conf = mddev->private;
5000 int cnt = 0;
5001 int hash;
5002
5003 if (cb->list.next && !list_empty(&cb->list)) {
5004 spin_lock_irq(&conf->device_lock);
5005 while (!list_empty(&cb->list)) {
5006 sh = list_first_entry(&cb->list, struct stripe_head, lru);
5007 list_del_init(&sh->lru);
5008 /*
5009 * avoid race release_stripe_plug() sees
5010 * STRIPE_ON_UNPLUG_LIST clear but the stripe
5011 * is still in our list
5012 */
5013 smp_mb__before_atomic();
5014 clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
5015 /*
5016 * STRIPE_ON_RELEASE_LIST could be set here. In that
5017 * case, the count is always > 1 here
5018 */
5019 hash = sh->hash_lock_index;
5020 __release_stripe(conf, sh, &cb->temp_inactive_list[hash]);
5021 cnt++;
5022 }
5023 spin_unlock_irq(&conf->device_lock);
5024 }
5025 release_inactive_stripe_list(conf, cb->temp_inactive_list,
5026 NR_STRIPE_HASH_LOCKS);
5027 if (mddev->queue)
5028 trace_block_unplug(mddev->queue, cnt, !from_schedule);
5029 kfree(cb);
5030}
5031
5032static void release_stripe_plug(struct mddev *mddev,
5033 struct stripe_head *sh)
5034{
5035 struct blk_plug_cb *blk_cb = blk_check_plugged(
5036 raid5_unplug, mddev,
5037 sizeof(struct raid5_plug_cb));
5038 struct raid5_plug_cb *cb;
5039
5040 if (!blk_cb) {
5041 raid5_release_stripe(sh);
5042 return;
5043 }
5044
5045 cb = container_of(blk_cb, struct raid5_plug_cb, cb);
5046
5047 if (cb->list.next == NULL) {
5048 int i;
5049 INIT_LIST_HEAD(&cb->list);
5050 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5051 INIT_LIST_HEAD(cb->temp_inactive_list + i);
5052 }
5053
5054 if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
5055 list_add_tail(&sh->lru, &cb->list);
5056 else
5057 raid5_release_stripe(sh);
5058}
5059
5060static void make_discard_request(struct mddev *mddev, struct bio *bi)
5061{
5062 struct r5conf *conf = mddev->private;
5063 sector_t logical_sector, last_sector;
5064 struct stripe_head *sh;
5065 int remaining;
5066 int stripe_sectors;
5067
5068 if (mddev->reshape_position != MaxSector)
5069 /* Skip discard while reshape is happening */
5070 return;
5071
5072 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5073 last_sector = bi->bi_iter.bi_sector + (bi->bi_iter.bi_size>>9);
5074
5075 bi->bi_next = NULL;
5076 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5077
5078 stripe_sectors = conf->chunk_sectors *
5079 (conf->raid_disks - conf->max_degraded);
5080 logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
5081 stripe_sectors);
5082 sector_div(last_sector, stripe_sectors);
5083
5084 logical_sector *= conf->chunk_sectors;
5085 last_sector *= conf->chunk_sectors;
5086
5087 for (; logical_sector < last_sector;
5088 logical_sector += STRIPE_SECTORS) {
5089 DEFINE_WAIT(w);
5090 int d;
5091 again:
5092 sh = raid5_get_active_stripe(conf, logical_sector, 0, 0, 0);
5093 prepare_to_wait(&conf->wait_for_overlap, &w,
5094 TASK_UNINTERRUPTIBLE);
5095 set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5096 if (test_bit(STRIPE_SYNCING, &sh->state)) {
5097 raid5_release_stripe(sh);
5098 schedule();
5099 goto again;
5100 }
5101 clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
5102 spin_lock_irq(&sh->stripe_lock);
5103 for (d = 0; d < conf->raid_disks; d++) {
5104 if (d == sh->pd_idx || d == sh->qd_idx)
5105 continue;
5106 if (sh->dev[d].towrite || sh->dev[d].toread) {
5107 set_bit(R5_Overlap, &sh->dev[d].flags);
5108 spin_unlock_irq(&sh->stripe_lock);
5109 raid5_release_stripe(sh);
5110 schedule();
5111 goto again;
5112 }
5113 }
5114 set_bit(STRIPE_DISCARD, &sh->state);
5115 finish_wait(&conf->wait_for_overlap, &w);
5116 sh->overwrite_disks = 0;
5117 for (d = 0; d < conf->raid_disks; d++) {
5118 if (d == sh->pd_idx || d == sh->qd_idx)
5119 continue;
5120 sh->dev[d].towrite = bi;
5121 set_bit(R5_OVERWRITE, &sh->dev[d].flags);
5122 raid5_inc_bi_active_stripes(bi);
5123 sh->overwrite_disks++;
5124 }
5125 spin_unlock_irq(&sh->stripe_lock);
5126 if (conf->mddev->bitmap) {
5127 for (d = 0;
5128 d < conf->raid_disks - conf->max_degraded;
5129 d++)
5130 bitmap_startwrite(mddev->bitmap,
5131 sh->sector,
5132 STRIPE_SECTORS,
5133 0);
5134 sh->bm_seq = conf->seq_flush + 1;
5135 set_bit(STRIPE_BIT_DELAY, &sh->state);
5136 }
5137
5138 set_bit(STRIPE_HANDLE, &sh->state);
5139 clear_bit(STRIPE_DELAYED, &sh->state);
5140 if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5141 atomic_inc(&conf->preread_active_stripes);
5142 release_stripe_plug(mddev, sh);
5143 }
5144
5145 remaining = raid5_dec_bi_active_stripes(bi);
5146 if (remaining == 0) {
5147 md_write_end(mddev);
5148 bio_endio(bi);
5149 }
5150}
5151
5152static void make_request(struct mddev *mddev, struct bio * bi)
5153{
5154 struct r5conf *conf = mddev->private;
5155 int dd_idx;
5156 sector_t new_sector;
5157 sector_t logical_sector, last_sector;
5158 struct stripe_head *sh;
5159 const int rw = bio_data_dir(bi);
5160 int remaining;
5161 DEFINE_WAIT(w);
5162 bool do_prepare;
5163
5164 if (unlikely(bi->bi_rw & REQ_FLUSH)) {
5165 int ret = r5l_handle_flush_request(conf->log, bi);
5166
5167 if (ret == 0)
5168 return;
5169 if (ret == -ENODEV) {
5170 md_flush_request(mddev, bi);
5171 return;
5172 }
5173 /* ret == -EAGAIN, fallback */
5174 }
5175
5176 md_write_start(mddev, bi);
5177
5178 /*
5179 * If array is degraded, better not do chunk aligned read because
5180 * later we might have to read it again in order to reconstruct
5181 * data on failed drives.
5182 */
5183 if (rw == READ && mddev->degraded == 0 &&
5184 mddev->reshape_position == MaxSector) {
5185 bi = chunk_aligned_read(mddev, bi);
5186 if (!bi)
5187 return;
5188 }
5189
5190 if (unlikely(bi->bi_rw & REQ_DISCARD)) {
5191 make_discard_request(mddev, bi);
5192 return;
5193 }
5194
5195 logical_sector = bi->bi_iter.bi_sector & ~((sector_t)STRIPE_SECTORS-1);
5196 last_sector = bio_end_sector(bi);
5197 bi->bi_next = NULL;
5198 bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
5199
5200 prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
5201 for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
5202 int previous;
5203 int seq;
5204
5205 do_prepare = false;
5206 retry:
5207 seq = read_seqcount_begin(&conf->gen_lock);
5208 previous = 0;
5209 if (do_prepare)
5210 prepare_to_wait(&conf->wait_for_overlap, &w,
5211 TASK_UNINTERRUPTIBLE);
5212 if (unlikely(conf->reshape_progress != MaxSector)) {
5213 /* spinlock is needed as reshape_progress may be
5214 * 64bit on a 32bit platform, and so it might be
5215 * possible to see a half-updated value
5216 * Of course reshape_progress could change after
5217 * the lock is dropped, so once we get a reference
5218 * to the stripe that we think it is, we will have
5219 * to check again.
5220 */
5221 spin_lock_irq(&conf->device_lock);
5222 if (mddev->reshape_backwards
5223 ? logical_sector < conf->reshape_progress
5224 : logical_sector >= conf->reshape_progress) {
5225 previous = 1;
5226 } else {
5227 if (mddev->reshape_backwards
5228 ? logical_sector < conf->reshape_safe
5229 : logical_sector >= conf->reshape_safe) {
5230 spin_unlock_irq(&conf->device_lock);
5231 schedule();
5232 do_prepare = true;
5233 goto retry;
5234 }
5235 }
5236 spin_unlock_irq(&conf->device_lock);
5237 }
5238
5239 new_sector = raid5_compute_sector(conf, logical_sector,
5240 previous,
5241 &dd_idx, NULL);
5242 pr_debug("raid456: make_request, sector %llu logical %llu\n",
5243 (unsigned long long)new_sector,
5244 (unsigned long long)logical_sector);
5245
5246 sh = raid5_get_active_stripe(conf, new_sector, previous,
5247 (bi->bi_rw&RWA_MASK), 0);
5248 if (sh) {
5249 if (unlikely(previous)) {
5250 /* expansion might have moved on while waiting for a
5251 * stripe, so we must do the range check again.
5252 * Expansion could still move past after this
5253 * test, but as we are holding a reference to
5254 * 'sh', we know that if that happens,
5255 * STRIPE_EXPANDING will get set and the expansion
5256 * won't proceed until we finish with the stripe.
5257 */
5258 int must_retry = 0;
5259 spin_lock_irq(&conf->device_lock);
5260 if (mddev->reshape_backwards
5261 ? logical_sector >= conf->reshape_progress
5262 : logical_sector < conf->reshape_progress)
5263 /* mismatch, need to try again */
5264 must_retry = 1;
5265 spin_unlock_irq(&conf->device_lock);
5266 if (must_retry) {
5267 raid5_release_stripe(sh);
5268 schedule();
5269 do_prepare = true;
5270 goto retry;
5271 }
5272 }
5273 if (read_seqcount_retry(&conf->gen_lock, seq)) {
5274 /* Might have got the wrong stripe_head
5275 * by accident
5276 */
5277 raid5_release_stripe(sh);
5278 goto retry;
5279 }
5280
5281 if (rw == WRITE &&
5282 logical_sector >= mddev->suspend_lo &&
5283 logical_sector < mddev->suspend_hi) {
5284 raid5_release_stripe(sh);
5285 /* As the suspend_* range is controlled by
5286 * userspace, we want an interruptible
5287 * wait.
5288 */
5289 prepare_to_wait(&conf->wait_for_overlap,
5290 &w, TASK_INTERRUPTIBLE);
5291 if (logical_sector >= mddev->suspend_lo &&
5292 logical_sector < mddev->suspend_hi) {
5293 sigset_t full, old;
5294 sigfillset(&full);
5295 sigprocmask(SIG_BLOCK, &full, &old);
5296 schedule();
5297 sigprocmask(SIG_SETMASK, &old, NULL);
5298 do_prepare = true;
5299 }
5300 goto retry;
5301 }
5302
5303 if (test_bit(STRIPE_EXPANDING, &sh->state) ||
5304 !add_stripe_bio(sh, bi, dd_idx, rw, previous)) {
5305 /* Stripe is busy expanding or
5306 * add failed due to overlap. Flush everything
5307 * and wait a while
5308 */
5309 md_wakeup_thread(mddev->thread);
5310 raid5_release_stripe(sh);
5311 schedule();
5312 do_prepare = true;
5313 goto retry;
5314 }
5315 set_bit(STRIPE_HANDLE, &sh->state);
5316 clear_bit(STRIPE_DELAYED, &sh->state);
5317 if ((!sh->batch_head || sh == sh->batch_head) &&
5318 (bi->bi_rw & REQ_SYNC) &&
5319 !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
5320 atomic_inc(&conf->preread_active_stripes);
5321 release_stripe_plug(mddev, sh);
5322 } else {
5323 /* cannot get stripe for read-ahead, just give-up */
5324 bi->bi_error = -EIO;
5325 break;
5326 }
5327 }
5328 finish_wait(&conf->wait_for_overlap, &w);
5329
5330 remaining = raid5_dec_bi_active_stripes(bi);
5331 if (remaining == 0) {
5332
5333 if ( rw == WRITE )
5334 md_write_end(mddev);
5335
5336 trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
5337 bi, 0);
5338 bio_endio(bi);
5339 }
5340}
5341
5342static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
5343
5344static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5345{
5346 /* reshaping is quite different to recovery/resync so it is
5347 * handled quite separately ... here.
5348 *
5349 * On each call to sync_request, we gather one chunk worth of
5350 * destination stripes and flag them as expanding.
5351 * Then we find all the source stripes and request reads.
5352 * As the reads complete, handle_stripe will copy the data
5353 * into the destination stripe and release that stripe.
5354 */
5355 struct r5conf *conf = mddev->private;
5356 struct stripe_head *sh;
5357 sector_t first_sector, last_sector;
5358 int raid_disks = conf->previous_raid_disks;
5359 int data_disks = raid_disks - conf->max_degraded;
5360 int new_data_disks = conf->raid_disks - conf->max_degraded;
5361 int i;
5362 int dd_idx;
5363 sector_t writepos, readpos, safepos;
5364 sector_t stripe_addr;
5365 int reshape_sectors;
5366 struct list_head stripes;
5367 sector_t retn;
5368
5369 if (sector_nr == 0) {
5370 /* If restarting in the middle, skip the initial sectors */
5371 if (mddev->reshape_backwards &&
5372 conf->reshape_progress < raid5_size(mddev, 0, 0)) {
5373 sector_nr = raid5_size(mddev, 0, 0)
5374 - conf->reshape_progress;
5375 } else if (mddev->reshape_backwards &&
5376 conf->reshape_progress == MaxSector) {
5377 /* shouldn't happen, but just in case, finish up.*/
5378 sector_nr = MaxSector;
5379 } else if (!mddev->reshape_backwards &&
5380 conf->reshape_progress > 0)
5381 sector_nr = conf->reshape_progress;
5382 sector_div(sector_nr, new_data_disks);
5383 if (sector_nr) {
5384 mddev->curr_resync_completed = sector_nr;
5385 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5386 *skipped = 1;
5387 retn = sector_nr;
5388 goto finish;
5389 }
5390 }
5391
5392 /* We need to process a full chunk at a time.
5393 * If old and new chunk sizes differ, we need to process the
5394 * largest of these
5395 */
5396
5397 reshape_sectors = max(conf->chunk_sectors, conf->prev_chunk_sectors);
5398
5399 /* We update the metadata at least every 10 seconds, or when
5400 * the data about to be copied would over-write the source of
5401 * the data at the front of the range. i.e. one new_stripe
5402 * along from reshape_progress new_maps to after where
5403 * reshape_safe old_maps to
5404 */
5405 writepos = conf->reshape_progress;
5406 sector_div(writepos, new_data_disks);
5407 readpos = conf->reshape_progress;
5408 sector_div(readpos, data_disks);
5409 safepos = conf->reshape_safe;
5410 sector_div(safepos, data_disks);
5411 if (mddev->reshape_backwards) {
5412 BUG_ON(writepos < reshape_sectors);
5413 writepos -= reshape_sectors;
5414 readpos += reshape_sectors;
5415 safepos += reshape_sectors;
5416 } else {
5417 writepos += reshape_sectors;
5418 /* readpos and safepos are worst-case calculations.
5419 * A negative number is overly pessimistic, and causes
5420 * obvious problems for unsigned storage. So clip to 0.
5421 */
5422 readpos -= min_t(sector_t, reshape_sectors, readpos);
5423 safepos -= min_t(sector_t, reshape_sectors, safepos);
5424 }
5425
5426 /* Having calculated the 'writepos' possibly use it
5427 * to set 'stripe_addr' which is where we will write to.
5428 */
5429 if (mddev->reshape_backwards) {
5430 BUG_ON(conf->reshape_progress == 0);
5431 stripe_addr = writepos;
5432 BUG_ON((mddev->dev_sectors &
5433 ~((sector_t)reshape_sectors - 1))
5434 - reshape_sectors - stripe_addr
5435 != sector_nr);
5436 } else {
5437 BUG_ON(writepos != sector_nr + reshape_sectors);
5438 stripe_addr = sector_nr;
5439 }
5440
5441 /* 'writepos' is the most advanced device address we might write.
5442 * 'readpos' is the least advanced device address we might read.
5443 * 'safepos' is the least address recorded in the metadata as having
5444 * been reshaped.
5445 * If there is a min_offset_diff, these are adjusted either by
5446 * increasing the safepos/readpos if diff is negative, or
5447 * increasing writepos if diff is positive.
5448 * If 'readpos' is then behind 'writepos', there is no way that we can
5449 * ensure safety in the face of a crash - that must be done by userspace
5450 * making a backup of the data. So in that case there is no particular
5451 * rush to update metadata.
5452 * Otherwise if 'safepos' is behind 'writepos', then we really need to
5453 * update the metadata to advance 'safepos' to match 'readpos' so that
5454 * we can be safe in the event of a crash.
5455 * So we insist on updating metadata if safepos is behind writepos and
5456 * readpos is beyond writepos.
5457 * In any case, update the metadata every 10 seconds.
5458 * Maybe that number should be configurable, but I'm not sure it is
5459 * worth it.... maybe it could be a multiple of safemode_delay???
5460 */
5461 if (conf->min_offset_diff < 0) {
5462 safepos += -conf->min_offset_diff;
5463 readpos += -conf->min_offset_diff;
5464 } else
5465 writepos += conf->min_offset_diff;
5466
5467 if ((mddev->reshape_backwards
5468 ? (safepos > writepos && readpos < writepos)
5469 : (safepos < writepos && readpos > writepos)) ||
5470 time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
5471 /* Cannot proceed until we've updated the superblock... */
5472 wait_event(conf->wait_for_overlap,
5473 atomic_read(&conf->reshape_stripes)==0
5474 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5475 if (atomic_read(&conf->reshape_stripes) != 0)
5476 return 0;
5477 mddev->reshape_position = conf->reshape_progress;
5478 mddev->curr_resync_completed = sector_nr;
5479 conf->reshape_checkpoint = jiffies;
5480 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5481 md_wakeup_thread(mddev->thread);
5482 wait_event(mddev->sb_wait, mddev->flags == 0 ||
5483 test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5484 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5485 return 0;
5486 spin_lock_irq(&conf->device_lock);
5487 conf->reshape_safe = mddev->reshape_position;
5488 spin_unlock_irq(&conf->device_lock);
5489 wake_up(&conf->wait_for_overlap);
5490 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5491 }
5492
5493 INIT_LIST_HEAD(&stripes);
5494 for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
5495 int j;
5496 int skipped_disk = 0;
5497 sh = raid5_get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
5498 set_bit(STRIPE_EXPANDING, &sh->state);
5499 atomic_inc(&conf->reshape_stripes);
5500 /* If any of this stripe is beyond the end of the old
5501 * array, then we need to zero those blocks
5502 */
5503 for (j=sh->disks; j--;) {
5504 sector_t s;
5505 if (j == sh->pd_idx)
5506 continue;
5507 if (conf->level == 6 &&
5508 j == sh->qd_idx)
5509 continue;
5510 s = raid5_compute_blocknr(sh, j, 0);
5511 if (s < raid5_size(mddev, 0, 0)) {
5512 skipped_disk = 1;
5513 continue;
5514 }
5515 memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
5516 set_bit(R5_Expanded, &sh->dev[j].flags);
5517 set_bit(R5_UPTODATE, &sh->dev[j].flags);
5518 }
5519 if (!skipped_disk) {
5520 set_bit(STRIPE_EXPAND_READY, &sh->state);
5521 set_bit(STRIPE_HANDLE, &sh->state);
5522 }
5523 list_add(&sh->lru, &stripes);
5524 }
5525 spin_lock_irq(&conf->device_lock);
5526 if (mddev->reshape_backwards)
5527 conf->reshape_progress -= reshape_sectors * new_data_disks;
5528 else
5529 conf->reshape_progress += reshape_sectors * new_data_disks;
5530 spin_unlock_irq(&conf->device_lock);
5531 /* Ok, those stripe are ready. We can start scheduling
5532 * reads on the source stripes.
5533 * The source stripes are determined by mapping the first and last
5534 * block on the destination stripes.
5535 */
5536 first_sector =
5537 raid5_compute_sector(conf, stripe_addr*(new_data_disks),
5538 1, &dd_idx, NULL);
5539 last_sector =
5540 raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
5541 * new_data_disks - 1),
5542 1, &dd_idx, NULL);
5543 if (last_sector >= mddev->dev_sectors)
5544 last_sector = mddev->dev_sectors - 1;
5545 while (first_sector <= last_sector) {
5546 sh = raid5_get_active_stripe(conf, first_sector, 1, 0, 1);
5547 set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
5548 set_bit(STRIPE_HANDLE, &sh->state);
5549 raid5_release_stripe(sh);
5550 first_sector += STRIPE_SECTORS;
5551 }
5552 /* Now that the sources are clearly marked, we can release
5553 * the destination stripes
5554 */
5555 while (!list_empty(&stripes)) {
5556 sh = list_entry(stripes.next, struct stripe_head, lru);
5557 list_del_init(&sh->lru);
5558 raid5_release_stripe(sh);
5559 }
5560 /* If this takes us to the resync_max point where we have to pause,
5561 * then we need to write out the superblock.
5562 */
5563 sector_nr += reshape_sectors;
5564 retn = reshape_sectors;
5565finish:
5566 if (mddev->curr_resync_completed > mddev->resync_max ||
5567 (sector_nr - mddev->curr_resync_completed) * 2
5568 >= mddev->resync_max - mddev->curr_resync_completed) {
5569 /* Cannot proceed until we've updated the superblock... */
5570 wait_event(conf->wait_for_overlap,
5571 atomic_read(&conf->reshape_stripes) == 0
5572 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5573 if (atomic_read(&conf->reshape_stripes) != 0)
5574 goto ret;
5575 mddev->reshape_position = conf->reshape_progress;
5576 mddev->curr_resync_completed = sector_nr;
5577 conf->reshape_checkpoint = jiffies;
5578 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5579 md_wakeup_thread(mddev->thread);
5580 wait_event(mddev->sb_wait,
5581 !test_bit(MD_CHANGE_DEVS, &mddev->flags)
5582 || test_bit(MD_RECOVERY_INTR, &mddev->recovery));
5583 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
5584 goto ret;
5585 spin_lock_irq(&conf->device_lock);
5586 conf->reshape_safe = mddev->reshape_position;
5587 spin_unlock_irq(&conf->device_lock);
5588 wake_up(&conf->wait_for_overlap);
5589 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
5590 }
5591ret:
5592 return retn;
5593}
5594
5595static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
5596{
5597 struct r5conf *conf = mddev->private;
5598 struct stripe_head *sh;
5599 sector_t max_sector = mddev->dev_sectors;
5600 sector_t sync_blocks;
5601 int still_degraded = 0;
5602 int i;
5603
5604 if (sector_nr >= max_sector) {
5605 /* just being told to finish up .. nothing much to do */
5606
5607 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
5608 end_reshape(conf);
5609 return 0;
5610 }
5611
5612 if (mddev->curr_resync < max_sector) /* aborted */
5613 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
5614 &sync_blocks, 1);
5615 else /* completed sync */
5616 conf->fullsync = 0;
5617 bitmap_close_sync(mddev->bitmap);
5618
5619 return 0;
5620 }
5621
5622 /* Allow raid5_quiesce to complete */
5623 wait_event(conf->wait_for_overlap, conf->quiesce != 2);
5624
5625 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
5626 return reshape_request(mddev, sector_nr, skipped);
5627
5628 /* No need to check resync_max as we never do more than one
5629 * stripe, and as resync_max will always be on a chunk boundary,
5630 * if the check in md_do_sync didn't fire, there is no chance
5631 * of overstepping resync_max here
5632 */
5633
5634 /* if there is too many failed drives and we are trying
5635 * to resync, then assert that we are finished, because there is
5636 * nothing we can do.
5637 */
5638 if (mddev->degraded >= conf->max_degraded &&
5639 test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
5640 sector_t rv = mddev->dev_sectors - sector_nr;
5641 *skipped = 1;
5642 return rv;
5643 }
5644 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
5645 !conf->fullsync &&
5646 !bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
5647 sync_blocks >= STRIPE_SECTORS) {
5648 /* we can skip this block, and probably more */
5649 sync_blocks /= STRIPE_SECTORS;
5650 *skipped = 1;
5651 return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
5652 }
5653
5654 bitmap_cond_end_sync(mddev->bitmap, sector_nr, false);
5655
5656 sh = raid5_get_active_stripe(conf, sector_nr, 0, 1, 0);
5657 if (sh == NULL) {
5658 sh = raid5_get_active_stripe(conf, sector_nr, 0, 0, 0);
5659 /* make sure we don't swamp the stripe cache if someone else
5660 * is trying to get access
5661 */
5662 schedule_timeout_uninterruptible(1);
5663 }
5664 /* Need to check if array will still be degraded after recovery/resync
5665 * Note in case of > 1 drive failures it's possible we're rebuilding
5666 * one drive while leaving another faulty drive in array.
5667 */
5668 rcu_read_lock();
5669 for (i = 0; i < conf->raid_disks; i++) {
5670 struct md_rdev *rdev = ACCESS_ONCE(conf->disks[i].rdev);
5671
5672 if (rdev == NULL || test_bit(Faulty, &rdev->flags))
5673 still_degraded = 1;
5674 }
5675 rcu_read_unlock();
5676
5677 bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
5678
5679 set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
5680 set_bit(STRIPE_HANDLE, &sh->state);
5681
5682 raid5_release_stripe(sh);
5683
5684 return STRIPE_SECTORS;
5685}
5686
5687static int retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
5688{
5689 /* We may not be able to submit a whole bio at once as there
5690 * may not be enough stripe_heads available.
5691 * We cannot pre-allocate enough stripe_heads as we may need
5692 * more than exist in the cache (if we allow ever large chunks).
5693 * So we do one stripe head at a time and record in
5694 * ->bi_hw_segments how many have been done.
5695 *
5696 * We *know* that this entire raid_bio is in one chunk, so
5697 * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
5698 */
5699 struct stripe_head *sh;
5700 int dd_idx;
5701 sector_t sector, logical_sector, last_sector;
5702 int scnt = 0;
5703 int remaining;
5704 int handled = 0;
5705
5706 logical_sector = raid_bio->bi_iter.bi_sector &
5707 ~((sector_t)STRIPE_SECTORS-1);
5708 sector = raid5_compute_sector(conf, logical_sector,
5709 0, &dd_idx, NULL);
5710 last_sector = bio_end_sector(raid_bio);
5711
5712 for (; logical_sector < last_sector;
5713 logical_sector += STRIPE_SECTORS,
5714 sector += STRIPE_SECTORS,
5715 scnt++) {
5716
5717 if (scnt < raid5_bi_processed_stripes(raid_bio))
5718 /* already done this stripe */
5719 continue;
5720
5721 sh = raid5_get_active_stripe(conf, sector, 0, 1, 1);
5722
5723 if (!sh) {
5724 /* failed to get a stripe - must wait */
5725 raid5_set_bi_processed_stripes(raid_bio, scnt);
5726 conf->retry_read_aligned = raid_bio;
5727 return handled;
5728 }
5729
5730 if (!add_stripe_bio(sh, raid_bio, dd_idx, 0, 0)) {
5731 raid5_release_stripe(sh);
5732 raid5_set_bi_processed_stripes(raid_bio, scnt);
5733 conf->retry_read_aligned = raid_bio;
5734 return handled;
5735 }
5736
5737 set_bit(R5_ReadNoMerge, &sh->dev[dd_idx].flags);
5738 handle_stripe(sh);
5739 raid5_release_stripe(sh);
5740 handled++;
5741 }
5742 remaining = raid5_dec_bi_active_stripes(raid_bio);
5743 if (remaining == 0) {
5744 trace_block_bio_complete(bdev_get_queue(raid_bio->bi_bdev),
5745 raid_bio, 0);
5746 bio_endio(raid_bio);
5747 }
5748 if (atomic_dec_and_test(&conf->active_aligned_reads))
5749 wake_up(&conf->wait_for_quiescent);
5750 return handled;
5751}
5752
5753static int handle_active_stripes(struct r5conf *conf, int group,
5754 struct r5worker *worker,
5755 struct list_head *temp_inactive_list)
5756{
5757 struct stripe_head *batch[MAX_STRIPE_BATCH], *sh;
5758 int i, batch_size = 0, hash;
5759 bool release_inactive = false;
5760
5761 while (batch_size < MAX_STRIPE_BATCH &&
5762 (sh = __get_priority_stripe(conf, group)) != NULL)
5763 batch[batch_size++] = sh;
5764
5765 if (batch_size == 0) {
5766 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
5767 if (!list_empty(temp_inactive_list + i))
5768 break;
5769 if (i == NR_STRIPE_HASH_LOCKS) {
5770 spin_unlock_irq(&conf->device_lock);
5771 r5l_flush_stripe_to_raid(conf->log);
5772 spin_lock_irq(&conf->device_lock);
5773 return batch_size;
5774 }
5775 release_inactive = true;
5776 }
5777 spin_unlock_irq(&conf->device_lock);
5778
5779 release_inactive_stripe_list(conf, temp_inactive_list,
5780 NR_STRIPE_HASH_LOCKS);
5781
5782 r5l_flush_stripe_to_raid(conf->log);
5783 if (release_inactive) {
5784 spin_lock_irq(&conf->device_lock);
5785 return 0;
5786 }
5787
5788 for (i = 0; i < batch_size; i++)
5789 handle_stripe(batch[i]);
5790 r5l_write_stripe_run(conf->log);
5791
5792 cond_resched();
5793
5794 spin_lock_irq(&conf->device_lock);
5795 for (i = 0; i < batch_size; i++) {
5796 hash = batch[i]->hash_lock_index;
5797 __release_stripe(conf, batch[i], &temp_inactive_list[hash]);
5798 }
5799 return batch_size;
5800}
5801
5802static void raid5_do_work(struct work_struct *work)
5803{
5804 struct r5worker *worker = container_of(work, struct r5worker, work);
5805 struct r5worker_group *group = worker->group;
5806 struct r5conf *conf = group->conf;
5807 int group_id = group - conf->worker_groups;
5808 int handled;
5809 struct blk_plug plug;
5810
5811 pr_debug("+++ raid5worker active\n");
5812
5813 blk_start_plug(&plug);
5814 handled = 0;
5815 spin_lock_irq(&conf->device_lock);
5816 while (1) {
5817 int batch_size, released;
5818
5819 released = release_stripe_list(conf, worker->temp_inactive_list);
5820
5821 batch_size = handle_active_stripes(conf, group_id, worker,
5822 worker->temp_inactive_list);
5823 worker->working = false;
5824 if (!batch_size && !released)
5825 break;
5826 handled += batch_size;
5827 }
5828 pr_debug("%d stripes handled\n", handled);
5829
5830 spin_unlock_irq(&conf->device_lock);
5831
5832 r5l_flush_stripe_to_raid(conf->log);
5833
5834 async_tx_issue_pending_all();
5835 blk_finish_plug(&plug);
5836
5837 pr_debug("--- raid5worker inactive\n");
5838}
5839
5840/*
5841 * This is our raid5 kernel thread.
5842 *
5843 * We scan the hash table for stripes which can be handled now.
5844 * During the scan, completed stripes are saved for us by the interrupt
5845 * handler, so that they will not have to wait for our next wakeup.
5846 */
5847static void raid5d(struct md_thread *thread)
5848{
5849 struct mddev *mddev = thread->mddev;
5850 struct r5conf *conf = mddev->private;
5851 int handled;
5852 struct blk_plug plug;
5853
5854 pr_debug("+++ raid5d active\n");
5855
5856 md_check_recovery(mddev);
5857
5858 if (!bio_list_empty(&conf->return_bi) &&
5859 !test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5860 struct bio_list tmp = BIO_EMPTY_LIST;
5861 spin_lock_irq(&conf->device_lock);
5862 if (!test_bit(MD_CHANGE_PENDING, &mddev->flags)) {
5863 bio_list_merge(&tmp, &conf->return_bi);
5864 bio_list_init(&conf->return_bi);
5865 }
5866 spin_unlock_irq(&conf->device_lock);
5867 return_io(&tmp);
5868 }
5869
5870 blk_start_plug(&plug);
5871 handled = 0;
5872 spin_lock_irq(&conf->device_lock);
5873 while (1) {
5874 struct bio *bio;
5875 int batch_size, released;
5876
5877 released = release_stripe_list(conf, conf->temp_inactive_list);
5878 if (released)
5879 clear_bit(R5_DID_ALLOC, &conf->cache_state);
5880
5881 if (
5882 !list_empty(&conf->bitmap_list)) {
5883 /* Now is a good time to flush some bitmap updates */
5884 conf->seq_flush++;
5885 spin_unlock_irq(&conf->device_lock);
5886 bitmap_unplug(mddev->bitmap);
5887 spin_lock_irq(&conf->device_lock);
5888 conf->seq_write = conf->seq_flush;
5889 activate_bit_delay(conf, conf->temp_inactive_list);
5890 }
5891 raid5_activate_delayed(conf);
5892
5893 while ((bio = remove_bio_from_retry(conf))) {
5894 int ok;
5895 spin_unlock_irq(&conf->device_lock);
5896 ok = retry_aligned_read(conf, bio);
5897 spin_lock_irq(&conf->device_lock);
5898 if (!ok)
5899 break;
5900 handled++;
5901 }
5902
5903 batch_size = handle_active_stripes(conf, ANY_GROUP, NULL,
5904 conf->temp_inactive_list);
5905 if (!batch_size && !released)
5906 break;
5907 handled += batch_size;
5908
5909 if (mddev->flags & ~(1<<MD_CHANGE_PENDING)) {
5910 spin_unlock_irq(&conf->device_lock);
5911 md_check_recovery(mddev);
5912 spin_lock_irq(&conf->device_lock);
5913 }
5914 }
5915 pr_debug("%d stripes handled\n", handled);
5916
5917 spin_unlock_irq(&conf->device_lock);
5918 if (test_and_clear_bit(R5_ALLOC_MORE, &conf->cache_state) &&
5919 mutex_trylock(&conf->cache_size_mutex)) {
5920 grow_one_stripe(conf, __GFP_NOWARN);
5921 /* Set flag even if allocation failed. This helps
5922 * slow down allocation requests when mem is short
5923 */
5924 set_bit(R5_DID_ALLOC, &conf->cache_state);
5925 mutex_unlock(&conf->cache_size_mutex);
5926 }
5927
5928 r5l_flush_stripe_to_raid(conf->log);
5929
5930 async_tx_issue_pending_all();
5931 blk_finish_plug(&plug);
5932
5933 pr_debug("--- raid5d inactive\n");
5934}
5935
5936static ssize_t
5937raid5_show_stripe_cache_size(struct mddev *mddev, char *page)
5938{
5939 struct r5conf *conf;
5940 int ret = 0;
5941 spin_lock(&mddev->lock);
5942 conf = mddev->private;
5943 if (conf)
5944 ret = sprintf(page, "%d\n", conf->min_nr_stripes);
5945 spin_unlock(&mddev->lock);
5946 return ret;
5947}
5948
5949int
5950raid5_set_cache_size(struct mddev *mddev, int size)
5951{
5952 struct r5conf *conf = mddev->private;
5953 int err;
5954
5955 if (size <= 16 || size > 32768)
5956 return -EINVAL;
5957
5958 conf->min_nr_stripes = size;
5959 mutex_lock(&conf->cache_size_mutex);
5960 while (size < conf->max_nr_stripes &&
5961 drop_one_stripe(conf))
5962 ;
5963 mutex_unlock(&conf->cache_size_mutex);
5964
5965
5966 err = md_allow_write(mddev);
5967 if (err)
5968 return err;
5969
5970 mutex_lock(&conf->cache_size_mutex);
5971 while (size > conf->max_nr_stripes)
5972 if (!grow_one_stripe(conf, GFP_KERNEL))
5973 break;
5974 mutex_unlock(&conf->cache_size_mutex);
5975
5976 return 0;
5977}
5978EXPORT_SYMBOL(raid5_set_cache_size);
5979
5980static ssize_t
5981raid5_store_stripe_cache_size(struct mddev *mddev, const char *page, size_t len)
5982{
5983 struct r5conf *conf;
5984 unsigned long new;
5985 int err;
5986
5987 if (len >= PAGE_SIZE)
5988 return -EINVAL;
5989 if (kstrtoul(page, 10, &new))
5990 return -EINVAL;
5991 err = mddev_lock(mddev);
5992 if (err)
5993 return err;
5994 conf = mddev->private;
5995 if (!conf)
5996 err = -ENODEV;
5997 else
5998 err = raid5_set_cache_size(mddev, new);
5999 mddev_unlock(mddev);
6000
6001 return err ?: len;
6002}
6003
6004static struct md_sysfs_entry
6005raid5_stripecache_size = __ATTR(stripe_cache_size, S_IRUGO | S_IWUSR,
6006 raid5_show_stripe_cache_size,
6007 raid5_store_stripe_cache_size);
6008
6009static ssize_t
6010raid5_show_rmw_level(struct mddev *mddev, char *page)
6011{
6012 struct r5conf *conf = mddev->private;
6013 if (conf)
6014 return sprintf(page, "%d\n", conf->rmw_level);
6015 else
6016 return 0;
6017}
6018
6019static ssize_t
6020raid5_store_rmw_level(struct mddev *mddev, const char *page, size_t len)
6021{
6022 struct r5conf *conf = mddev->private;
6023 unsigned long new;
6024
6025 if (!conf)
6026 return -ENODEV;
6027
6028 if (len >= PAGE_SIZE)
6029 return -EINVAL;
6030
6031 if (kstrtoul(page, 10, &new))
6032 return -EINVAL;
6033
6034 if (new != PARITY_DISABLE_RMW && !raid6_call.xor_syndrome)
6035 return -EINVAL;
6036
6037 if (new != PARITY_DISABLE_RMW &&
6038 new != PARITY_ENABLE_RMW &&
6039 new != PARITY_PREFER_RMW)
6040 return -EINVAL;
6041
6042 conf->rmw_level = new;
6043 return len;
6044}
6045
6046static struct md_sysfs_entry
6047raid5_rmw_level = __ATTR(rmw_level, S_IRUGO | S_IWUSR,
6048 raid5_show_rmw_level,
6049 raid5_store_rmw_level);
6050
6051
6052static ssize_t
6053raid5_show_preread_threshold(struct mddev *mddev, char *page)
6054{
6055 struct r5conf *conf;
6056 int ret = 0;
6057 spin_lock(&mddev->lock);
6058 conf = mddev->private;
6059 if (conf)
6060 ret = sprintf(page, "%d\n", conf->bypass_threshold);
6061 spin_unlock(&mddev->lock);
6062 return ret;
6063}
6064
6065static ssize_t
6066raid5_store_preread_threshold(struct mddev *mddev, const char *page, size_t len)
6067{
6068 struct r5conf *conf;
6069 unsigned long new;
6070 int err;
6071
6072 if (len >= PAGE_SIZE)
6073 return -EINVAL;
6074 if (kstrtoul(page, 10, &new))
6075 return -EINVAL;
6076
6077 err = mddev_lock(mddev);
6078 if (err)
6079 return err;
6080 conf = mddev->private;
6081 if (!conf)
6082 err = -ENODEV;
6083 else if (new > conf->min_nr_stripes)
6084 err = -EINVAL;
6085 else
6086 conf->bypass_threshold = new;
6087 mddev_unlock(mddev);
6088 return err ?: len;
6089}
6090
6091static struct md_sysfs_entry
6092raid5_preread_bypass_threshold = __ATTR(preread_bypass_threshold,
6093 S_IRUGO | S_IWUSR,
6094 raid5_show_preread_threshold,
6095 raid5_store_preread_threshold);
6096
6097static ssize_t
6098raid5_show_skip_copy(struct mddev *mddev, char *page)
6099{
6100 struct r5conf *conf;
6101 int ret = 0;
6102 spin_lock(&mddev->lock);
6103 conf = mddev->private;
6104 if (conf)
6105 ret = sprintf(page, "%d\n", conf->skip_copy);
6106 spin_unlock(&mddev->lock);
6107 return ret;
6108}
6109
6110static ssize_t
6111raid5_store_skip_copy(struct mddev *mddev, const char *page, size_t len)
6112{
6113 struct r5conf *conf;
6114 unsigned long new;
6115 int err;
6116
6117 if (len >= PAGE_SIZE)
6118 return -EINVAL;
6119 if (kstrtoul(page, 10, &new))
6120 return -EINVAL;
6121 new = !!new;
6122
6123 err = mddev_lock(mddev);
6124 if (err)
6125 return err;
6126 conf = mddev->private;
6127 if (!conf)
6128 err = -ENODEV;
6129 else if (new != conf->skip_copy) {
6130 mddev_suspend(mddev);
6131 conf->skip_copy = new;
6132 if (new)
6133 mddev->queue->backing_dev_info.capabilities |=
6134 BDI_CAP_STABLE_WRITES;
6135 else
6136 mddev->queue->backing_dev_info.capabilities &=
6137 ~BDI_CAP_STABLE_WRITES;
6138 mddev_resume(mddev);
6139 }
6140 mddev_unlock(mddev);
6141 return err ?: len;
6142}
6143
6144static struct md_sysfs_entry
6145raid5_skip_copy = __ATTR(skip_copy, S_IRUGO | S_IWUSR,
6146 raid5_show_skip_copy,
6147 raid5_store_skip_copy);
6148
6149static ssize_t
6150stripe_cache_active_show(struct mddev *mddev, char *page)
6151{
6152 struct r5conf *conf = mddev->private;
6153 if (conf)
6154 return sprintf(page, "%d\n", atomic_read(&conf->active_stripes));
6155 else
6156 return 0;
6157}
6158
6159static struct md_sysfs_entry
6160raid5_stripecache_active = __ATTR_RO(stripe_cache_active);
6161
6162static ssize_t
6163raid5_show_group_thread_cnt(struct mddev *mddev, char *page)
6164{
6165 struct r5conf *conf;
6166 int ret = 0;
6167 spin_lock(&mddev->lock);
6168 conf = mddev->private;
6169 if (conf)
6170 ret = sprintf(page, "%d\n", conf->worker_cnt_per_group);
6171 spin_unlock(&mddev->lock);
6172 return ret;
6173}
6174
6175static int alloc_thread_groups(struct r5conf *conf, int cnt,
6176 int *group_cnt,
6177 int *worker_cnt_per_group,
6178 struct r5worker_group **worker_groups);
6179static ssize_t
6180raid5_store_group_thread_cnt(struct mddev *mddev, const char *page, size_t len)
6181{
6182 struct r5conf *conf;
6183 unsigned long new;
6184 int err;
6185 struct r5worker_group *new_groups, *old_groups;
6186 int group_cnt, worker_cnt_per_group;
6187
6188 if (len >= PAGE_SIZE)
6189 return -EINVAL;
6190 if (kstrtoul(page, 10, &new))
6191 return -EINVAL;
6192
6193 err = mddev_lock(mddev);
6194 if (err)
6195 return err;
6196 conf = mddev->private;
6197 if (!conf)
6198 err = -ENODEV;
6199 else if (new != conf->worker_cnt_per_group) {
6200 mddev_suspend(mddev);
6201
6202 old_groups = conf->worker_groups;
6203 if (old_groups)
6204 flush_workqueue(raid5_wq);
6205
6206 err = alloc_thread_groups(conf, new,
6207 &group_cnt, &worker_cnt_per_group,
6208 &new_groups);
6209 if (!err) {
6210 spin_lock_irq(&conf->device_lock);
6211 conf->group_cnt = group_cnt;
6212 conf->worker_cnt_per_group = worker_cnt_per_group;
6213 conf->worker_groups = new_groups;
6214 spin_unlock_irq(&conf->device_lock);
6215
6216 if (old_groups)
6217 kfree(old_groups[0].workers);
6218 kfree(old_groups);
6219 }
6220 mddev_resume(mddev);
6221 }
6222 mddev_unlock(mddev);
6223
6224 return err ?: len;
6225}
6226
6227static struct md_sysfs_entry
6228raid5_group_thread_cnt = __ATTR(group_thread_cnt, S_IRUGO | S_IWUSR,
6229 raid5_show_group_thread_cnt,
6230 raid5_store_group_thread_cnt);
6231
6232static struct attribute *raid5_attrs[] = {
6233 &raid5_stripecache_size.attr,
6234 &raid5_stripecache_active.attr,
6235 &raid5_preread_bypass_threshold.attr,
6236 &raid5_group_thread_cnt.attr,
6237 &raid5_skip_copy.attr,
6238 &raid5_rmw_level.attr,
6239 NULL,
6240};
6241static struct attribute_group raid5_attrs_group = {
6242 .name = NULL,
6243 .attrs = raid5_attrs,
6244};
6245
6246static int alloc_thread_groups(struct r5conf *conf, int cnt,
6247 int *group_cnt,
6248 int *worker_cnt_per_group,
6249 struct r5worker_group **worker_groups)
6250{
6251 int i, j, k;
6252 ssize_t size;
6253 struct r5worker *workers;
6254
6255 *worker_cnt_per_group = cnt;
6256 if (cnt == 0) {
6257 *group_cnt = 0;
6258 *worker_groups = NULL;
6259 return 0;
6260 }
6261 *group_cnt = num_possible_nodes();
6262 size = sizeof(struct r5worker) * cnt;
6263 workers = kzalloc(size * *group_cnt, GFP_NOIO);
6264 *worker_groups = kzalloc(sizeof(struct r5worker_group) *
6265 *group_cnt, GFP_NOIO);
6266 if (!*worker_groups || !workers) {
6267 kfree(workers);
6268 kfree(*worker_groups);
6269 return -ENOMEM;
6270 }
6271
6272 for (i = 0; i < *group_cnt; i++) {
6273 struct r5worker_group *group;
6274
6275 group = &(*worker_groups)[i];
6276 INIT_LIST_HEAD(&group->handle_list);
6277 group->conf = conf;
6278 group->workers = workers + i * cnt;
6279
6280 for (j = 0; j < cnt; j++) {
6281 struct r5worker *worker = group->workers + j;
6282 worker->group = group;
6283 INIT_WORK(&worker->work, raid5_do_work);
6284
6285 for (k = 0; k < NR_STRIPE_HASH_LOCKS; k++)
6286 INIT_LIST_HEAD(worker->temp_inactive_list + k);
6287 }
6288 }
6289
6290 return 0;
6291}
6292
6293static void free_thread_groups(struct r5conf *conf)
6294{
6295 if (conf->worker_groups)
6296 kfree(conf->worker_groups[0].workers);
6297 kfree(conf->worker_groups);
6298 conf->worker_groups = NULL;
6299}
6300
6301static sector_t
6302raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks)
6303{
6304 struct r5conf *conf = mddev->private;
6305
6306 if (!sectors)
6307 sectors = mddev->dev_sectors;
6308 if (!raid_disks)
6309 /* size is defined by the smallest of previous and new size */
6310 raid_disks = min(conf->raid_disks, conf->previous_raid_disks);
6311
6312 sectors &= ~((sector_t)conf->chunk_sectors - 1);
6313 sectors &= ~((sector_t)conf->prev_chunk_sectors - 1);
6314 return sectors * (raid_disks - conf->max_degraded);
6315}
6316
6317static void free_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6318{
6319 safe_put_page(percpu->spare_page);
6320 if (percpu->scribble)
6321 flex_array_free(percpu->scribble);
6322 percpu->spare_page = NULL;
6323 percpu->scribble = NULL;
6324}
6325
6326static int alloc_scratch_buffer(struct r5conf *conf, struct raid5_percpu *percpu)
6327{
6328 if (conf->level == 6 && !percpu->spare_page)
6329 percpu->spare_page = alloc_page(GFP_KERNEL);
6330 if (!percpu->scribble)
6331 percpu->scribble = scribble_alloc(max(conf->raid_disks,
6332 conf->previous_raid_disks),
6333 max(conf->chunk_sectors,
6334 conf->prev_chunk_sectors)
6335 / STRIPE_SECTORS,
6336 GFP_KERNEL);
6337
6338 if (!percpu->scribble || (conf->level == 6 && !percpu->spare_page)) {
6339 free_scratch_buffer(conf, percpu);
6340 return -ENOMEM;
6341 }
6342
6343 return 0;
6344}
6345
6346static void raid5_free_percpu(struct r5conf *conf)
6347{
6348 unsigned long cpu;
6349
6350 if (!conf->percpu)
6351 return;
6352
6353#ifdef CONFIG_HOTPLUG_CPU
6354 unregister_cpu_notifier(&conf->cpu_notify);
6355#endif
6356
6357 get_online_cpus();
6358 for_each_possible_cpu(cpu)
6359 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6360 put_online_cpus();
6361
6362 free_percpu(conf->percpu);
6363}
6364
6365static void free_conf(struct r5conf *conf)
6366{
6367 if (conf->log)
6368 r5l_exit_log(conf->log);
6369 if (conf->shrinker.seeks)
6370 unregister_shrinker(&conf->shrinker);
6371
6372 free_thread_groups(conf);
6373 shrink_stripes(conf);
6374 raid5_free_percpu(conf);
6375 kfree(conf->disks);
6376 kfree(conf->stripe_hashtbl);
6377 kfree(conf);
6378}
6379
6380#ifdef CONFIG_HOTPLUG_CPU
6381static int raid456_cpu_notify(struct notifier_block *nfb, unsigned long action,
6382 void *hcpu)
6383{
6384 struct r5conf *conf = container_of(nfb, struct r5conf, cpu_notify);
6385 long cpu = (long)hcpu;
6386 struct raid5_percpu *percpu = per_cpu_ptr(conf->percpu, cpu);
6387
6388 switch (action) {
6389 case CPU_UP_PREPARE:
6390 case CPU_UP_PREPARE_FROZEN:
6391 if (alloc_scratch_buffer(conf, percpu)) {
6392 pr_err("%s: failed memory allocation for cpu%ld\n",
6393 __func__, cpu);
6394 return notifier_from_errno(-ENOMEM);
6395 }
6396 break;
6397 case CPU_DEAD:
6398 case CPU_DEAD_FROZEN:
6399 free_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6400 break;
6401 default:
6402 break;
6403 }
6404 return NOTIFY_OK;
6405}
6406#endif
6407
6408static int raid5_alloc_percpu(struct r5conf *conf)
6409{
6410 unsigned long cpu;
6411 int err = 0;
6412
6413 conf->percpu = alloc_percpu(struct raid5_percpu);
6414 if (!conf->percpu)
6415 return -ENOMEM;
6416
6417#ifdef CONFIG_HOTPLUG_CPU
6418 conf->cpu_notify.notifier_call = raid456_cpu_notify;
6419 conf->cpu_notify.priority = 0;
6420 err = register_cpu_notifier(&conf->cpu_notify);
6421 if (err)
6422 return err;
6423#endif
6424
6425 get_online_cpus();
6426 for_each_present_cpu(cpu) {
6427 err = alloc_scratch_buffer(conf, per_cpu_ptr(conf->percpu, cpu));
6428 if (err) {
6429 pr_err("%s: failed memory allocation for cpu%ld\n",
6430 __func__, cpu);
6431 break;
6432 }
6433 }
6434 put_online_cpus();
6435
6436 if (!err) {
6437 conf->scribble_disks = max(conf->raid_disks,
6438 conf->previous_raid_disks);
6439 conf->scribble_sectors = max(conf->chunk_sectors,
6440 conf->prev_chunk_sectors);
6441 }
6442 return err;
6443}
6444
6445static unsigned long raid5_cache_scan(struct shrinker *shrink,
6446 struct shrink_control *sc)
6447{
6448 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6449 unsigned long ret = SHRINK_STOP;
6450
6451 if (mutex_trylock(&conf->cache_size_mutex)) {
6452 ret= 0;
6453 while (ret < sc->nr_to_scan &&
6454 conf->max_nr_stripes > conf->min_nr_stripes) {
6455 if (drop_one_stripe(conf) == 0) {
6456 ret = SHRINK_STOP;
6457 break;
6458 }
6459 ret++;
6460 }
6461 mutex_unlock(&conf->cache_size_mutex);
6462 }
6463 return ret;
6464}
6465
6466static unsigned long raid5_cache_count(struct shrinker *shrink,
6467 struct shrink_control *sc)
6468{
6469 struct r5conf *conf = container_of(shrink, struct r5conf, shrinker);
6470
6471 if (conf->max_nr_stripes < conf->min_nr_stripes)
6472 /* unlikely, but not impossible */
6473 return 0;
6474 return conf->max_nr_stripes - conf->min_nr_stripes;
6475}
6476
6477static struct r5conf *setup_conf(struct mddev *mddev)
6478{
6479 struct r5conf *conf;
6480 int raid_disk, memory, max_disks;
6481 struct md_rdev *rdev;
6482 struct disk_info *disk;
6483 char pers_name[6];
6484 int i;
6485 int group_cnt, worker_cnt_per_group;
6486 struct r5worker_group *new_group;
6487
6488 if (mddev->new_level != 5
6489 && mddev->new_level != 4
6490 && mddev->new_level != 6) {
6491 printk(KERN_ERR "md/raid:%s: raid level not set to 4/5/6 (%d)\n",
6492 mdname(mddev), mddev->new_level);
6493 return ERR_PTR(-EIO);
6494 }
6495 if ((mddev->new_level == 5
6496 && !algorithm_valid_raid5(mddev->new_layout)) ||
6497 (mddev->new_level == 6
6498 && !algorithm_valid_raid6(mddev->new_layout))) {
6499 printk(KERN_ERR "md/raid:%s: layout %d not supported\n",
6500 mdname(mddev), mddev->new_layout);
6501 return ERR_PTR(-EIO);
6502 }
6503 if (mddev->new_level == 6 && mddev->raid_disks < 4) {
6504 printk(KERN_ERR "md/raid:%s: not enough configured devices (%d, minimum 4)\n",
6505 mdname(mddev), mddev->raid_disks);
6506 return ERR_PTR(-EINVAL);
6507 }
6508
6509 if (!mddev->new_chunk_sectors ||
6510 (mddev->new_chunk_sectors << 9) % PAGE_SIZE ||
6511 !is_power_of_2(mddev->new_chunk_sectors)) {
6512 printk(KERN_ERR "md/raid:%s: invalid chunk size %d\n",
6513 mdname(mddev), mddev->new_chunk_sectors << 9);
6514 return ERR_PTR(-EINVAL);
6515 }
6516
6517 conf = kzalloc(sizeof(struct r5conf), GFP_KERNEL);
6518 if (conf == NULL)
6519 goto abort;
6520 /* Don't enable multi-threading by default*/
6521 if (!alloc_thread_groups(conf, 0, &group_cnt, &worker_cnt_per_group,
6522 &new_group)) {
6523 conf->group_cnt = group_cnt;
6524 conf->worker_cnt_per_group = worker_cnt_per_group;
6525 conf->worker_groups = new_group;
6526 } else
6527 goto abort;
6528 spin_lock_init(&conf->device_lock);
6529 seqcount_init(&conf->gen_lock);
6530 mutex_init(&conf->cache_size_mutex);
6531 init_waitqueue_head(&conf->wait_for_quiescent);
6532 init_waitqueue_head(&conf->wait_for_stripe);
6533 init_waitqueue_head(&conf->wait_for_overlap);
6534 INIT_LIST_HEAD(&conf->handle_list);
6535 INIT_LIST_HEAD(&conf->hold_list);
6536 INIT_LIST_HEAD(&conf->delayed_list);
6537 INIT_LIST_HEAD(&conf->bitmap_list);
6538 bio_list_init(&conf->return_bi);
6539 init_llist_head(&conf->released_stripes);
6540 atomic_set(&conf->active_stripes, 0);
6541 atomic_set(&conf->preread_active_stripes, 0);
6542 atomic_set(&conf->active_aligned_reads, 0);
6543 conf->bypass_threshold = BYPASS_THRESHOLD;
6544 conf->recovery_disabled = mddev->recovery_disabled - 1;
6545
6546 conf->raid_disks = mddev->raid_disks;
6547 if (mddev->reshape_position == MaxSector)
6548 conf->previous_raid_disks = mddev->raid_disks;
6549 else
6550 conf->previous_raid_disks = mddev->raid_disks - mddev->delta_disks;
6551 max_disks = max(conf->raid_disks, conf->previous_raid_disks);
6552
6553 conf->disks = kzalloc(max_disks * sizeof(struct disk_info),
6554 GFP_KERNEL);
6555 if (!conf->disks)
6556 goto abort;
6557
6558 conf->mddev = mddev;
6559
6560 if ((conf->stripe_hashtbl = kzalloc(PAGE_SIZE, GFP_KERNEL)) == NULL)
6561 goto abort;
6562
6563 /* We init hash_locks[0] separately to that it can be used
6564 * as the reference lock in the spin_lock_nest_lock() call
6565 * in lock_all_device_hash_locks_irq in order to convince
6566 * lockdep that we know what we are doing.
6567 */
6568 spin_lock_init(conf->hash_locks);
6569 for (i = 1; i < NR_STRIPE_HASH_LOCKS; i++)
6570 spin_lock_init(conf->hash_locks + i);
6571
6572 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6573 INIT_LIST_HEAD(conf->inactive_list + i);
6574
6575 for (i = 0; i < NR_STRIPE_HASH_LOCKS; i++)
6576 INIT_LIST_HEAD(conf->temp_inactive_list + i);
6577
6578 conf->level = mddev->new_level;
6579 conf->chunk_sectors = mddev->new_chunk_sectors;
6580 if (raid5_alloc_percpu(conf) != 0)
6581 goto abort;
6582
6583 pr_debug("raid456: run(%s) called.\n", mdname(mddev));
6584
6585 rdev_for_each(rdev, mddev) {
6586 raid_disk = rdev->raid_disk;
6587 if (raid_disk >= max_disks
6588 || raid_disk < 0 || test_bit(Journal, &rdev->flags))
6589 continue;
6590 disk = conf->disks + raid_disk;
6591
6592 if (test_bit(Replacement, &rdev->flags)) {
6593 if (disk->replacement)
6594 goto abort;
6595 disk->replacement = rdev;
6596 } else {
6597 if (disk->rdev)
6598 goto abort;
6599 disk->rdev = rdev;
6600 }
6601
6602 if (test_bit(In_sync, &rdev->flags)) {
6603 char b[BDEVNAME_SIZE];
6604 printk(KERN_INFO "md/raid:%s: device %s operational as raid"
6605 " disk %d\n",
6606 mdname(mddev), bdevname(rdev->bdev, b), raid_disk);
6607 } else if (rdev->saved_raid_disk != raid_disk)
6608 /* Cannot rely on bitmap to complete recovery */
6609 conf->fullsync = 1;
6610 }
6611
6612 conf->level = mddev->new_level;
6613 if (conf->level == 6) {
6614 conf->max_degraded = 2;
6615 if (raid6_call.xor_syndrome)
6616 conf->rmw_level = PARITY_ENABLE_RMW;
6617 else
6618 conf->rmw_level = PARITY_DISABLE_RMW;
6619 } else {
6620 conf->max_degraded = 1;
6621 conf->rmw_level = PARITY_ENABLE_RMW;
6622 }
6623 conf->algorithm = mddev->new_layout;
6624 conf->reshape_progress = mddev->reshape_position;
6625 if (conf->reshape_progress != MaxSector) {
6626 conf->prev_chunk_sectors = mddev->chunk_sectors;
6627 conf->prev_algo = mddev->layout;
6628 } else {
6629 conf->prev_chunk_sectors = conf->chunk_sectors;
6630 conf->prev_algo = conf->algorithm;
6631 }
6632
6633 conf->min_nr_stripes = NR_STRIPES;
6634 memory = conf->min_nr_stripes * (sizeof(struct stripe_head) +
6635 max_disks * ((sizeof(struct bio) + PAGE_SIZE))) / 1024;
6636 atomic_set(&conf->empty_inactive_list_nr, NR_STRIPE_HASH_LOCKS);
6637 if (grow_stripes(conf, conf->min_nr_stripes)) {
6638 printk(KERN_ERR
6639 "md/raid:%s: couldn't allocate %dkB for buffers\n",
6640 mdname(mddev), memory);
6641 goto abort;
6642 } else
6643 printk(KERN_INFO "md/raid:%s: allocated %dkB\n",
6644 mdname(mddev), memory);
6645 /*
6646 * Losing a stripe head costs more than the time to refill it,
6647 * it reduces the queue depth and so can hurt throughput.
6648 * So set it rather large, scaled by number of devices.
6649 */
6650 conf->shrinker.seeks = DEFAULT_SEEKS * conf->raid_disks * 4;
6651 conf->shrinker.scan_objects = raid5_cache_scan;
6652 conf->shrinker.count_objects = raid5_cache_count;
6653 conf->shrinker.batch = 128;
6654 conf->shrinker.flags = 0;
6655 register_shrinker(&conf->shrinker);
6656
6657 sprintf(pers_name, "raid%d", mddev->new_level);
6658 conf->thread = md_register_thread(raid5d, mddev, pers_name);
6659 if (!conf->thread) {
6660 printk(KERN_ERR
6661 "md/raid:%s: couldn't allocate thread.\n",
6662 mdname(mddev));
6663 goto abort;
6664 }
6665
6666 return conf;
6667
6668 abort:
6669 if (conf) {
6670 free_conf(conf);
6671 return ERR_PTR(-EIO);
6672 } else
6673 return ERR_PTR(-ENOMEM);
6674}
6675
6676static int only_parity(int raid_disk, int algo, int raid_disks, int max_degraded)
6677{
6678 switch (algo) {
6679 case ALGORITHM_PARITY_0:
6680 if (raid_disk < max_degraded)
6681 return 1;
6682 break;
6683 case ALGORITHM_PARITY_N:
6684 if (raid_disk >= raid_disks - max_degraded)
6685 return 1;
6686 break;
6687 case ALGORITHM_PARITY_0_6:
6688 if (raid_disk == 0 ||
6689 raid_disk == raid_disks - 1)
6690 return 1;
6691 break;
6692 case ALGORITHM_LEFT_ASYMMETRIC_6:
6693 case ALGORITHM_RIGHT_ASYMMETRIC_6:
6694 case ALGORITHM_LEFT_SYMMETRIC_6:
6695 case ALGORITHM_RIGHT_SYMMETRIC_6:
6696 if (raid_disk == raid_disks - 1)
6697 return 1;
6698 }
6699 return 0;
6700}
6701
6702static int run(struct mddev *mddev)
6703{
6704 struct r5conf *conf;
6705 int working_disks = 0;
6706 int dirty_parity_disks = 0;
6707 struct md_rdev *rdev;
6708 struct md_rdev *journal_dev = NULL;
6709 sector_t reshape_offset = 0;
6710 int i;
6711 long long min_offset_diff = 0;
6712 int first = 1;
6713
6714 if (mddev->recovery_cp != MaxSector)
6715 printk(KERN_NOTICE "md/raid:%s: not clean"
6716 " -- starting background reconstruction\n",
6717 mdname(mddev));
6718
6719 rdev_for_each(rdev, mddev) {
6720 long long diff;
6721
6722 if (test_bit(Journal, &rdev->flags)) {
6723 journal_dev = rdev;
6724 continue;
6725 }
6726 if (rdev->raid_disk < 0)
6727 continue;
6728 diff = (rdev->new_data_offset - rdev->data_offset);
6729 if (first) {
6730 min_offset_diff = diff;
6731 first = 0;
6732 } else if (mddev->reshape_backwards &&
6733 diff < min_offset_diff)
6734 min_offset_diff = diff;
6735 else if (!mddev->reshape_backwards &&
6736 diff > min_offset_diff)
6737 min_offset_diff = diff;
6738 }
6739
6740 if (mddev->reshape_position != MaxSector) {
6741 /* Check that we can continue the reshape.
6742 * Difficulties arise if the stripe we would write to
6743 * next is at or after the stripe we would read from next.
6744 * For a reshape that changes the number of devices, this
6745 * is only possible for a very short time, and mdadm makes
6746 * sure that time appears to have past before assembling
6747 * the array. So we fail if that time hasn't passed.
6748 * For a reshape that keeps the number of devices the same
6749 * mdadm must be monitoring the reshape can keeping the
6750 * critical areas read-only and backed up. It will start
6751 * the array in read-only mode, so we check for that.
6752 */
6753 sector_t here_new, here_old;
6754 int old_disks;
6755 int max_degraded = (mddev->level == 6 ? 2 : 1);
6756 int chunk_sectors;
6757 int new_data_disks;
6758
6759 if (journal_dev) {
6760 printk(KERN_ERR "md/raid:%s: don't support reshape with journal - aborting.\n",
6761 mdname(mddev));
6762 return -EINVAL;
6763 }
6764
6765 if (mddev->new_level != mddev->level) {
6766 printk(KERN_ERR "md/raid:%s: unsupported reshape "
6767 "required - aborting.\n",
6768 mdname(mddev));
6769 return -EINVAL;
6770 }
6771 old_disks = mddev->raid_disks - mddev->delta_disks;
6772 /* reshape_position must be on a new-stripe boundary, and one
6773 * further up in new geometry must map after here in old
6774 * geometry.
6775 * If the chunk sizes are different, then as we perform reshape
6776 * in units of the largest of the two, reshape_position needs
6777 * be a multiple of the largest chunk size times new data disks.
6778 */
6779 here_new = mddev->reshape_position;
6780 chunk_sectors = max(mddev->chunk_sectors, mddev->new_chunk_sectors);
6781 new_data_disks = mddev->raid_disks - max_degraded;
6782 if (sector_div(here_new, chunk_sectors * new_data_disks)) {
6783 printk(KERN_ERR "md/raid:%s: reshape_position not "
6784 "on a stripe boundary\n", mdname(mddev));
6785 return -EINVAL;
6786 }
6787 reshape_offset = here_new * chunk_sectors;
6788 /* here_new is the stripe we will write to */
6789 here_old = mddev->reshape_position;
6790 sector_div(here_old, chunk_sectors * (old_disks-max_degraded));
6791 /* here_old is the first stripe that we might need to read
6792 * from */
6793 if (mddev->delta_disks == 0) {
6794 /* We cannot be sure it is safe to start an in-place
6795 * reshape. It is only safe if user-space is monitoring
6796 * and taking constant backups.
6797 * mdadm always starts a situation like this in
6798 * readonly mode so it can take control before
6799 * allowing any writes. So just check for that.
6800 */
6801 if (abs(min_offset_diff) >= mddev->chunk_sectors &&
6802 abs(min_offset_diff) >= mddev->new_chunk_sectors)
6803 /* not really in-place - so OK */;
6804 else if (mddev->ro == 0) {
6805 printk(KERN_ERR "md/raid:%s: in-place reshape "
6806 "must be started in read-only mode "
6807 "- aborting\n",
6808 mdname(mddev));
6809 return -EINVAL;
6810 }
6811 } else if (mddev->reshape_backwards
6812 ? (here_new * chunk_sectors + min_offset_diff <=
6813 here_old * chunk_sectors)
6814 : (here_new * chunk_sectors >=
6815 here_old * chunk_sectors + (-min_offset_diff))) {
6816 /* Reading from the same stripe as writing to - bad */
6817 printk(KERN_ERR "md/raid:%s: reshape_position too early for "
6818 "auto-recovery - aborting.\n",
6819 mdname(mddev));
6820 return -EINVAL;
6821 }
6822 printk(KERN_INFO "md/raid:%s: reshape will continue\n",
6823 mdname(mddev));
6824 /* OK, we should be able to continue; */
6825 } else {
6826 BUG_ON(mddev->level != mddev->new_level);
6827 BUG_ON(mddev->layout != mddev->new_layout);
6828 BUG_ON(mddev->chunk_sectors != mddev->new_chunk_sectors);
6829 BUG_ON(mddev->delta_disks != 0);
6830 }
6831
6832 if (mddev->private == NULL)
6833 conf = setup_conf(mddev);
6834 else
6835 conf = mddev->private;
6836
6837 if (IS_ERR(conf))
6838 return PTR_ERR(conf);
6839
6840 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !journal_dev) {
6841 printk(KERN_ERR "md/raid:%s: journal disk is missing, force array readonly\n",
6842 mdname(mddev));
6843 mddev->ro = 1;
6844 set_disk_ro(mddev->gendisk, 1);
6845 }
6846
6847 conf->min_offset_diff = min_offset_diff;
6848 mddev->thread = conf->thread;
6849 conf->thread = NULL;
6850 mddev->private = conf;
6851
6852 for (i = 0; i < conf->raid_disks && conf->previous_raid_disks;
6853 i++) {
6854 rdev = conf->disks[i].rdev;
6855 if (!rdev && conf->disks[i].replacement) {
6856 /* The replacement is all we have yet */
6857 rdev = conf->disks[i].replacement;
6858 conf->disks[i].replacement = NULL;
6859 clear_bit(Replacement, &rdev->flags);
6860 conf->disks[i].rdev = rdev;
6861 }
6862 if (!rdev)
6863 continue;
6864 if (conf->disks[i].replacement &&
6865 conf->reshape_progress != MaxSector) {
6866 /* replacements and reshape simply do not mix. */
6867 printk(KERN_ERR "md: cannot handle concurrent "
6868 "replacement and reshape.\n");
6869 goto abort;
6870 }
6871 if (test_bit(In_sync, &rdev->flags)) {
6872 working_disks++;
6873 continue;
6874 }
6875 /* This disc is not fully in-sync. However if it
6876 * just stored parity (beyond the recovery_offset),
6877 * when we don't need to be concerned about the
6878 * array being dirty.
6879 * When reshape goes 'backwards', we never have
6880 * partially completed devices, so we only need
6881 * to worry about reshape going forwards.
6882 */
6883 /* Hack because v0.91 doesn't store recovery_offset properly. */
6884 if (mddev->major_version == 0 &&
6885 mddev->minor_version > 90)
6886 rdev->recovery_offset = reshape_offset;
6887
6888 if (rdev->recovery_offset < reshape_offset) {
6889 /* We need to check old and new layout */
6890 if (!only_parity(rdev->raid_disk,
6891 conf->algorithm,
6892 conf->raid_disks,
6893 conf->max_degraded))
6894 continue;
6895 }
6896 if (!only_parity(rdev->raid_disk,
6897 conf->prev_algo,
6898 conf->previous_raid_disks,
6899 conf->max_degraded))
6900 continue;
6901 dirty_parity_disks++;
6902 }
6903
6904 /*
6905 * 0 for a fully functional array, 1 or 2 for a degraded array.
6906 */
6907 mddev->degraded = calc_degraded(conf);
6908
6909 if (has_failed(conf)) {
6910 printk(KERN_ERR "md/raid:%s: not enough operational devices"
6911 " (%d/%d failed)\n",
6912 mdname(mddev), mddev->degraded, conf->raid_disks);
6913 goto abort;
6914 }
6915
6916 /* device size must be a multiple of chunk size */
6917 mddev->dev_sectors &= ~(mddev->chunk_sectors - 1);
6918 mddev->resync_max_sectors = mddev->dev_sectors;
6919
6920 if (mddev->degraded > dirty_parity_disks &&
6921 mddev->recovery_cp != MaxSector) {
6922 if (mddev->ok_start_degraded)
6923 printk(KERN_WARNING
6924 "md/raid:%s: starting dirty degraded array"
6925 " - data corruption possible.\n",
6926 mdname(mddev));
6927 else {
6928 printk(KERN_ERR
6929 "md/raid:%s: cannot start dirty degraded array.\n",
6930 mdname(mddev));
6931 goto abort;
6932 }
6933 }
6934
6935 if (mddev->degraded == 0)
6936 printk(KERN_INFO "md/raid:%s: raid level %d active with %d out of %d"
6937 " devices, algorithm %d\n", mdname(mddev), conf->level,
6938 mddev->raid_disks-mddev->degraded, mddev->raid_disks,
6939 mddev->new_layout);
6940 else
6941 printk(KERN_ALERT "md/raid:%s: raid level %d active with %d"
6942 " out of %d devices, algorithm %d\n",
6943 mdname(mddev), conf->level,
6944 mddev->raid_disks - mddev->degraded,
6945 mddev->raid_disks, mddev->new_layout);
6946
6947 print_raid5_conf(conf);
6948
6949 if (conf->reshape_progress != MaxSector) {
6950 conf->reshape_safe = conf->reshape_progress;
6951 atomic_set(&conf->reshape_stripes, 0);
6952 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
6953 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
6954 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
6955 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
6956 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
6957 "reshape");
6958 }
6959
6960 /* Ok, everything is just fine now */
6961 if (mddev->to_remove == &raid5_attrs_group)
6962 mddev->to_remove = NULL;
6963 else if (mddev->kobj.sd &&
6964 sysfs_create_group(&mddev->kobj, &raid5_attrs_group))
6965 printk(KERN_WARNING
6966 "raid5: failed to create sysfs attributes for %s\n",
6967 mdname(mddev));
6968 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
6969
6970 if (mddev->queue) {
6971 int chunk_size;
6972 bool discard_supported = true;
6973 /* read-ahead size must cover two whole stripes, which
6974 * is 2 * (datadisks) * chunksize where 'n' is the
6975 * number of raid devices
6976 */
6977 int data_disks = conf->previous_raid_disks - conf->max_degraded;
6978 int stripe = data_disks *
6979 ((mddev->chunk_sectors << 9) / PAGE_SIZE);
6980 if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
6981 mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
6982
6983 chunk_size = mddev->chunk_sectors << 9;
6984 blk_queue_io_min(mddev->queue, chunk_size);
6985 blk_queue_io_opt(mddev->queue, chunk_size *
6986 (conf->raid_disks - conf->max_degraded));
6987 mddev->queue->limits.raid_partial_stripes_expensive = 1;
6988 /*
6989 * We can only discard a whole stripe. It doesn't make sense to
6990 * discard data disk but write parity disk
6991 */
6992 stripe = stripe * PAGE_SIZE;
6993 /* Round up to power of 2, as discard handling
6994 * currently assumes that */
6995 while ((stripe-1) & stripe)
6996 stripe = (stripe | (stripe-1)) + 1;
6997 mddev->queue->limits.discard_alignment = stripe;
6998 mddev->queue->limits.discard_granularity = stripe;
6999
7000 /*
7001 * We use 16-bit counter of active stripes in bi_phys_segments
7002 * (minus one for over-loaded initialization)
7003 */
7004 blk_queue_max_hw_sectors(mddev->queue, 0xfffe * STRIPE_SECTORS);
7005 blk_queue_max_discard_sectors(mddev->queue,
7006 0xfffe * STRIPE_SECTORS);
7007
7008 /*
7009 * unaligned part of discard request will be ignored, so can't
7010 * guarantee discard_zeroes_data
7011 */
7012 mddev->queue->limits.discard_zeroes_data = 0;
7013
7014 blk_queue_max_write_same_sectors(mddev->queue, 0);
7015
7016 rdev_for_each(rdev, mddev) {
7017 disk_stack_limits(mddev->gendisk, rdev->bdev,
7018 rdev->data_offset << 9);
7019 disk_stack_limits(mddev->gendisk, rdev->bdev,
7020 rdev->new_data_offset << 9);
7021 /*
7022 * discard_zeroes_data is required, otherwise data
7023 * could be lost. Consider a scenario: discard a stripe
7024 * (the stripe could be inconsistent if
7025 * discard_zeroes_data is 0); write one disk of the
7026 * stripe (the stripe could be inconsistent again
7027 * depending on which disks are used to calculate
7028 * parity); the disk is broken; The stripe data of this
7029 * disk is lost.
7030 */
7031 if (!blk_queue_discard(bdev_get_queue(rdev->bdev)) ||
7032 !bdev_get_queue(rdev->bdev)->
7033 limits.discard_zeroes_data)
7034 discard_supported = false;
7035 /* Unfortunately, discard_zeroes_data is not currently
7036 * a guarantee - just a hint. So we only allow DISCARD
7037 * if the sysadmin has confirmed that only safe devices
7038 * are in use by setting a module parameter.
7039 */
7040 if (!devices_handle_discard_safely) {
7041 if (discard_supported) {
7042 pr_info("md/raid456: discard support disabled due to uncertainty.\n");
7043 pr_info("Set raid456.devices_handle_discard_safely=Y to override.\n");
7044 }
7045 discard_supported = false;
7046 }
7047 }
7048
7049 if (discard_supported &&
7050 mddev->queue->limits.max_discard_sectors >= (stripe >> 9) &&
7051 mddev->queue->limits.discard_granularity >= stripe)
7052 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
7053 mddev->queue);
7054 else
7055 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
7056 mddev->queue);
7057 }
7058
7059 if (journal_dev) {
7060 char b[BDEVNAME_SIZE];
7061
7062 printk(KERN_INFO"md/raid:%s: using device %s as journal\n",
7063 mdname(mddev), bdevname(journal_dev->bdev, b));
7064 r5l_init_log(conf, journal_dev);
7065 }
7066
7067 return 0;
7068abort:
7069 md_unregister_thread(&mddev->thread);
7070 print_raid5_conf(conf);
7071 free_conf(conf);
7072 mddev->private = NULL;
7073 printk(KERN_ALERT "md/raid:%s: failed to run raid set.\n", mdname(mddev));
7074 return -EIO;
7075}
7076
7077static void raid5_free(struct mddev *mddev, void *priv)
7078{
7079 struct r5conf *conf = priv;
7080
7081 free_conf(conf);
7082 mddev->to_remove = &raid5_attrs_group;
7083}
7084
7085static void status(struct seq_file *seq, struct mddev *mddev)
7086{
7087 struct r5conf *conf = mddev->private;
7088 int i;
7089
7090 seq_printf(seq, " level %d, %dk chunk, algorithm %d", mddev->level,
7091 conf->chunk_sectors / 2, mddev->layout);
7092 seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded);
7093 for (i = 0; i < conf->raid_disks; i++)
7094 seq_printf (seq, "%s",
7095 conf->disks[i].rdev &&
7096 test_bit(In_sync, &conf->disks[i].rdev->flags) ? "U" : "_");
7097 seq_printf (seq, "]");
7098}
7099
7100static void print_raid5_conf (struct r5conf *conf)
7101{
7102 int i;
7103 struct disk_info *tmp;
7104
7105 printk(KERN_DEBUG "RAID conf printout:\n");
7106 if (!conf) {
7107 printk("(conf==NULL)\n");
7108 return;
7109 }
7110 printk(KERN_DEBUG " --- level:%d rd:%d wd:%d\n", conf->level,
7111 conf->raid_disks,
7112 conf->raid_disks - conf->mddev->degraded);
7113
7114 for (i = 0; i < conf->raid_disks; i++) {
7115 char b[BDEVNAME_SIZE];
7116 tmp = conf->disks + i;
7117 if (tmp->rdev)
7118 printk(KERN_DEBUG " disk %d, o:%d, dev:%s\n",
7119 i, !test_bit(Faulty, &tmp->rdev->flags),
7120 bdevname(tmp->rdev->bdev, b));
7121 }
7122}
7123
7124static int raid5_spare_active(struct mddev *mddev)
7125{
7126 int i;
7127 struct r5conf *conf = mddev->private;
7128 struct disk_info *tmp;
7129 int count = 0;
7130 unsigned long flags;
7131
7132 for (i = 0; i < conf->raid_disks; i++) {
7133 tmp = conf->disks + i;
7134 if (tmp->replacement
7135 && tmp->replacement->recovery_offset == MaxSector
7136 && !test_bit(Faulty, &tmp->replacement->flags)
7137 && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
7138 /* Replacement has just become active. */
7139 if (!tmp->rdev
7140 || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
7141 count++;
7142 if (tmp->rdev) {
7143 /* Replaced device not technically faulty,
7144 * but we need to be sure it gets removed
7145 * and never re-added.
7146 */
7147 set_bit(Faulty, &tmp->rdev->flags);
7148 sysfs_notify_dirent_safe(
7149 tmp->rdev->sysfs_state);
7150 }
7151 sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
7152 } else if (tmp->rdev
7153 && tmp->rdev->recovery_offset == MaxSector
7154 && !test_bit(Faulty, &tmp->rdev->flags)
7155 && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
7156 count++;
7157 sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
7158 }
7159 }
7160 spin_lock_irqsave(&conf->device_lock, flags);
7161 mddev->degraded = calc_degraded(conf);
7162 spin_unlock_irqrestore(&conf->device_lock, flags);
7163 print_raid5_conf(conf);
7164 return count;
7165}
7166
7167static int raid5_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
7168{
7169 struct r5conf *conf = mddev->private;
7170 int err = 0;
7171 int number = rdev->raid_disk;
7172 struct md_rdev **rdevp;
7173 struct disk_info *p = conf->disks + number;
7174
7175 print_raid5_conf(conf);
7176 if (test_bit(Journal, &rdev->flags)) {
7177 /*
7178 * journal disk is not removable, but we need give a chance to
7179 * update superblock of other disks. Otherwise journal disk
7180 * will be considered as 'fresh'
7181 */
7182 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7183 return -EINVAL;
7184 }
7185 if (rdev == p->rdev)
7186 rdevp = &p->rdev;
7187 else if (rdev == p->replacement)
7188 rdevp = &p->replacement;
7189 else
7190 return 0;
7191
7192 if (number >= conf->raid_disks &&
7193 conf->reshape_progress == MaxSector)
7194 clear_bit(In_sync, &rdev->flags);
7195
7196 if (test_bit(In_sync, &rdev->flags) ||
7197 atomic_read(&rdev->nr_pending)) {
7198 err = -EBUSY;
7199 goto abort;
7200 }
7201 /* Only remove non-faulty devices if recovery
7202 * isn't possible.
7203 */
7204 if (!test_bit(Faulty, &rdev->flags) &&
7205 mddev->recovery_disabled != conf->recovery_disabled &&
7206 !has_failed(conf) &&
7207 (!p->replacement || p->replacement == rdev) &&
7208 number < conf->raid_disks) {
7209 err = -EBUSY;
7210 goto abort;
7211 }
7212 *rdevp = NULL;
7213 synchronize_rcu();
7214 if (atomic_read(&rdev->nr_pending)) {
7215 /* lost the race, try later */
7216 err = -EBUSY;
7217 *rdevp = rdev;
7218 } else if (p->replacement) {
7219 /* We must have just cleared 'rdev' */
7220 p->rdev = p->replacement;
7221 clear_bit(Replacement, &p->replacement->flags);
7222 smp_mb(); /* Make sure other CPUs may see both as identical
7223 * but will never see neither - if they are careful
7224 */
7225 p->replacement = NULL;
7226 clear_bit(WantReplacement, &rdev->flags);
7227 } else
7228 /* We might have just removed the Replacement as faulty-
7229 * clear the bit just in case
7230 */
7231 clear_bit(WantReplacement, &rdev->flags);
7232abort:
7233
7234 print_raid5_conf(conf);
7235 return err;
7236}
7237
7238static int raid5_add_disk(struct mddev *mddev, struct md_rdev *rdev)
7239{
7240 struct r5conf *conf = mddev->private;
7241 int err = -EEXIST;
7242 int disk;
7243 struct disk_info *p;
7244 int first = 0;
7245 int last = conf->raid_disks - 1;
7246
7247 if (test_bit(Journal, &rdev->flags))
7248 return -EINVAL;
7249 if (mddev->recovery_disabled == conf->recovery_disabled)
7250 return -EBUSY;
7251
7252 if (rdev->saved_raid_disk < 0 && has_failed(conf))
7253 /* no point adding a device */
7254 return -EINVAL;
7255
7256 if (rdev->raid_disk >= 0)
7257 first = last = rdev->raid_disk;
7258
7259 /*
7260 * find the disk ... but prefer rdev->saved_raid_disk
7261 * if possible.
7262 */
7263 if (rdev->saved_raid_disk >= 0 &&
7264 rdev->saved_raid_disk >= first &&
7265 conf->disks[rdev->saved_raid_disk].rdev == NULL)
7266 first = rdev->saved_raid_disk;
7267
7268 for (disk = first; disk <= last; disk++) {
7269 p = conf->disks + disk;
7270 if (p->rdev == NULL) {
7271 clear_bit(In_sync, &rdev->flags);
7272 rdev->raid_disk = disk;
7273 err = 0;
7274 if (rdev->saved_raid_disk != disk)
7275 conf->fullsync = 1;
7276 rcu_assign_pointer(p->rdev, rdev);
7277 goto out;
7278 }
7279 }
7280 for (disk = first; disk <= last; disk++) {
7281 p = conf->disks + disk;
7282 if (test_bit(WantReplacement, &p->rdev->flags) &&
7283 p->replacement == NULL) {
7284 clear_bit(In_sync, &rdev->flags);
7285 set_bit(Replacement, &rdev->flags);
7286 rdev->raid_disk = disk;
7287 err = 0;
7288 conf->fullsync = 1;
7289 rcu_assign_pointer(p->replacement, rdev);
7290 break;
7291 }
7292 }
7293out:
7294 print_raid5_conf(conf);
7295 return err;
7296}
7297
7298static int raid5_resize(struct mddev *mddev, sector_t sectors)
7299{
7300 /* no resync is happening, and there is enough space
7301 * on all devices, so we can resize.
7302 * We need to make sure resync covers any new space.
7303 * If the array is shrinking we should possibly wait until
7304 * any io in the removed space completes, but it hardly seems
7305 * worth it.
7306 */
7307 sector_t newsize;
7308 struct r5conf *conf = mddev->private;
7309
7310 if (conf->log)
7311 return -EINVAL;
7312 sectors &= ~((sector_t)conf->chunk_sectors - 1);
7313 newsize = raid5_size(mddev, sectors, mddev->raid_disks);
7314 if (mddev->external_size &&
7315 mddev->array_sectors > newsize)
7316 return -EINVAL;
7317 if (mddev->bitmap) {
7318 int ret = bitmap_resize(mddev->bitmap, sectors, 0, 0);
7319 if (ret)
7320 return ret;
7321 }
7322 md_set_array_sectors(mddev, newsize);
7323 set_capacity(mddev->gendisk, mddev->array_sectors);
7324 revalidate_disk(mddev->gendisk);
7325 if (sectors > mddev->dev_sectors &&
7326 mddev->recovery_cp > mddev->dev_sectors) {
7327 mddev->recovery_cp = mddev->dev_sectors;
7328 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7329 }
7330 mddev->dev_sectors = sectors;
7331 mddev->resync_max_sectors = sectors;
7332 return 0;
7333}
7334
7335static int check_stripe_cache(struct mddev *mddev)
7336{
7337 /* Can only proceed if there are plenty of stripe_heads.
7338 * We need a minimum of one full stripe,, and for sensible progress
7339 * it is best to have about 4 times that.
7340 * If we require 4 times, then the default 256 4K stripe_heads will
7341 * allow for chunk sizes up to 256K, which is probably OK.
7342 * If the chunk size is greater, user-space should request more
7343 * stripe_heads first.
7344 */
7345 struct r5conf *conf = mddev->private;
7346 if (((mddev->chunk_sectors << 9) / STRIPE_SIZE) * 4
7347 > conf->min_nr_stripes ||
7348 ((mddev->new_chunk_sectors << 9) / STRIPE_SIZE) * 4
7349 > conf->min_nr_stripes) {
7350 printk(KERN_WARNING "md/raid:%s: reshape: not enough stripes. Needed %lu\n",
7351 mdname(mddev),
7352 ((max(mddev->chunk_sectors, mddev->new_chunk_sectors) << 9)
7353 / STRIPE_SIZE)*4);
7354 return 0;
7355 }
7356 return 1;
7357}
7358
7359static int check_reshape(struct mddev *mddev)
7360{
7361 struct r5conf *conf = mddev->private;
7362
7363 if (conf->log)
7364 return -EINVAL;
7365 if (mddev->delta_disks == 0 &&
7366 mddev->new_layout == mddev->layout &&
7367 mddev->new_chunk_sectors == mddev->chunk_sectors)
7368 return 0; /* nothing to do */
7369 if (has_failed(conf))
7370 return -EINVAL;
7371 if (mddev->delta_disks < 0 && mddev->reshape_position == MaxSector) {
7372 /* We might be able to shrink, but the devices must
7373 * be made bigger first.
7374 * For raid6, 4 is the minimum size.
7375 * Otherwise 2 is the minimum
7376 */
7377 int min = 2;
7378 if (mddev->level == 6)
7379 min = 4;
7380 if (mddev->raid_disks + mddev->delta_disks < min)
7381 return -EINVAL;
7382 }
7383
7384 if (!check_stripe_cache(mddev))
7385 return -ENOSPC;
7386
7387 if (mddev->new_chunk_sectors > mddev->chunk_sectors ||
7388 mddev->delta_disks > 0)
7389 if (resize_chunks(conf,
7390 conf->previous_raid_disks
7391 + max(0, mddev->delta_disks),
7392 max(mddev->new_chunk_sectors,
7393 mddev->chunk_sectors)
7394 ) < 0)
7395 return -ENOMEM;
7396 return resize_stripes(conf, (conf->previous_raid_disks
7397 + mddev->delta_disks));
7398}
7399
7400static int raid5_start_reshape(struct mddev *mddev)
7401{
7402 struct r5conf *conf = mddev->private;
7403 struct md_rdev *rdev;
7404 int spares = 0;
7405 unsigned long flags;
7406
7407 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
7408 return -EBUSY;
7409
7410 if (!check_stripe_cache(mddev))
7411 return -ENOSPC;
7412
7413 if (has_failed(conf))
7414 return -EINVAL;
7415
7416 rdev_for_each(rdev, mddev) {
7417 if (!test_bit(In_sync, &rdev->flags)
7418 && !test_bit(Faulty, &rdev->flags))
7419 spares++;
7420 }
7421
7422 if (spares - mddev->degraded < mddev->delta_disks - conf->max_degraded)
7423 /* Not enough devices even to make a degraded array
7424 * of that size
7425 */
7426 return -EINVAL;
7427
7428 /* Refuse to reduce size of the array. Any reductions in
7429 * array size must be through explicit setting of array_size
7430 * attribute.
7431 */
7432 if (raid5_size(mddev, 0, conf->raid_disks + mddev->delta_disks)
7433 < mddev->array_sectors) {
7434 printk(KERN_ERR "md/raid:%s: array size must be reduced "
7435 "before number of disks\n", mdname(mddev));
7436 return -EINVAL;
7437 }
7438
7439 atomic_set(&conf->reshape_stripes, 0);
7440 spin_lock_irq(&conf->device_lock);
7441 write_seqcount_begin(&conf->gen_lock);
7442 conf->previous_raid_disks = conf->raid_disks;
7443 conf->raid_disks += mddev->delta_disks;
7444 conf->prev_chunk_sectors = conf->chunk_sectors;
7445 conf->chunk_sectors = mddev->new_chunk_sectors;
7446 conf->prev_algo = conf->algorithm;
7447 conf->algorithm = mddev->new_layout;
7448 conf->generation++;
7449 /* Code that selects data_offset needs to see the generation update
7450 * if reshape_progress has been set - so a memory barrier needed.
7451 */
7452 smp_mb();
7453 if (mddev->reshape_backwards)
7454 conf->reshape_progress = raid5_size(mddev, 0, 0);
7455 else
7456 conf->reshape_progress = 0;
7457 conf->reshape_safe = conf->reshape_progress;
7458 write_seqcount_end(&conf->gen_lock);
7459 spin_unlock_irq(&conf->device_lock);
7460
7461 /* Now make sure any requests that proceeded on the assumption
7462 * the reshape wasn't running - like Discard or Read - have
7463 * completed.
7464 */
7465 mddev_suspend(mddev);
7466 mddev_resume(mddev);
7467
7468 /* Add some new drives, as many as will fit.
7469 * We know there are enough to make the newly sized array work.
7470 * Don't add devices if we are reducing the number of
7471 * devices in the array. This is because it is not possible
7472 * to correctly record the "partially reconstructed" state of
7473 * such devices during the reshape and confusion could result.
7474 */
7475 if (mddev->delta_disks >= 0) {
7476 rdev_for_each(rdev, mddev)
7477 if (rdev->raid_disk < 0 &&
7478 !test_bit(Faulty, &rdev->flags)) {
7479 if (raid5_add_disk(mddev, rdev) == 0) {
7480 if (rdev->raid_disk
7481 >= conf->previous_raid_disks)
7482 set_bit(In_sync, &rdev->flags);
7483 else
7484 rdev->recovery_offset = 0;
7485
7486 if (sysfs_link_rdev(mddev, rdev))
7487 /* Failure here is OK */;
7488 }
7489 } else if (rdev->raid_disk >= conf->previous_raid_disks
7490 && !test_bit(Faulty, &rdev->flags)) {
7491 /* This is a spare that was manually added */
7492 set_bit(In_sync, &rdev->flags);
7493 }
7494
7495 /* When a reshape changes the number of devices,
7496 * ->degraded is measured against the larger of the
7497 * pre and post number of devices.
7498 */
7499 spin_lock_irqsave(&conf->device_lock, flags);
7500 mddev->degraded = calc_degraded(conf);
7501 spin_unlock_irqrestore(&conf->device_lock, flags);
7502 }
7503 mddev->raid_disks = conf->raid_disks;
7504 mddev->reshape_position = conf->reshape_progress;
7505 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7506
7507 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7508 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7509 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7510 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7511 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7512 mddev->sync_thread = md_register_thread(md_do_sync, mddev,
7513 "reshape");
7514 if (!mddev->sync_thread) {
7515 mddev->recovery = 0;
7516 spin_lock_irq(&conf->device_lock);
7517 write_seqcount_begin(&conf->gen_lock);
7518 mddev->raid_disks = conf->raid_disks = conf->previous_raid_disks;
7519 mddev->new_chunk_sectors =
7520 conf->chunk_sectors = conf->prev_chunk_sectors;
7521 mddev->new_layout = conf->algorithm = conf->prev_algo;
7522 rdev_for_each(rdev, mddev)
7523 rdev->new_data_offset = rdev->data_offset;
7524 smp_wmb();
7525 conf->generation --;
7526 conf->reshape_progress = MaxSector;
7527 mddev->reshape_position = MaxSector;
7528 write_seqcount_end(&conf->gen_lock);
7529 spin_unlock_irq(&conf->device_lock);
7530 return -EAGAIN;
7531 }
7532 conf->reshape_checkpoint = jiffies;
7533 md_wakeup_thread(mddev->sync_thread);
7534 md_new_event(mddev);
7535 return 0;
7536}
7537
7538/* This is called from the reshape thread and should make any
7539 * changes needed in 'conf'
7540 */
7541static void end_reshape(struct r5conf *conf)
7542{
7543
7544 if (!test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery)) {
7545
7546 spin_lock_irq(&conf->device_lock);
7547 conf->previous_raid_disks = conf->raid_disks;
7548 md_finish_reshape(conf->mddev);
7549 smp_wmb();
7550 conf->reshape_progress = MaxSector;
7551 conf->mddev->reshape_position = MaxSector;
7552 spin_unlock_irq(&conf->device_lock);
7553 wake_up(&conf->wait_for_overlap);
7554
7555 /* read-ahead size must cover two whole stripes, which is
7556 * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
7557 */
7558 if (conf->mddev->queue) {
7559 int data_disks = conf->raid_disks - conf->max_degraded;
7560 int stripe = data_disks * ((conf->chunk_sectors << 9)
7561 / PAGE_SIZE);
7562 if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
7563 conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
7564 }
7565 }
7566}
7567
7568/* This is called from the raid5d thread with mddev_lock held.
7569 * It makes config changes to the device.
7570 */
7571static void raid5_finish_reshape(struct mddev *mddev)
7572{
7573 struct r5conf *conf = mddev->private;
7574
7575 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7576
7577 if (mddev->delta_disks > 0) {
7578 md_set_array_sectors(mddev, raid5_size(mddev, 0, 0));
7579 set_capacity(mddev->gendisk, mddev->array_sectors);
7580 revalidate_disk(mddev->gendisk);
7581 } else {
7582 int d;
7583 spin_lock_irq(&conf->device_lock);
7584 mddev->degraded = calc_degraded(conf);
7585 spin_unlock_irq(&conf->device_lock);
7586 for (d = conf->raid_disks ;
7587 d < conf->raid_disks - mddev->delta_disks;
7588 d++) {
7589 struct md_rdev *rdev = conf->disks[d].rdev;
7590 if (rdev)
7591 clear_bit(In_sync, &rdev->flags);
7592 rdev = conf->disks[d].replacement;
7593 if (rdev)
7594 clear_bit(In_sync, &rdev->flags);
7595 }
7596 }
7597 mddev->layout = conf->algorithm;
7598 mddev->chunk_sectors = conf->chunk_sectors;
7599 mddev->reshape_position = MaxSector;
7600 mddev->delta_disks = 0;
7601 mddev->reshape_backwards = 0;
7602 }
7603}
7604
7605static void raid5_quiesce(struct mddev *mddev, int state)
7606{
7607 struct r5conf *conf = mddev->private;
7608
7609 switch(state) {
7610 case 2: /* resume for a suspend */
7611 wake_up(&conf->wait_for_overlap);
7612 break;
7613
7614 case 1: /* stop all writes */
7615 lock_all_device_hash_locks_irq(conf);
7616 /* '2' tells resync/reshape to pause so that all
7617 * active stripes can drain
7618 */
7619 conf->quiesce = 2;
7620 wait_event_cmd(conf->wait_for_quiescent,
7621 atomic_read(&conf->active_stripes) == 0 &&
7622 atomic_read(&conf->active_aligned_reads) == 0,
7623 unlock_all_device_hash_locks_irq(conf),
7624 lock_all_device_hash_locks_irq(conf));
7625 conf->quiesce = 1;
7626 unlock_all_device_hash_locks_irq(conf);
7627 /* allow reshape to continue */
7628 wake_up(&conf->wait_for_overlap);
7629 break;
7630
7631 case 0: /* re-enable writes */
7632 lock_all_device_hash_locks_irq(conf);
7633 conf->quiesce = 0;
7634 wake_up(&conf->wait_for_quiescent);
7635 wake_up(&conf->wait_for_overlap);
7636 unlock_all_device_hash_locks_irq(conf);
7637 break;
7638 }
7639 r5l_quiesce(conf->log, state);
7640}
7641
7642static void *raid45_takeover_raid0(struct mddev *mddev, int level)
7643{
7644 struct r0conf *raid0_conf = mddev->private;
7645 sector_t sectors;
7646
7647 /* for raid0 takeover only one zone is supported */
7648 if (raid0_conf->nr_strip_zones > 1) {
7649 printk(KERN_ERR "md/raid:%s: cannot takeover raid0 with more than one zone.\n",
7650 mdname(mddev));
7651 return ERR_PTR(-EINVAL);
7652 }
7653
7654 sectors = raid0_conf->strip_zone[0].zone_end;
7655 sector_div(sectors, raid0_conf->strip_zone[0].nb_dev);
7656 mddev->dev_sectors = sectors;
7657 mddev->new_level = level;
7658 mddev->new_layout = ALGORITHM_PARITY_N;
7659 mddev->new_chunk_sectors = mddev->chunk_sectors;
7660 mddev->raid_disks += 1;
7661 mddev->delta_disks = 1;
7662 /* make sure it will be not marked as dirty */
7663 mddev->recovery_cp = MaxSector;
7664
7665 return setup_conf(mddev);
7666}
7667
7668static void *raid5_takeover_raid1(struct mddev *mddev)
7669{
7670 int chunksect;
7671
7672 if (mddev->raid_disks != 2 ||
7673 mddev->degraded > 1)
7674 return ERR_PTR(-EINVAL);
7675
7676 /* Should check if there are write-behind devices? */
7677
7678 chunksect = 64*2; /* 64K by default */
7679
7680 /* The array must be an exact multiple of chunksize */
7681 while (chunksect && (mddev->array_sectors & (chunksect-1)))
7682 chunksect >>= 1;
7683
7684 if ((chunksect<<9) < STRIPE_SIZE)
7685 /* array size does not allow a suitable chunk size */
7686 return ERR_PTR(-EINVAL);
7687
7688 mddev->new_level = 5;
7689 mddev->new_layout = ALGORITHM_LEFT_SYMMETRIC;
7690 mddev->new_chunk_sectors = chunksect;
7691
7692 return setup_conf(mddev);
7693}
7694
7695static void *raid5_takeover_raid6(struct mddev *mddev)
7696{
7697 int new_layout;
7698
7699 switch (mddev->layout) {
7700 case ALGORITHM_LEFT_ASYMMETRIC_6:
7701 new_layout = ALGORITHM_LEFT_ASYMMETRIC;
7702 break;
7703 case ALGORITHM_RIGHT_ASYMMETRIC_6:
7704 new_layout = ALGORITHM_RIGHT_ASYMMETRIC;
7705 break;
7706 case ALGORITHM_LEFT_SYMMETRIC_6:
7707 new_layout = ALGORITHM_LEFT_SYMMETRIC;
7708 break;
7709 case ALGORITHM_RIGHT_SYMMETRIC_6:
7710 new_layout = ALGORITHM_RIGHT_SYMMETRIC;
7711 break;
7712 case ALGORITHM_PARITY_0_6:
7713 new_layout = ALGORITHM_PARITY_0;
7714 break;
7715 case ALGORITHM_PARITY_N:
7716 new_layout = ALGORITHM_PARITY_N;
7717 break;
7718 default:
7719 return ERR_PTR(-EINVAL);
7720 }
7721 mddev->new_level = 5;
7722 mddev->new_layout = new_layout;
7723 mddev->delta_disks = -1;
7724 mddev->raid_disks -= 1;
7725 return setup_conf(mddev);
7726}
7727
7728static int raid5_check_reshape(struct mddev *mddev)
7729{
7730 /* For a 2-drive array, the layout and chunk size can be changed
7731 * immediately as not restriping is needed.
7732 * For larger arrays we record the new value - after validation
7733 * to be used by a reshape pass.
7734 */
7735 struct r5conf *conf = mddev->private;
7736 int new_chunk = mddev->new_chunk_sectors;
7737
7738 if (mddev->new_layout >= 0 && !algorithm_valid_raid5(mddev->new_layout))
7739 return -EINVAL;
7740 if (new_chunk > 0) {
7741 if (!is_power_of_2(new_chunk))
7742 return -EINVAL;
7743 if (new_chunk < (PAGE_SIZE>>9))
7744 return -EINVAL;
7745 if (mddev->array_sectors & (new_chunk-1))
7746 /* not factor of array size */
7747 return -EINVAL;
7748 }
7749
7750 /* They look valid */
7751
7752 if (mddev->raid_disks == 2) {
7753 /* can make the change immediately */
7754 if (mddev->new_layout >= 0) {
7755 conf->algorithm = mddev->new_layout;
7756 mddev->layout = mddev->new_layout;
7757 }
7758 if (new_chunk > 0) {
7759 conf->chunk_sectors = new_chunk ;
7760 mddev->chunk_sectors = new_chunk;
7761 }
7762 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7763 md_wakeup_thread(mddev->thread);
7764 }
7765 return check_reshape(mddev);
7766}
7767
7768static int raid6_check_reshape(struct mddev *mddev)
7769{
7770 int new_chunk = mddev->new_chunk_sectors;
7771
7772 if (mddev->new_layout >= 0 && !algorithm_valid_raid6(mddev->new_layout))
7773 return -EINVAL;
7774 if (new_chunk > 0) {
7775 if (!is_power_of_2(new_chunk))
7776 return -EINVAL;
7777 if (new_chunk < (PAGE_SIZE >> 9))
7778 return -EINVAL;
7779 if (mddev->array_sectors & (new_chunk-1))
7780 /* not factor of array size */
7781 return -EINVAL;
7782 }
7783
7784 /* They look valid */
7785 return check_reshape(mddev);
7786}
7787
7788static void *raid5_takeover(struct mddev *mddev)
7789{
7790 /* raid5 can take over:
7791 * raid0 - if there is only one strip zone - make it a raid4 layout
7792 * raid1 - if there are two drives. We need to know the chunk size
7793 * raid4 - trivial - just use a raid4 layout.
7794 * raid6 - Providing it is a *_6 layout
7795 */
7796 if (mddev->level == 0)
7797 return raid45_takeover_raid0(mddev, 5);
7798 if (mddev->level == 1)
7799 return raid5_takeover_raid1(mddev);
7800 if (mddev->level == 4) {
7801 mddev->new_layout = ALGORITHM_PARITY_N;
7802 mddev->new_level = 5;
7803 return setup_conf(mddev);
7804 }
7805 if (mddev->level == 6)
7806 return raid5_takeover_raid6(mddev);
7807
7808 return ERR_PTR(-EINVAL);
7809}
7810
7811static void *raid4_takeover(struct mddev *mddev)
7812{
7813 /* raid4 can take over:
7814 * raid0 - if there is only one strip zone
7815 * raid5 - if layout is right
7816 */
7817 if (mddev->level == 0)
7818 return raid45_takeover_raid0(mddev, 4);
7819 if (mddev->level == 5 &&
7820 mddev->layout == ALGORITHM_PARITY_N) {
7821 mddev->new_layout = 0;
7822 mddev->new_level = 4;
7823 return setup_conf(mddev);
7824 }
7825 return ERR_PTR(-EINVAL);
7826}
7827
7828static struct md_personality raid5_personality;
7829
7830static void *raid6_takeover(struct mddev *mddev)
7831{
7832 /* Currently can only take over a raid5. We map the
7833 * personality to an equivalent raid6 personality
7834 * with the Q block at the end.
7835 */
7836 int new_layout;
7837
7838 if (mddev->pers != &raid5_personality)
7839 return ERR_PTR(-EINVAL);
7840 if (mddev->degraded > 1)
7841 return ERR_PTR(-EINVAL);
7842 if (mddev->raid_disks > 253)
7843 return ERR_PTR(-EINVAL);
7844 if (mddev->raid_disks < 3)
7845 return ERR_PTR(-EINVAL);
7846
7847 switch (mddev->layout) {
7848 case ALGORITHM_LEFT_ASYMMETRIC:
7849 new_layout = ALGORITHM_LEFT_ASYMMETRIC_6;
7850 break;
7851 case ALGORITHM_RIGHT_ASYMMETRIC:
7852 new_layout = ALGORITHM_RIGHT_ASYMMETRIC_6;
7853 break;
7854 case ALGORITHM_LEFT_SYMMETRIC:
7855 new_layout = ALGORITHM_LEFT_SYMMETRIC_6;
7856 break;
7857 case ALGORITHM_RIGHT_SYMMETRIC:
7858 new_layout = ALGORITHM_RIGHT_SYMMETRIC_6;
7859 break;
7860 case ALGORITHM_PARITY_0:
7861 new_layout = ALGORITHM_PARITY_0_6;
7862 break;
7863 case ALGORITHM_PARITY_N:
7864 new_layout = ALGORITHM_PARITY_N;
7865 break;
7866 default:
7867 return ERR_PTR(-EINVAL);
7868 }
7869 mddev->new_level = 6;
7870 mddev->new_layout = new_layout;
7871 mddev->delta_disks = 1;
7872 mddev->raid_disks += 1;
7873 return setup_conf(mddev);
7874}
7875
7876static struct md_personality raid6_personality =
7877{
7878 .name = "raid6",
7879 .level = 6,
7880 .owner = THIS_MODULE,
7881 .make_request = make_request,
7882 .run = run,
7883 .free = raid5_free,
7884 .status = status,
7885 .error_handler = error,
7886 .hot_add_disk = raid5_add_disk,
7887 .hot_remove_disk= raid5_remove_disk,
7888 .spare_active = raid5_spare_active,
7889 .sync_request = sync_request,
7890 .resize = raid5_resize,
7891 .size = raid5_size,
7892 .check_reshape = raid6_check_reshape,
7893 .start_reshape = raid5_start_reshape,
7894 .finish_reshape = raid5_finish_reshape,
7895 .quiesce = raid5_quiesce,
7896 .takeover = raid6_takeover,
7897 .congested = raid5_congested,
7898};
7899static struct md_personality raid5_personality =
7900{
7901 .name = "raid5",
7902 .level = 5,
7903 .owner = THIS_MODULE,
7904 .make_request = make_request,
7905 .run = run,
7906 .free = raid5_free,
7907 .status = status,
7908 .error_handler = error,
7909 .hot_add_disk = raid5_add_disk,
7910 .hot_remove_disk= raid5_remove_disk,
7911 .spare_active = raid5_spare_active,
7912 .sync_request = sync_request,
7913 .resize = raid5_resize,
7914 .size = raid5_size,
7915 .check_reshape = raid5_check_reshape,
7916 .start_reshape = raid5_start_reshape,
7917 .finish_reshape = raid5_finish_reshape,
7918 .quiesce = raid5_quiesce,
7919 .takeover = raid5_takeover,
7920 .congested = raid5_congested,
7921};
7922
7923static struct md_personality raid4_personality =
7924{
7925 .name = "raid4",
7926 .level = 4,
7927 .owner = THIS_MODULE,
7928 .make_request = make_request,
7929 .run = run,
7930 .free = raid5_free,
7931 .status = status,
7932 .error_handler = error,
7933 .hot_add_disk = raid5_add_disk,
7934 .hot_remove_disk= raid5_remove_disk,
7935 .spare_active = raid5_spare_active,
7936 .sync_request = sync_request,
7937 .resize = raid5_resize,
7938 .size = raid5_size,
7939 .check_reshape = raid5_check_reshape,
7940 .start_reshape = raid5_start_reshape,
7941 .finish_reshape = raid5_finish_reshape,
7942 .quiesce = raid5_quiesce,
7943 .takeover = raid4_takeover,
7944 .congested = raid5_congested,
7945};
7946
7947static int __init raid5_init(void)
7948{
7949 raid5_wq = alloc_workqueue("raid5wq",
7950 WQ_UNBOUND|WQ_MEM_RECLAIM|WQ_CPU_INTENSIVE|WQ_SYSFS, 0);
7951 if (!raid5_wq)
7952 return -ENOMEM;
7953 register_md_personality(&raid6_personality);
7954 register_md_personality(&raid5_personality);
7955 register_md_personality(&raid4_personality);
7956 return 0;
7957}
7958
7959static void raid5_exit(void)
7960{
7961 unregister_md_personality(&raid6_personality);
7962 unregister_md_personality(&raid5_personality);
7963 unregister_md_personality(&raid4_personality);
7964 destroy_workqueue(raid5_wq);
7965}
7966
7967module_init(raid5_init);
7968module_exit(raid5_exit);
7969MODULE_LICENSE("GPL");
7970MODULE_DESCRIPTION("RAID4/5/6 (striping with parity) personality for MD");
7971MODULE_ALIAS("md-personality-4"); /* RAID5 */
7972MODULE_ALIAS("md-raid5");
7973MODULE_ALIAS("md-raid4");
7974MODULE_ALIAS("md-level-5");
7975MODULE_ALIAS("md-level-4");
7976MODULE_ALIAS("md-personality-8"); /* RAID6 */
7977MODULE_ALIAS("md-raid6");
7978MODULE_ALIAS("md-level-6");
7979
7980/* This used to be two separate modules, they were: */
7981MODULE_ALIAS("raid5");
7982MODULE_ALIAS("raid6");