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