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