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