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