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