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