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