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