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