]> git.karo-electronics.de Git - mv-sheeva.git/blob - drivers/md/raid10.c
md: tidy up rdev_for_each usage.
[mv-sheeva.git] / drivers / md / raid10.c
1 /*
2  * raid10.c : Multiple Devices driver for Linux
3  *
4  * Copyright (C) 2000-2004 Neil Brown
5  *
6  * RAID-10 support for md.
7  *
8  * Base on code in raid1.c.  See raid1.c for further copyright information.
9  *
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2, or (at your option)
14  * any later version.
15  *
16  * You should have received a copy of the GNU General Public License
17  * (for example /usr/src/linux/COPYING); if not, write to the Free
18  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19  */
20
21 #include <linux/slab.h>
22 #include <linux/delay.h>
23 #include <linux/blkdev.h>
24 #include <linux/module.h>
25 #include <linux/seq_file.h>
26 #include <linux/ratelimit.h>
27 #include "md.h"
28 #include "raid10.h"
29 #include "raid0.h"
30 #include "bitmap.h"
31
32 /*
33  * RAID10 provides a combination of RAID0 and RAID1 functionality.
34  * The layout of data is defined by
35  *    chunk_size
36  *    raid_disks
37  *    near_copies (stored in low byte of layout)
38  *    far_copies (stored in second byte of layout)
39  *    far_offset (stored in bit 16 of layout )
40  *
41  * The data to be stored is divided into chunks using chunksize.
42  * Each device is divided into far_copies sections.
43  * In each section, chunks are laid out in a style similar to raid0, but
44  * near_copies copies of each chunk is stored (each on a different drive).
45  * The starting device for each section is offset near_copies from the starting
46  * device of the previous section.
47  * Thus they are (near_copies*far_copies) of each chunk, and each is on a different
48  * drive.
49  * near_copies and far_copies must be at least one, and their product is at most
50  * raid_disks.
51  *
52  * If far_offset is true, then the far_copies are handled a bit differently.
53  * The copies are still in different stripes, but instead of be very far apart
54  * on disk, there are adjacent stripes.
55  */
56
57 /*
58  * Number of guaranteed r10bios in case of extreme VM load:
59  */
60 #define NR_RAID10_BIOS 256
61
62 /* When there are this many requests queue to be written by
63  * the raid10 thread, we become 'congested' to provide back-pressure
64  * for writeback.
65  */
66 static int max_queued_requests = 1024;
67
68 static void allow_barrier(struct r10conf *conf);
69 static void lower_barrier(struct r10conf *conf);
70 static int enough(struct r10conf *conf, int ignore);
71
72 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
73 {
74         struct r10conf *conf = data;
75         int size = offsetof(struct r10bio, devs[conf->copies]);
76
77         /* allocate a r10bio with room for raid_disks entries in the
78          * bios array */
79         return kzalloc(size, gfp_flags);
80 }
81
82 static void r10bio_pool_free(void *r10_bio, void *data)
83 {
84         kfree(r10_bio);
85 }
86
87 /* Maximum size of each resync request */
88 #define RESYNC_BLOCK_SIZE (64*1024)
89 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
90 /* amount of memory to reserve for resync requests */
91 #define RESYNC_WINDOW (1024*1024)
92 /* maximum number of concurrent requests, memory permitting */
93 #define RESYNC_DEPTH (32*1024*1024/RESYNC_BLOCK_SIZE)
94
95 /*
96  * When performing a resync, we need to read and compare, so
97  * we need as many pages are there are copies.
98  * When performing a recovery, we need 2 bios, one for read,
99  * one for write (we recover only one drive per r10buf)
100  *
101  */
102 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
103 {
104         struct r10conf *conf = data;
105         struct page *page;
106         struct r10bio *r10_bio;
107         struct bio *bio;
108         int i, j;
109         int nalloc;
110
111         r10_bio = r10bio_pool_alloc(gfp_flags, conf);
112         if (!r10_bio)
113                 return NULL;
114
115         if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery))
116                 nalloc = conf->copies; /* resync */
117         else
118                 nalloc = 2; /* recovery */
119
120         /*
121          * Allocate bios.
122          */
123         for (j = nalloc ; j-- ; ) {
124                 bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
125                 if (!bio)
126                         goto out_free_bio;
127                 r10_bio->devs[j].bio = bio;
128                 if (!conf->have_replacement)
129                         continue;
130                 bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
131                 if (!bio)
132                         goto out_free_bio;
133                 r10_bio->devs[j].repl_bio = bio;
134         }
135         /*
136          * Allocate RESYNC_PAGES data pages and attach them
137          * where needed.
138          */
139         for (j = 0 ; j < nalloc; j++) {
140                 struct bio *rbio = r10_bio->devs[j].repl_bio;
141                 bio = r10_bio->devs[j].bio;
142                 for (i = 0; i < RESYNC_PAGES; i++) {
143                         if (j == 1 && !test_bit(MD_RECOVERY_SYNC,
144                                                 &conf->mddev->recovery)) {
145                                 /* we can share bv_page's during recovery */
146                                 struct bio *rbio = r10_bio->devs[0].bio;
147                                 page = rbio->bi_io_vec[i].bv_page;
148                                 get_page(page);
149                         } else
150                                 page = alloc_page(gfp_flags);
151                         if (unlikely(!page))
152                                 goto out_free_pages;
153
154                         bio->bi_io_vec[i].bv_page = page;
155                         if (rbio)
156                                 rbio->bi_io_vec[i].bv_page = page;
157                 }
158         }
159
160         return r10_bio;
161
162 out_free_pages:
163         for ( ; i > 0 ; i--)
164                 safe_put_page(bio->bi_io_vec[i-1].bv_page);
165         while (j--)
166                 for (i = 0; i < RESYNC_PAGES ; i++)
167                         safe_put_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
168         j = -1;
169 out_free_bio:
170         while (++j < nalloc) {
171                 bio_put(r10_bio->devs[j].bio);
172                 if (r10_bio->devs[j].repl_bio)
173                         bio_put(r10_bio->devs[j].repl_bio);
174         }
175         r10bio_pool_free(r10_bio, conf);
176         return NULL;
177 }
178
179 static void r10buf_pool_free(void *__r10_bio, void *data)
180 {
181         int i;
182         struct r10conf *conf = data;
183         struct r10bio *r10bio = __r10_bio;
184         int j;
185
186         for (j=0; j < conf->copies; j++) {
187                 struct bio *bio = r10bio->devs[j].bio;
188                 if (bio) {
189                         for (i = 0; i < RESYNC_PAGES; i++) {
190                                 safe_put_page(bio->bi_io_vec[i].bv_page);
191                                 bio->bi_io_vec[i].bv_page = NULL;
192                         }
193                         bio_put(bio);
194                 }
195                 bio = r10bio->devs[j].repl_bio;
196                 if (bio)
197                         bio_put(bio);
198         }
199         r10bio_pool_free(r10bio, conf);
200 }
201
202 static void put_all_bios(struct r10conf *conf, struct r10bio *r10_bio)
203 {
204         int i;
205
206         for (i = 0; i < conf->copies; i++) {
207                 struct bio **bio = & r10_bio->devs[i].bio;
208                 if (!BIO_SPECIAL(*bio))
209                         bio_put(*bio);
210                 *bio = NULL;
211                 bio = &r10_bio->devs[i].repl_bio;
212                 if (r10_bio->read_slot < 0 && !BIO_SPECIAL(*bio))
213                         bio_put(*bio);
214                 *bio = NULL;
215         }
216 }
217
218 static void free_r10bio(struct r10bio *r10_bio)
219 {
220         struct r10conf *conf = r10_bio->mddev->private;
221
222         put_all_bios(conf, r10_bio);
223         mempool_free(r10_bio, conf->r10bio_pool);
224 }
225
226 static void put_buf(struct r10bio *r10_bio)
227 {
228         struct r10conf *conf = r10_bio->mddev->private;
229
230         mempool_free(r10_bio, conf->r10buf_pool);
231
232         lower_barrier(conf);
233 }
234
235 static void reschedule_retry(struct r10bio *r10_bio)
236 {
237         unsigned long flags;
238         struct mddev *mddev = r10_bio->mddev;
239         struct r10conf *conf = mddev->private;
240
241         spin_lock_irqsave(&conf->device_lock, flags);
242         list_add(&r10_bio->retry_list, &conf->retry_list);
243         conf->nr_queued ++;
244         spin_unlock_irqrestore(&conf->device_lock, flags);
245
246         /* wake up frozen array... */
247         wake_up(&conf->wait_barrier);
248
249         md_wakeup_thread(mddev->thread);
250 }
251
252 /*
253  * raid_end_bio_io() is called when we have finished servicing a mirrored
254  * operation and are ready to return a success/failure code to the buffer
255  * cache layer.
256  */
257 static void raid_end_bio_io(struct r10bio *r10_bio)
258 {
259         struct bio *bio = r10_bio->master_bio;
260         int done;
261         struct r10conf *conf = r10_bio->mddev->private;
262
263         if (bio->bi_phys_segments) {
264                 unsigned long flags;
265                 spin_lock_irqsave(&conf->device_lock, flags);
266                 bio->bi_phys_segments--;
267                 done = (bio->bi_phys_segments == 0);
268                 spin_unlock_irqrestore(&conf->device_lock, flags);
269         } else
270                 done = 1;
271         if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
272                 clear_bit(BIO_UPTODATE, &bio->bi_flags);
273         if (done) {
274                 bio_endio(bio, 0);
275                 /*
276                  * Wake up any possible resync thread that waits for the device
277                  * to go idle.
278                  */
279                 allow_barrier(conf);
280         }
281         free_r10bio(r10_bio);
282 }
283
284 /*
285  * Update disk head position estimator based on IRQ completion info.
286  */
287 static inline void update_head_pos(int slot, struct r10bio *r10_bio)
288 {
289         struct r10conf *conf = r10_bio->mddev->private;
290
291         conf->mirrors[r10_bio->devs[slot].devnum].head_position =
292                 r10_bio->devs[slot].addr + (r10_bio->sectors);
293 }
294
295 /*
296  * Find the disk number which triggered given bio
297  */
298 static int find_bio_disk(struct r10conf *conf, struct r10bio *r10_bio,
299                          struct bio *bio, int *slotp, int *replp)
300 {
301         int slot;
302         int repl = 0;
303
304         for (slot = 0; slot < conf->copies; slot++) {
305                 if (r10_bio->devs[slot].bio == bio)
306                         break;
307                 if (r10_bio->devs[slot].repl_bio == bio) {
308                         repl = 1;
309                         break;
310                 }
311         }
312
313         BUG_ON(slot == conf->copies);
314         update_head_pos(slot, r10_bio);
315
316         if (slotp)
317                 *slotp = slot;
318         if (replp)
319                 *replp = repl;
320         return r10_bio->devs[slot].devnum;
321 }
322
323 static void raid10_end_read_request(struct bio *bio, int error)
324 {
325         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
326         struct r10bio *r10_bio = bio->bi_private;
327         int slot, dev;
328         struct md_rdev *rdev;
329         struct r10conf *conf = r10_bio->mddev->private;
330
331
332         slot = r10_bio->read_slot;
333         dev = r10_bio->devs[slot].devnum;
334         rdev = r10_bio->devs[slot].rdev;
335         /*
336          * this branch is our 'one mirror IO has finished' event handler:
337          */
338         update_head_pos(slot, r10_bio);
339
340         if (uptodate) {
341                 /*
342                  * Set R10BIO_Uptodate in our master bio, so that
343                  * we will return a good error code to the higher
344                  * levels even if IO on some other mirrored buffer fails.
345                  *
346                  * The 'master' represents the composite IO operation to
347                  * user-side. So if something waits for IO, then it will
348                  * wait for the 'master' bio.
349                  */
350                 set_bit(R10BIO_Uptodate, &r10_bio->state);
351         } else {
352                 /* If all other devices that store this block have
353                  * failed, we want to return the error upwards rather
354                  * than fail the last device.  Here we redefine
355                  * "uptodate" to mean "Don't want to retry"
356                  */
357                 unsigned long flags;
358                 spin_lock_irqsave(&conf->device_lock, flags);
359                 if (!enough(conf, rdev->raid_disk))
360                         uptodate = 1;
361                 spin_unlock_irqrestore(&conf->device_lock, flags);
362         }
363         if (uptodate) {
364                 raid_end_bio_io(r10_bio);
365                 rdev_dec_pending(rdev, conf->mddev);
366         } else {
367                 /*
368                  * oops, read error - keep the refcount on the rdev
369                  */
370                 char b[BDEVNAME_SIZE];
371                 printk_ratelimited(KERN_ERR
372                                    "md/raid10:%s: %s: rescheduling sector %llu\n",
373                                    mdname(conf->mddev),
374                                    bdevname(rdev->bdev, b),
375                                    (unsigned long long)r10_bio->sector);
376                 set_bit(R10BIO_ReadError, &r10_bio->state);
377                 reschedule_retry(r10_bio);
378         }
379 }
380
381 static void close_write(struct r10bio *r10_bio)
382 {
383         /* clear the bitmap if all writes complete successfully */
384         bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
385                         r10_bio->sectors,
386                         !test_bit(R10BIO_Degraded, &r10_bio->state),
387                         0);
388         md_write_end(r10_bio->mddev);
389 }
390
391 static void one_write_done(struct r10bio *r10_bio)
392 {
393         if (atomic_dec_and_test(&r10_bio->remaining)) {
394                 if (test_bit(R10BIO_WriteError, &r10_bio->state))
395                         reschedule_retry(r10_bio);
396                 else {
397                         close_write(r10_bio);
398                         if (test_bit(R10BIO_MadeGood, &r10_bio->state))
399                                 reschedule_retry(r10_bio);
400                         else
401                                 raid_end_bio_io(r10_bio);
402                 }
403         }
404 }
405
406 static void raid10_end_write_request(struct bio *bio, int error)
407 {
408         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
409         struct r10bio *r10_bio = bio->bi_private;
410         int dev;
411         int dec_rdev = 1;
412         struct r10conf *conf = r10_bio->mddev->private;
413         int slot, repl;
414         struct md_rdev *rdev = NULL;
415
416         dev = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
417
418         if (repl)
419                 rdev = conf->mirrors[dev].replacement;
420         if (!rdev) {
421                 smp_rmb();
422                 repl = 0;
423                 rdev = conf->mirrors[dev].rdev;
424         }
425         /*
426          * this branch is our 'one mirror IO has finished' event handler:
427          */
428         if (!uptodate) {
429                 if (repl)
430                         /* Never record new bad blocks to replacement,
431                          * just fail it.
432                          */
433                         md_error(rdev->mddev, rdev);
434                 else {
435                         set_bit(WriteErrorSeen, &rdev->flags);
436                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
437                                 set_bit(MD_RECOVERY_NEEDED,
438                                         &rdev->mddev->recovery);
439                         set_bit(R10BIO_WriteError, &r10_bio->state);
440                         dec_rdev = 0;
441                 }
442         } else {
443                 /*
444                  * Set R10BIO_Uptodate in our master bio, so that
445                  * we will return a good error code for to the higher
446                  * levels even if IO on some other mirrored buffer fails.
447                  *
448                  * The 'master' represents the composite IO operation to
449                  * user-side. So if something waits for IO, then it will
450                  * wait for the 'master' bio.
451                  */
452                 sector_t first_bad;
453                 int bad_sectors;
454
455                 set_bit(R10BIO_Uptodate, &r10_bio->state);
456
457                 /* Maybe we can clear some bad blocks. */
458                 if (is_badblock(rdev,
459                                 r10_bio->devs[slot].addr,
460                                 r10_bio->sectors,
461                                 &first_bad, &bad_sectors)) {
462                         bio_put(bio);
463                         if (repl)
464                                 r10_bio->devs[slot].repl_bio = IO_MADE_GOOD;
465                         else
466                                 r10_bio->devs[slot].bio = IO_MADE_GOOD;
467                         dec_rdev = 0;
468                         set_bit(R10BIO_MadeGood, &r10_bio->state);
469                 }
470         }
471
472         /*
473          *
474          * Let's see if all mirrored write operations have finished
475          * already.
476          */
477         one_write_done(r10_bio);
478         if (dec_rdev)
479                 rdev_dec_pending(conf->mirrors[dev].rdev, conf->mddev);
480 }
481
482 /*
483  * RAID10 layout manager
484  * As well as the chunksize and raid_disks count, there are two
485  * parameters: near_copies and far_copies.
486  * near_copies * far_copies must be <= raid_disks.
487  * Normally one of these will be 1.
488  * If both are 1, we get raid0.
489  * If near_copies == raid_disks, we get raid1.
490  *
491  * Chunks are laid out in raid0 style with near_copies copies of the
492  * first chunk, followed by near_copies copies of the next chunk and
493  * so on.
494  * If far_copies > 1, then after 1/far_copies of the array has been assigned
495  * as described above, we start again with a device offset of near_copies.
496  * So we effectively have another copy of the whole array further down all
497  * the drives, but with blocks on different drives.
498  * With this layout, and block is never stored twice on the one device.
499  *
500  * raid10_find_phys finds the sector offset of a given virtual sector
501  * on each device that it is on.
502  *
503  * raid10_find_virt does the reverse mapping, from a device and a
504  * sector offset to a virtual address
505  */
506
507 static void raid10_find_phys(struct r10conf *conf, struct r10bio *r10bio)
508 {
509         int n,f;
510         sector_t sector;
511         sector_t chunk;
512         sector_t stripe;
513         int dev;
514
515         int slot = 0;
516
517         /* now calculate first sector/dev */
518         chunk = r10bio->sector >> conf->chunk_shift;
519         sector = r10bio->sector & conf->chunk_mask;
520
521         chunk *= conf->near_copies;
522         stripe = chunk;
523         dev = sector_div(stripe, conf->raid_disks);
524         if (conf->far_offset)
525                 stripe *= conf->far_copies;
526
527         sector += stripe << conf->chunk_shift;
528
529         /* and calculate all the others */
530         for (n=0; n < conf->near_copies; n++) {
531                 int d = dev;
532                 sector_t s = sector;
533                 r10bio->devs[slot].addr = sector;
534                 r10bio->devs[slot].devnum = d;
535                 slot++;
536
537                 for (f = 1; f < conf->far_copies; f++) {
538                         d += conf->near_copies;
539                         if (d >= conf->raid_disks)
540                                 d -= conf->raid_disks;
541                         s += conf->stride;
542                         r10bio->devs[slot].devnum = d;
543                         r10bio->devs[slot].addr = s;
544                         slot++;
545                 }
546                 dev++;
547                 if (dev >= conf->raid_disks) {
548                         dev = 0;
549                         sector += (conf->chunk_mask + 1);
550                 }
551         }
552         BUG_ON(slot != conf->copies);
553 }
554
555 static sector_t raid10_find_virt(struct r10conf *conf, sector_t sector, int dev)
556 {
557         sector_t offset, chunk, vchunk;
558
559         offset = sector & conf->chunk_mask;
560         if (conf->far_offset) {
561                 int fc;
562                 chunk = sector >> conf->chunk_shift;
563                 fc = sector_div(chunk, conf->far_copies);
564                 dev -= fc * conf->near_copies;
565                 if (dev < 0)
566                         dev += conf->raid_disks;
567         } else {
568                 while (sector >= conf->stride) {
569                         sector -= conf->stride;
570                         if (dev < conf->near_copies)
571                                 dev += conf->raid_disks - conf->near_copies;
572                         else
573                                 dev -= conf->near_copies;
574                 }
575                 chunk = sector >> conf->chunk_shift;
576         }
577         vchunk = chunk * conf->raid_disks + dev;
578         sector_div(vchunk, conf->near_copies);
579         return (vchunk << conf->chunk_shift) + offset;
580 }
581
582 /**
583  *      raid10_mergeable_bvec -- tell bio layer if a two requests can be merged
584  *      @q: request queue
585  *      @bvm: properties of new bio
586  *      @biovec: the request that could be merged to it.
587  *
588  *      Return amount of bytes we can accept at this offset
589  *      If near_copies == raid_disk, there are no striping issues,
590  *      but in that case, the function isn't called at all.
591  */
592 static int raid10_mergeable_bvec(struct request_queue *q,
593                                  struct bvec_merge_data *bvm,
594                                  struct bio_vec *biovec)
595 {
596         struct mddev *mddev = q->queuedata;
597         sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
598         int max;
599         unsigned int chunk_sectors = mddev->chunk_sectors;
600         unsigned int bio_sectors = bvm->bi_size >> 9;
601
602         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
603         if (max < 0) max = 0; /* bio_add cannot handle a negative return */
604         if (max <= biovec->bv_len && bio_sectors == 0)
605                 return biovec->bv_len;
606         else
607                 return max;
608 }
609
610 /*
611  * This routine returns the disk from which the requested read should
612  * be done. There is a per-array 'next expected sequential IO' sector
613  * number - if this matches on the next IO then we use the last disk.
614  * There is also a per-disk 'last know head position' sector that is
615  * maintained from IRQ contexts, both the normal and the resync IO
616  * completion handlers update this position correctly. If there is no
617  * perfect sequential match then we pick the disk whose head is closest.
618  *
619  * If there are 2 mirrors in the same 2 devices, performance degrades
620  * because position is mirror, not device based.
621  *
622  * The rdev for the device selected will have nr_pending incremented.
623  */
624
625 /*
626  * FIXME: possibly should rethink readbalancing and do it differently
627  * depending on near_copies / far_copies geometry.
628  */
629 static struct md_rdev *read_balance(struct r10conf *conf,
630                                     struct r10bio *r10_bio,
631                                     int *max_sectors)
632 {
633         const sector_t this_sector = r10_bio->sector;
634         int disk, slot;
635         int sectors = r10_bio->sectors;
636         int best_good_sectors;
637         sector_t new_distance, best_dist;
638         struct md_rdev *rdev, *best_rdev;
639         int do_balance;
640         int best_slot;
641
642         raid10_find_phys(conf, r10_bio);
643         rcu_read_lock();
644 retry:
645         sectors = r10_bio->sectors;
646         best_slot = -1;
647         best_rdev = NULL;
648         best_dist = MaxSector;
649         best_good_sectors = 0;
650         do_balance = 1;
651         /*
652          * Check if we can balance. We can balance on the whole
653          * device if no resync is going on (recovery is ok), or below
654          * the resync window. We take the first readable disk when
655          * above the resync window.
656          */
657         if (conf->mddev->recovery_cp < MaxSector
658             && (this_sector + sectors >= conf->next_resync))
659                 do_balance = 0;
660
661         for (slot = 0; slot < conf->copies ; slot++) {
662                 sector_t first_bad;
663                 int bad_sectors;
664                 sector_t dev_sector;
665
666                 if (r10_bio->devs[slot].bio == IO_BLOCKED)
667                         continue;
668                 disk = r10_bio->devs[slot].devnum;
669                 rdev = rcu_dereference(conf->mirrors[disk].replacement);
670                 if (rdev == NULL || test_bit(Faulty, &rdev->flags) ||
671                     r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
672                         rdev = rcu_dereference(conf->mirrors[disk].rdev);
673                 if (rdev == NULL)
674                         continue;
675                 if (test_bit(Faulty, &rdev->flags))
676                         continue;
677                 if (!test_bit(In_sync, &rdev->flags) &&
678                     r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
679                         continue;
680
681                 dev_sector = r10_bio->devs[slot].addr;
682                 if (is_badblock(rdev, dev_sector, sectors,
683                                 &first_bad, &bad_sectors)) {
684                         if (best_dist < MaxSector)
685                                 /* Already have a better slot */
686                                 continue;
687                         if (first_bad <= dev_sector) {
688                                 /* Cannot read here.  If this is the
689                                  * 'primary' device, then we must not read
690                                  * beyond 'bad_sectors' from another device.
691                                  */
692                                 bad_sectors -= (dev_sector - first_bad);
693                                 if (!do_balance && sectors > bad_sectors)
694                                         sectors = bad_sectors;
695                                 if (best_good_sectors > sectors)
696                                         best_good_sectors = sectors;
697                         } else {
698                                 sector_t good_sectors =
699                                         first_bad - dev_sector;
700                                 if (good_sectors > best_good_sectors) {
701                                         best_good_sectors = good_sectors;
702                                         best_slot = slot;
703                                         best_rdev = rdev;
704                                 }
705                                 if (!do_balance)
706                                         /* Must read from here */
707                                         break;
708                         }
709                         continue;
710                 } else
711                         best_good_sectors = sectors;
712
713                 if (!do_balance)
714                         break;
715
716                 /* This optimisation is debatable, and completely destroys
717                  * sequential read speed for 'far copies' arrays.  So only
718                  * keep it for 'near' arrays, and review those later.
719                  */
720                 if (conf->near_copies > 1 && !atomic_read(&rdev->nr_pending))
721                         break;
722
723                 /* for far > 1 always use the lowest address */
724                 if (conf->far_copies > 1)
725                         new_distance = r10_bio->devs[slot].addr;
726                 else
727                         new_distance = abs(r10_bio->devs[slot].addr -
728                                            conf->mirrors[disk].head_position);
729                 if (new_distance < best_dist) {
730                         best_dist = new_distance;
731                         best_slot = slot;
732                         best_rdev = rdev;
733                 }
734         }
735         if (slot >= conf->copies) {
736                 slot = best_slot;
737                 rdev = best_rdev;
738         }
739
740         if (slot >= 0) {
741                 atomic_inc(&rdev->nr_pending);
742                 if (test_bit(Faulty, &rdev->flags)) {
743                         /* Cannot risk returning a device that failed
744                          * before we inc'ed nr_pending
745                          */
746                         rdev_dec_pending(rdev, conf->mddev);
747                         goto retry;
748                 }
749                 r10_bio->read_slot = slot;
750         } else
751                 rdev = NULL;
752         rcu_read_unlock();
753         *max_sectors = best_good_sectors;
754
755         return rdev;
756 }
757
758 static int raid10_congested(void *data, int bits)
759 {
760         struct mddev *mddev = data;
761         struct r10conf *conf = mddev->private;
762         int i, ret = 0;
763
764         if ((bits & (1 << BDI_async_congested)) &&
765             conf->pending_count >= max_queued_requests)
766                 return 1;
767
768         if (mddev_congested(mddev, bits))
769                 return 1;
770         rcu_read_lock();
771         for (i = 0; i < conf->raid_disks && ret == 0; i++) {
772                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
773                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
774                         struct request_queue *q = bdev_get_queue(rdev->bdev);
775
776                         ret |= bdi_congested(&q->backing_dev_info, bits);
777                 }
778         }
779         rcu_read_unlock();
780         return ret;
781 }
782
783 static void flush_pending_writes(struct r10conf *conf)
784 {
785         /* Any writes that have been queued but are awaiting
786          * bitmap updates get flushed here.
787          */
788         spin_lock_irq(&conf->device_lock);
789
790         if (conf->pending_bio_list.head) {
791                 struct bio *bio;
792                 bio = bio_list_get(&conf->pending_bio_list);
793                 conf->pending_count = 0;
794                 spin_unlock_irq(&conf->device_lock);
795                 /* flush any pending bitmap writes to disk
796                  * before proceeding w/ I/O */
797                 bitmap_unplug(conf->mddev->bitmap);
798                 wake_up(&conf->wait_barrier);
799
800                 while (bio) { /* submit pending writes */
801                         struct bio *next = bio->bi_next;
802                         bio->bi_next = NULL;
803                         generic_make_request(bio);
804                         bio = next;
805                 }
806         } else
807                 spin_unlock_irq(&conf->device_lock);
808 }
809
810 /* Barriers....
811  * Sometimes we need to suspend IO while we do something else,
812  * either some resync/recovery, or reconfigure the array.
813  * To do this we raise a 'barrier'.
814  * The 'barrier' is a counter that can be raised multiple times
815  * to count how many activities are happening which preclude
816  * normal IO.
817  * We can only raise the barrier if there is no pending IO.
818  * i.e. if nr_pending == 0.
819  * We choose only to raise the barrier if no-one is waiting for the
820  * barrier to go down.  This means that as soon as an IO request
821  * is ready, no other operations which require a barrier will start
822  * until the IO request has had a chance.
823  *
824  * So: regular IO calls 'wait_barrier'.  When that returns there
825  *    is no backgroup IO happening,  It must arrange to call
826  *    allow_barrier when it has finished its IO.
827  * backgroup IO calls must call raise_barrier.  Once that returns
828  *    there is no normal IO happeing.  It must arrange to call
829  *    lower_barrier when the particular background IO completes.
830  */
831
832 static void raise_barrier(struct r10conf *conf, int force)
833 {
834         BUG_ON(force && !conf->barrier);
835         spin_lock_irq(&conf->resync_lock);
836
837         /* Wait until no block IO is waiting (unless 'force') */
838         wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
839                             conf->resync_lock, );
840
841         /* block any new IO from starting */
842         conf->barrier++;
843
844         /* Now wait for all pending IO to complete */
845         wait_event_lock_irq(conf->wait_barrier,
846                             !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
847                             conf->resync_lock, );
848
849         spin_unlock_irq(&conf->resync_lock);
850 }
851
852 static void lower_barrier(struct r10conf *conf)
853 {
854         unsigned long flags;
855         spin_lock_irqsave(&conf->resync_lock, flags);
856         conf->barrier--;
857         spin_unlock_irqrestore(&conf->resync_lock, flags);
858         wake_up(&conf->wait_barrier);
859 }
860
861 static void wait_barrier(struct r10conf *conf)
862 {
863         spin_lock_irq(&conf->resync_lock);
864         if (conf->barrier) {
865                 conf->nr_waiting++;
866                 /* Wait for the barrier to drop.
867                  * However if there are already pending
868                  * requests (preventing the barrier from
869                  * rising completely), and the
870                  * pre-process bio queue isn't empty,
871                  * then don't wait, as we need to empty
872                  * that queue to get the nr_pending
873                  * count down.
874                  */
875                 wait_event_lock_irq(conf->wait_barrier,
876                                     !conf->barrier ||
877                                     (conf->nr_pending &&
878                                      current->bio_list &&
879                                      !bio_list_empty(current->bio_list)),
880                                     conf->resync_lock,
881                         );
882                 conf->nr_waiting--;
883         }
884         conf->nr_pending++;
885         spin_unlock_irq(&conf->resync_lock);
886 }
887
888 static void allow_barrier(struct r10conf *conf)
889 {
890         unsigned long flags;
891         spin_lock_irqsave(&conf->resync_lock, flags);
892         conf->nr_pending--;
893         spin_unlock_irqrestore(&conf->resync_lock, flags);
894         wake_up(&conf->wait_barrier);
895 }
896
897 static void freeze_array(struct r10conf *conf)
898 {
899         /* stop syncio and normal IO and wait for everything to
900          * go quiet.
901          * We increment barrier and nr_waiting, and then
902          * wait until nr_pending match nr_queued+1
903          * This is called in the context of one normal IO request
904          * that has failed. Thus any sync request that might be pending
905          * will be blocked by nr_pending, and we need to wait for
906          * pending IO requests to complete or be queued for re-try.
907          * Thus the number queued (nr_queued) plus this request (1)
908          * must match the number of pending IOs (nr_pending) before
909          * we continue.
910          */
911         spin_lock_irq(&conf->resync_lock);
912         conf->barrier++;
913         conf->nr_waiting++;
914         wait_event_lock_irq(conf->wait_barrier,
915                             conf->nr_pending == conf->nr_queued+1,
916                             conf->resync_lock,
917                             flush_pending_writes(conf));
918
919         spin_unlock_irq(&conf->resync_lock);
920 }
921
922 static void unfreeze_array(struct r10conf *conf)
923 {
924         /* reverse the effect of the freeze */
925         spin_lock_irq(&conf->resync_lock);
926         conf->barrier--;
927         conf->nr_waiting--;
928         wake_up(&conf->wait_barrier);
929         spin_unlock_irq(&conf->resync_lock);
930 }
931
932 static void make_request(struct mddev *mddev, struct bio * bio)
933 {
934         struct r10conf *conf = mddev->private;
935         struct r10bio *r10_bio;
936         struct bio *read_bio;
937         int i;
938         int chunk_sects = conf->chunk_mask + 1;
939         const int rw = bio_data_dir(bio);
940         const unsigned long do_sync = (bio->bi_rw & REQ_SYNC);
941         const unsigned long do_fua = (bio->bi_rw & REQ_FUA);
942         unsigned long flags;
943         struct md_rdev *blocked_rdev;
944         int plugged;
945         int sectors_handled;
946         int max_sectors;
947
948         if (unlikely(bio->bi_rw & REQ_FLUSH)) {
949                 md_flush_request(mddev, bio);
950                 return;
951         }
952
953         /* If this request crosses a chunk boundary, we need to
954          * split it.  This will only happen for 1 PAGE (or less) requests.
955          */
956         if (unlikely( (bio->bi_sector & conf->chunk_mask) + (bio->bi_size >> 9)
957                       > chunk_sects &&
958                     conf->near_copies < conf->raid_disks)) {
959                 struct bio_pair *bp;
960                 /* Sanity check -- queue functions should prevent this happening */
961                 if (bio->bi_vcnt != 1 ||
962                     bio->bi_idx != 0)
963                         goto bad_map;
964                 /* This is a one page bio that upper layers
965                  * refuse to split for us, so we need to split it.
966                  */
967                 bp = bio_split(bio,
968                                chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
969
970                 /* Each of these 'make_request' calls will call 'wait_barrier'.
971                  * If the first succeeds but the second blocks due to the resync
972                  * thread raising the barrier, we will deadlock because the
973                  * IO to the underlying device will be queued in generic_make_request
974                  * and will never complete, so will never reduce nr_pending.
975                  * So increment nr_waiting here so no new raise_barriers will
976                  * succeed, and so the second wait_barrier cannot block.
977                  */
978                 spin_lock_irq(&conf->resync_lock);
979                 conf->nr_waiting++;
980                 spin_unlock_irq(&conf->resync_lock);
981
982                 make_request(mddev, &bp->bio1);
983                 make_request(mddev, &bp->bio2);
984
985                 spin_lock_irq(&conf->resync_lock);
986                 conf->nr_waiting--;
987                 wake_up(&conf->wait_barrier);
988                 spin_unlock_irq(&conf->resync_lock);
989
990                 bio_pair_release(bp);
991                 return;
992         bad_map:
993                 printk("md/raid10:%s: make_request bug: can't convert block across chunks"
994                        " or bigger than %dk %llu %d\n", mdname(mddev), chunk_sects/2,
995                        (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
996
997                 bio_io_error(bio);
998                 return;
999         }
1000
1001         md_write_start(mddev, bio);
1002
1003         /*
1004          * Register the new request and wait if the reconstruction
1005          * thread has put up a bar for new requests.
1006          * Continue immediately if no resync is active currently.
1007          */
1008         wait_barrier(conf);
1009
1010         r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1011
1012         r10_bio->master_bio = bio;
1013         r10_bio->sectors = bio->bi_size >> 9;
1014
1015         r10_bio->mddev = mddev;
1016         r10_bio->sector = bio->bi_sector;
1017         r10_bio->state = 0;
1018
1019         /* We might need to issue multiple reads to different
1020          * devices if there are bad blocks around, so we keep
1021          * track of the number of reads in bio->bi_phys_segments.
1022          * If this is 0, there is only one r10_bio and no locking
1023          * will be needed when the request completes.  If it is
1024          * non-zero, then it is the number of not-completed requests.
1025          */
1026         bio->bi_phys_segments = 0;
1027         clear_bit(BIO_SEG_VALID, &bio->bi_flags);
1028
1029         if (rw == READ) {
1030                 /*
1031                  * read balancing logic:
1032                  */
1033                 struct md_rdev *rdev;
1034                 int slot;
1035
1036 read_again:
1037                 rdev = read_balance(conf, r10_bio, &max_sectors);
1038                 if (!rdev) {
1039                         raid_end_bio_io(r10_bio);
1040                         return;
1041                 }
1042                 slot = r10_bio->read_slot;
1043
1044                 read_bio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1045                 md_trim_bio(read_bio, r10_bio->sector - bio->bi_sector,
1046                             max_sectors);
1047
1048                 r10_bio->devs[slot].bio = read_bio;
1049                 r10_bio->devs[slot].rdev = rdev;
1050
1051                 read_bio->bi_sector = r10_bio->devs[slot].addr +
1052                         rdev->data_offset;
1053                 read_bio->bi_bdev = rdev->bdev;
1054                 read_bio->bi_end_io = raid10_end_read_request;
1055                 read_bio->bi_rw = READ | do_sync;
1056                 read_bio->bi_private = r10_bio;
1057
1058                 if (max_sectors < r10_bio->sectors) {
1059                         /* Could not read all from this device, so we will
1060                          * need another r10_bio.
1061                          */
1062                         sectors_handled = (r10_bio->sectors + max_sectors
1063                                            - bio->bi_sector);
1064                         r10_bio->sectors = max_sectors;
1065                         spin_lock_irq(&conf->device_lock);
1066                         if (bio->bi_phys_segments == 0)
1067                                 bio->bi_phys_segments = 2;
1068                         else
1069                                 bio->bi_phys_segments++;
1070                         spin_unlock(&conf->device_lock);
1071                         /* Cannot call generic_make_request directly
1072                          * as that will be queued in __generic_make_request
1073                          * and subsequent mempool_alloc might block
1074                          * waiting for it.  so hand bio over to raid10d.
1075                          */
1076                         reschedule_retry(r10_bio);
1077
1078                         r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1079
1080                         r10_bio->master_bio = bio;
1081                         r10_bio->sectors = ((bio->bi_size >> 9)
1082                                             - sectors_handled);
1083                         r10_bio->state = 0;
1084                         r10_bio->mddev = mddev;
1085                         r10_bio->sector = bio->bi_sector + sectors_handled;
1086                         goto read_again;
1087                 } else
1088                         generic_make_request(read_bio);
1089                 return;
1090         }
1091
1092         /*
1093          * WRITE:
1094          */
1095         if (conf->pending_count >= max_queued_requests) {
1096                 md_wakeup_thread(mddev->thread);
1097                 wait_event(conf->wait_barrier,
1098                            conf->pending_count < max_queued_requests);
1099         }
1100         /* first select target devices under rcu_lock and
1101          * inc refcount on their rdev.  Record them by setting
1102          * bios[x] to bio
1103          * If there are known/acknowledged bad blocks on any device
1104          * on which we have seen a write error, we want to avoid
1105          * writing to those blocks.  This potentially requires several
1106          * writes to write around the bad blocks.  Each set of writes
1107          * gets its own r10_bio with a set of bios attached.  The number
1108          * of r10_bios is recored in bio->bi_phys_segments just as with
1109          * the read case.
1110          */
1111         plugged = mddev_check_plugged(mddev);
1112
1113         r10_bio->read_slot = -1; /* make sure repl_bio gets freed */
1114         raid10_find_phys(conf, r10_bio);
1115 retry_write:
1116         blocked_rdev = NULL;
1117         rcu_read_lock();
1118         max_sectors = r10_bio->sectors;
1119
1120         for (i = 0;  i < conf->copies; i++) {
1121                 int d = r10_bio->devs[i].devnum;
1122                 struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
1123                 struct md_rdev *rrdev = rcu_dereference(
1124                         conf->mirrors[d].replacement);
1125                 if (rdev == rrdev)
1126                         rrdev = NULL;
1127                 if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
1128                         atomic_inc(&rdev->nr_pending);
1129                         blocked_rdev = rdev;
1130                         break;
1131                 }
1132                 if (rrdev && unlikely(test_bit(Blocked, &rrdev->flags))) {
1133                         atomic_inc(&rrdev->nr_pending);
1134                         blocked_rdev = rrdev;
1135                         break;
1136                 }
1137                 if (rrdev && test_bit(Faulty, &rrdev->flags))
1138                         rrdev = NULL;
1139
1140                 r10_bio->devs[i].bio = NULL;
1141                 r10_bio->devs[i].repl_bio = NULL;
1142                 if (!rdev || test_bit(Faulty, &rdev->flags)) {
1143                         set_bit(R10BIO_Degraded, &r10_bio->state);
1144                         continue;
1145                 }
1146                 if (test_bit(WriteErrorSeen, &rdev->flags)) {
1147                         sector_t first_bad;
1148                         sector_t dev_sector = r10_bio->devs[i].addr;
1149                         int bad_sectors;
1150                         int is_bad;
1151
1152                         is_bad = is_badblock(rdev, dev_sector,
1153                                              max_sectors,
1154                                              &first_bad, &bad_sectors);
1155                         if (is_bad < 0) {
1156                                 /* Mustn't write here until the bad block
1157                                  * is acknowledged
1158                                  */
1159                                 atomic_inc(&rdev->nr_pending);
1160                                 set_bit(BlockedBadBlocks, &rdev->flags);
1161                                 blocked_rdev = rdev;
1162                                 break;
1163                         }
1164                         if (is_bad && first_bad <= dev_sector) {
1165                                 /* Cannot write here at all */
1166                                 bad_sectors -= (dev_sector - first_bad);
1167                                 if (bad_sectors < max_sectors)
1168                                         /* Mustn't write more than bad_sectors
1169                                          * to other devices yet
1170                                          */
1171                                         max_sectors = bad_sectors;
1172                                 /* We don't set R10BIO_Degraded as that
1173                                  * only applies if the disk is missing,
1174                                  * so it might be re-added, and we want to
1175                                  * know to recover this chunk.
1176                                  * In this case the device is here, and the
1177                                  * fact that this chunk is not in-sync is
1178                                  * recorded in the bad block log.
1179                                  */
1180                                 continue;
1181                         }
1182                         if (is_bad) {
1183                                 int good_sectors = first_bad - dev_sector;
1184                                 if (good_sectors < max_sectors)
1185                                         max_sectors = good_sectors;
1186                         }
1187                 }
1188                 r10_bio->devs[i].bio = bio;
1189                 atomic_inc(&rdev->nr_pending);
1190                 if (rrdev) {
1191                         r10_bio->devs[i].repl_bio = bio;
1192                         atomic_inc(&rrdev->nr_pending);
1193                 }
1194         }
1195         rcu_read_unlock();
1196
1197         if (unlikely(blocked_rdev)) {
1198                 /* Have to wait for this device to get unblocked, then retry */
1199                 int j;
1200                 int d;
1201
1202                 for (j = 0; j < i; j++) {
1203                         if (r10_bio->devs[j].bio) {
1204                                 d = r10_bio->devs[j].devnum;
1205                                 rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1206                         }
1207                         if (r10_bio->devs[j].repl_bio) {
1208                                 struct md_rdev *rdev;
1209                                 d = r10_bio->devs[j].devnum;
1210                                 rdev = conf->mirrors[d].replacement;
1211                                 if (!rdev) {
1212                                         /* Race with remove_disk */
1213                                         smp_mb();
1214                                         rdev = conf->mirrors[d].rdev;
1215                                 }
1216                                 rdev_dec_pending(rdev, mddev);
1217                         }
1218                 }
1219                 allow_barrier(conf);
1220                 md_wait_for_blocked_rdev(blocked_rdev, mddev);
1221                 wait_barrier(conf);
1222                 goto retry_write;
1223         }
1224
1225         if (max_sectors < r10_bio->sectors) {
1226                 /* We are splitting this into multiple parts, so
1227                  * we need to prepare for allocating another r10_bio.
1228                  */
1229                 r10_bio->sectors = max_sectors;
1230                 spin_lock_irq(&conf->device_lock);
1231                 if (bio->bi_phys_segments == 0)
1232                         bio->bi_phys_segments = 2;
1233                 else
1234                         bio->bi_phys_segments++;
1235                 spin_unlock_irq(&conf->device_lock);
1236         }
1237         sectors_handled = r10_bio->sector + max_sectors - bio->bi_sector;
1238
1239         atomic_set(&r10_bio->remaining, 1);
1240         bitmap_startwrite(mddev->bitmap, r10_bio->sector, r10_bio->sectors, 0);
1241
1242         for (i = 0; i < conf->copies; i++) {
1243                 struct bio *mbio;
1244                 int d = r10_bio->devs[i].devnum;
1245                 if (!r10_bio->devs[i].bio)
1246                         continue;
1247
1248                 mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1249                 md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1250                             max_sectors);
1251                 r10_bio->devs[i].bio = mbio;
1252
1253                 mbio->bi_sector = (r10_bio->devs[i].addr+
1254                                    conf->mirrors[d].rdev->data_offset);
1255                 mbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1256                 mbio->bi_end_io = raid10_end_write_request;
1257                 mbio->bi_rw = WRITE | do_sync | do_fua;
1258                 mbio->bi_private = r10_bio;
1259
1260                 atomic_inc(&r10_bio->remaining);
1261                 spin_lock_irqsave(&conf->device_lock, flags);
1262                 bio_list_add(&conf->pending_bio_list, mbio);
1263                 conf->pending_count++;
1264                 spin_unlock_irqrestore(&conf->device_lock, flags);
1265
1266                 if (!r10_bio->devs[i].repl_bio)
1267                         continue;
1268
1269                 mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1270                 md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1271                             max_sectors);
1272                 r10_bio->devs[i].repl_bio = mbio;
1273
1274                 /* We are actively writing to the original device
1275                  * so it cannot disappear, so the replacement cannot
1276                  * become NULL here
1277                  */
1278                 mbio->bi_sector = (r10_bio->devs[i].addr+
1279                                    conf->mirrors[d].replacement->data_offset);
1280                 mbio->bi_bdev = conf->mirrors[d].replacement->bdev;
1281                 mbio->bi_end_io = raid10_end_write_request;
1282                 mbio->bi_rw = WRITE | do_sync | do_fua;
1283                 mbio->bi_private = r10_bio;
1284
1285                 atomic_inc(&r10_bio->remaining);
1286                 spin_lock_irqsave(&conf->device_lock, flags);
1287                 bio_list_add(&conf->pending_bio_list, mbio);
1288                 conf->pending_count++;
1289                 spin_unlock_irqrestore(&conf->device_lock, flags);
1290         }
1291
1292         /* Don't remove the bias on 'remaining' (one_write_done) until
1293          * after checking if we need to go around again.
1294          */
1295
1296         if (sectors_handled < (bio->bi_size >> 9)) {
1297                 one_write_done(r10_bio);
1298                 /* We need another r10_bio.  It has already been counted
1299                  * in bio->bi_phys_segments.
1300                  */
1301                 r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1302
1303                 r10_bio->master_bio = bio;
1304                 r10_bio->sectors = (bio->bi_size >> 9) - sectors_handled;
1305
1306                 r10_bio->mddev = mddev;
1307                 r10_bio->sector = bio->bi_sector + sectors_handled;
1308                 r10_bio->state = 0;
1309                 goto retry_write;
1310         }
1311         one_write_done(r10_bio);
1312
1313         /* In case raid10d snuck in to freeze_array */
1314         wake_up(&conf->wait_barrier);
1315
1316         if (do_sync || !mddev->bitmap || !plugged)
1317                 md_wakeup_thread(mddev->thread);
1318 }
1319
1320 static void status(struct seq_file *seq, struct mddev *mddev)
1321 {
1322         struct r10conf *conf = mddev->private;
1323         int i;
1324
1325         if (conf->near_copies < conf->raid_disks)
1326                 seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
1327         if (conf->near_copies > 1)
1328                 seq_printf(seq, " %d near-copies", conf->near_copies);
1329         if (conf->far_copies > 1) {
1330                 if (conf->far_offset)
1331                         seq_printf(seq, " %d offset-copies", conf->far_copies);
1332                 else
1333                         seq_printf(seq, " %d far-copies", conf->far_copies);
1334         }
1335         seq_printf(seq, " [%d/%d] [", conf->raid_disks,
1336                                         conf->raid_disks - mddev->degraded);
1337         for (i = 0; i < conf->raid_disks; i++)
1338                 seq_printf(seq, "%s",
1339                               conf->mirrors[i].rdev &&
1340                               test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
1341         seq_printf(seq, "]");
1342 }
1343
1344 /* check if there are enough drives for
1345  * every block to appear on atleast one.
1346  * Don't consider the device numbered 'ignore'
1347  * as we might be about to remove it.
1348  */
1349 static int enough(struct r10conf *conf, int ignore)
1350 {
1351         int first = 0;
1352
1353         do {
1354                 int n = conf->copies;
1355                 int cnt = 0;
1356                 while (n--) {
1357                         if (conf->mirrors[first].rdev &&
1358                             first != ignore)
1359                                 cnt++;
1360                         first = (first+1) % conf->raid_disks;
1361                 }
1362                 if (cnt == 0)
1363                         return 0;
1364         } while (first != 0);
1365         return 1;
1366 }
1367
1368 static void error(struct mddev *mddev, struct md_rdev *rdev)
1369 {
1370         char b[BDEVNAME_SIZE];
1371         struct r10conf *conf = mddev->private;
1372
1373         /*
1374          * If it is not operational, then we have already marked it as dead
1375          * else if it is the last working disks, ignore the error, let the
1376          * next level up know.
1377          * else mark the drive as failed
1378          */
1379         if (test_bit(In_sync, &rdev->flags)
1380             && !enough(conf, rdev->raid_disk))
1381                 /*
1382                  * Don't fail the drive, just return an IO error.
1383                  */
1384                 return;
1385         if (test_and_clear_bit(In_sync, &rdev->flags)) {
1386                 unsigned long flags;
1387                 spin_lock_irqsave(&conf->device_lock, flags);
1388                 mddev->degraded++;
1389                 spin_unlock_irqrestore(&conf->device_lock, flags);
1390                 /*
1391                  * if recovery is running, make sure it aborts.
1392                  */
1393                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1394         }
1395         set_bit(Blocked, &rdev->flags);
1396         set_bit(Faulty, &rdev->flags);
1397         set_bit(MD_CHANGE_DEVS, &mddev->flags);
1398         printk(KERN_ALERT
1399                "md/raid10:%s: Disk failure on %s, disabling device.\n"
1400                "md/raid10:%s: Operation continuing on %d devices.\n",
1401                mdname(mddev), bdevname(rdev->bdev, b),
1402                mdname(mddev), conf->raid_disks - mddev->degraded);
1403 }
1404
1405 static void print_conf(struct r10conf *conf)
1406 {
1407         int i;
1408         struct mirror_info *tmp;
1409
1410         printk(KERN_DEBUG "RAID10 conf printout:\n");
1411         if (!conf) {
1412                 printk(KERN_DEBUG "(!conf)\n");
1413                 return;
1414         }
1415         printk(KERN_DEBUG " --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded,
1416                 conf->raid_disks);
1417
1418         for (i = 0; i < conf->raid_disks; i++) {
1419                 char b[BDEVNAME_SIZE];
1420                 tmp = conf->mirrors + i;
1421                 if (tmp->rdev)
1422                         printk(KERN_DEBUG " disk %d, wo:%d, o:%d, dev:%s\n",
1423                                 i, !test_bit(In_sync, &tmp->rdev->flags),
1424                                 !test_bit(Faulty, &tmp->rdev->flags),
1425                                 bdevname(tmp->rdev->bdev,b));
1426         }
1427 }
1428
1429 static void close_sync(struct r10conf *conf)
1430 {
1431         wait_barrier(conf);
1432         allow_barrier(conf);
1433
1434         mempool_destroy(conf->r10buf_pool);
1435         conf->r10buf_pool = NULL;
1436 }
1437
1438 static int raid10_spare_active(struct mddev *mddev)
1439 {
1440         int i;
1441         struct r10conf *conf = mddev->private;
1442         struct mirror_info *tmp;
1443         int count = 0;
1444         unsigned long flags;
1445
1446         /*
1447          * Find all non-in_sync disks within the RAID10 configuration
1448          * and mark them in_sync
1449          */
1450         for (i = 0; i < conf->raid_disks; i++) {
1451                 tmp = conf->mirrors + i;
1452                 if (tmp->replacement
1453                     && tmp->replacement->recovery_offset == MaxSector
1454                     && !test_bit(Faulty, &tmp->replacement->flags)
1455                     && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
1456                         /* Replacement has just become active */
1457                         if (!tmp->rdev
1458                             || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
1459                                 count++;
1460                         if (tmp->rdev) {
1461                                 /* Replaced device not technically faulty,
1462                                  * but we need to be sure it gets removed
1463                                  * and never re-added.
1464                                  */
1465                                 set_bit(Faulty, &tmp->rdev->flags);
1466                                 sysfs_notify_dirent_safe(
1467                                         tmp->rdev->sysfs_state);
1468                         }
1469                         sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
1470                 } else if (tmp->rdev
1471                            && !test_bit(Faulty, &tmp->rdev->flags)
1472                            && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1473                         count++;
1474                         sysfs_notify_dirent(tmp->rdev->sysfs_state);
1475                 }
1476         }
1477         spin_lock_irqsave(&conf->device_lock, flags);
1478         mddev->degraded -= count;
1479         spin_unlock_irqrestore(&conf->device_lock, flags);
1480
1481         print_conf(conf);
1482         return count;
1483 }
1484
1485
1486 static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1487 {
1488         struct r10conf *conf = mddev->private;
1489         int err = -EEXIST;
1490         int mirror;
1491         int first = 0;
1492         int last = conf->raid_disks - 1;
1493
1494         if (mddev->recovery_cp < MaxSector)
1495                 /* only hot-add to in-sync arrays, as recovery is
1496                  * very different from resync
1497                  */
1498                 return -EBUSY;
1499         if (rdev->saved_raid_disk < 0 && !enough(conf, -1))
1500                 return -EINVAL;
1501
1502         if (rdev->raid_disk >= 0)
1503                 first = last = rdev->raid_disk;
1504
1505         if (rdev->saved_raid_disk >= first &&
1506             conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1507                 mirror = rdev->saved_raid_disk;
1508         else
1509                 mirror = first;
1510         for ( ; mirror <= last ; mirror++) {
1511                 struct mirror_info *p = &conf->mirrors[mirror];
1512                 if (p->recovery_disabled == mddev->recovery_disabled)
1513                         continue;
1514                 if (p->rdev) {
1515                         if (!test_bit(WantReplacement, &p->rdev->flags) ||
1516                             p->replacement != NULL)
1517                                 continue;
1518                         clear_bit(In_sync, &rdev->flags);
1519                         set_bit(Replacement, &rdev->flags);
1520                         rdev->raid_disk = mirror;
1521                         err = 0;
1522                         disk_stack_limits(mddev->gendisk, rdev->bdev,
1523                                           rdev->data_offset << 9);
1524                         if (rdev->bdev->bd_disk->queue->merge_bvec_fn) {
1525                                 blk_queue_max_segments(mddev->queue, 1);
1526                                 blk_queue_segment_boundary(mddev->queue,
1527                                                            PAGE_CACHE_SIZE - 1);
1528                         }
1529                         conf->fullsync = 1;
1530                         rcu_assign_pointer(p->replacement, rdev);
1531                         break;
1532                 }
1533
1534                 disk_stack_limits(mddev->gendisk, rdev->bdev,
1535                                   rdev->data_offset << 9);
1536                 /* as we don't honour merge_bvec_fn, we must
1537                  * never risk violating it, so limit
1538                  * ->max_segments to one lying with a single
1539                  * page, as a one page request is never in
1540                  * violation.
1541                  */
1542                 if (rdev->bdev->bd_disk->queue->merge_bvec_fn) {
1543                         blk_queue_max_segments(mddev->queue, 1);
1544                         blk_queue_segment_boundary(mddev->queue,
1545                                                    PAGE_CACHE_SIZE - 1);
1546                 }
1547
1548                 p->head_position = 0;
1549                 p->recovery_disabled = mddev->recovery_disabled - 1;
1550                 rdev->raid_disk = mirror;
1551                 err = 0;
1552                 if (rdev->saved_raid_disk != mirror)
1553                         conf->fullsync = 1;
1554                 rcu_assign_pointer(p->rdev, rdev);
1555                 break;
1556         }
1557
1558         md_integrity_add_rdev(rdev, mddev);
1559         print_conf(conf);
1560         return err;
1561 }
1562
1563 static int raid10_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1564 {
1565         struct r10conf *conf = mddev->private;
1566         int err = 0;
1567         int number = rdev->raid_disk;
1568         struct md_rdev **rdevp;
1569         struct mirror_info *p = conf->mirrors + number;
1570
1571         print_conf(conf);
1572         if (rdev == p->rdev)
1573                 rdevp = &p->rdev;
1574         else if (rdev == p->replacement)
1575                 rdevp = &p->replacement;
1576         else
1577                 return 0;
1578
1579         if (test_bit(In_sync, &rdev->flags) ||
1580             atomic_read(&rdev->nr_pending)) {
1581                 err = -EBUSY;
1582                 goto abort;
1583         }
1584         /* Only remove faulty devices if recovery
1585          * is not possible.
1586          */
1587         if (!test_bit(Faulty, &rdev->flags) &&
1588             mddev->recovery_disabled != p->recovery_disabled &&
1589             (!p->replacement || p->replacement == rdev) &&
1590             enough(conf, -1)) {
1591                 err = -EBUSY;
1592                 goto abort;
1593         }
1594         *rdevp = NULL;
1595         synchronize_rcu();
1596         if (atomic_read(&rdev->nr_pending)) {
1597                 /* lost the race, try later */
1598                 err = -EBUSY;
1599                 *rdevp = rdev;
1600                 goto abort;
1601         } else if (p->replacement) {
1602                 /* We must have just cleared 'rdev' */
1603                 p->rdev = p->replacement;
1604                 clear_bit(Replacement, &p->replacement->flags);
1605                 smp_mb(); /* Make sure other CPUs may see both as identical
1606                            * but will never see neither -- if they are careful.
1607                            */
1608                 p->replacement = NULL;
1609                 clear_bit(WantReplacement, &rdev->flags);
1610         } else
1611                 /* We might have just remove the Replacement as faulty
1612                  * Clear the flag just in case
1613                  */
1614                 clear_bit(WantReplacement, &rdev->flags);
1615
1616         err = md_integrity_register(mddev);
1617
1618 abort:
1619
1620         print_conf(conf);
1621         return err;
1622 }
1623
1624
1625 static void end_sync_read(struct bio *bio, int error)
1626 {
1627         struct r10bio *r10_bio = bio->bi_private;
1628         struct r10conf *conf = r10_bio->mddev->private;
1629         int d;
1630
1631         d = find_bio_disk(conf, r10_bio, bio, NULL, NULL);
1632
1633         if (test_bit(BIO_UPTODATE, &bio->bi_flags))
1634                 set_bit(R10BIO_Uptodate, &r10_bio->state);
1635         else
1636                 /* The write handler will notice the lack of
1637                  * R10BIO_Uptodate and record any errors etc
1638                  */
1639                 atomic_add(r10_bio->sectors,
1640                            &conf->mirrors[d].rdev->corrected_errors);
1641
1642         /* for reconstruct, we always reschedule after a read.
1643          * for resync, only after all reads
1644          */
1645         rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1646         if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1647             atomic_dec_and_test(&r10_bio->remaining)) {
1648                 /* we have read all the blocks,
1649                  * do the comparison in process context in raid10d
1650                  */
1651                 reschedule_retry(r10_bio);
1652         }
1653 }
1654
1655 static void end_sync_request(struct r10bio *r10_bio)
1656 {
1657         struct mddev *mddev = r10_bio->mddev;
1658
1659         while (atomic_dec_and_test(&r10_bio->remaining)) {
1660                 if (r10_bio->master_bio == NULL) {
1661                         /* the primary of several recovery bios */
1662                         sector_t s = r10_bio->sectors;
1663                         if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1664                             test_bit(R10BIO_WriteError, &r10_bio->state))
1665                                 reschedule_retry(r10_bio);
1666                         else
1667                                 put_buf(r10_bio);
1668                         md_done_sync(mddev, s, 1);
1669                         break;
1670                 } else {
1671                         struct r10bio *r10_bio2 = (struct r10bio *)r10_bio->master_bio;
1672                         if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1673                             test_bit(R10BIO_WriteError, &r10_bio->state))
1674                                 reschedule_retry(r10_bio);
1675                         else
1676                                 put_buf(r10_bio);
1677                         r10_bio = r10_bio2;
1678                 }
1679         }
1680 }
1681
1682 static void end_sync_write(struct bio *bio, int error)
1683 {
1684         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1685         struct r10bio *r10_bio = bio->bi_private;
1686         struct mddev *mddev = r10_bio->mddev;
1687         struct r10conf *conf = mddev->private;
1688         int d;
1689         sector_t first_bad;
1690         int bad_sectors;
1691         int slot;
1692         int repl;
1693         struct md_rdev *rdev = NULL;
1694
1695         d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
1696         if (repl)
1697                 rdev = conf->mirrors[d].replacement;
1698         else
1699                 rdev = conf->mirrors[d].rdev;
1700
1701         if (!uptodate) {
1702                 if (repl)
1703                         md_error(mddev, rdev);
1704                 else {
1705                         set_bit(WriteErrorSeen, &rdev->flags);
1706                         if (!test_and_set_bit(WantReplacement, &rdev->flags))
1707                                 set_bit(MD_RECOVERY_NEEDED,
1708                                         &rdev->mddev->recovery);
1709                         set_bit(R10BIO_WriteError, &r10_bio->state);
1710                 }
1711         } else if (is_badblock(rdev,
1712                              r10_bio->devs[slot].addr,
1713                              r10_bio->sectors,
1714                              &first_bad, &bad_sectors))
1715                 set_bit(R10BIO_MadeGood, &r10_bio->state);
1716
1717         rdev_dec_pending(rdev, mddev);
1718
1719         end_sync_request(r10_bio);
1720 }
1721
1722 /*
1723  * Note: sync and recover and handled very differently for raid10
1724  * This code is for resync.
1725  * For resync, we read through virtual addresses and read all blocks.
1726  * If there is any error, we schedule a write.  The lowest numbered
1727  * drive is authoritative.
1728  * However requests come for physical address, so we need to map.
1729  * For every physical address there are raid_disks/copies virtual addresses,
1730  * which is always are least one, but is not necessarly an integer.
1731  * This means that a physical address can span multiple chunks, so we may
1732  * have to submit multiple io requests for a single sync request.
1733  */
1734 /*
1735  * We check if all blocks are in-sync and only write to blocks that
1736  * aren't in sync
1737  */
1738 static void sync_request_write(struct mddev *mddev, struct r10bio *r10_bio)
1739 {
1740         struct r10conf *conf = mddev->private;
1741         int i, first;
1742         struct bio *tbio, *fbio;
1743
1744         atomic_set(&r10_bio->remaining, 1);
1745
1746         /* find the first device with a block */
1747         for (i=0; i<conf->copies; i++)
1748                 if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1749                         break;
1750
1751         if (i == conf->copies)
1752                 goto done;
1753
1754         first = i;
1755         fbio = r10_bio->devs[i].bio;
1756
1757         /* now find blocks with errors */
1758         for (i=0 ; i < conf->copies ; i++) {
1759                 int  j, d;
1760                 int vcnt = r10_bio->sectors >> (PAGE_SHIFT-9);
1761
1762                 tbio = r10_bio->devs[i].bio;
1763
1764                 if (tbio->bi_end_io != end_sync_read)
1765                         continue;
1766                 if (i == first)
1767                         continue;
1768                 if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags)) {
1769                         /* We know that the bi_io_vec layout is the same for
1770                          * both 'first' and 'i', so we just compare them.
1771                          * All vec entries are PAGE_SIZE;
1772                          */
1773                         for (j = 0; j < vcnt; j++)
1774                                 if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
1775                                            page_address(tbio->bi_io_vec[j].bv_page),
1776                                            PAGE_SIZE))
1777                                         break;
1778                         if (j == vcnt)
1779                                 continue;
1780                         mddev->resync_mismatches += r10_bio->sectors;
1781                         if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1782                                 /* Don't fix anything. */
1783                                 continue;
1784                 }
1785                 /* Ok, we need to write this bio, either to correct an
1786                  * inconsistency or to correct an unreadable block.
1787                  * First we need to fixup bv_offset, bv_len and
1788                  * bi_vecs, as the read request might have corrupted these
1789                  */
1790                 tbio->bi_vcnt = vcnt;
1791                 tbio->bi_size = r10_bio->sectors << 9;
1792                 tbio->bi_idx = 0;
1793                 tbio->bi_phys_segments = 0;
1794                 tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1795                 tbio->bi_flags |= 1 << BIO_UPTODATE;
1796                 tbio->bi_next = NULL;
1797                 tbio->bi_rw = WRITE;
1798                 tbio->bi_private = r10_bio;
1799                 tbio->bi_sector = r10_bio->devs[i].addr;
1800
1801                 for (j=0; j < vcnt ; j++) {
1802                         tbio->bi_io_vec[j].bv_offset = 0;
1803                         tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
1804
1805                         memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1806                                page_address(fbio->bi_io_vec[j].bv_page),
1807                                PAGE_SIZE);
1808                 }
1809                 tbio->bi_end_io = end_sync_write;
1810
1811                 d = r10_bio->devs[i].devnum;
1812                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1813                 atomic_inc(&r10_bio->remaining);
1814                 md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
1815
1816                 tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
1817                 tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1818                 generic_make_request(tbio);
1819         }
1820
1821         /* Now write out to any replacement devices
1822          * that are active
1823          */
1824         for (i = 0; i < conf->copies; i++) {
1825                 int j, d;
1826                 int vcnt = r10_bio->sectors >> (PAGE_SHIFT-9);
1827
1828                 tbio = r10_bio->devs[i].repl_bio;
1829                 if (!tbio || !tbio->bi_end_io)
1830                         continue;
1831                 if (r10_bio->devs[i].bio->bi_end_io != end_sync_write
1832                     && r10_bio->devs[i].bio != fbio)
1833                         for (j = 0; j < vcnt; j++)
1834                                 memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1835                                        page_address(fbio->bi_io_vec[j].bv_page),
1836                                        PAGE_SIZE);
1837                 d = r10_bio->devs[i].devnum;
1838                 atomic_inc(&r10_bio->remaining);
1839                 md_sync_acct(conf->mirrors[d].replacement->bdev,
1840                              tbio->bi_size >> 9);
1841                 generic_make_request(tbio);
1842         }
1843
1844 done:
1845         if (atomic_dec_and_test(&r10_bio->remaining)) {
1846                 md_done_sync(mddev, r10_bio->sectors, 1);
1847                 put_buf(r10_bio);
1848         }
1849 }
1850
1851 /*
1852  * Now for the recovery code.
1853  * Recovery happens across physical sectors.
1854  * We recover all non-is_sync drives by finding the virtual address of
1855  * each, and then choose a working drive that also has that virt address.
1856  * There is a separate r10_bio for each non-in_sync drive.
1857  * Only the first two slots are in use. The first for reading,
1858  * The second for writing.
1859  *
1860  */
1861 static void fix_recovery_read_error(struct r10bio *r10_bio)
1862 {
1863         /* We got a read error during recovery.
1864          * We repeat the read in smaller page-sized sections.
1865          * If a read succeeds, write it to the new device or record
1866          * a bad block if we cannot.
1867          * If a read fails, record a bad block on both old and
1868          * new devices.
1869          */
1870         struct mddev *mddev = r10_bio->mddev;
1871         struct r10conf *conf = mddev->private;
1872         struct bio *bio = r10_bio->devs[0].bio;
1873         sector_t sect = 0;
1874         int sectors = r10_bio->sectors;
1875         int idx = 0;
1876         int dr = r10_bio->devs[0].devnum;
1877         int dw = r10_bio->devs[1].devnum;
1878
1879         while (sectors) {
1880                 int s = sectors;
1881                 struct md_rdev *rdev;
1882                 sector_t addr;
1883                 int ok;
1884
1885                 if (s > (PAGE_SIZE>>9))
1886                         s = PAGE_SIZE >> 9;
1887
1888                 rdev = conf->mirrors[dr].rdev;
1889                 addr = r10_bio->devs[0].addr + sect,
1890                 ok = sync_page_io(rdev,
1891                                   addr,
1892                                   s << 9,
1893                                   bio->bi_io_vec[idx].bv_page,
1894                                   READ, false);
1895                 if (ok) {
1896                         rdev = conf->mirrors[dw].rdev;
1897                         addr = r10_bio->devs[1].addr + sect;
1898                         ok = sync_page_io(rdev,
1899                                           addr,
1900                                           s << 9,
1901                                           bio->bi_io_vec[idx].bv_page,
1902                                           WRITE, false);
1903                         if (!ok) {
1904                                 set_bit(WriteErrorSeen, &rdev->flags);
1905                                 if (!test_and_set_bit(WantReplacement,
1906                                                       &rdev->flags))
1907                                         set_bit(MD_RECOVERY_NEEDED,
1908                                                 &rdev->mddev->recovery);
1909                         }
1910                 }
1911                 if (!ok) {
1912                         /* We don't worry if we cannot set a bad block -
1913                          * it really is bad so there is no loss in not
1914                          * recording it yet
1915                          */
1916                         rdev_set_badblocks(rdev, addr, s, 0);
1917
1918                         if (rdev != conf->mirrors[dw].rdev) {
1919                                 /* need bad block on destination too */
1920                                 struct md_rdev *rdev2 = conf->mirrors[dw].rdev;
1921                                 addr = r10_bio->devs[1].addr + sect;
1922                                 ok = rdev_set_badblocks(rdev2, addr, s, 0);
1923                                 if (!ok) {
1924                                         /* just abort the recovery */
1925                                         printk(KERN_NOTICE
1926                                                "md/raid10:%s: recovery aborted"
1927                                                " due to read error\n",
1928                                                mdname(mddev));
1929
1930                                         conf->mirrors[dw].recovery_disabled
1931                                                 = mddev->recovery_disabled;
1932                                         set_bit(MD_RECOVERY_INTR,
1933                                                 &mddev->recovery);
1934                                         break;
1935                                 }
1936                         }
1937                 }
1938
1939                 sectors -= s;
1940                 sect += s;
1941                 idx++;
1942         }
1943 }
1944
1945 static void recovery_request_write(struct mddev *mddev, struct r10bio *r10_bio)
1946 {
1947         struct r10conf *conf = mddev->private;
1948         int d;
1949         struct bio *wbio, *wbio2;
1950
1951         if (!test_bit(R10BIO_Uptodate, &r10_bio->state)) {
1952                 fix_recovery_read_error(r10_bio);
1953                 end_sync_request(r10_bio);
1954                 return;
1955         }
1956
1957         /*
1958          * share the pages with the first bio
1959          * and submit the write request
1960          */
1961         d = r10_bio->devs[1].devnum;
1962         wbio = r10_bio->devs[1].bio;
1963         wbio2 = r10_bio->devs[1].repl_bio;
1964         if (wbio->bi_end_io) {
1965                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1966                 md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
1967                 generic_make_request(wbio);
1968         }
1969         if (wbio2 && wbio2->bi_end_io) {
1970                 atomic_inc(&conf->mirrors[d].replacement->nr_pending);
1971                 md_sync_acct(conf->mirrors[d].replacement->bdev,
1972                              wbio2->bi_size >> 9);
1973                 generic_make_request(wbio2);
1974         }
1975 }
1976
1977
1978 /*
1979  * Used by fix_read_error() to decay the per rdev read_errors.
1980  * We halve the read error count for every hour that has elapsed
1981  * since the last recorded read error.
1982  *
1983  */
1984 static void check_decay_read_errors(struct mddev *mddev, struct md_rdev *rdev)
1985 {
1986         struct timespec cur_time_mon;
1987         unsigned long hours_since_last;
1988         unsigned int read_errors = atomic_read(&rdev->read_errors);
1989
1990         ktime_get_ts(&cur_time_mon);
1991
1992         if (rdev->last_read_error.tv_sec == 0 &&
1993             rdev->last_read_error.tv_nsec == 0) {
1994                 /* first time we've seen a read error */
1995                 rdev->last_read_error = cur_time_mon;
1996                 return;
1997         }
1998
1999         hours_since_last = (cur_time_mon.tv_sec -
2000                             rdev->last_read_error.tv_sec) / 3600;
2001
2002         rdev->last_read_error = cur_time_mon;
2003
2004         /*
2005          * if hours_since_last is > the number of bits in read_errors
2006          * just set read errors to 0. We do this to avoid
2007          * overflowing the shift of read_errors by hours_since_last.
2008          */
2009         if (hours_since_last >= 8 * sizeof(read_errors))
2010                 atomic_set(&rdev->read_errors, 0);
2011         else
2012                 atomic_set(&rdev->read_errors, read_errors >> hours_since_last);
2013 }
2014
2015 static int r10_sync_page_io(struct md_rdev *rdev, sector_t sector,
2016                             int sectors, struct page *page, int rw)
2017 {
2018         sector_t first_bad;
2019         int bad_sectors;
2020
2021         if (is_badblock(rdev, sector, sectors, &first_bad, &bad_sectors)
2022             && (rw == READ || test_bit(WriteErrorSeen, &rdev->flags)))
2023                 return -1;
2024         if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2025                 /* success */
2026                 return 1;
2027         if (rw == WRITE) {
2028                 set_bit(WriteErrorSeen, &rdev->flags);
2029                 if (!test_and_set_bit(WantReplacement, &rdev->flags))
2030                         set_bit(MD_RECOVERY_NEEDED,
2031                                 &rdev->mddev->recovery);
2032         }
2033         /* need to record an error - either for the block or the device */
2034         if (!rdev_set_badblocks(rdev, sector, sectors, 0))
2035                 md_error(rdev->mddev, rdev);
2036         return 0;
2037 }
2038
2039 /*
2040  * This is a kernel thread which:
2041  *
2042  *      1.      Retries failed read operations on working mirrors.
2043  *      2.      Updates the raid superblock when problems encounter.
2044  *      3.      Performs writes following reads for array synchronising.
2045  */
2046
2047 static void fix_read_error(struct r10conf *conf, struct mddev *mddev, struct r10bio *r10_bio)
2048 {
2049         int sect = 0; /* Offset from r10_bio->sector */
2050         int sectors = r10_bio->sectors;
2051         struct md_rdev*rdev;
2052         int max_read_errors = atomic_read(&mddev->max_corr_read_errors);
2053         int d = r10_bio->devs[r10_bio->read_slot].devnum;
2054
2055         /* still own a reference to this rdev, so it cannot
2056          * have been cleared recently.
2057          */
2058         rdev = conf->mirrors[d].rdev;
2059
2060         if (test_bit(Faulty, &rdev->flags))
2061                 /* drive has already been failed, just ignore any
2062                    more fix_read_error() attempts */
2063                 return;
2064
2065         check_decay_read_errors(mddev, rdev);
2066         atomic_inc(&rdev->read_errors);
2067         if (atomic_read(&rdev->read_errors) > max_read_errors) {
2068                 char b[BDEVNAME_SIZE];
2069                 bdevname(rdev->bdev, b);
2070
2071                 printk(KERN_NOTICE
2072                        "md/raid10:%s: %s: Raid device exceeded "
2073                        "read_error threshold [cur %d:max %d]\n",
2074                        mdname(mddev), b,
2075                        atomic_read(&rdev->read_errors), max_read_errors);
2076                 printk(KERN_NOTICE
2077                        "md/raid10:%s: %s: Failing raid device\n",
2078                        mdname(mddev), b);
2079                 md_error(mddev, conf->mirrors[d].rdev);
2080                 r10_bio->devs[r10_bio->read_slot].bio = IO_BLOCKED;
2081                 return;
2082         }
2083
2084         while(sectors) {
2085                 int s = sectors;
2086                 int sl = r10_bio->read_slot;
2087                 int success = 0;
2088                 int start;
2089
2090                 if (s > (PAGE_SIZE>>9))
2091                         s = PAGE_SIZE >> 9;
2092
2093                 rcu_read_lock();
2094                 do {
2095                         sector_t first_bad;
2096                         int bad_sectors;
2097
2098                         d = r10_bio->devs[sl].devnum;
2099                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2100                         if (rdev &&
2101                             test_bit(In_sync, &rdev->flags) &&
2102                             is_badblock(rdev, r10_bio->devs[sl].addr + sect, s,
2103                                         &first_bad, &bad_sectors) == 0) {
2104                                 atomic_inc(&rdev->nr_pending);
2105                                 rcu_read_unlock();
2106                                 success = sync_page_io(rdev,
2107                                                        r10_bio->devs[sl].addr +
2108                                                        sect,
2109                                                        s<<9,
2110                                                        conf->tmppage, READ, false);
2111                                 rdev_dec_pending(rdev, mddev);
2112                                 rcu_read_lock();
2113                                 if (success)
2114                                         break;
2115                         }
2116                         sl++;
2117                         if (sl == conf->copies)
2118                                 sl = 0;
2119                 } while (!success && sl != r10_bio->read_slot);
2120                 rcu_read_unlock();
2121
2122                 if (!success) {
2123                         /* Cannot read from anywhere, just mark the block
2124                          * as bad on the first device to discourage future
2125                          * reads.
2126                          */
2127                         int dn = r10_bio->devs[r10_bio->read_slot].devnum;
2128                         rdev = conf->mirrors[dn].rdev;
2129
2130                         if (!rdev_set_badblocks(
2131                                     rdev,
2132                                     r10_bio->devs[r10_bio->read_slot].addr
2133                                     + sect,
2134                                     s, 0)) {
2135                                 md_error(mddev, rdev);
2136                                 r10_bio->devs[r10_bio->read_slot].bio
2137                                         = IO_BLOCKED;
2138                         }
2139                         break;
2140                 }
2141
2142                 start = sl;
2143                 /* write it back and re-read */
2144                 rcu_read_lock();
2145                 while (sl != r10_bio->read_slot) {
2146                         char b[BDEVNAME_SIZE];
2147
2148                         if (sl==0)
2149                                 sl = conf->copies;
2150                         sl--;
2151                         d = r10_bio->devs[sl].devnum;
2152                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2153                         if (!rdev ||
2154                             !test_bit(In_sync, &rdev->flags))
2155                                 continue;
2156
2157                         atomic_inc(&rdev->nr_pending);
2158                         rcu_read_unlock();
2159                         if (r10_sync_page_io(rdev,
2160                                              r10_bio->devs[sl].addr +
2161                                              sect,
2162                                              s<<9, conf->tmppage, WRITE)
2163                             == 0) {
2164                                 /* Well, this device is dead */
2165                                 printk(KERN_NOTICE
2166                                        "md/raid10:%s: read correction "
2167                                        "write failed"
2168                                        " (%d sectors at %llu on %s)\n",
2169                                        mdname(mddev), s,
2170                                        (unsigned long long)(
2171                                                sect + rdev->data_offset),
2172                                        bdevname(rdev->bdev, b));
2173                                 printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2174                                        "drive\n",
2175                                        mdname(mddev),
2176                                        bdevname(rdev->bdev, b));
2177                         }
2178                         rdev_dec_pending(rdev, mddev);
2179                         rcu_read_lock();
2180                 }
2181                 sl = start;
2182                 while (sl != r10_bio->read_slot) {
2183                         char b[BDEVNAME_SIZE];
2184
2185                         if (sl==0)
2186                                 sl = conf->copies;
2187                         sl--;
2188                         d = r10_bio->devs[sl].devnum;
2189                         rdev = rcu_dereference(conf->mirrors[d].rdev);
2190                         if (!rdev ||
2191                             !test_bit(In_sync, &rdev->flags))
2192                                 continue;
2193
2194                         atomic_inc(&rdev->nr_pending);
2195                         rcu_read_unlock();
2196                         switch (r10_sync_page_io(rdev,
2197                                              r10_bio->devs[sl].addr +
2198                                              sect,
2199                                              s<<9, conf->tmppage,
2200                                                  READ)) {
2201                         case 0:
2202                                 /* Well, this device is dead */
2203                                 printk(KERN_NOTICE
2204                                        "md/raid10:%s: unable to read back "
2205                                        "corrected sectors"
2206                                        " (%d sectors at %llu on %s)\n",
2207                                        mdname(mddev), s,
2208                                        (unsigned long long)(
2209                                                sect + rdev->data_offset),
2210                                        bdevname(rdev->bdev, b));
2211                                 printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2212                                        "drive\n",
2213                                        mdname(mddev),
2214                                        bdevname(rdev->bdev, b));
2215                                 break;
2216                         case 1:
2217                                 printk(KERN_INFO
2218                                        "md/raid10:%s: read error corrected"
2219                                        " (%d sectors at %llu on %s)\n",
2220                                        mdname(mddev), s,
2221                                        (unsigned long long)(
2222                                                sect + rdev->data_offset),
2223                                        bdevname(rdev->bdev, b));
2224                                 atomic_add(s, &rdev->corrected_errors);
2225                         }
2226
2227                         rdev_dec_pending(rdev, mddev);
2228                         rcu_read_lock();
2229                 }
2230                 rcu_read_unlock();
2231
2232                 sectors -= s;
2233                 sect += s;
2234         }
2235 }
2236
2237 static void bi_complete(struct bio *bio, int error)
2238 {
2239         complete((struct completion *)bio->bi_private);
2240 }
2241
2242 static int submit_bio_wait(int rw, struct bio *bio)
2243 {
2244         struct completion event;
2245         rw |= REQ_SYNC;
2246
2247         init_completion(&event);
2248         bio->bi_private = &event;
2249         bio->bi_end_io = bi_complete;
2250         submit_bio(rw, bio);
2251         wait_for_completion(&event);
2252
2253         return test_bit(BIO_UPTODATE, &bio->bi_flags);
2254 }
2255
2256 static int narrow_write_error(struct r10bio *r10_bio, int i)
2257 {
2258         struct bio *bio = r10_bio->master_bio;
2259         struct mddev *mddev = r10_bio->mddev;
2260         struct r10conf *conf = mddev->private;
2261         struct md_rdev *rdev = conf->mirrors[r10_bio->devs[i].devnum].rdev;
2262         /* bio has the data to be written to slot 'i' where
2263          * we just recently had a write error.
2264          * We repeatedly clone the bio and trim down to one block,
2265          * then try the write.  Where the write fails we record
2266          * a bad block.
2267          * It is conceivable that the bio doesn't exactly align with
2268          * blocks.  We must handle this.
2269          *
2270          * We currently own a reference to the rdev.
2271          */
2272
2273         int block_sectors;
2274         sector_t sector;
2275         int sectors;
2276         int sect_to_write = r10_bio->sectors;
2277         int ok = 1;
2278
2279         if (rdev->badblocks.shift < 0)
2280                 return 0;
2281
2282         block_sectors = 1 << rdev->badblocks.shift;
2283         sector = r10_bio->sector;
2284         sectors = ((r10_bio->sector + block_sectors)
2285                    & ~(sector_t)(block_sectors - 1))
2286                 - sector;
2287
2288         while (sect_to_write) {
2289                 struct bio *wbio;
2290                 if (sectors > sect_to_write)
2291                         sectors = sect_to_write;
2292                 /* Write at 'sector' for 'sectors' */
2293                 wbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
2294                 md_trim_bio(wbio, sector - bio->bi_sector, sectors);
2295                 wbio->bi_sector = (r10_bio->devs[i].addr+
2296                                    rdev->data_offset+
2297                                    (sector - r10_bio->sector));
2298                 wbio->bi_bdev = rdev->bdev;
2299                 if (submit_bio_wait(WRITE, wbio) == 0)
2300                         /* Failure! */
2301                         ok = rdev_set_badblocks(rdev, sector,
2302                                                 sectors, 0)
2303                                 && ok;
2304
2305                 bio_put(wbio);
2306                 sect_to_write -= sectors;
2307                 sector += sectors;
2308                 sectors = block_sectors;
2309         }
2310         return ok;
2311 }
2312
2313 static void handle_read_error(struct mddev *mddev, struct r10bio *r10_bio)
2314 {
2315         int slot = r10_bio->read_slot;
2316         struct bio *bio;
2317         struct r10conf *conf = mddev->private;
2318         struct md_rdev *rdev = r10_bio->devs[slot].rdev;
2319         char b[BDEVNAME_SIZE];
2320         unsigned long do_sync;
2321         int max_sectors;
2322
2323         /* we got a read error. Maybe the drive is bad.  Maybe just
2324          * the block and we can fix it.
2325          * We freeze all other IO, and try reading the block from
2326          * other devices.  When we find one, we re-write
2327          * and check it that fixes the read error.
2328          * This is all done synchronously while the array is
2329          * frozen.
2330          */
2331         bio = r10_bio->devs[slot].bio;
2332         bdevname(bio->bi_bdev, b);
2333         bio_put(bio);
2334         r10_bio->devs[slot].bio = NULL;
2335
2336         if (mddev->ro == 0) {
2337                 freeze_array(conf);
2338                 fix_read_error(conf, mddev, r10_bio);
2339                 unfreeze_array(conf);
2340         } else
2341                 r10_bio->devs[slot].bio = IO_BLOCKED;
2342
2343         rdev_dec_pending(rdev, mddev);
2344
2345 read_more:
2346         rdev = read_balance(conf, r10_bio, &max_sectors);
2347         if (rdev == NULL) {
2348                 printk(KERN_ALERT "md/raid10:%s: %s: unrecoverable I/O"
2349                        " read error for block %llu\n",
2350                        mdname(mddev), b,
2351                        (unsigned long long)r10_bio->sector);
2352                 raid_end_bio_io(r10_bio);
2353                 return;
2354         }
2355
2356         do_sync = (r10_bio->master_bio->bi_rw & REQ_SYNC);
2357         slot = r10_bio->read_slot;
2358         printk_ratelimited(
2359                 KERN_ERR
2360                 "md/raid10:%s: %s: redirecting"
2361                 "sector %llu to another mirror\n",
2362                 mdname(mddev),
2363                 bdevname(rdev->bdev, b),
2364                 (unsigned long long)r10_bio->sector);
2365         bio = bio_clone_mddev(r10_bio->master_bio,
2366                               GFP_NOIO, mddev);
2367         md_trim_bio(bio,
2368                     r10_bio->sector - bio->bi_sector,
2369                     max_sectors);
2370         r10_bio->devs[slot].bio = bio;
2371         r10_bio->devs[slot].rdev = rdev;
2372         bio->bi_sector = r10_bio->devs[slot].addr
2373                 + rdev->data_offset;
2374         bio->bi_bdev = rdev->bdev;
2375         bio->bi_rw = READ | do_sync;
2376         bio->bi_private = r10_bio;
2377         bio->bi_end_io = raid10_end_read_request;
2378         if (max_sectors < r10_bio->sectors) {
2379                 /* Drat - have to split this up more */
2380                 struct bio *mbio = r10_bio->master_bio;
2381                 int sectors_handled =
2382                         r10_bio->sector + max_sectors
2383                         - mbio->bi_sector;
2384                 r10_bio->sectors = max_sectors;
2385                 spin_lock_irq(&conf->device_lock);
2386                 if (mbio->bi_phys_segments == 0)
2387                         mbio->bi_phys_segments = 2;
2388                 else
2389                         mbio->bi_phys_segments++;
2390                 spin_unlock_irq(&conf->device_lock);
2391                 generic_make_request(bio);
2392
2393                 r10_bio = mempool_alloc(conf->r10bio_pool,
2394                                         GFP_NOIO);
2395                 r10_bio->master_bio = mbio;
2396                 r10_bio->sectors = (mbio->bi_size >> 9)
2397                         - sectors_handled;
2398                 r10_bio->state = 0;
2399                 set_bit(R10BIO_ReadError,
2400                         &r10_bio->state);
2401                 r10_bio->mddev = mddev;
2402                 r10_bio->sector = mbio->bi_sector
2403                         + sectors_handled;
2404
2405                 goto read_more;
2406         } else
2407                 generic_make_request(bio);
2408 }
2409
2410 static void handle_write_completed(struct r10conf *conf, struct r10bio *r10_bio)
2411 {
2412         /* Some sort of write request has finished and it
2413          * succeeded in writing where we thought there was a
2414          * bad block.  So forget the bad block.
2415          * Or possibly if failed and we need to record
2416          * a bad block.
2417          */
2418         int m;
2419         struct md_rdev *rdev;
2420
2421         if (test_bit(R10BIO_IsSync, &r10_bio->state) ||
2422             test_bit(R10BIO_IsRecover, &r10_bio->state)) {
2423                 for (m = 0; m < conf->copies; m++) {
2424                         int dev = r10_bio->devs[m].devnum;
2425                         rdev = conf->mirrors[dev].rdev;
2426                         if (r10_bio->devs[m].bio == NULL)
2427                                 continue;
2428                         if (test_bit(BIO_UPTODATE,
2429                                      &r10_bio->devs[m].bio->bi_flags)) {
2430                                 rdev_clear_badblocks(
2431                                         rdev,
2432                                         r10_bio->devs[m].addr,
2433                                         r10_bio->sectors);
2434                         } else {
2435                                 if (!rdev_set_badblocks(
2436                                             rdev,
2437                                             r10_bio->devs[m].addr,
2438                                             r10_bio->sectors, 0))
2439                                         md_error(conf->mddev, rdev);
2440                         }
2441                         rdev = conf->mirrors[dev].replacement;
2442                         if (r10_bio->devs[m].repl_bio == NULL)
2443                                 continue;
2444                         if (test_bit(BIO_UPTODATE,
2445                                      &r10_bio->devs[m].repl_bio->bi_flags)) {
2446                                 rdev_clear_badblocks(
2447                                         rdev,
2448                                         r10_bio->devs[m].addr,
2449                                         r10_bio->sectors);
2450                         } else {
2451                                 if (!rdev_set_badblocks(
2452                                             rdev,
2453                                             r10_bio->devs[m].addr,
2454                                             r10_bio->sectors, 0))
2455                                         md_error(conf->mddev, rdev);
2456                         }
2457                 }
2458                 put_buf(r10_bio);
2459         } else {
2460                 for (m = 0; m < conf->copies; m++) {
2461                         int dev = r10_bio->devs[m].devnum;
2462                         struct bio *bio = r10_bio->devs[m].bio;
2463                         rdev = conf->mirrors[dev].rdev;
2464                         if (bio == IO_MADE_GOOD) {
2465                                 rdev_clear_badblocks(
2466                                         rdev,
2467                                         r10_bio->devs[m].addr,
2468                                         r10_bio->sectors);
2469                                 rdev_dec_pending(rdev, conf->mddev);
2470                         } else if (bio != NULL &&
2471                                    !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2472                                 if (!narrow_write_error(r10_bio, m)) {
2473                                         md_error(conf->mddev, rdev);
2474                                         set_bit(R10BIO_Degraded,
2475                                                 &r10_bio->state);
2476                                 }
2477                                 rdev_dec_pending(rdev, conf->mddev);
2478                         }
2479                         bio = r10_bio->devs[m].repl_bio;
2480                         rdev = conf->mirrors[dev].replacement;
2481                         if (rdev && bio == IO_MADE_GOOD) {
2482                                 rdev_clear_badblocks(
2483                                         rdev,
2484                                         r10_bio->devs[m].addr,
2485                                         r10_bio->sectors);
2486                                 rdev_dec_pending(rdev, conf->mddev);
2487                         }
2488                 }
2489                 if (test_bit(R10BIO_WriteError,
2490                              &r10_bio->state))
2491                         close_write(r10_bio);
2492                 raid_end_bio_io(r10_bio);
2493         }
2494 }
2495
2496 static void raid10d(struct mddev *mddev)
2497 {
2498         struct r10bio *r10_bio;
2499         unsigned long flags;
2500         struct r10conf *conf = mddev->private;
2501         struct list_head *head = &conf->retry_list;
2502         struct blk_plug plug;
2503
2504         md_check_recovery(mddev);
2505
2506         blk_start_plug(&plug);
2507         for (;;) {
2508
2509                 flush_pending_writes(conf);
2510
2511                 spin_lock_irqsave(&conf->device_lock, flags);
2512                 if (list_empty(head)) {
2513                         spin_unlock_irqrestore(&conf->device_lock, flags);
2514                         break;
2515                 }
2516                 r10_bio = list_entry(head->prev, struct r10bio, retry_list);
2517                 list_del(head->prev);
2518                 conf->nr_queued--;
2519                 spin_unlock_irqrestore(&conf->device_lock, flags);
2520
2521                 mddev = r10_bio->mddev;
2522                 conf = mddev->private;
2523                 if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
2524                     test_bit(R10BIO_WriteError, &r10_bio->state))
2525                         handle_write_completed(conf, r10_bio);
2526                 else if (test_bit(R10BIO_IsSync, &r10_bio->state))
2527                         sync_request_write(mddev, r10_bio);
2528                 else if (test_bit(R10BIO_IsRecover, &r10_bio->state))
2529                         recovery_request_write(mddev, r10_bio);
2530                 else if (test_bit(R10BIO_ReadError, &r10_bio->state))
2531                         handle_read_error(mddev, r10_bio);
2532                 else {
2533                         /* just a partial read to be scheduled from a
2534                          * separate context
2535                          */
2536                         int slot = r10_bio->read_slot;
2537                         generic_make_request(r10_bio->devs[slot].bio);
2538                 }
2539
2540                 cond_resched();
2541                 if (mddev->flags & ~(1<<MD_CHANGE_PENDING))
2542                         md_check_recovery(mddev);
2543         }
2544         blk_finish_plug(&plug);
2545 }
2546
2547
2548 static int init_resync(struct r10conf *conf)
2549 {
2550         int buffs;
2551         int i;
2552
2553         buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2554         BUG_ON(conf->r10buf_pool);
2555         conf->have_replacement = 0;
2556         for (i = 0; i < conf->raid_disks; i++)
2557                 if (conf->mirrors[i].replacement)
2558                         conf->have_replacement = 1;
2559         conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
2560         if (!conf->r10buf_pool)
2561                 return -ENOMEM;
2562         conf->next_resync = 0;
2563         return 0;
2564 }
2565
2566 /*
2567  * perform a "sync" on one "block"
2568  *
2569  * We need to make sure that no normal I/O request - particularly write
2570  * requests - conflict with active sync requests.
2571  *
2572  * This is achieved by tracking pending requests and a 'barrier' concept
2573  * that can be installed to exclude normal IO requests.
2574  *
2575  * Resync and recovery are handled very differently.
2576  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
2577  *
2578  * For resync, we iterate over virtual addresses, read all copies,
2579  * and update if there are differences.  If only one copy is live,
2580  * skip it.
2581  * For recovery, we iterate over physical addresses, read a good
2582  * value for each non-in_sync drive, and over-write.
2583  *
2584  * So, for recovery we may have several outstanding complex requests for a
2585  * given address, one for each out-of-sync device.  We model this by allocating
2586  * a number of r10_bio structures, one for each out-of-sync device.
2587  * As we setup these structures, we collect all bio's together into a list
2588  * which we then process collectively to add pages, and then process again
2589  * to pass to generic_make_request.
2590  *
2591  * The r10_bio structures are linked using a borrowed master_bio pointer.
2592  * This link is counted in ->remaining.  When the r10_bio that points to NULL
2593  * has its remaining count decremented to 0, the whole complex operation
2594  * is complete.
2595  *
2596  */
2597
2598 static sector_t sync_request(struct mddev *mddev, sector_t sector_nr,
2599                              int *skipped, int go_faster)
2600 {
2601         struct r10conf *conf = mddev->private;
2602         struct r10bio *r10_bio;
2603         struct bio *biolist = NULL, *bio;
2604         sector_t max_sector, nr_sectors;
2605         int i;
2606         int max_sync;
2607         sector_t sync_blocks;
2608         sector_t sectors_skipped = 0;
2609         int chunks_skipped = 0;
2610
2611         if (!conf->r10buf_pool)
2612                 if (init_resync(conf))
2613                         return 0;
2614
2615  skipped:
2616         max_sector = mddev->dev_sectors;
2617         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2618                 max_sector = mddev->resync_max_sectors;
2619         if (sector_nr >= max_sector) {
2620                 /* If we aborted, we need to abort the
2621                  * sync on the 'current' bitmap chucks (there can
2622                  * be several when recovering multiple devices).
2623                  * as we may have started syncing it but not finished.
2624                  * We can find the current address in
2625                  * mddev->curr_resync, but for recovery,
2626                  * we need to convert that to several
2627                  * virtual addresses.
2628                  */
2629                 if (mddev->curr_resync < max_sector) { /* aborted */
2630                         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2631                                 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
2632                                                 &sync_blocks, 1);
2633                         else for (i=0; i<conf->raid_disks; i++) {
2634                                 sector_t sect =
2635                                         raid10_find_virt(conf, mddev->curr_resync, i);
2636                                 bitmap_end_sync(mddev->bitmap, sect,
2637                                                 &sync_blocks, 1);
2638                         }
2639                 } else {
2640                         /* completed sync */
2641                         if ((!mddev->bitmap || conf->fullsync)
2642                             && conf->have_replacement
2643                             && test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2644                                 /* Completed a full sync so the replacements
2645                                  * are now fully recovered.
2646                                  */
2647                                 for (i = 0; i < conf->raid_disks; i++)
2648                                         if (conf->mirrors[i].replacement)
2649                                                 conf->mirrors[i].replacement
2650                                                         ->recovery_offset
2651                                                         = MaxSector;
2652                         }
2653                         conf->fullsync = 0;
2654                 }
2655                 bitmap_close_sync(mddev->bitmap);
2656                 close_sync(conf);
2657                 *skipped = 1;
2658                 return sectors_skipped;
2659         }
2660         if (chunks_skipped >= conf->raid_disks) {
2661                 /* if there has been nothing to do on any drive,
2662                  * then there is nothing to do at all..
2663                  */
2664                 *skipped = 1;
2665                 return (max_sector - sector_nr) + sectors_skipped;
2666         }
2667
2668         if (max_sector > mddev->resync_max)
2669                 max_sector = mddev->resync_max; /* Don't do IO beyond here */
2670
2671         /* make sure whole request will fit in a chunk - if chunks
2672          * are meaningful
2673          */
2674         if (conf->near_copies < conf->raid_disks &&
2675             max_sector > (sector_nr | conf->chunk_mask))
2676                 max_sector = (sector_nr | conf->chunk_mask) + 1;
2677         /*
2678          * If there is non-resync activity waiting for us then
2679          * put in a delay to throttle resync.
2680          */
2681         if (!go_faster && conf->nr_waiting)
2682                 msleep_interruptible(1000);
2683
2684         /* Again, very different code for resync and recovery.
2685          * Both must result in an r10bio with a list of bios that
2686          * have bi_end_io, bi_sector, bi_bdev set,
2687          * and bi_private set to the r10bio.
2688          * For recovery, we may actually create several r10bios
2689          * with 2 bios in each, that correspond to the bios in the main one.
2690          * In this case, the subordinate r10bios link back through a
2691          * borrowed master_bio pointer, and the counter in the master
2692          * includes a ref from each subordinate.
2693          */
2694         /* First, we decide what to do and set ->bi_end_io
2695          * To end_sync_read if we want to read, and
2696          * end_sync_write if we will want to write.
2697          */
2698
2699         max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
2700         if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2701                 /* recovery... the complicated one */
2702                 int j;
2703                 r10_bio = NULL;
2704
2705                 for (i=0 ; i<conf->raid_disks; i++) {
2706                         int still_degraded;
2707                         struct r10bio *rb2;
2708                         sector_t sect;
2709                         int must_sync;
2710                         int any_working;
2711                         struct mirror_info *mirror = &conf->mirrors[i];
2712
2713                         if ((mirror->rdev == NULL ||
2714                              test_bit(In_sync, &mirror->rdev->flags))
2715                             &&
2716                             (mirror->replacement == NULL ||
2717                              test_bit(Faulty,
2718                                       &mirror->replacement->flags)))
2719                                 continue;
2720
2721                         still_degraded = 0;
2722                         /* want to reconstruct this device */
2723                         rb2 = r10_bio;
2724                         sect = raid10_find_virt(conf, sector_nr, i);
2725                         /* Unless we are doing a full sync, or a replacement
2726                          * we only need to recover the block if it is set in
2727                          * the bitmap
2728                          */
2729                         must_sync = bitmap_start_sync(mddev->bitmap, sect,
2730                                                       &sync_blocks, 1);
2731                         if (sync_blocks < max_sync)
2732                                 max_sync = sync_blocks;
2733                         if (!must_sync &&
2734                             mirror->replacement == NULL &&
2735                             !conf->fullsync) {
2736                                 /* yep, skip the sync_blocks here, but don't assume
2737                                  * that there will never be anything to do here
2738                                  */
2739                                 chunks_skipped = -1;
2740                                 continue;
2741                         }
2742
2743                         r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
2744                         raise_barrier(conf, rb2 != NULL);
2745                         atomic_set(&r10_bio->remaining, 0);
2746
2747                         r10_bio->master_bio = (struct bio*)rb2;
2748                         if (rb2)
2749                                 atomic_inc(&rb2->remaining);
2750                         r10_bio->mddev = mddev;
2751                         set_bit(R10BIO_IsRecover, &r10_bio->state);
2752                         r10_bio->sector = sect;
2753
2754                         raid10_find_phys(conf, r10_bio);
2755
2756                         /* Need to check if the array will still be
2757                          * degraded
2758                          */
2759                         for (j=0; j<conf->raid_disks; j++)
2760                                 if (conf->mirrors[j].rdev == NULL ||
2761                                     test_bit(Faulty, &conf->mirrors[j].rdev->flags)) {
2762                                         still_degraded = 1;
2763                                         break;
2764                                 }
2765
2766                         must_sync = bitmap_start_sync(mddev->bitmap, sect,
2767                                                       &sync_blocks, still_degraded);
2768
2769                         any_working = 0;
2770                         for (j=0; j<conf->copies;j++) {
2771                                 int k;
2772                                 int d = r10_bio->devs[j].devnum;
2773                                 sector_t from_addr, to_addr;
2774                                 struct md_rdev *rdev;
2775                                 sector_t sector, first_bad;
2776                                 int bad_sectors;
2777                                 if (!conf->mirrors[d].rdev ||
2778                                     !test_bit(In_sync, &conf->mirrors[d].rdev->flags))
2779                                         continue;
2780                                 /* This is where we read from */
2781                                 any_working = 1;
2782                                 rdev = conf->mirrors[d].rdev;
2783                                 sector = r10_bio->devs[j].addr;
2784
2785                                 if (is_badblock(rdev, sector, max_sync,
2786                                                 &first_bad, &bad_sectors)) {
2787                                         if (first_bad > sector)
2788                                                 max_sync = first_bad - sector;
2789                                         else {
2790                                                 bad_sectors -= (sector
2791                                                                 - first_bad);
2792                                                 if (max_sync > bad_sectors)
2793                                                         max_sync = bad_sectors;
2794                                                 continue;
2795                                         }
2796                                 }
2797                                 bio = r10_bio->devs[0].bio;
2798                                 bio->bi_next = biolist;
2799                                 biolist = bio;
2800                                 bio->bi_private = r10_bio;
2801                                 bio->bi_end_io = end_sync_read;
2802                                 bio->bi_rw = READ;
2803                                 from_addr = r10_bio->devs[j].addr;
2804                                 bio->bi_sector = from_addr + rdev->data_offset;
2805                                 bio->bi_bdev = rdev->bdev;
2806                                 atomic_inc(&rdev->nr_pending);
2807                                 /* and we write to 'i' (if not in_sync) */
2808
2809                                 for (k=0; k<conf->copies; k++)
2810                                         if (r10_bio->devs[k].devnum == i)
2811                                                 break;
2812                                 BUG_ON(k == conf->copies);
2813                                 to_addr = r10_bio->devs[k].addr;
2814                                 r10_bio->devs[0].devnum = d;
2815                                 r10_bio->devs[0].addr = from_addr;
2816                                 r10_bio->devs[1].devnum = i;
2817                                 r10_bio->devs[1].addr = to_addr;
2818
2819                                 rdev = mirror->rdev;
2820                                 if (!test_bit(In_sync, &rdev->flags)) {
2821                                         bio = r10_bio->devs[1].bio;
2822                                         bio->bi_next = biolist;
2823                                         biolist = bio;
2824                                         bio->bi_private = r10_bio;
2825                                         bio->bi_end_io = end_sync_write;
2826                                         bio->bi_rw = WRITE;
2827                                         bio->bi_sector = to_addr
2828                                                 + rdev->data_offset;
2829                                         bio->bi_bdev = rdev->bdev;
2830                                         atomic_inc(&r10_bio->remaining);
2831                                 } else
2832                                         r10_bio->devs[1].bio->bi_end_io = NULL;
2833
2834                                 /* and maybe write to replacement */
2835                                 bio = r10_bio->devs[1].repl_bio;
2836                                 if (bio)
2837                                         bio->bi_end_io = NULL;
2838                                 rdev = mirror->replacement;
2839                                 /* Note: if rdev != NULL, then bio
2840                                  * cannot be NULL as r10buf_pool_alloc will
2841                                  * have allocated it.
2842                                  * So the second test here is pointless.
2843                                  * But it keeps semantic-checkers happy, and
2844                                  * this comment keeps human reviewers
2845                                  * happy.
2846                                  */
2847                                 if (rdev == NULL || bio == NULL ||
2848                                     test_bit(Faulty, &rdev->flags))
2849                                         break;
2850                                 bio->bi_next = biolist;
2851                                 biolist = bio;
2852                                 bio->bi_private = r10_bio;
2853                                 bio->bi_end_io = end_sync_write;
2854                                 bio->bi_rw = WRITE;
2855                                 bio->bi_sector = to_addr + rdev->data_offset;
2856                                 bio->bi_bdev = rdev->bdev;
2857                                 atomic_inc(&r10_bio->remaining);
2858                                 break;
2859                         }
2860                         if (j == conf->copies) {
2861                                 /* Cannot recover, so abort the recovery or
2862                                  * record a bad block */
2863                                 put_buf(r10_bio);
2864                                 if (rb2)
2865                                         atomic_dec(&rb2->remaining);
2866                                 r10_bio = rb2;
2867                                 if (any_working) {
2868                                         /* problem is that there are bad blocks
2869                                          * on other device(s)
2870                                          */
2871                                         int k;
2872                                         for (k = 0; k < conf->copies; k++)
2873                                                 if (r10_bio->devs[k].devnum == i)
2874                                                         break;
2875                                         if (!test_bit(In_sync,
2876                                                       &mirror->rdev->flags)
2877                                             && !rdev_set_badblocks(
2878                                                     mirror->rdev,
2879                                                     r10_bio->devs[k].addr,
2880                                                     max_sync, 0))
2881                                                 any_working = 0;
2882                                         if (mirror->replacement &&
2883                                             !rdev_set_badblocks(
2884                                                     mirror->replacement,
2885                                                     r10_bio->devs[k].addr,
2886                                                     max_sync, 0))
2887                                                 any_working = 0;
2888                                 }
2889                                 if (!any_working)  {
2890                                         if (!test_and_set_bit(MD_RECOVERY_INTR,
2891                                                               &mddev->recovery))
2892                                                 printk(KERN_INFO "md/raid10:%s: insufficient "
2893                                                        "working devices for recovery.\n",
2894                                                        mdname(mddev));
2895                                         mirror->recovery_disabled
2896                                                 = mddev->recovery_disabled;
2897                                 }
2898                                 break;
2899                         }
2900                 }
2901                 if (biolist == NULL) {
2902                         while (r10_bio) {
2903                                 struct r10bio *rb2 = r10_bio;
2904                                 r10_bio = (struct r10bio*) rb2->master_bio;
2905                                 rb2->master_bio = NULL;
2906                                 put_buf(rb2);
2907                         }
2908                         goto giveup;
2909                 }
2910         } else {
2911                 /* resync. Schedule a read for every block at this virt offset */
2912                 int count = 0;
2913
2914                 bitmap_cond_end_sync(mddev->bitmap, sector_nr);
2915
2916                 if (!bitmap_start_sync(mddev->bitmap, sector_nr,
2917                                        &sync_blocks, mddev->degraded) &&
2918                     !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED,
2919                                                  &mddev->recovery)) {
2920                         /* We can skip this block */
2921                         *skipped = 1;
2922                         return sync_blocks + sectors_skipped;
2923                 }
2924                 if (sync_blocks < max_sync)
2925                         max_sync = sync_blocks;
2926                 r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
2927
2928                 r10_bio->mddev = mddev;
2929                 atomic_set(&r10_bio->remaining, 0);
2930                 raise_barrier(conf, 0);
2931                 conf->next_resync = sector_nr;
2932
2933                 r10_bio->master_bio = NULL;
2934                 r10_bio->sector = sector_nr;
2935                 set_bit(R10BIO_IsSync, &r10_bio->state);
2936                 raid10_find_phys(conf, r10_bio);
2937                 r10_bio->sectors = (sector_nr | conf->chunk_mask) - sector_nr +1;
2938
2939                 for (i=0; i<conf->copies; i++) {
2940                         int d = r10_bio->devs[i].devnum;
2941                         sector_t first_bad, sector;
2942                         int bad_sectors;
2943
2944                         if (r10_bio->devs[i].repl_bio)
2945                                 r10_bio->devs[i].repl_bio->bi_end_io = NULL;
2946
2947                         bio = r10_bio->devs[i].bio;
2948                         bio->bi_end_io = NULL;
2949                         clear_bit(BIO_UPTODATE, &bio->bi_flags);
2950                         if (conf->mirrors[d].rdev == NULL ||
2951                             test_bit(Faulty, &conf->mirrors[d].rdev->flags))
2952                                 continue;
2953                         sector = r10_bio->devs[i].addr;
2954                         if (is_badblock(conf->mirrors[d].rdev,
2955                                         sector, max_sync,
2956                                         &first_bad, &bad_sectors)) {
2957                                 if (first_bad > sector)
2958                                         max_sync = first_bad - sector;
2959                                 else {
2960                                         bad_sectors -= (sector - first_bad);
2961                                         if (max_sync > bad_sectors)
2962                                                 max_sync = max_sync;
2963                                         continue;
2964                                 }
2965                         }
2966                         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2967                         atomic_inc(&r10_bio->remaining);
2968                         bio->bi_next = biolist;
2969                         biolist = bio;
2970                         bio->bi_private = r10_bio;
2971                         bio->bi_end_io = end_sync_read;
2972                         bio->bi_rw = READ;
2973                         bio->bi_sector = sector +
2974                                 conf->mirrors[d].rdev->data_offset;
2975                         bio->bi_bdev = conf->mirrors[d].rdev->bdev;
2976                         count++;
2977
2978                         if (conf->mirrors[d].replacement == NULL ||
2979                             test_bit(Faulty,
2980                                      &conf->mirrors[d].replacement->flags))
2981                                 continue;
2982
2983                         /* Need to set up for writing to the replacement */
2984                         bio = r10_bio->devs[i].repl_bio;
2985                         clear_bit(BIO_UPTODATE, &bio->bi_flags);
2986
2987                         sector = r10_bio->devs[i].addr;
2988                         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2989                         bio->bi_next = biolist;
2990                         biolist = bio;
2991                         bio->bi_private = r10_bio;
2992                         bio->bi_end_io = end_sync_write;
2993                         bio->bi_rw = WRITE;
2994                         bio->bi_sector = sector +
2995                                 conf->mirrors[d].replacement->data_offset;
2996                         bio->bi_bdev = conf->mirrors[d].replacement->bdev;
2997                         count++;
2998                 }
2999
3000                 if (count < 2) {
3001                         for (i=0; i<conf->copies; i++) {
3002                                 int d = r10_bio->devs[i].devnum;
3003                                 if (r10_bio->devs[i].bio->bi_end_io)
3004                                         rdev_dec_pending(conf->mirrors[d].rdev,
3005                                                          mddev);
3006                                 if (r10_bio->devs[i].repl_bio &&
3007                                     r10_bio->devs[i].repl_bio->bi_end_io)
3008                                         rdev_dec_pending(
3009                                                 conf->mirrors[d].replacement,
3010                                                 mddev);
3011                         }
3012                         put_buf(r10_bio);
3013                         biolist = NULL;
3014                         goto giveup;
3015                 }
3016         }
3017
3018         for (bio = biolist; bio ; bio=bio->bi_next) {
3019
3020                 bio->bi_flags &= ~(BIO_POOL_MASK - 1);
3021                 if (bio->bi_end_io)
3022                         bio->bi_flags |= 1 << BIO_UPTODATE;
3023                 bio->bi_vcnt = 0;
3024                 bio->bi_idx = 0;
3025                 bio->bi_phys_segments = 0;
3026                 bio->bi_size = 0;
3027         }
3028
3029         nr_sectors = 0;
3030         if (sector_nr + max_sync < max_sector)
3031                 max_sector = sector_nr + max_sync;
3032         do {
3033                 struct page *page;
3034                 int len = PAGE_SIZE;
3035                 if (sector_nr + (len>>9) > max_sector)
3036                         len = (max_sector - sector_nr) << 9;
3037                 if (len == 0)
3038                         break;
3039                 for (bio= biolist ; bio ; bio=bio->bi_next) {
3040                         struct bio *bio2;
3041                         page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
3042                         if (bio_add_page(bio, page, len, 0))
3043                                 continue;
3044
3045                         /* stop here */
3046                         bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
3047                         for (bio2 = biolist;
3048                              bio2 && bio2 != bio;
3049                              bio2 = bio2->bi_next) {
3050                                 /* remove last page from this bio */
3051                                 bio2->bi_vcnt--;
3052                                 bio2->bi_size -= len;
3053                                 bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
3054                         }
3055                         goto bio_full;
3056                 }
3057                 nr_sectors += len>>9;
3058                 sector_nr += len>>9;
3059         } while (biolist->bi_vcnt < RESYNC_PAGES);
3060  bio_full:
3061         r10_bio->sectors = nr_sectors;
3062
3063         while (biolist) {
3064                 bio = biolist;
3065                 biolist = biolist->bi_next;
3066
3067                 bio->bi_next = NULL;
3068                 r10_bio = bio->bi_private;
3069                 r10_bio->sectors = nr_sectors;
3070
3071                 if (bio->bi_end_io == end_sync_read) {
3072                         md_sync_acct(bio->bi_bdev, nr_sectors);
3073                         generic_make_request(bio);
3074                 }
3075         }
3076
3077         if (sectors_skipped)
3078                 /* pretend they weren't skipped, it makes
3079                  * no important difference in this case
3080                  */
3081                 md_done_sync(mddev, sectors_skipped, 1);
3082
3083         return sectors_skipped + nr_sectors;
3084  giveup:
3085         /* There is nowhere to write, so all non-sync
3086          * drives must be failed or in resync, all drives
3087          * have a bad block, so try the next chunk...
3088          */
3089         if (sector_nr + max_sync < max_sector)
3090                 max_sector = sector_nr + max_sync;
3091
3092         sectors_skipped += (max_sector - sector_nr);
3093         chunks_skipped ++;
3094         sector_nr = max_sector;
3095         goto skipped;
3096 }
3097
3098 static sector_t
3099 raid10_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3100 {
3101         sector_t size;
3102         struct r10conf *conf = mddev->private;
3103
3104         if (!raid_disks)
3105                 raid_disks = conf->raid_disks;
3106         if (!sectors)
3107                 sectors = conf->dev_sectors;
3108
3109         size = sectors >> conf->chunk_shift;
3110         sector_div(size, conf->far_copies);
3111         size = size * raid_disks;
3112         sector_div(size, conf->near_copies);
3113
3114         return size << conf->chunk_shift;
3115 }
3116
3117
3118 static struct r10conf *setup_conf(struct mddev *mddev)
3119 {
3120         struct r10conf *conf = NULL;
3121         int nc, fc, fo;
3122         sector_t stride, size;
3123         int err = -EINVAL;
3124
3125         if (mddev->new_chunk_sectors < (PAGE_SIZE >> 9) ||
3126             !is_power_of_2(mddev->new_chunk_sectors)) {
3127                 printk(KERN_ERR "md/raid10:%s: chunk size must be "
3128                        "at least PAGE_SIZE(%ld) and be a power of 2.\n",
3129                        mdname(mddev), PAGE_SIZE);
3130                 goto out;
3131         }
3132
3133         nc = mddev->new_layout & 255;
3134         fc = (mddev->new_layout >> 8) & 255;
3135         fo = mddev->new_layout & (1<<16);
3136
3137         if ((nc*fc) <2 || (nc*fc) > mddev->raid_disks ||
3138             (mddev->new_layout >> 17)) {
3139                 printk(KERN_ERR "md/raid10:%s: unsupported raid10 layout: 0x%8x\n",
3140                        mdname(mddev), mddev->new_layout);
3141                 goto out;
3142         }
3143
3144         err = -ENOMEM;
3145         conf = kzalloc(sizeof(struct r10conf), GFP_KERNEL);
3146         if (!conf)
3147                 goto out;
3148
3149         conf->mirrors = kzalloc(sizeof(struct mirror_info)*mddev->raid_disks,
3150                                 GFP_KERNEL);
3151         if (!conf->mirrors)
3152                 goto out;
3153
3154         conf->tmppage = alloc_page(GFP_KERNEL);
3155         if (!conf->tmppage)
3156                 goto out;
3157
3158
3159         conf->raid_disks = mddev->raid_disks;
3160         conf->near_copies = nc;
3161         conf->far_copies = fc;
3162         conf->copies = nc*fc;
3163         conf->far_offset = fo;
3164         conf->chunk_mask = mddev->new_chunk_sectors - 1;
3165         conf->chunk_shift = ffz(~mddev->new_chunk_sectors);
3166
3167         conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
3168                                            r10bio_pool_free, conf);
3169         if (!conf->r10bio_pool)
3170                 goto out;
3171
3172         size = mddev->dev_sectors >> conf->chunk_shift;
3173         sector_div(size, fc);
3174         size = size * conf->raid_disks;
3175         sector_div(size, nc);
3176         /* 'size' is now the number of chunks in the array */
3177         /* calculate "used chunks per device" in 'stride' */
3178         stride = size * conf->copies;
3179
3180         /* We need to round up when dividing by raid_disks to
3181          * get the stride size.
3182          */
3183         stride += conf->raid_disks - 1;
3184         sector_div(stride, conf->raid_disks);
3185
3186         conf->dev_sectors = stride << conf->chunk_shift;
3187
3188         if (fo)
3189                 stride = 1;
3190         else
3191                 sector_div(stride, fc);
3192         conf->stride = stride << conf->chunk_shift;
3193
3194
3195         spin_lock_init(&conf->device_lock);
3196         INIT_LIST_HEAD(&conf->retry_list);
3197
3198         spin_lock_init(&conf->resync_lock);
3199         init_waitqueue_head(&conf->wait_barrier);
3200
3201         conf->thread = md_register_thread(raid10d, mddev, NULL);
3202         if (!conf->thread)
3203                 goto out;
3204
3205         conf->mddev = mddev;
3206         return conf;
3207
3208  out:
3209         printk(KERN_ERR "md/raid10:%s: couldn't allocate memory.\n",
3210                mdname(mddev));
3211         if (conf) {
3212                 if (conf->r10bio_pool)
3213                         mempool_destroy(conf->r10bio_pool);
3214                 kfree(conf->mirrors);
3215                 safe_put_page(conf->tmppage);
3216                 kfree(conf);
3217         }
3218         return ERR_PTR(err);
3219 }
3220
3221 static int run(struct mddev *mddev)
3222 {
3223         struct r10conf *conf;
3224         int i, disk_idx, chunk_size;
3225         struct mirror_info *disk;
3226         struct md_rdev *rdev;
3227         sector_t size;
3228
3229         /*
3230          * copy the already verified devices into our private RAID10
3231          * bookkeeping area. [whatever we allocate in run(),
3232          * should be freed in stop()]
3233          */
3234
3235         if (mddev->private == NULL) {
3236                 conf = setup_conf(mddev);
3237                 if (IS_ERR(conf))
3238                         return PTR_ERR(conf);
3239                 mddev->private = conf;
3240         }
3241         conf = mddev->private;
3242         if (!conf)
3243                 goto out;
3244
3245         mddev->thread = conf->thread;
3246         conf->thread = NULL;
3247
3248         chunk_size = mddev->chunk_sectors << 9;
3249         blk_queue_io_min(mddev->queue, chunk_size);
3250         if (conf->raid_disks % conf->near_copies)
3251                 blk_queue_io_opt(mddev->queue, chunk_size * conf->raid_disks);
3252         else
3253                 blk_queue_io_opt(mddev->queue, chunk_size *
3254                                  (conf->raid_disks / conf->near_copies));
3255
3256         rdev_for_each(rdev, mddev) {
3257
3258                 disk_idx = rdev->raid_disk;
3259                 if (disk_idx >= conf->raid_disks
3260                     || disk_idx < 0)
3261                         continue;
3262                 disk = conf->mirrors + disk_idx;
3263
3264                 if (test_bit(Replacement, &rdev->flags)) {
3265                         if (disk->replacement)
3266                                 goto out_free_conf;
3267                         disk->replacement = rdev;
3268                 } else {
3269                         if (disk->rdev)
3270                                 goto out_free_conf;
3271                         disk->rdev = rdev;
3272                 }
3273
3274                 disk_stack_limits(mddev->gendisk, rdev->bdev,
3275                                   rdev->data_offset << 9);
3276                 /* as we don't honour merge_bvec_fn, we must never risk
3277                  * violating it, so limit max_segments to 1 lying
3278                  * within a single page.
3279                  */
3280                 if (rdev->bdev->bd_disk->queue->merge_bvec_fn) {
3281                         blk_queue_max_segments(mddev->queue, 1);
3282                         blk_queue_segment_boundary(mddev->queue,
3283                                                    PAGE_CACHE_SIZE - 1);
3284                 }
3285
3286                 disk->head_position = 0;
3287         }
3288         /* need to check that every block has at least one working mirror */
3289         if (!enough(conf, -1)) {
3290                 printk(KERN_ERR "md/raid10:%s: not enough operational mirrors.\n",
3291                        mdname(mddev));
3292                 goto out_free_conf;
3293         }
3294
3295         mddev->degraded = 0;
3296         for (i = 0; i < conf->raid_disks; i++) {
3297
3298                 disk = conf->mirrors + i;
3299
3300                 if (!disk->rdev && disk->replacement) {
3301                         /* The replacement is all we have - use it */
3302                         disk->rdev = disk->replacement;
3303                         disk->replacement = NULL;
3304                         clear_bit(Replacement, &disk->rdev->flags);
3305                 }
3306
3307                 if (!disk->rdev ||
3308                     !test_bit(In_sync, &disk->rdev->flags)) {
3309                         disk->head_position = 0;
3310                         mddev->degraded++;
3311                         if (disk->rdev)
3312                                 conf->fullsync = 1;
3313                 }
3314                 disk->recovery_disabled = mddev->recovery_disabled - 1;
3315         }
3316
3317         if (mddev->recovery_cp != MaxSector)
3318                 printk(KERN_NOTICE "md/raid10:%s: not clean"
3319                        " -- starting background reconstruction\n",
3320                        mdname(mddev));
3321         printk(KERN_INFO
3322                 "md/raid10:%s: active with %d out of %d devices\n",
3323                 mdname(mddev), conf->raid_disks - mddev->degraded,
3324                 conf->raid_disks);
3325         /*
3326          * Ok, everything is just fine now
3327          */
3328         mddev->dev_sectors = conf->dev_sectors;
3329         size = raid10_size(mddev, 0, 0);
3330         md_set_array_sectors(mddev, size);
3331         mddev->resync_max_sectors = size;
3332
3333         mddev->queue->backing_dev_info.congested_fn = raid10_congested;
3334         mddev->queue->backing_dev_info.congested_data = mddev;
3335
3336         /* Calculate max read-ahead size.
3337          * We need to readahead at least twice a whole stripe....
3338          * maybe...
3339          */
3340         {
3341                 int stripe = conf->raid_disks *
3342                         ((mddev->chunk_sectors << 9) / PAGE_SIZE);
3343                 stripe /= conf->near_copies;
3344                 if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
3345                         mddev->queue->backing_dev_info.ra_pages = 2* stripe;
3346         }
3347
3348         if (conf->near_copies < conf->raid_disks)
3349                 blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
3350
3351         if (md_integrity_register(mddev))
3352                 goto out_free_conf;
3353
3354         return 0;
3355
3356 out_free_conf:
3357         md_unregister_thread(&mddev->thread);
3358         if (conf->r10bio_pool)
3359                 mempool_destroy(conf->r10bio_pool);
3360         safe_put_page(conf->tmppage);
3361         kfree(conf->mirrors);
3362         kfree(conf);
3363         mddev->private = NULL;
3364 out:
3365         return -EIO;
3366 }
3367
3368 static int stop(struct mddev *mddev)
3369 {
3370         struct r10conf *conf = mddev->private;
3371
3372         raise_barrier(conf, 0);
3373         lower_barrier(conf);
3374
3375         md_unregister_thread(&mddev->thread);
3376         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
3377         if (conf->r10bio_pool)
3378                 mempool_destroy(conf->r10bio_pool);
3379         kfree(conf->mirrors);
3380         kfree(conf);
3381         mddev->private = NULL;
3382         return 0;
3383 }
3384
3385 static void raid10_quiesce(struct mddev *mddev, int state)
3386 {
3387         struct r10conf *conf = mddev->private;
3388
3389         switch(state) {
3390         case 1:
3391                 raise_barrier(conf, 0);
3392                 break;
3393         case 0:
3394                 lower_barrier(conf);
3395                 break;
3396         }
3397 }
3398
3399 static void *raid10_takeover_raid0(struct mddev *mddev)
3400 {
3401         struct md_rdev *rdev;
3402         struct r10conf *conf;
3403
3404         if (mddev->degraded > 0) {
3405                 printk(KERN_ERR "md/raid10:%s: Error: degraded raid0!\n",
3406                        mdname(mddev));
3407                 return ERR_PTR(-EINVAL);
3408         }
3409
3410         /* Set new parameters */
3411         mddev->new_level = 10;
3412         /* new layout: far_copies = 1, near_copies = 2 */
3413         mddev->new_layout = (1<<8) + 2;
3414         mddev->new_chunk_sectors = mddev->chunk_sectors;
3415         mddev->delta_disks = mddev->raid_disks;
3416         mddev->raid_disks *= 2;
3417         /* make sure it will be not marked as dirty */
3418         mddev->recovery_cp = MaxSector;
3419
3420         conf = setup_conf(mddev);
3421         if (!IS_ERR(conf)) {
3422                 rdev_for_each(rdev, mddev)
3423                         if (rdev->raid_disk >= 0)
3424                                 rdev->new_raid_disk = rdev->raid_disk * 2;
3425                 conf->barrier = 1;
3426         }
3427
3428         return conf;
3429 }
3430
3431 static void *raid10_takeover(struct mddev *mddev)
3432 {
3433         struct r0conf *raid0_conf;
3434
3435         /* raid10 can take over:
3436          *  raid0 - providing it has only two drives
3437          */
3438         if (mddev->level == 0) {
3439                 /* for raid0 takeover only one zone is supported */
3440                 raid0_conf = mddev->private;
3441                 if (raid0_conf->nr_strip_zones > 1) {
3442                         printk(KERN_ERR "md/raid10:%s: cannot takeover raid 0"
3443                                " with more than one zone.\n",
3444                                mdname(mddev));
3445                         return ERR_PTR(-EINVAL);
3446                 }
3447                 return raid10_takeover_raid0(mddev);
3448         }
3449         return ERR_PTR(-EINVAL);
3450 }
3451
3452 static struct md_personality raid10_personality =
3453 {
3454         .name           = "raid10",
3455         .level          = 10,
3456         .owner          = THIS_MODULE,
3457         .make_request   = make_request,
3458         .run            = run,
3459         .stop           = stop,
3460         .status         = status,
3461         .error_handler  = error,
3462         .hot_add_disk   = raid10_add_disk,
3463         .hot_remove_disk= raid10_remove_disk,
3464         .spare_active   = raid10_spare_active,
3465         .sync_request   = sync_request,
3466         .quiesce        = raid10_quiesce,
3467         .size           = raid10_size,
3468         .takeover       = raid10_takeover,
3469 };
3470
3471 static int __init raid_init(void)
3472 {
3473         return register_md_personality(&raid10_personality);
3474 }
3475
3476 static void raid_exit(void)
3477 {
3478         unregister_md_personality(&raid10_personality);
3479 }
3480
3481 module_init(raid_init);
3482 module_exit(raid_exit);
3483 MODULE_LICENSE("GPL");
3484 MODULE_DESCRIPTION("RAID10 (striped mirror) personality for MD");
3485 MODULE_ALIAS("md-personality-9"); /* RAID10 */
3486 MODULE_ALIAS("md-raid10");
3487 MODULE_ALIAS("md-level-10");
3488
3489 module_param(max_queued_requests, int, S_IRUGO|S_IWUSR);