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