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