[PATCH] md: auto-correct correctable read errors in raid10
[safe/jmp/linux-2.6] / 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 futher 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 "dm-bio-list.h"
22 #include <linux/raid/raid10.h>
23 #include <linux/raid/bitmap.h>
24
25 /*
26  * RAID10 provides a combination of RAID0 and RAID1 functionality.
27  * The layout of data is defined by
28  *    chunk_size
29  *    raid_disks
30  *    near_copies (stored in low byte of layout)
31  *    far_copies (stored in second byte of layout)
32  *
33  * The data to be stored is divided into chunks using chunksize.
34  * Each device is divided into far_copies sections.
35  * In each section, chunks are laid out in a style similar to raid0, but
36  * near_copies copies of each chunk is stored (each on a different drive).
37  * The starting device for each section is offset near_copies from the starting
38  * device of the previous section.
39  * Thus there are (near_copies*far_copies) of each chunk, and each is on a different
40  * drive.
41  * near_copies and far_copies must be at least one, and their product is at most
42  * raid_disks.
43  */
44
45 /*
46  * Number of guaranteed r10bios in case of extreme VM load:
47  */
48 #define NR_RAID10_BIOS 256
49
50 static void unplug_slaves(mddev_t *mddev);
51
52 static void allow_barrier(conf_t *conf);
53 static void lower_barrier(conf_t *conf);
54
55 static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
56 {
57         conf_t *conf = data;
58         r10bio_t *r10_bio;
59         int size = offsetof(struct r10bio_s, devs[conf->copies]);
60
61         /* allocate a r10bio with room for raid_disks entries in the bios array */
62         r10_bio = kmalloc(size, gfp_flags);
63         if (r10_bio)
64                 memset(r10_bio, 0, size);
65         else
66                 unplug_slaves(conf->mddev);
67
68         return r10_bio;
69 }
70
71 static void r10bio_pool_free(void *r10_bio, void *data)
72 {
73         kfree(r10_bio);
74 }
75
76 #define RESYNC_BLOCK_SIZE (64*1024)
77 //#define RESYNC_BLOCK_SIZE PAGE_SIZE
78 #define RESYNC_SECTORS (RESYNC_BLOCK_SIZE >> 9)
79 #define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
80 #define RESYNC_WINDOW (2048*1024)
81
82 /*
83  * When performing a resync, we need to read and compare, so
84  * we need as many pages are there are copies.
85  * When performing a recovery, we need 2 bios, one for read,
86  * one for write (we recover only one drive per r10buf)
87  *
88  */
89 static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
90 {
91         conf_t *conf = data;
92         struct page *page;
93         r10bio_t *r10_bio;
94         struct bio *bio;
95         int i, j;
96         int nalloc;
97
98         r10_bio = r10bio_pool_alloc(gfp_flags, conf);
99         if (!r10_bio) {
100                 unplug_slaves(conf->mddev);
101                 return NULL;
102         }
103
104         if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery))
105                 nalloc = conf->copies; /* resync */
106         else
107                 nalloc = 2; /* recovery */
108
109         /*
110          * Allocate bios.
111          */
112         for (j = nalloc ; j-- ; ) {
113                 bio = bio_alloc(gfp_flags, RESYNC_PAGES);
114                 if (!bio)
115                         goto out_free_bio;
116                 r10_bio->devs[j].bio = bio;
117         }
118         /*
119          * Allocate RESYNC_PAGES data pages and attach them
120          * where needed.
121          */
122         for (j = 0 ; j < nalloc; j++) {
123                 bio = r10_bio->devs[j].bio;
124                 for (i = 0; i < RESYNC_PAGES; i++) {
125                         page = alloc_page(gfp_flags);
126                         if (unlikely(!page))
127                                 goto out_free_pages;
128
129                         bio->bi_io_vec[i].bv_page = page;
130                 }
131         }
132
133         return r10_bio;
134
135 out_free_pages:
136         for ( ; i > 0 ; i--)
137                 __free_page(bio->bi_io_vec[i-1].bv_page);
138         while (j--)
139                 for (i = 0; i < RESYNC_PAGES ; i++)
140                         __free_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
141         j = -1;
142 out_free_bio:
143         while ( ++j < nalloc )
144                 bio_put(r10_bio->devs[j].bio);
145         r10bio_pool_free(r10_bio, conf);
146         return NULL;
147 }
148
149 static void r10buf_pool_free(void *__r10_bio, void *data)
150 {
151         int i;
152         conf_t *conf = data;
153         r10bio_t *r10bio = __r10_bio;
154         int j;
155
156         for (j=0; j < conf->copies; j++) {
157                 struct bio *bio = r10bio->devs[j].bio;
158                 if (bio) {
159                         for (i = 0; i < RESYNC_PAGES; i++) {
160                                 __free_page(bio->bi_io_vec[i].bv_page);
161                                 bio->bi_io_vec[i].bv_page = NULL;
162                         }
163                         bio_put(bio);
164                 }
165         }
166         r10bio_pool_free(r10bio, conf);
167 }
168
169 static void put_all_bios(conf_t *conf, r10bio_t *r10_bio)
170 {
171         int i;
172
173         for (i = 0; i < conf->copies; i++) {
174                 struct bio **bio = & r10_bio->devs[i].bio;
175                 if (*bio)
176                         bio_put(*bio);
177                 *bio = NULL;
178         }
179 }
180
181 static inline void free_r10bio(r10bio_t *r10_bio)
182 {
183         conf_t *conf = mddev_to_conf(r10_bio->mddev);
184
185         /*
186          * Wake up any possible resync thread that waits for the device
187          * to go idle.
188          */
189         allow_barrier(conf);
190
191         put_all_bios(conf, r10_bio);
192         mempool_free(r10_bio, conf->r10bio_pool);
193 }
194
195 static inline void put_buf(r10bio_t *r10_bio)
196 {
197         conf_t *conf = mddev_to_conf(r10_bio->mddev);
198
199         mempool_free(r10_bio, conf->r10buf_pool);
200
201         lower_barrier(conf);
202 }
203
204 static void reschedule_retry(r10bio_t *r10_bio)
205 {
206         unsigned long flags;
207         mddev_t *mddev = r10_bio->mddev;
208         conf_t *conf = mddev_to_conf(mddev);
209
210         spin_lock_irqsave(&conf->device_lock, flags);
211         list_add(&r10_bio->retry_list, &conf->retry_list);
212         conf->nr_queued ++;
213         spin_unlock_irqrestore(&conf->device_lock, flags);
214
215         md_wakeup_thread(mddev->thread);
216 }
217
218 /*
219  * raid_end_bio_io() is called when we have finished servicing a mirrored
220  * operation and are ready to return a success/failure code to the buffer
221  * cache layer.
222  */
223 static void raid_end_bio_io(r10bio_t *r10_bio)
224 {
225         struct bio *bio = r10_bio->master_bio;
226
227         bio_endio(bio, bio->bi_size,
228                 test_bit(R10BIO_Uptodate, &r10_bio->state) ? 0 : -EIO);
229         free_r10bio(r10_bio);
230 }
231
232 /*
233  * Update disk head position estimator based on IRQ completion info.
234  */
235 static inline void update_head_pos(int slot, r10bio_t *r10_bio)
236 {
237         conf_t *conf = mddev_to_conf(r10_bio->mddev);
238
239         conf->mirrors[r10_bio->devs[slot].devnum].head_position =
240                 r10_bio->devs[slot].addr + (r10_bio->sectors);
241 }
242
243 static int raid10_end_read_request(struct bio *bio, unsigned int bytes_done, int error)
244 {
245         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
246         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
247         int slot, dev;
248         conf_t *conf = mddev_to_conf(r10_bio->mddev);
249
250         if (bio->bi_size)
251                 return 1;
252
253         slot = r10_bio->read_slot;
254         dev = r10_bio->devs[slot].devnum;
255         /*
256          * this branch is our 'one mirror IO has finished' event handler:
257          */
258         update_head_pos(slot, r10_bio);
259
260         if (uptodate) {
261                 /*
262                  * Set R10BIO_Uptodate in our master bio, so that
263                  * we will return a good error code to the higher
264                  * levels even if IO on some other mirrored buffer fails.
265                  *
266                  * The 'master' represents the composite IO operation to
267                  * user-side. So if something waits for IO, then it will
268                  * wait for the 'master' bio.
269                  */
270                 set_bit(R10BIO_Uptodate, &r10_bio->state);
271                 raid_end_bio_io(r10_bio);
272         } else {
273                 /*
274                  * oops, read error:
275                  */
276                 char b[BDEVNAME_SIZE];
277                 if (printk_ratelimit())
278                         printk(KERN_ERR "raid10: %s: rescheduling sector %llu\n",
279                                bdevname(conf->mirrors[dev].rdev->bdev,b), (unsigned long long)r10_bio->sector);
280                 reschedule_retry(r10_bio);
281         }
282
283         rdev_dec_pending(conf->mirrors[dev].rdev, conf->mddev);
284         return 0;
285 }
286
287 static int raid10_end_write_request(struct bio *bio, unsigned int bytes_done, int error)
288 {
289         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
290         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
291         int slot, dev;
292         conf_t *conf = mddev_to_conf(r10_bio->mddev);
293
294         if (bio->bi_size)
295                 return 1;
296
297         for (slot = 0; slot < conf->copies; slot++)
298                 if (r10_bio->devs[slot].bio == bio)
299                         break;
300         dev = r10_bio->devs[slot].devnum;
301
302         /*
303          * this branch is our 'one mirror IO has finished' event handler:
304          */
305         if (!uptodate) {
306                 md_error(r10_bio->mddev, conf->mirrors[dev].rdev);
307                 /* an I/O failed, we can't clear the bitmap */
308                 set_bit(R10BIO_Degraded, &r10_bio->state);
309         } else
310                 /*
311                  * Set R10BIO_Uptodate in our master bio, so that
312                  * we will return a good error code for 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
321         update_head_pos(slot, r10_bio);
322
323         /*
324          *
325          * Let's see if all mirrored write operations have finished
326          * already.
327          */
328         if (atomic_dec_and_test(&r10_bio->remaining)) {
329                 /* clear the bitmap if all writes complete successfully */
330                 bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
331                                 r10_bio->sectors,
332                                 !test_bit(R10BIO_Degraded, &r10_bio->state),
333                                 0);
334                 md_write_end(r10_bio->mddev);
335                 raid_end_bio_io(r10_bio);
336         }
337
338         rdev_dec_pending(conf->mirrors[dev].rdev, conf->mddev);
339         return 0;
340 }
341
342
343 /*
344  * RAID10 layout manager
345  * Aswell as the chunksize and raid_disks count, there are two
346  * parameters: near_copies and far_copies.
347  * near_copies * far_copies must be <= raid_disks.
348  * Normally one of these will be 1.
349  * If both are 1, we get raid0.
350  * If near_copies == raid_disks, we get raid1.
351  *
352  * Chunks are layed out in raid0 style with near_copies copies of the
353  * first chunk, followed by near_copies copies of the next chunk and
354  * so on.
355  * If far_copies > 1, then after 1/far_copies of the array has been assigned
356  * as described above, we start again with a device offset of near_copies.
357  * So we effectively have another copy of the whole array further down all
358  * the drives, but with blocks on different drives.
359  * With this layout, and block is never stored twice on the one device.
360  *
361  * raid10_find_phys finds the sector offset of a given virtual sector
362  * on each device that it is on. If a block isn't on a device,
363  * that entry in the array is set to MaxSector.
364  *
365  * raid10_find_virt does the reverse mapping, from a device and a
366  * sector offset to a virtual address
367  */
368
369 static void raid10_find_phys(conf_t *conf, r10bio_t *r10bio)
370 {
371         int n,f;
372         sector_t sector;
373         sector_t chunk;
374         sector_t stripe;
375         int dev;
376
377         int slot = 0;
378
379         /* now calculate first sector/dev */
380         chunk = r10bio->sector >> conf->chunk_shift;
381         sector = r10bio->sector & conf->chunk_mask;
382
383         chunk *= conf->near_copies;
384         stripe = chunk;
385         dev = sector_div(stripe, conf->raid_disks);
386
387         sector += stripe << conf->chunk_shift;
388
389         /* and calculate all the others */
390         for (n=0; n < conf->near_copies; n++) {
391                 int d = dev;
392                 sector_t s = sector;
393                 r10bio->devs[slot].addr = sector;
394                 r10bio->devs[slot].devnum = d;
395                 slot++;
396
397                 for (f = 1; f < conf->far_copies; f++) {
398                         d += conf->near_copies;
399                         if (d >= conf->raid_disks)
400                                 d -= conf->raid_disks;
401                         s += conf->stride;
402                         r10bio->devs[slot].devnum = d;
403                         r10bio->devs[slot].addr = s;
404                         slot++;
405                 }
406                 dev++;
407                 if (dev >= conf->raid_disks) {
408                         dev = 0;
409                         sector += (conf->chunk_mask + 1);
410                 }
411         }
412         BUG_ON(slot != conf->copies);
413 }
414
415 static sector_t raid10_find_virt(conf_t *conf, sector_t sector, int dev)
416 {
417         sector_t offset, chunk, vchunk;
418
419         while (sector > conf->stride) {
420                 sector -= conf->stride;
421                 if (dev < conf->near_copies)
422                         dev += conf->raid_disks - conf->near_copies;
423                 else
424                         dev -= conf->near_copies;
425         }
426
427         offset = sector & conf->chunk_mask;
428         chunk = sector >> conf->chunk_shift;
429         vchunk = chunk * conf->raid_disks + dev;
430         sector_div(vchunk, conf->near_copies);
431         return (vchunk << conf->chunk_shift) + offset;
432 }
433
434 /**
435  *      raid10_mergeable_bvec -- tell bio layer if a two requests can be merged
436  *      @q: request queue
437  *      @bio: the buffer head that's been built up so far
438  *      @biovec: the request that could be merged to it.
439  *
440  *      Return amount of bytes we can accept at this offset
441  *      If near_copies == raid_disk, there are no striping issues,
442  *      but in that case, the function isn't called at all.
443  */
444 static int raid10_mergeable_bvec(request_queue_t *q, struct bio *bio,
445                                 struct bio_vec *bio_vec)
446 {
447         mddev_t *mddev = q->queuedata;
448         sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
449         int max;
450         unsigned int chunk_sectors = mddev->chunk_size >> 9;
451         unsigned int bio_sectors = bio->bi_size >> 9;
452
453         max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
454         if (max < 0) max = 0; /* bio_add cannot handle a negative return */
455         if (max <= bio_vec->bv_len && bio_sectors == 0)
456                 return bio_vec->bv_len;
457         else
458                 return max;
459 }
460
461 /*
462  * This routine returns the disk from which the requested read should
463  * be done. There is a per-array 'next expected sequential IO' sector
464  * number - if this matches on the next IO then we use the last disk.
465  * There is also a per-disk 'last know head position' sector that is
466  * maintained from IRQ contexts, both the normal and the resync IO
467  * completion handlers update this position correctly. If there is no
468  * perfect sequential match then we pick the disk whose head is closest.
469  *
470  * If there are 2 mirrors in the same 2 devices, performance degrades
471  * because position is mirror, not device based.
472  *
473  * The rdev for the device selected will have nr_pending incremented.
474  */
475
476 /*
477  * FIXME: possibly should rethink readbalancing and do it differently
478  * depending on near_copies / far_copies geometry.
479  */
480 static int read_balance(conf_t *conf, r10bio_t *r10_bio)
481 {
482         const unsigned long this_sector = r10_bio->sector;
483         int disk, slot, nslot;
484         const int sectors = r10_bio->sectors;
485         sector_t new_distance, current_distance;
486         mdk_rdev_t *rdev;
487
488         raid10_find_phys(conf, r10_bio);
489         rcu_read_lock();
490         /*
491          * Check if we can balance. We can balance on the whole
492          * device if no resync is going on (recovery is ok), or below
493          * the resync window. We take the first readable disk when
494          * above the resync window.
495          */
496         if (conf->mddev->recovery_cp < MaxSector
497             && (this_sector + sectors >= conf->next_resync)) {
498                 /* make sure that disk is operational */
499                 slot = 0;
500                 disk = r10_bio->devs[slot].devnum;
501
502                 while ((rdev = rcu_dereference(conf->mirrors[disk].rdev)) == NULL ||
503                        !test_bit(In_sync, &rdev->flags)) {
504                         slot++;
505                         if (slot == conf->copies) {
506                                 slot = 0;
507                                 disk = -1;
508                                 break;
509                         }
510                         disk = r10_bio->devs[slot].devnum;
511                 }
512                 goto rb_out;
513         }
514
515
516         /* make sure the disk is operational */
517         slot = 0;
518         disk = r10_bio->devs[slot].devnum;
519         while ((rdev=rcu_dereference(conf->mirrors[disk].rdev)) == NULL ||
520                !test_bit(In_sync, &rdev->flags)) {
521                 slot ++;
522                 if (slot == conf->copies) {
523                         disk = -1;
524                         goto rb_out;
525                 }
526                 disk = r10_bio->devs[slot].devnum;
527         }
528
529
530         current_distance = abs(r10_bio->devs[slot].addr -
531                                conf->mirrors[disk].head_position);
532
533         /* Find the disk whose head is closest */
534
535         for (nslot = slot; nslot < conf->copies; nslot++) {
536                 int ndisk = r10_bio->devs[nslot].devnum;
537
538
539                 if ((rdev=rcu_dereference(conf->mirrors[ndisk].rdev)) == NULL ||
540                     !test_bit(In_sync, &rdev->flags))
541                         continue;
542
543                 /* This optimisation is debatable, and completely destroys
544                  * sequential read speed for 'far copies' arrays.  So only
545                  * keep it for 'near' arrays, and review those later.
546                  */
547                 if (conf->near_copies > 1 && !atomic_read(&rdev->nr_pending)) {
548                         disk = ndisk;
549                         slot = nslot;
550                         break;
551                 }
552                 new_distance = abs(r10_bio->devs[nslot].addr -
553                                    conf->mirrors[ndisk].head_position);
554                 if (new_distance < current_distance) {
555                         current_distance = new_distance;
556                         disk = ndisk;
557                         slot = nslot;
558                 }
559         }
560
561 rb_out:
562         r10_bio->read_slot = slot;
563 /*      conf->next_seq_sect = this_sector + sectors;*/
564
565         if (disk >= 0 && (rdev=rcu_dereference(conf->mirrors[disk].rdev))!= NULL)
566                 atomic_inc(&conf->mirrors[disk].rdev->nr_pending);
567         rcu_read_unlock();
568
569         return disk;
570 }
571
572 static void unplug_slaves(mddev_t *mddev)
573 {
574         conf_t *conf = mddev_to_conf(mddev);
575         int i;
576
577         rcu_read_lock();
578         for (i=0; i<mddev->raid_disks; i++) {
579                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
580                 if (rdev && !test_bit(Faulty, &rdev->flags) && atomic_read(&rdev->nr_pending)) {
581                         request_queue_t *r_queue = bdev_get_queue(rdev->bdev);
582
583                         atomic_inc(&rdev->nr_pending);
584                         rcu_read_unlock();
585
586                         if (r_queue->unplug_fn)
587                                 r_queue->unplug_fn(r_queue);
588
589                         rdev_dec_pending(rdev, mddev);
590                         rcu_read_lock();
591                 }
592         }
593         rcu_read_unlock();
594 }
595
596 static void raid10_unplug(request_queue_t *q)
597 {
598         mddev_t *mddev = q->queuedata;
599
600         unplug_slaves(q->queuedata);
601         md_wakeup_thread(mddev->thread);
602 }
603
604 static int raid10_issue_flush(request_queue_t *q, struct gendisk *disk,
605                              sector_t *error_sector)
606 {
607         mddev_t *mddev = q->queuedata;
608         conf_t *conf = mddev_to_conf(mddev);
609         int i, ret = 0;
610
611         rcu_read_lock();
612         for (i=0; i<mddev->raid_disks && ret == 0; i++) {
613                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[i].rdev);
614                 if (rdev && !test_bit(Faulty, &rdev->flags)) {
615                         struct block_device *bdev = rdev->bdev;
616                         request_queue_t *r_queue = bdev_get_queue(bdev);
617
618                         if (!r_queue->issue_flush_fn)
619                                 ret = -EOPNOTSUPP;
620                         else {
621                                 atomic_inc(&rdev->nr_pending);
622                                 rcu_read_unlock();
623                                 ret = r_queue->issue_flush_fn(r_queue, bdev->bd_disk,
624                                                               error_sector);
625                                 rdev_dec_pending(rdev, mddev);
626                                 rcu_read_lock();
627                         }
628                 }
629         }
630         rcu_read_unlock();
631         return ret;
632 }
633
634 /* Barriers....
635  * Sometimes we need to suspend IO while we do something else,
636  * either some resync/recovery, or reconfigure the array.
637  * To do this we raise a 'barrier'.
638  * The 'barrier' is a counter that can be raised multiple times
639  * to count how many activities are happening which preclude
640  * normal IO.
641  * We can only raise the barrier if there is no pending IO.
642  * i.e. if nr_pending == 0.
643  * We choose only to raise the barrier if no-one is waiting for the
644  * barrier to go down.  This means that as soon as an IO request
645  * is ready, no other operations which require a barrier will start
646  * until the IO request has had a chance.
647  *
648  * So: regular IO calls 'wait_barrier'.  When that returns there
649  *    is no backgroup IO happening,  It must arrange to call
650  *    allow_barrier when it has finished its IO.
651  * backgroup IO calls must call raise_barrier.  Once that returns
652  *    there is no normal IO happeing.  It must arrange to call
653  *    lower_barrier when the particular background IO completes.
654  */
655 #define RESYNC_DEPTH 32
656
657 static void raise_barrier(conf_t *conf, int force)
658 {
659         BUG_ON(force && !conf->barrier);
660         spin_lock_irq(&conf->resync_lock);
661
662         /* Wait until no block IO is waiting (unless 'force') */
663         wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
664                             conf->resync_lock,
665                             raid10_unplug(conf->mddev->queue));
666
667         /* block any new IO from starting */
668         conf->barrier++;
669
670         /* No wait for all pending IO to complete */
671         wait_event_lock_irq(conf->wait_barrier,
672                             !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
673                             conf->resync_lock,
674                             raid10_unplug(conf->mddev->queue));
675
676         spin_unlock_irq(&conf->resync_lock);
677 }
678
679 static void lower_barrier(conf_t *conf)
680 {
681         unsigned long flags;
682         spin_lock_irqsave(&conf->resync_lock, flags);
683         conf->barrier--;
684         spin_unlock_irqrestore(&conf->resync_lock, flags);
685         wake_up(&conf->wait_barrier);
686 }
687
688 static void wait_barrier(conf_t *conf)
689 {
690         spin_lock_irq(&conf->resync_lock);
691         if (conf->barrier) {
692                 conf->nr_waiting++;
693                 wait_event_lock_irq(conf->wait_barrier, !conf->barrier,
694                                     conf->resync_lock,
695                                     raid10_unplug(conf->mddev->queue));
696                 conf->nr_waiting--;
697         }
698         conf->nr_pending++;
699         spin_unlock_irq(&conf->resync_lock);
700 }
701
702 static void allow_barrier(conf_t *conf)
703 {
704         unsigned long flags;
705         spin_lock_irqsave(&conf->resync_lock, flags);
706         conf->nr_pending--;
707         spin_unlock_irqrestore(&conf->resync_lock, flags);
708         wake_up(&conf->wait_barrier);
709 }
710
711 static void freeze_array(conf_t *conf)
712 {
713         /* stop syncio and normal IO and wait for everything to
714          * go quite.
715          * We increment barrier and nr_waiting, and then
716          * wait until barrier+nr_pending match nr_queued+2
717          */
718         spin_lock_irq(&conf->resync_lock);
719         conf->barrier++;
720         conf->nr_waiting++;
721         wait_event_lock_irq(conf->wait_barrier,
722                             conf->barrier+conf->nr_pending == conf->nr_queued+2,
723                             conf->resync_lock,
724                             raid10_unplug(conf->mddev->queue));
725         spin_unlock_irq(&conf->resync_lock);
726 }
727
728 static void unfreeze_array(conf_t *conf)
729 {
730         /* reverse the effect of the freeze */
731         spin_lock_irq(&conf->resync_lock);
732         conf->barrier--;
733         conf->nr_waiting--;
734         wake_up(&conf->wait_barrier);
735         spin_unlock_irq(&conf->resync_lock);
736 }
737
738 static int make_request(request_queue_t *q, struct bio * bio)
739 {
740         mddev_t *mddev = q->queuedata;
741         conf_t *conf = mddev_to_conf(mddev);
742         mirror_info_t *mirror;
743         r10bio_t *r10_bio;
744         struct bio *read_bio;
745         int i;
746         int chunk_sects = conf->chunk_mask + 1;
747         const int rw = bio_data_dir(bio);
748         struct bio_list bl;
749         unsigned long flags;
750
751         if (unlikely(bio_barrier(bio))) {
752                 bio_endio(bio, bio->bi_size, -EOPNOTSUPP);
753                 return 0;
754         }
755
756         /* If this request crosses a chunk boundary, we need to
757          * split it.  This will only happen for 1 PAGE (or less) requests.
758          */
759         if (unlikely( (bio->bi_sector & conf->chunk_mask) + (bio->bi_size >> 9)
760                       > chunk_sects &&
761                     conf->near_copies < conf->raid_disks)) {
762                 struct bio_pair *bp;
763                 /* Sanity check -- queue functions should prevent this happening */
764                 if (bio->bi_vcnt != 1 ||
765                     bio->bi_idx != 0)
766                         goto bad_map;
767                 /* This is a one page bio that upper layers
768                  * refuse to split for us, so we need to split it.
769                  */
770                 bp = bio_split(bio, bio_split_pool,
771                                chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
772                 if (make_request(q, &bp->bio1))
773                         generic_make_request(&bp->bio1);
774                 if (make_request(q, &bp->bio2))
775                         generic_make_request(&bp->bio2);
776
777                 bio_pair_release(bp);
778                 return 0;
779         bad_map:
780                 printk("raid10_make_request bug: can't convert block across chunks"
781                        " or bigger than %dk %llu %d\n", chunk_sects/2,
782                        (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
783
784                 bio_io_error(bio, bio->bi_size);
785                 return 0;
786         }
787
788         md_write_start(mddev, bio);
789
790         /*
791          * Register the new request and wait if the reconstruction
792          * thread has put up a bar for new requests.
793          * Continue immediately if no resync is active currently.
794          */
795         wait_barrier(conf);
796
797         disk_stat_inc(mddev->gendisk, ios[rw]);
798         disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bio));
799
800         r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
801
802         r10_bio->master_bio = bio;
803         r10_bio->sectors = bio->bi_size >> 9;
804
805         r10_bio->mddev = mddev;
806         r10_bio->sector = bio->bi_sector;
807         r10_bio->state = 0;
808
809         if (rw == READ) {
810                 /*
811                  * read balancing logic:
812                  */
813                 int disk = read_balance(conf, r10_bio);
814                 int slot = r10_bio->read_slot;
815                 if (disk < 0) {
816                         raid_end_bio_io(r10_bio);
817                         return 0;
818                 }
819                 mirror = conf->mirrors + disk;
820
821                 read_bio = bio_clone(bio, GFP_NOIO);
822
823                 r10_bio->devs[slot].bio = read_bio;
824
825                 read_bio->bi_sector = r10_bio->devs[slot].addr +
826                         mirror->rdev->data_offset;
827                 read_bio->bi_bdev = mirror->rdev->bdev;
828                 read_bio->bi_end_io = raid10_end_read_request;
829                 read_bio->bi_rw = READ;
830                 read_bio->bi_private = r10_bio;
831
832                 generic_make_request(read_bio);
833                 return 0;
834         }
835
836         /*
837          * WRITE:
838          */
839         /* first select target devices under spinlock and
840          * inc refcount on their rdev.  Record them by setting
841          * bios[x] to bio
842          */
843         raid10_find_phys(conf, r10_bio);
844         rcu_read_lock();
845         for (i = 0;  i < conf->copies; i++) {
846                 int d = r10_bio->devs[i].devnum;
847                 mdk_rdev_t *rdev = rcu_dereference(conf->mirrors[d].rdev);
848                 if (rdev &&
849                     !test_bit(Faulty, &rdev->flags)) {
850                         atomic_inc(&rdev->nr_pending);
851                         r10_bio->devs[i].bio = bio;
852                 } else {
853                         r10_bio->devs[i].bio = NULL;
854                         set_bit(R10BIO_Degraded, &r10_bio->state);
855                 }
856         }
857         rcu_read_unlock();
858
859         atomic_set(&r10_bio->remaining, 0);
860
861         bio_list_init(&bl);
862         for (i = 0; i < conf->copies; i++) {
863                 struct bio *mbio;
864                 int d = r10_bio->devs[i].devnum;
865                 if (!r10_bio->devs[i].bio)
866                         continue;
867
868                 mbio = bio_clone(bio, GFP_NOIO);
869                 r10_bio->devs[i].bio = mbio;
870
871                 mbio->bi_sector = r10_bio->devs[i].addr+
872                         conf->mirrors[d].rdev->data_offset;
873                 mbio->bi_bdev = conf->mirrors[d].rdev->bdev;
874                 mbio->bi_end_io = raid10_end_write_request;
875                 mbio->bi_rw = WRITE;
876                 mbio->bi_private = r10_bio;
877
878                 atomic_inc(&r10_bio->remaining);
879                 bio_list_add(&bl, mbio);
880         }
881
882         bitmap_startwrite(mddev->bitmap, bio->bi_sector, r10_bio->sectors, 0);
883         spin_lock_irqsave(&conf->device_lock, flags);
884         bio_list_merge(&conf->pending_bio_list, &bl);
885         blk_plug_device(mddev->queue);
886         spin_unlock_irqrestore(&conf->device_lock, flags);
887
888         return 0;
889 }
890
891 static void status(struct seq_file *seq, mddev_t *mddev)
892 {
893         conf_t *conf = mddev_to_conf(mddev);
894         int i;
895
896         if (conf->near_copies < conf->raid_disks)
897                 seq_printf(seq, " %dK chunks", mddev->chunk_size/1024);
898         if (conf->near_copies > 1)
899                 seq_printf(seq, " %d near-copies", conf->near_copies);
900         if (conf->far_copies > 1)
901                 seq_printf(seq, " %d far-copies", conf->far_copies);
902
903         seq_printf(seq, " [%d/%d] [", conf->raid_disks,
904                                                 conf->working_disks);
905         for (i = 0; i < conf->raid_disks; i++)
906                 seq_printf(seq, "%s",
907                               conf->mirrors[i].rdev &&
908                               test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
909         seq_printf(seq, "]");
910 }
911
912 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
913 {
914         char b[BDEVNAME_SIZE];
915         conf_t *conf = mddev_to_conf(mddev);
916
917         /*
918          * If it is not operational, then we have already marked it as dead
919          * else if it is the last working disks, ignore the error, let the
920          * next level up know.
921          * else mark the drive as failed
922          */
923         if (test_bit(In_sync, &rdev->flags)
924             && conf->working_disks == 1)
925                 /*
926                  * Don't fail the drive, just return an IO error.
927                  * The test should really be more sophisticated than
928                  * "working_disks == 1", but it isn't critical, and
929                  * can wait until we do more sophisticated "is the drive
930                  * really dead" tests...
931                  */
932                 return;
933         if (test_bit(In_sync, &rdev->flags)) {
934                 mddev->degraded++;
935                 conf->working_disks--;
936                 /*
937                  * if recovery is running, make sure it aborts.
938                  */
939                 set_bit(MD_RECOVERY_ERR, &mddev->recovery);
940         }
941         clear_bit(In_sync, &rdev->flags);
942         set_bit(Faulty, &rdev->flags);
943         mddev->sb_dirty = 1;
944         printk(KERN_ALERT "raid10: Disk failure on %s, disabling device. \n"
945                 "       Operation continuing on %d devices\n",
946                 bdevname(rdev->bdev,b), conf->working_disks);
947 }
948
949 static void print_conf(conf_t *conf)
950 {
951         int i;
952         mirror_info_t *tmp;
953
954         printk("RAID10 conf printout:\n");
955         if (!conf) {
956                 printk("(!conf)\n");
957                 return;
958         }
959         printk(" --- wd:%d rd:%d\n", conf->working_disks,
960                 conf->raid_disks);
961
962         for (i = 0; i < conf->raid_disks; i++) {
963                 char b[BDEVNAME_SIZE];
964                 tmp = conf->mirrors + i;
965                 if (tmp->rdev)
966                         printk(" disk %d, wo:%d, o:%d, dev:%s\n",
967                                 i, !test_bit(In_sync, &tmp->rdev->flags),
968                                 !test_bit(Faulty, &tmp->rdev->flags),
969                                 bdevname(tmp->rdev->bdev,b));
970         }
971 }
972
973 static void close_sync(conf_t *conf)
974 {
975         wait_barrier(conf);
976         allow_barrier(conf);
977
978         mempool_destroy(conf->r10buf_pool);
979         conf->r10buf_pool = NULL;
980 }
981
982 /* check if there are enough drives for
983  * every block to appear on atleast one
984  */
985 static int enough(conf_t *conf)
986 {
987         int first = 0;
988
989         do {
990                 int n = conf->copies;
991                 int cnt = 0;
992                 while (n--) {
993                         if (conf->mirrors[first].rdev)
994                                 cnt++;
995                         first = (first+1) % conf->raid_disks;
996                 }
997                 if (cnt == 0)
998                         return 0;
999         } while (first != 0);
1000         return 1;
1001 }
1002
1003 static int raid10_spare_active(mddev_t *mddev)
1004 {
1005         int i;
1006         conf_t *conf = mddev->private;
1007         mirror_info_t *tmp;
1008
1009         /*
1010          * Find all non-in_sync disks within the RAID10 configuration
1011          * and mark them in_sync
1012          */
1013         for (i = 0; i < conf->raid_disks; i++) {
1014                 tmp = conf->mirrors + i;
1015                 if (tmp->rdev
1016                     && !test_bit(Faulty, &tmp->rdev->flags)
1017                     && !test_bit(In_sync, &tmp->rdev->flags)) {
1018                         conf->working_disks++;
1019                         mddev->degraded--;
1020                         set_bit(In_sync, &tmp->rdev->flags);
1021                 }
1022         }
1023
1024         print_conf(conf);
1025         return 0;
1026 }
1027
1028
1029 static int raid10_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
1030 {
1031         conf_t *conf = mddev->private;
1032         int found = 0;
1033         int mirror;
1034         mirror_info_t *p;
1035
1036         if (mddev->recovery_cp < MaxSector)
1037                 /* only hot-add to in-sync arrays, as recovery is
1038                  * very different from resync
1039                  */
1040                 return 0;
1041         if (!enough(conf))
1042                 return 0;
1043
1044         if (rdev->saved_raid_disk >= 0 &&
1045             conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1046                 mirror = rdev->saved_raid_disk;
1047         else
1048                 mirror = 0;
1049         for ( ; mirror < mddev->raid_disks; mirror++)
1050                 if ( !(p=conf->mirrors+mirror)->rdev) {
1051
1052                         blk_queue_stack_limits(mddev->queue,
1053                                                rdev->bdev->bd_disk->queue);
1054                         /* as we don't honour merge_bvec_fn, we must never risk
1055                          * violating it, so limit ->max_sector to one PAGE, as
1056                          * a one page request is never in violation.
1057                          */
1058                         if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
1059                             mddev->queue->max_sectors > (PAGE_SIZE>>9))
1060                                 mddev->queue->max_sectors = (PAGE_SIZE>>9);
1061
1062                         p->head_position = 0;
1063                         rdev->raid_disk = mirror;
1064                         found = 1;
1065                         if (rdev->saved_raid_disk != mirror)
1066                                 conf->fullsync = 1;
1067                         rcu_assign_pointer(p->rdev, rdev);
1068                         break;
1069                 }
1070
1071         print_conf(conf);
1072         return found;
1073 }
1074
1075 static int raid10_remove_disk(mddev_t *mddev, int number)
1076 {
1077         conf_t *conf = mddev->private;
1078         int err = 0;
1079         mdk_rdev_t *rdev;
1080         mirror_info_t *p = conf->mirrors+ number;
1081
1082         print_conf(conf);
1083         rdev = p->rdev;
1084         if (rdev) {
1085                 if (test_bit(In_sync, &rdev->flags) ||
1086                     atomic_read(&rdev->nr_pending)) {
1087                         err = -EBUSY;
1088                         goto abort;
1089                 }
1090                 p->rdev = NULL;
1091                 synchronize_rcu();
1092                 if (atomic_read(&rdev->nr_pending)) {
1093                         /* lost the race, try later */
1094                         err = -EBUSY;
1095                         p->rdev = rdev;
1096                 }
1097         }
1098 abort:
1099
1100         print_conf(conf);
1101         return err;
1102 }
1103
1104
1105 static int end_sync_read(struct bio *bio, unsigned int bytes_done, int error)
1106 {
1107         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1108         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1109         conf_t *conf = mddev_to_conf(r10_bio->mddev);
1110         int i,d;
1111
1112         if (bio->bi_size)
1113                 return 1;
1114
1115         for (i=0; i<conf->copies; i++)
1116                 if (r10_bio->devs[i].bio == bio)
1117                         break;
1118         if (i == conf->copies)
1119                 BUG();
1120         update_head_pos(i, r10_bio);
1121         d = r10_bio->devs[i].devnum;
1122         if (!uptodate)
1123                 md_error(r10_bio->mddev,
1124                          conf->mirrors[d].rdev);
1125
1126         /* for reconstruct, we always reschedule after a read.
1127          * for resync, only after all reads
1128          */
1129         if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1130             atomic_dec_and_test(&r10_bio->remaining)) {
1131                 /* we have read all the blocks,
1132                  * do the comparison in process context in raid10d
1133                  */
1134                 reschedule_retry(r10_bio);
1135         }
1136         rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1137         return 0;
1138 }
1139
1140 static int end_sync_write(struct bio *bio, unsigned int bytes_done, int error)
1141 {
1142         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1143         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1144         mddev_t *mddev = r10_bio->mddev;
1145         conf_t *conf = mddev_to_conf(mddev);
1146         int i,d;
1147
1148         if (bio->bi_size)
1149                 return 1;
1150
1151         for (i = 0; i < conf->copies; i++)
1152                 if (r10_bio->devs[i].bio == bio)
1153                         break;
1154         d = r10_bio->devs[i].devnum;
1155
1156         if (!uptodate)
1157                 md_error(mddev, conf->mirrors[d].rdev);
1158         update_head_pos(i, r10_bio);
1159
1160         while (atomic_dec_and_test(&r10_bio->remaining)) {
1161                 if (r10_bio->master_bio == NULL) {
1162                         /* the primary of several recovery bios */
1163                         md_done_sync(mddev, r10_bio->sectors, 1);
1164                         put_buf(r10_bio);
1165                         break;
1166                 } else {
1167                         r10bio_t *r10_bio2 = (r10bio_t *)r10_bio->master_bio;
1168                         put_buf(r10_bio);
1169                         r10_bio = r10_bio2;
1170                 }
1171         }
1172         rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1173         return 0;
1174 }
1175
1176 /*
1177  * Note: sync and recover and handled very differently for raid10
1178  * This code is for resync.
1179  * For resync, we read through virtual addresses and read all blocks.
1180  * If there is any error, we schedule a write.  The lowest numbered
1181  * drive is authoritative.
1182  * However requests come for physical address, so we need to map.
1183  * For every physical address there are raid_disks/copies virtual addresses,
1184  * which is always are least one, but is not necessarly an integer.
1185  * This means that a physical address can span multiple chunks, so we may
1186  * have to submit multiple io requests for a single sync request.
1187  */
1188 /*
1189  * We check if all blocks are in-sync and only write to blocks that
1190  * aren't in sync
1191  */
1192 static void sync_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1193 {
1194         conf_t *conf = mddev_to_conf(mddev);
1195         int i, first;
1196         struct bio *tbio, *fbio;
1197
1198         atomic_set(&r10_bio->remaining, 1);
1199
1200         /* find the first device with a block */
1201         for (i=0; i<conf->copies; i++)
1202                 if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1203                         break;
1204
1205         if (i == conf->copies)
1206                 goto done;
1207
1208         first = i;
1209         fbio = r10_bio->devs[i].bio;
1210
1211         /* now find blocks with errors */
1212         for (i=first+1 ; i < conf->copies ; i++) {
1213                 int vcnt, j, d;
1214
1215                 if (!test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1216                         continue;
1217                 /* We know that the bi_io_vec layout is the same for
1218                  * both 'first' and 'i', so we just compare them.
1219                  * All vec entries are PAGE_SIZE;
1220                  */
1221                 tbio = r10_bio->devs[i].bio;
1222                 vcnt = r10_bio->sectors >> (PAGE_SHIFT-9);
1223                 for (j = 0; j < vcnt; j++)
1224                         if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
1225                                    page_address(tbio->bi_io_vec[j].bv_page),
1226                                    PAGE_SIZE))
1227                                 break;
1228                 if (j == vcnt)
1229                         continue;
1230                 mddev->resync_mismatches += r10_bio->sectors;
1231                 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
1232                         /* Don't fix anything. */
1233                         continue;
1234                 /* Ok, we need to write this bio
1235                  * First we need to fixup bv_offset, bv_len and
1236                  * bi_vecs, as the read request might have corrupted these
1237                  */
1238                 tbio->bi_vcnt = vcnt;
1239                 tbio->bi_size = r10_bio->sectors << 9;
1240                 tbio->bi_idx = 0;
1241                 tbio->bi_phys_segments = 0;
1242                 tbio->bi_hw_segments = 0;
1243                 tbio->bi_hw_front_size = 0;
1244                 tbio->bi_hw_back_size = 0;
1245                 tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1246                 tbio->bi_flags |= 1 << BIO_UPTODATE;
1247                 tbio->bi_next = NULL;
1248                 tbio->bi_rw = WRITE;
1249                 tbio->bi_private = r10_bio;
1250                 tbio->bi_sector = r10_bio->devs[i].addr;
1251
1252                 for (j=0; j < vcnt ; j++) {
1253                         tbio->bi_io_vec[j].bv_offset = 0;
1254                         tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
1255
1256                         memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1257                                page_address(fbio->bi_io_vec[j].bv_page),
1258                                PAGE_SIZE);
1259                 }
1260                 tbio->bi_end_io = end_sync_write;
1261
1262                 d = r10_bio->devs[i].devnum;
1263                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1264                 atomic_inc(&r10_bio->remaining);
1265                 md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
1266
1267                 tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
1268                 tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1269                 generic_make_request(tbio);
1270         }
1271
1272 done:
1273         if (atomic_dec_and_test(&r10_bio->remaining)) {
1274                 md_done_sync(mddev, r10_bio->sectors, 1);
1275                 put_buf(r10_bio);
1276         }
1277 }
1278
1279 /*
1280  * Now for the recovery code.
1281  * Recovery happens across physical sectors.
1282  * We recover all non-is_sync drives by finding the virtual address of
1283  * each, and then choose a working drive that also has that virt address.
1284  * There is a separate r10_bio for each non-in_sync drive.
1285  * Only the first two slots are in use. The first for reading,
1286  * The second for writing.
1287  *
1288  */
1289
1290 static void recovery_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1291 {
1292         conf_t *conf = mddev_to_conf(mddev);
1293         int i, d;
1294         struct bio *bio, *wbio;
1295
1296
1297         /* move the pages across to the second bio
1298          * and submit the write request
1299          */
1300         bio = r10_bio->devs[0].bio;
1301         wbio = r10_bio->devs[1].bio;
1302         for (i=0; i < wbio->bi_vcnt; i++) {
1303                 struct page *p = bio->bi_io_vec[i].bv_page;
1304                 bio->bi_io_vec[i].bv_page = wbio->bi_io_vec[i].bv_page;
1305                 wbio->bi_io_vec[i].bv_page = p;
1306         }
1307         d = r10_bio->devs[1].devnum;
1308
1309         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1310         md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
1311         generic_make_request(wbio);
1312 }
1313
1314
1315 /*
1316  * This is a kernel thread which:
1317  *
1318  *      1.      Retries failed read operations on working mirrors.
1319  *      2.      Updates the raid superblock when problems encounter.
1320  *      3.      Performs writes following reads for array syncronising.
1321  */
1322
1323 static void raid10d(mddev_t *mddev)
1324 {
1325         r10bio_t *r10_bio;
1326         struct bio *bio;
1327         unsigned long flags;
1328         conf_t *conf = mddev_to_conf(mddev);
1329         struct list_head *head = &conf->retry_list;
1330         int unplug=0;
1331         mdk_rdev_t *rdev;
1332
1333         md_check_recovery(mddev);
1334
1335         for (;;) {
1336                 char b[BDEVNAME_SIZE];
1337                 spin_lock_irqsave(&conf->device_lock, flags);
1338
1339                 if (conf->pending_bio_list.head) {
1340                         bio = bio_list_get(&conf->pending_bio_list);
1341                         blk_remove_plug(mddev->queue);
1342                         spin_unlock_irqrestore(&conf->device_lock, flags);
1343                         /* flush any pending bitmap writes to disk before proceeding w/ I/O */
1344                         if (bitmap_unplug(mddev->bitmap) != 0)
1345                                 printk("%s: bitmap file write failed!\n", mdname(mddev));
1346
1347                         while (bio) { /* submit pending writes */
1348                                 struct bio *next = bio->bi_next;
1349                                 bio->bi_next = NULL;
1350                                 generic_make_request(bio);
1351                                 bio = next;
1352                         }
1353                         unplug = 1;
1354
1355                         continue;
1356                 }
1357
1358                 if (list_empty(head))
1359                         break;
1360                 r10_bio = list_entry(head->prev, r10bio_t, retry_list);
1361                 list_del(head->prev);
1362                 conf->nr_queued--;
1363                 spin_unlock_irqrestore(&conf->device_lock, flags);
1364
1365                 mddev = r10_bio->mddev;
1366                 conf = mddev_to_conf(mddev);
1367                 if (test_bit(R10BIO_IsSync, &r10_bio->state)) {
1368                         sync_request_write(mddev, r10_bio);
1369                         unplug = 1;
1370                 } else  if (test_bit(R10BIO_IsRecover, &r10_bio->state)) {
1371                         recovery_request_write(mddev, r10_bio);
1372                         unplug = 1;
1373                 } else {
1374                         int mirror;
1375                         /* we got a read error. Maybe the drive is bad.  Maybe just
1376                          * the block and we can fix it.
1377                          * We freeze all other IO, and try reading the block from
1378                          * other devices.  When we find one, we re-write
1379                          * and check it that fixes the read error.
1380                          * This is all done synchronously while the array is
1381                          * frozen.
1382                          */
1383                         int sect = 0; /* Offset from r10_bio->sector */
1384                         int sectors = r10_bio->sectors;
1385                         freeze_array(conf);
1386                         if (mddev->ro == 0) while(sectors) {
1387                                 int s = sectors;
1388                                 int sl = r10_bio->read_slot;
1389                                 int success = 0;
1390
1391                                 if (s > (PAGE_SIZE>>9))
1392                                         s = PAGE_SIZE >> 9;
1393
1394                                 do {
1395                                         int d = r10_bio->devs[sl].devnum;
1396                                         rdev = conf->mirrors[d].rdev;
1397                                         if (rdev &&
1398                                             test_bit(In_sync, &rdev->flags) &&
1399                                             sync_page_io(rdev->bdev,
1400                                                          r10_bio->devs[sl].addr +
1401                                                          sect + rdev->data_offset,
1402                                                          s<<9,
1403                                                          conf->tmppage, READ))
1404                                                 success = 1;
1405                                         else {
1406                                                 sl++;
1407                                                 if (sl == conf->copies)
1408                                                         sl = 0;
1409                                         }
1410                                 } while (!success && sl != r10_bio->read_slot);
1411
1412                                 if (success) {
1413                                         /* write it back and re-read */
1414                                         while (sl != r10_bio->read_slot) {
1415                                                 int d;
1416                                                 if (sl==0)
1417                                                         sl = conf->copies;
1418                                                 sl--;
1419                                                 d = r10_bio->devs[sl].devnum;
1420                                                 rdev = conf->mirrors[d].rdev;
1421                                                 if (rdev &&
1422                                                     test_bit(In_sync, &rdev->flags)) {
1423                                                         if (sync_page_io(rdev->bdev,
1424                                                                          r10_bio->devs[sl].addr +
1425                                                                          sect + rdev->data_offset,
1426                                                                          s<<9, conf->tmppage, WRITE) == 0 ||
1427                                                             sync_page_io(rdev->bdev,
1428                                                                          r10_bio->devs[sl].addr +
1429                                                                          sect + rdev->data_offset,
1430                                                                          s<<9, conf->tmppage, READ) == 0) {
1431                                                                 /* Well, this device is dead */
1432                                                                 md_error(mddev, rdev);
1433                                                         }
1434                                                 }
1435                                         }
1436                                 } else {
1437                                         /* Cannot read from anywhere -- bye bye array */
1438                                         md_error(mddev, conf->mirrors[r10_bio->devs[r10_bio->read_slot].devnum].rdev);
1439                                         break;
1440                                 }
1441                                 sectors -= s;
1442                                 sect += s;
1443                         }
1444
1445                         unfreeze_array(conf);
1446
1447                         bio = r10_bio->devs[r10_bio->read_slot].bio;
1448                         r10_bio->devs[r10_bio->read_slot].bio = NULL;
1449                         bio_put(bio);
1450                         mirror = read_balance(conf, r10_bio);
1451                         if (mirror == -1) {
1452                                 printk(KERN_ALERT "raid10: %s: unrecoverable I/O"
1453                                        " read error for block %llu\n",
1454                                        bdevname(bio->bi_bdev,b),
1455                                        (unsigned long long)r10_bio->sector);
1456                                 raid_end_bio_io(r10_bio);
1457                         } else {
1458                                 rdev = conf->mirrors[mirror].rdev;
1459                                 if (printk_ratelimit())
1460                                         printk(KERN_ERR "raid10: %s: redirecting sector %llu to"
1461                                                " another mirror\n",
1462                                                bdevname(rdev->bdev,b),
1463                                                (unsigned long long)r10_bio->sector);
1464                                 bio = bio_clone(r10_bio->master_bio, GFP_NOIO);
1465                                 r10_bio->devs[r10_bio->read_slot].bio = bio;
1466                                 bio->bi_sector = r10_bio->devs[r10_bio->read_slot].addr
1467                                         + rdev->data_offset;
1468                                 bio->bi_bdev = rdev->bdev;
1469                                 bio->bi_rw = READ;
1470                                 bio->bi_private = r10_bio;
1471                                 bio->bi_end_io = raid10_end_read_request;
1472                                 unplug = 1;
1473                                 generic_make_request(bio);
1474                         }
1475                 }
1476         }
1477         spin_unlock_irqrestore(&conf->device_lock, flags);
1478         if (unplug)
1479                 unplug_slaves(mddev);
1480 }
1481
1482
1483 static int init_resync(conf_t *conf)
1484 {
1485         int buffs;
1486
1487         buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
1488         if (conf->r10buf_pool)
1489                 BUG();
1490         conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
1491         if (!conf->r10buf_pool)
1492                 return -ENOMEM;
1493         conf->next_resync = 0;
1494         return 0;
1495 }
1496
1497 /*
1498  * perform a "sync" on one "block"
1499  *
1500  * We need to make sure that no normal I/O request - particularly write
1501  * requests - conflict with active sync requests.
1502  *
1503  * This is achieved by tracking pending requests and a 'barrier' concept
1504  * that can be installed to exclude normal IO requests.
1505  *
1506  * Resync and recovery are handled very differently.
1507  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
1508  *
1509  * For resync, we iterate over virtual addresses, read all copies,
1510  * and update if there are differences.  If only one copy is live,
1511  * skip it.
1512  * For recovery, we iterate over physical addresses, read a good
1513  * value for each non-in_sync drive, and over-write.
1514  *
1515  * So, for recovery we may have several outstanding complex requests for a
1516  * given address, one for each out-of-sync device.  We model this by allocating
1517  * a number of r10_bio structures, one for each out-of-sync device.
1518  * As we setup these structures, we collect all bio's together into a list
1519  * which we then process collectively to add pages, and then process again
1520  * to pass to generic_make_request.
1521  *
1522  * The r10_bio structures are linked using a borrowed master_bio pointer.
1523  * This link is counted in ->remaining.  When the r10_bio that points to NULL
1524  * has its remaining count decremented to 0, the whole complex operation
1525  * is complete.
1526  *
1527  */
1528
1529 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
1530 {
1531         conf_t *conf = mddev_to_conf(mddev);
1532         r10bio_t *r10_bio;
1533         struct bio *biolist = NULL, *bio;
1534         sector_t max_sector, nr_sectors;
1535         int disk;
1536         int i;
1537         int max_sync;
1538         int sync_blocks;
1539
1540         sector_t sectors_skipped = 0;
1541         int chunks_skipped = 0;
1542
1543         if (!conf->r10buf_pool)
1544                 if (init_resync(conf))
1545                         return 0;
1546
1547  skipped:
1548         max_sector = mddev->size << 1;
1549         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
1550                 max_sector = mddev->resync_max_sectors;
1551         if (sector_nr >= max_sector) {
1552                 /* If we aborted, we need to abort the
1553                  * sync on the 'current' bitmap chucks (there can
1554                  * be several when recovering multiple devices).
1555                  * as we may have started syncing it but not finished.
1556                  * We can find the current address in
1557                  * mddev->curr_resync, but for recovery,
1558                  * we need to convert that to several
1559                  * virtual addresses.
1560                  */
1561                 if (mddev->curr_resync < max_sector) { /* aborted */
1562                         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
1563                                 bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
1564                                                 &sync_blocks, 1);
1565                         else for (i=0; i<conf->raid_disks; i++) {
1566                                 sector_t sect =
1567                                         raid10_find_virt(conf, mddev->curr_resync, i);
1568                                 bitmap_end_sync(mddev->bitmap, sect,
1569                                                 &sync_blocks, 1);
1570                         }
1571                 } else /* completed sync */
1572                         conf->fullsync = 0;
1573
1574                 bitmap_close_sync(mddev->bitmap);
1575                 close_sync(conf);
1576                 *skipped = 1;
1577                 return sectors_skipped;
1578         }
1579         if (chunks_skipped >= conf->raid_disks) {
1580                 /* if there has been nothing to do on any drive,
1581                  * then there is nothing to do at all..
1582                  */
1583                 *skipped = 1;
1584                 return (max_sector - sector_nr) + sectors_skipped;
1585         }
1586
1587         /* make sure whole request will fit in a chunk - if chunks
1588          * are meaningful
1589          */
1590         if (conf->near_copies < conf->raid_disks &&
1591             max_sector > (sector_nr | conf->chunk_mask))
1592                 max_sector = (sector_nr | conf->chunk_mask) + 1;
1593         /*
1594          * If there is non-resync activity waiting for us then
1595          * put in a delay to throttle resync.
1596          */
1597         if (!go_faster && conf->nr_waiting)
1598                 msleep_interruptible(1000);
1599
1600         /* Again, very different code for resync and recovery.
1601          * Both must result in an r10bio with a list of bios that
1602          * have bi_end_io, bi_sector, bi_bdev set,
1603          * and bi_private set to the r10bio.
1604          * For recovery, we may actually create several r10bios
1605          * with 2 bios in each, that correspond to the bios in the main one.
1606          * In this case, the subordinate r10bios link back through a
1607          * borrowed master_bio pointer, and the counter in the master
1608          * includes a ref from each subordinate.
1609          */
1610         /* First, we decide what to do and set ->bi_end_io
1611          * To end_sync_read if we want to read, and
1612          * end_sync_write if we will want to write.
1613          */
1614
1615         max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
1616         if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
1617                 /* recovery... the complicated one */
1618                 int i, j, k;
1619                 r10_bio = NULL;
1620
1621                 for (i=0 ; i<conf->raid_disks; i++)
1622                         if (conf->mirrors[i].rdev &&
1623                             !test_bit(In_sync, &conf->mirrors[i].rdev->flags)) {
1624                                 int still_degraded = 0;
1625                                 /* want to reconstruct this device */
1626                                 r10bio_t *rb2 = r10_bio;
1627                                 sector_t sect = raid10_find_virt(conf, sector_nr, i);
1628                                 int must_sync;
1629                                 /* Unless we are doing a full sync, we only need
1630                                  * to recover the block if it is set in the bitmap
1631                                  */
1632                                 must_sync = bitmap_start_sync(mddev->bitmap, sect,
1633                                                               &sync_blocks, 1);
1634                                 if (sync_blocks < max_sync)
1635                                         max_sync = sync_blocks;
1636                                 if (!must_sync &&
1637                                     !conf->fullsync) {
1638                                         /* yep, skip the sync_blocks here, but don't assume
1639                                          * that there will never be anything to do here
1640                                          */
1641                                         chunks_skipped = -1;
1642                                         continue;
1643                                 }
1644
1645                                 r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1646                                 raise_barrier(conf, rb2 != NULL);
1647                                 atomic_set(&r10_bio->remaining, 0);
1648
1649                                 r10_bio->master_bio = (struct bio*)rb2;
1650                                 if (rb2)
1651                                         atomic_inc(&rb2->remaining);
1652                                 r10_bio->mddev = mddev;
1653                                 set_bit(R10BIO_IsRecover, &r10_bio->state);
1654                                 r10_bio->sector = sect;
1655
1656                                 raid10_find_phys(conf, r10_bio);
1657                                 /* Need to check if this section will still be
1658                                  * degraded
1659                                  */
1660                                 for (j=0; j<conf->copies;j++) {
1661                                         int d = r10_bio->devs[j].devnum;
1662                                         if (conf->mirrors[d].rdev == NULL ||
1663                                             test_bit(Faulty, &conf->mirrors[d].rdev->flags))
1664                                                 still_degraded = 1;
1665                                 }
1666                                 must_sync = bitmap_start_sync(mddev->bitmap, sect,
1667                                                               &sync_blocks, still_degraded);
1668
1669                                 for (j=0; j<conf->copies;j++) {
1670                                         int d = r10_bio->devs[j].devnum;
1671                                         if (conf->mirrors[d].rdev &&
1672                                             test_bit(In_sync, &conf->mirrors[d].rdev->flags)) {
1673                                                 /* This is where we read from */
1674                                                 bio = r10_bio->devs[0].bio;
1675                                                 bio->bi_next = biolist;
1676                                                 biolist = bio;
1677                                                 bio->bi_private = r10_bio;
1678                                                 bio->bi_end_io = end_sync_read;
1679                                                 bio->bi_rw = 0;
1680                                                 bio->bi_sector = r10_bio->devs[j].addr +
1681                                                         conf->mirrors[d].rdev->data_offset;
1682                                                 bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1683                                                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1684                                                 atomic_inc(&r10_bio->remaining);
1685                                                 /* and we write to 'i' */
1686
1687                                                 for (k=0; k<conf->copies; k++)
1688                                                         if (r10_bio->devs[k].devnum == i)
1689                                                                 break;
1690                                                 bio = r10_bio->devs[1].bio;
1691                                                 bio->bi_next = biolist;
1692                                                 biolist = bio;
1693                                                 bio->bi_private = r10_bio;
1694                                                 bio->bi_end_io = end_sync_write;
1695                                                 bio->bi_rw = 1;
1696                                                 bio->bi_sector = r10_bio->devs[k].addr +
1697                                                         conf->mirrors[i].rdev->data_offset;
1698                                                 bio->bi_bdev = conf->mirrors[i].rdev->bdev;
1699
1700                                                 r10_bio->devs[0].devnum = d;
1701                                                 r10_bio->devs[1].devnum = i;
1702
1703                                                 break;
1704                                         }
1705                                 }
1706                                 if (j == conf->copies) {
1707                                         /* Cannot recover, so abort the recovery */
1708                                         put_buf(r10_bio);
1709                                         r10_bio = rb2;
1710                                         if (!test_and_set_bit(MD_RECOVERY_ERR, &mddev->recovery))
1711                                                 printk(KERN_INFO "raid10: %s: insufficient working devices for recovery.\n",
1712                                                        mdname(mddev));
1713                                         break;
1714                                 }
1715                         }
1716                 if (biolist == NULL) {
1717                         while (r10_bio) {
1718                                 r10bio_t *rb2 = r10_bio;
1719                                 r10_bio = (r10bio_t*) rb2->master_bio;
1720                                 rb2->master_bio = NULL;
1721                                 put_buf(rb2);
1722                         }
1723                         goto giveup;
1724                 }
1725         } else {
1726                 /* resync. Schedule a read for every block at this virt offset */
1727                 int count = 0;
1728
1729                 if (!bitmap_start_sync(mddev->bitmap, sector_nr,
1730                                        &sync_blocks, mddev->degraded) &&
1731                     !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
1732                         /* We can skip this block */
1733                         *skipped = 1;
1734                         return sync_blocks + sectors_skipped;
1735                 }
1736                 if (sync_blocks < max_sync)
1737                         max_sync = sync_blocks;
1738                 r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1739
1740                 r10_bio->mddev = mddev;
1741                 atomic_set(&r10_bio->remaining, 0);
1742                 raise_barrier(conf, 0);
1743                 conf->next_resync = sector_nr;
1744
1745                 r10_bio->master_bio = NULL;
1746                 r10_bio->sector = sector_nr;
1747                 set_bit(R10BIO_IsSync, &r10_bio->state);
1748                 raid10_find_phys(conf, r10_bio);
1749                 r10_bio->sectors = (sector_nr | conf->chunk_mask) - sector_nr +1;
1750
1751                 for (i=0; i<conf->copies; i++) {
1752                         int d = r10_bio->devs[i].devnum;
1753                         bio = r10_bio->devs[i].bio;
1754                         bio->bi_end_io = NULL;
1755                         if (conf->mirrors[d].rdev == NULL ||
1756                             test_bit(Faulty, &conf->mirrors[d].rdev->flags))
1757                                 continue;
1758                         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1759                         atomic_inc(&r10_bio->remaining);
1760                         bio->bi_next = biolist;
1761                         biolist = bio;
1762                         bio->bi_private = r10_bio;
1763                         bio->bi_end_io = end_sync_read;
1764                         bio->bi_rw = 0;
1765                         bio->bi_sector = r10_bio->devs[i].addr +
1766                                 conf->mirrors[d].rdev->data_offset;
1767                         bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1768                         count++;
1769                 }
1770
1771                 if (count < 2) {
1772                         for (i=0; i<conf->copies; i++) {
1773                                 int d = r10_bio->devs[i].devnum;
1774                                 if (r10_bio->devs[i].bio->bi_end_io)
1775                                         rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1776                         }
1777                         put_buf(r10_bio);
1778                         biolist = NULL;
1779                         goto giveup;
1780                 }
1781         }
1782
1783         for (bio = biolist; bio ; bio=bio->bi_next) {
1784
1785                 bio->bi_flags &= ~(BIO_POOL_MASK - 1);
1786                 if (bio->bi_end_io)
1787                         bio->bi_flags |= 1 << BIO_UPTODATE;
1788                 bio->bi_vcnt = 0;
1789                 bio->bi_idx = 0;
1790                 bio->bi_phys_segments = 0;
1791                 bio->bi_hw_segments = 0;
1792                 bio->bi_size = 0;
1793         }
1794
1795         nr_sectors = 0;
1796         if (sector_nr + max_sync < max_sector)
1797                 max_sector = sector_nr + max_sync;
1798         do {
1799                 struct page *page;
1800                 int len = PAGE_SIZE;
1801                 disk = 0;
1802                 if (sector_nr + (len>>9) > max_sector)
1803                         len = (max_sector - sector_nr) << 9;
1804                 if (len == 0)
1805                         break;
1806                 for (bio= biolist ; bio ; bio=bio->bi_next) {
1807                         page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
1808                         if (bio_add_page(bio, page, len, 0) == 0) {
1809                                 /* stop here */
1810                                 struct bio *bio2;
1811                                 bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
1812                                 for (bio2 = biolist; bio2 && bio2 != bio; bio2 = bio2->bi_next) {
1813                                         /* remove last page from this bio */
1814                                         bio2->bi_vcnt--;
1815                                         bio2->bi_size -= len;
1816                                         bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
1817                                 }
1818                                 goto bio_full;
1819                         }
1820                         disk = i;
1821                 }
1822                 nr_sectors += len>>9;
1823                 sector_nr += len>>9;
1824         } while (biolist->bi_vcnt < RESYNC_PAGES);
1825  bio_full:
1826         r10_bio->sectors = nr_sectors;
1827
1828         while (biolist) {
1829                 bio = biolist;
1830                 biolist = biolist->bi_next;
1831
1832                 bio->bi_next = NULL;
1833                 r10_bio = bio->bi_private;
1834                 r10_bio->sectors = nr_sectors;
1835
1836                 if (bio->bi_end_io == end_sync_read) {
1837                         md_sync_acct(bio->bi_bdev, nr_sectors);
1838                         generic_make_request(bio);
1839                 }
1840         }
1841
1842         if (sectors_skipped)
1843                 /* pretend they weren't skipped, it makes
1844                  * no important difference in this case
1845                  */
1846                 md_done_sync(mddev, sectors_skipped, 1);
1847
1848         return sectors_skipped + nr_sectors;
1849  giveup:
1850         /* There is nowhere to write, so all non-sync
1851          * drives must be failed, so try the next chunk...
1852          */
1853         {
1854         sector_t sec = max_sector - sector_nr;
1855         sectors_skipped += sec;
1856         chunks_skipped ++;
1857         sector_nr = max_sector;
1858         goto skipped;
1859         }
1860 }
1861
1862 static int run(mddev_t *mddev)
1863 {
1864         conf_t *conf;
1865         int i, disk_idx;
1866         mirror_info_t *disk;
1867         mdk_rdev_t *rdev;
1868         struct list_head *tmp;
1869         int nc, fc;
1870         sector_t stride, size;
1871
1872         if (mddev->level != 10) {
1873                 printk(KERN_ERR "raid10: %s: raid level not set correctly... (%d)\n",
1874                        mdname(mddev), mddev->level);
1875                 goto out;
1876         }
1877         nc = mddev->layout & 255;
1878         fc = (mddev->layout >> 8) & 255;
1879         if ((nc*fc) <2 || (nc*fc) > mddev->raid_disks ||
1880             (mddev->layout >> 16)) {
1881                 printk(KERN_ERR "raid10: %s: unsupported raid10 layout: 0x%8x\n",
1882                        mdname(mddev), mddev->layout);
1883                 goto out;
1884         }
1885         /*
1886          * copy the already verified devices into our private RAID10
1887          * bookkeeping area. [whatever we allocate in run(),
1888          * should be freed in stop()]
1889          */
1890         conf = kzalloc(sizeof(conf_t), GFP_KERNEL);
1891         mddev->private = conf;
1892         if (!conf) {
1893                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1894                         mdname(mddev));
1895                 goto out;
1896         }
1897         conf->mirrors = kzalloc(sizeof(struct mirror_info)*mddev->raid_disks,
1898                                  GFP_KERNEL);
1899         if (!conf->mirrors) {
1900                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1901                        mdname(mddev));
1902                 goto out_free_conf;
1903         }
1904
1905         conf->tmppage = alloc_page(GFP_KERNEL);
1906         if (!conf->tmppage)
1907                 goto out_free_conf;
1908
1909         conf->near_copies = nc;
1910         conf->far_copies = fc;
1911         conf->copies = nc*fc;
1912         conf->chunk_mask = (sector_t)(mddev->chunk_size>>9)-1;
1913         conf->chunk_shift = ffz(~mddev->chunk_size) - 9;
1914         stride = mddev->size >> (conf->chunk_shift-1);
1915         sector_div(stride, fc);
1916         conf->stride = stride << conf->chunk_shift;
1917
1918         conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
1919                                                 r10bio_pool_free, conf);
1920         if (!conf->r10bio_pool) {
1921                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1922                         mdname(mddev));
1923                 goto out_free_conf;
1924         }
1925
1926         ITERATE_RDEV(mddev, rdev, tmp) {
1927                 disk_idx = rdev->raid_disk;
1928                 if (disk_idx >= mddev->raid_disks
1929                     || disk_idx < 0)
1930                         continue;
1931                 disk = conf->mirrors + disk_idx;
1932
1933                 disk->rdev = rdev;
1934
1935                 blk_queue_stack_limits(mddev->queue,
1936                                        rdev->bdev->bd_disk->queue);
1937                 /* as we don't honour merge_bvec_fn, we must never risk
1938                  * violating it, so limit ->max_sector to one PAGE, as
1939                  * a one page request is never in violation.
1940                  */
1941                 if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
1942                     mddev->queue->max_sectors > (PAGE_SIZE>>9))
1943                         mddev->queue->max_sectors = (PAGE_SIZE>>9);
1944
1945                 disk->head_position = 0;
1946                 if (!test_bit(Faulty, &rdev->flags) && test_bit(In_sync, &rdev->flags))
1947                         conf->working_disks++;
1948         }
1949         conf->raid_disks = mddev->raid_disks;
1950         conf->mddev = mddev;
1951         spin_lock_init(&conf->device_lock);
1952         INIT_LIST_HEAD(&conf->retry_list);
1953
1954         spin_lock_init(&conf->resync_lock);
1955         init_waitqueue_head(&conf->wait_barrier);
1956
1957         /* need to check that every block has at least one working mirror */
1958         if (!enough(conf)) {
1959                 printk(KERN_ERR "raid10: not enough operational mirrors for %s\n",
1960                        mdname(mddev));
1961                 goto out_free_conf;
1962         }
1963
1964         mddev->degraded = 0;
1965         for (i = 0; i < conf->raid_disks; i++) {
1966
1967                 disk = conf->mirrors + i;
1968
1969                 if (!disk->rdev) {
1970                         disk->head_position = 0;
1971                         mddev->degraded++;
1972                 }
1973         }
1974
1975
1976         mddev->thread = md_register_thread(raid10d, mddev, "%s_raid10");
1977         if (!mddev->thread) {
1978                 printk(KERN_ERR
1979                        "raid10: couldn't allocate thread for %s\n",
1980                        mdname(mddev));
1981                 goto out_free_conf;
1982         }
1983
1984         printk(KERN_INFO
1985                 "raid10: raid set %s active with %d out of %d devices\n",
1986                 mdname(mddev), mddev->raid_disks - mddev->degraded,
1987                 mddev->raid_disks);
1988         /*
1989          * Ok, everything is just fine now
1990          */
1991         size = conf->stride * conf->raid_disks;
1992         sector_div(size, conf->near_copies);
1993         mddev->array_size = size/2;
1994         mddev->resync_max_sectors = size;
1995
1996         mddev->queue->unplug_fn = raid10_unplug;
1997         mddev->queue->issue_flush_fn = raid10_issue_flush;
1998
1999         /* Calculate max read-ahead size.
2000          * We need to readahead at least twice a whole stripe....
2001          * maybe...
2002          */
2003         {
2004                 int stripe = conf->raid_disks * mddev->chunk_size / PAGE_CACHE_SIZE;
2005                 stripe /= conf->near_copies;
2006                 if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
2007                         mddev->queue->backing_dev_info.ra_pages = 2* stripe;
2008         }
2009
2010         if (conf->near_copies < mddev->raid_disks)
2011                 blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
2012         return 0;
2013
2014 out_free_conf:
2015         if (conf->r10bio_pool)
2016                 mempool_destroy(conf->r10bio_pool);
2017         put_page(conf->tmppage);
2018         kfree(conf->mirrors);
2019         kfree(conf);
2020         mddev->private = NULL;
2021 out:
2022         return -EIO;
2023 }
2024
2025 static int stop(mddev_t *mddev)
2026 {
2027         conf_t *conf = mddev_to_conf(mddev);
2028
2029         md_unregister_thread(mddev->thread);
2030         mddev->thread = NULL;
2031         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
2032         if (conf->r10bio_pool)
2033                 mempool_destroy(conf->r10bio_pool);
2034         kfree(conf->mirrors);
2035         kfree(conf);
2036         mddev->private = NULL;
2037         return 0;
2038 }
2039
2040 static void raid10_quiesce(mddev_t *mddev, int state)
2041 {
2042         conf_t *conf = mddev_to_conf(mddev);
2043
2044         switch(state) {
2045         case 1:
2046                 raise_barrier(conf, 0);
2047                 break;
2048         case 0:
2049                 lower_barrier(conf);
2050                 break;
2051         }
2052         if (mddev->thread) {
2053                 if (mddev->bitmap)
2054                         mddev->thread->timeout = mddev->bitmap->daemon_sleep * HZ;
2055                 else
2056                         mddev->thread->timeout = MAX_SCHEDULE_TIMEOUT;
2057                 md_wakeup_thread(mddev->thread);
2058         }
2059 }
2060
2061 static mdk_personality_t raid10_personality =
2062 {
2063         .name           = "raid10",
2064         .owner          = THIS_MODULE,
2065         .make_request   = make_request,
2066         .run            = run,
2067         .stop           = stop,
2068         .status         = status,
2069         .error_handler  = error,
2070         .hot_add_disk   = raid10_add_disk,
2071         .hot_remove_disk= raid10_remove_disk,
2072         .spare_active   = raid10_spare_active,
2073         .sync_request   = sync_request,
2074         .quiesce        = raid10_quiesce,
2075 };
2076
2077 static int __init raid_init(void)
2078 {
2079         return register_md_personality(RAID10, &raid10_personality);
2080 }
2081
2082 static void raid_exit(void)
2083 {
2084         unregister_md_personality(RAID10);
2085 }
2086
2087 module_init(raid_init);
2088 module_exit(raid_exit);
2089 MODULE_LICENSE("GPL");
2090 MODULE_ALIAS("md-personality-9"); /* RAID10 */