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