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