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