Merge branch 'master'
[pandora-kernel.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(gfp_t 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(gfp_t 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         const int rw = bio_data_dir(bio);
672
673         if (unlikely(bio_barrier(bio))) {
674                 bio_endio(bio, bio->bi_size, -EOPNOTSUPP);
675                 return 0;
676         }
677
678         /* If this request crosses a chunk boundary, we need to
679          * split it.  This will only happen for 1 PAGE (or less) requests.
680          */
681         if (unlikely( (bio->bi_sector & conf->chunk_mask) + (bio->bi_size >> 9)
682                       > chunk_sects &&
683                     conf->near_copies < conf->raid_disks)) {
684                 struct bio_pair *bp;
685                 /* Sanity check -- queue functions should prevent this happening */
686                 if (bio->bi_vcnt != 1 ||
687                     bio->bi_idx != 0)
688                         goto bad_map;
689                 /* This is a one page bio that upper layers
690                  * refuse to split for us, so we need to split it.
691                  */
692                 bp = bio_split(bio, bio_split_pool,
693                                chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
694                 if (make_request(q, &bp->bio1))
695                         generic_make_request(&bp->bio1);
696                 if (make_request(q, &bp->bio2))
697                         generic_make_request(&bp->bio2);
698
699                 bio_pair_release(bp);
700                 return 0;
701         bad_map:
702                 printk("raid10_make_request bug: can't convert block across chunks"
703                        " or bigger than %dk %llu %d\n", chunk_sects/2,
704                        (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
705
706                 bio_io_error(bio, bio->bi_size);
707                 return 0;
708         }
709
710         md_write_start(mddev, bio);
711
712         /*
713          * Register the new request and wait if the reconstruction
714          * thread has put up a bar for new requests.
715          * Continue immediately if no resync is active currently.
716          */
717         spin_lock_irq(&conf->resync_lock);
718         wait_event_lock_irq(conf->wait_resume, !conf->barrier, conf->resync_lock, );
719         conf->nr_pending++;
720         spin_unlock_irq(&conf->resync_lock);
721
722         disk_stat_inc(mddev->gendisk, ios[rw]);
723         disk_stat_add(mddev->gendisk, sectors[rw], bio_sectors(bio));
724
725         r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
726
727         r10_bio->master_bio = bio;
728         r10_bio->sectors = bio->bi_size >> 9;
729
730         r10_bio->mddev = mddev;
731         r10_bio->sector = bio->bi_sector;
732
733         if (rw == READ) {
734                 /*
735                  * read balancing logic:
736                  */
737                 int disk = read_balance(conf, r10_bio);
738                 int slot = r10_bio->read_slot;
739                 if (disk < 0) {
740                         raid_end_bio_io(r10_bio);
741                         return 0;
742                 }
743                 mirror = conf->mirrors + disk;
744
745                 read_bio = bio_clone(bio, GFP_NOIO);
746
747                 r10_bio->devs[slot].bio = read_bio;
748
749                 read_bio->bi_sector = r10_bio->devs[slot].addr +
750                         mirror->rdev->data_offset;
751                 read_bio->bi_bdev = mirror->rdev->bdev;
752                 read_bio->bi_end_io = raid10_end_read_request;
753                 read_bio->bi_rw = READ;
754                 read_bio->bi_private = r10_bio;
755
756                 generic_make_request(read_bio);
757                 return 0;
758         }
759
760         /*
761          * WRITE:
762          */
763         /* first select target devices under spinlock and
764          * inc refcount on their rdev.  Record them by setting
765          * bios[x] to bio
766          */
767         raid10_find_phys(conf, r10_bio);
768         rcu_read_lock();
769         for (i = 0;  i < conf->copies; i++) {
770                 int d = r10_bio->devs[i].devnum;
771                 if (conf->mirrors[d].rdev &&
772                     !conf->mirrors[d].rdev->faulty) {
773                         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
774                         r10_bio->devs[i].bio = bio;
775                 } else
776                         r10_bio->devs[i].bio = NULL;
777         }
778         rcu_read_unlock();
779
780         atomic_set(&r10_bio->remaining, 1);
781
782         for (i = 0; i < conf->copies; i++) {
783                 struct bio *mbio;
784                 int d = r10_bio->devs[i].devnum;
785                 if (!r10_bio->devs[i].bio)
786                         continue;
787
788                 mbio = bio_clone(bio, GFP_NOIO);
789                 r10_bio->devs[i].bio = mbio;
790
791                 mbio->bi_sector = r10_bio->devs[i].addr+
792                         conf->mirrors[d].rdev->data_offset;
793                 mbio->bi_bdev = conf->mirrors[d].rdev->bdev;
794                 mbio->bi_end_io = raid10_end_write_request;
795                 mbio->bi_rw = WRITE;
796                 mbio->bi_private = r10_bio;
797
798                 atomic_inc(&r10_bio->remaining);
799                 generic_make_request(mbio);
800         }
801
802         if (atomic_dec_and_test(&r10_bio->remaining)) {
803                 md_write_end(mddev);
804                 raid_end_bio_io(r10_bio);
805         }
806
807         return 0;
808 }
809
810 static void status(struct seq_file *seq, mddev_t *mddev)
811 {
812         conf_t *conf = mddev_to_conf(mddev);
813         int i;
814
815         if (conf->near_copies < conf->raid_disks)
816                 seq_printf(seq, " %dK chunks", mddev->chunk_size/1024);
817         if (conf->near_copies > 1)
818                 seq_printf(seq, " %d near-copies", conf->near_copies);
819         if (conf->far_copies > 1)
820                 seq_printf(seq, " %d far-copies", conf->far_copies);
821
822         seq_printf(seq, " [%d/%d] [", conf->raid_disks,
823                                                 conf->working_disks);
824         for (i = 0; i < conf->raid_disks; i++)
825                 seq_printf(seq, "%s",
826                               conf->mirrors[i].rdev &&
827                               conf->mirrors[i].rdev->in_sync ? "U" : "_");
828         seq_printf(seq, "]");
829 }
830
831 static void error(mddev_t *mddev, mdk_rdev_t *rdev)
832 {
833         char b[BDEVNAME_SIZE];
834         conf_t *conf = mddev_to_conf(mddev);
835
836         /*
837          * If it is not operational, then we have already marked it as dead
838          * else if it is the last working disks, ignore the error, let the
839          * next level up know.
840          * else mark the drive as failed
841          */
842         if (rdev->in_sync
843             && conf->working_disks == 1)
844                 /*
845                  * Don't fail the drive, just return an IO error.
846                  * The test should really be more sophisticated than
847                  * "working_disks == 1", but it isn't critical, and
848                  * can wait until we do more sophisticated "is the drive
849                  * really dead" tests...
850                  */
851                 return;
852         if (rdev->in_sync) {
853                 mddev->degraded++;
854                 conf->working_disks--;
855                 /*
856                  * if recovery is running, make sure it aborts.
857                  */
858                 set_bit(MD_RECOVERY_ERR, &mddev->recovery);
859         }
860         rdev->in_sync = 0;
861         rdev->faulty = 1;
862         mddev->sb_dirty = 1;
863         printk(KERN_ALERT "raid10: Disk failure on %s, disabling device. \n"
864                 "       Operation continuing on %d devices\n",
865                 bdevname(rdev->bdev,b), conf->working_disks);
866 }
867
868 static void print_conf(conf_t *conf)
869 {
870         int i;
871         mirror_info_t *tmp;
872
873         printk("RAID10 conf printout:\n");
874         if (!conf) {
875                 printk("(!conf)\n");
876                 return;
877         }
878         printk(" --- wd:%d rd:%d\n", conf->working_disks,
879                 conf->raid_disks);
880
881         for (i = 0; i < conf->raid_disks; i++) {
882                 char b[BDEVNAME_SIZE];
883                 tmp = conf->mirrors + i;
884                 if (tmp->rdev)
885                         printk(" disk %d, wo:%d, o:%d, dev:%s\n",
886                                 i, !tmp->rdev->in_sync, !tmp->rdev->faulty,
887                                 bdevname(tmp->rdev->bdev,b));
888         }
889 }
890
891 static void close_sync(conf_t *conf)
892 {
893         spin_lock_irq(&conf->resync_lock);
894         wait_event_lock_irq(conf->wait_resume, !conf->barrier,
895                             conf->resync_lock,  unplug_slaves(conf->mddev));
896         spin_unlock_irq(&conf->resync_lock);
897
898         if (conf->barrier) BUG();
899         if (waitqueue_active(&conf->wait_idle)) BUG();
900
901         mempool_destroy(conf->r10buf_pool);
902         conf->r10buf_pool = NULL;
903 }
904
905 /* check if there are enough drives for
906  * every block to appear on atleast one
907  */
908 static int enough(conf_t *conf)
909 {
910         int first = 0;
911
912         do {
913                 int n = conf->copies;
914                 int cnt = 0;
915                 while (n--) {
916                         if (conf->mirrors[first].rdev)
917                                 cnt++;
918                         first = (first+1) % conf->raid_disks;
919                 }
920                 if (cnt == 0)
921                         return 0;
922         } while (first != 0);
923         return 1;
924 }
925
926 static int raid10_spare_active(mddev_t *mddev)
927 {
928         int i;
929         conf_t *conf = mddev->private;
930         mirror_info_t *tmp;
931
932         /*
933          * Find all non-in_sync disks within the RAID10 configuration
934          * and mark them in_sync
935          */
936         for (i = 0; i < conf->raid_disks; i++) {
937                 tmp = conf->mirrors + i;
938                 if (tmp->rdev
939                     && !tmp->rdev->faulty
940                     && !tmp->rdev->in_sync) {
941                         conf->working_disks++;
942                         mddev->degraded--;
943                         tmp->rdev->in_sync = 1;
944                 }
945         }
946
947         print_conf(conf);
948         return 0;
949 }
950
951
952 static int raid10_add_disk(mddev_t *mddev, mdk_rdev_t *rdev)
953 {
954         conf_t *conf = mddev->private;
955         int found = 0;
956         int mirror;
957         mirror_info_t *p;
958
959         if (mddev->recovery_cp < MaxSector)
960                 /* only hot-add to in-sync arrays, as recovery is
961                  * very different from resync
962                  */
963                 return 0;
964         if (!enough(conf))
965                 return 0;
966
967         for (mirror=0; mirror < mddev->raid_disks; mirror++)
968                 if ( !(p=conf->mirrors+mirror)->rdev) {
969
970                         blk_queue_stack_limits(mddev->queue,
971                                                rdev->bdev->bd_disk->queue);
972                         /* as we don't honour merge_bvec_fn, we must never risk
973                          * violating it, so limit ->max_sector to one PAGE, as
974                          * a one page request is never in violation.
975                          */
976                         if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
977                             mddev->queue->max_sectors > (PAGE_SIZE>>9))
978                                 mddev->queue->max_sectors = (PAGE_SIZE>>9);
979
980                         p->head_position = 0;
981                         rdev->raid_disk = mirror;
982                         found = 1;
983                         p->rdev = rdev;
984                         break;
985                 }
986
987         print_conf(conf);
988         return found;
989 }
990
991 static int raid10_remove_disk(mddev_t *mddev, int number)
992 {
993         conf_t *conf = mddev->private;
994         int err = 0;
995         mdk_rdev_t *rdev;
996         mirror_info_t *p = conf->mirrors+ number;
997
998         print_conf(conf);
999         rdev = p->rdev;
1000         if (rdev) {
1001                 if (rdev->in_sync ||
1002                     atomic_read(&rdev->nr_pending)) {
1003                         err = -EBUSY;
1004                         goto abort;
1005                 }
1006                 p->rdev = NULL;
1007                 synchronize_rcu();
1008                 if (atomic_read(&rdev->nr_pending)) {
1009                         /* lost the race, try later */
1010                         err = -EBUSY;
1011                         p->rdev = rdev;
1012                 }
1013         }
1014 abort:
1015
1016         print_conf(conf);
1017         return err;
1018 }
1019
1020
1021 static int end_sync_read(struct bio *bio, unsigned int bytes_done, int error)
1022 {
1023         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1024         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1025         conf_t *conf = mddev_to_conf(r10_bio->mddev);
1026         int i,d;
1027
1028         if (bio->bi_size)
1029                 return 1;
1030
1031         for (i=0; i<conf->copies; i++)
1032                 if (r10_bio->devs[i].bio == bio)
1033                         break;
1034         if (i == conf->copies)
1035                 BUG();
1036         update_head_pos(i, r10_bio);
1037         d = r10_bio->devs[i].devnum;
1038         if (!uptodate)
1039                 md_error(r10_bio->mddev,
1040                          conf->mirrors[d].rdev);
1041
1042         /* for reconstruct, we always reschedule after a read.
1043          * for resync, only after all reads
1044          */
1045         if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1046             atomic_dec_and_test(&r10_bio->remaining)) {
1047                 /* we have read all the blocks,
1048                  * do the comparison in process context in raid10d
1049                  */
1050                 reschedule_retry(r10_bio);
1051         }
1052         rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1053         return 0;
1054 }
1055
1056 static int end_sync_write(struct bio *bio, unsigned int bytes_done, int error)
1057 {
1058         int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1059         r10bio_t * r10_bio = (r10bio_t *)(bio->bi_private);
1060         mddev_t *mddev = r10_bio->mddev;
1061         conf_t *conf = mddev_to_conf(mddev);
1062         int i,d;
1063
1064         if (bio->bi_size)
1065                 return 1;
1066
1067         for (i = 0; i < conf->copies; i++)
1068                 if (r10_bio->devs[i].bio == bio)
1069                         break;
1070         d = r10_bio->devs[i].devnum;
1071
1072         if (!uptodate)
1073                 md_error(mddev, conf->mirrors[d].rdev);
1074         update_head_pos(i, r10_bio);
1075
1076         while (atomic_dec_and_test(&r10_bio->remaining)) {
1077                 if (r10_bio->master_bio == NULL) {
1078                         /* the primary of several recovery bios */
1079                         md_done_sync(mddev, r10_bio->sectors, 1);
1080                         put_buf(r10_bio);
1081                         break;
1082                 } else {
1083                         r10bio_t *r10_bio2 = (r10bio_t *)r10_bio->master_bio;
1084                         put_buf(r10_bio);
1085                         r10_bio = r10_bio2;
1086                 }
1087         }
1088         rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1089         return 0;
1090 }
1091
1092 /*
1093  * Note: sync and recover and handled very differently for raid10
1094  * This code is for resync.
1095  * For resync, we read through virtual addresses and read all blocks.
1096  * If there is any error, we schedule a write.  The lowest numbered
1097  * drive is authoritative.
1098  * However requests come for physical address, so we need to map.
1099  * For every physical address there are raid_disks/copies virtual addresses,
1100  * which is always are least one, but is not necessarly an integer.
1101  * This means that a physical address can span multiple chunks, so we may
1102  * have to submit multiple io requests for a single sync request.
1103  */
1104 /*
1105  * We check if all blocks are in-sync and only write to blocks that
1106  * aren't in sync
1107  */
1108 static void sync_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1109 {
1110         conf_t *conf = mddev_to_conf(mddev);
1111         int i, first;
1112         struct bio *tbio, *fbio;
1113
1114         atomic_set(&r10_bio->remaining, 1);
1115
1116         /* find the first device with a block */
1117         for (i=0; i<conf->copies; i++)
1118                 if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1119                         break;
1120
1121         if (i == conf->copies)
1122                 goto done;
1123
1124         first = i;
1125         fbio = r10_bio->devs[i].bio;
1126
1127         /* now find blocks with errors */
1128         for (i=first+1 ; i < conf->copies ; i++) {
1129                 int vcnt, j, d;
1130
1131                 if (!test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1132                         continue;
1133                 /* We know that the bi_io_vec layout is the same for
1134                  * both 'first' and 'i', so we just compare them.
1135                  * All vec entries are PAGE_SIZE;
1136                  */
1137                 tbio = r10_bio->devs[i].bio;
1138                 vcnt = r10_bio->sectors >> (PAGE_SHIFT-9);
1139                 for (j = 0; j < vcnt; j++)
1140                         if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
1141                                    page_address(tbio->bi_io_vec[j].bv_page),
1142                                    PAGE_SIZE))
1143                                 break;
1144                 if (j == vcnt)
1145                         continue;
1146                 /* Ok, we need to write this bio
1147                  * First we need to fixup bv_offset, bv_len and
1148                  * bi_vecs, as the read request might have corrupted these
1149                  */
1150                 tbio->bi_vcnt = vcnt;
1151                 tbio->bi_size = r10_bio->sectors << 9;
1152                 tbio->bi_idx = 0;
1153                 tbio->bi_phys_segments = 0;
1154                 tbio->bi_hw_segments = 0;
1155                 tbio->bi_hw_front_size = 0;
1156                 tbio->bi_hw_back_size = 0;
1157                 tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
1158                 tbio->bi_flags |= 1 << BIO_UPTODATE;
1159                 tbio->bi_next = NULL;
1160                 tbio->bi_rw = WRITE;
1161                 tbio->bi_private = r10_bio;
1162                 tbio->bi_sector = r10_bio->devs[i].addr;
1163
1164                 for (j=0; j < vcnt ; j++) {
1165                         tbio->bi_io_vec[j].bv_offset = 0;
1166                         tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
1167
1168                         memcpy(page_address(tbio->bi_io_vec[j].bv_page),
1169                                page_address(fbio->bi_io_vec[j].bv_page),
1170                                PAGE_SIZE);
1171                 }
1172                 tbio->bi_end_io = end_sync_write;
1173
1174                 d = r10_bio->devs[i].devnum;
1175                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1176                 atomic_inc(&r10_bio->remaining);
1177                 md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
1178
1179                 tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
1180                 tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
1181                 generic_make_request(tbio);
1182         }
1183
1184 done:
1185         if (atomic_dec_and_test(&r10_bio->remaining)) {
1186                 md_done_sync(mddev, r10_bio->sectors, 1);
1187                 put_buf(r10_bio);
1188         }
1189 }
1190
1191 /*
1192  * Now for the recovery code.
1193  * Recovery happens across physical sectors.
1194  * We recover all non-is_sync drives by finding the virtual address of
1195  * each, and then choose a working drive that also has that virt address.
1196  * There is a separate r10_bio for each non-in_sync drive.
1197  * Only the first two slots are in use. The first for reading,
1198  * The second for writing.
1199  *
1200  */
1201
1202 static void recovery_request_write(mddev_t *mddev, r10bio_t *r10_bio)
1203 {
1204         conf_t *conf = mddev_to_conf(mddev);
1205         int i, d;
1206         struct bio *bio, *wbio;
1207
1208
1209         /* move the pages across to the second bio
1210          * and submit the write request
1211          */
1212         bio = r10_bio->devs[0].bio;
1213         wbio = r10_bio->devs[1].bio;
1214         for (i=0; i < wbio->bi_vcnt; i++) {
1215                 struct page *p = bio->bi_io_vec[i].bv_page;
1216                 bio->bi_io_vec[i].bv_page = wbio->bi_io_vec[i].bv_page;
1217                 wbio->bi_io_vec[i].bv_page = p;
1218         }
1219         d = r10_bio->devs[1].devnum;
1220
1221         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1222         md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
1223         generic_make_request(wbio);
1224 }
1225
1226
1227 /*
1228  * This is a kernel thread which:
1229  *
1230  *      1.      Retries failed read operations on working mirrors.
1231  *      2.      Updates the raid superblock when problems encounter.
1232  *      3.      Performs writes following reads for array syncronising.
1233  */
1234
1235 static void raid10d(mddev_t *mddev)
1236 {
1237         r10bio_t *r10_bio;
1238         struct bio *bio;
1239         unsigned long flags;
1240         conf_t *conf = mddev_to_conf(mddev);
1241         struct list_head *head = &conf->retry_list;
1242         int unplug=0;
1243         mdk_rdev_t *rdev;
1244
1245         md_check_recovery(mddev);
1246
1247         for (;;) {
1248                 char b[BDEVNAME_SIZE];
1249                 spin_lock_irqsave(&conf->device_lock, flags);
1250                 if (list_empty(head))
1251                         break;
1252                 r10_bio = list_entry(head->prev, r10bio_t, retry_list);
1253                 list_del(head->prev);
1254                 spin_unlock_irqrestore(&conf->device_lock, flags);
1255
1256                 mddev = r10_bio->mddev;
1257                 conf = mddev_to_conf(mddev);
1258                 if (test_bit(R10BIO_IsSync, &r10_bio->state)) {
1259                         sync_request_write(mddev, r10_bio);
1260                         unplug = 1;
1261                 } else  if (test_bit(R10BIO_IsRecover, &r10_bio->state)) {
1262                         recovery_request_write(mddev, r10_bio);
1263                         unplug = 1;
1264                 } else {
1265                         int mirror;
1266                         bio = r10_bio->devs[r10_bio->read_slot].bio;
1267                         r10_bio->devs[r10_bio->read_slot].bio = NULL;
1268                         bio_put(bio);
1269                         mirror = read_balance(conf, r10_bio);
1270                         if (mirror == -1) {
1271                                 printk(KERN_ALERT "raid10: %s: unrecoverable I/O"
1272                                        " read error for block %llu\n",
1273                                        bdevname(bio->bi_bdev,b),
1274                                        (unsigned long long)r10_bio->sector);
1275                                 raid_end_bio_io(r10_bio);
1276                         } else {
1277                                 rdev = conf->mirrors[mirror].rdev;
1278                                 if (printk_ratelimit())
1279                                         printk(KERN_ERR "raid10: %s: redirecting sector %llu to"
1280                                                " another mirror\n",
1281                                                bdevname(rdev->bdev,b),
1282                                                (unsigned long long)r10_bio->sector);
1283                                 bio = bio_clone(r10_bio->master_bio, GFP_NOIO);
1284                                 r10_bio->devs[r10_bio->read_slot].bio = bio;
1285                                 bio->bi_sector = r10_bio->devs[r10_bio->read_slot].addr
1286                                         + rdev->data_offset;
1287                                 bio->bi_bdev = rdev->bdev;
1288                                 bio->bi_rw = READ;
1289                                 bio->bi_private = r10_bio;
1290                                 bio->bi_end_io = raid10_end_read_request;
1291                                 unplug = 1;
1292                                 generic_make_request(bio);
1293                         }
1294                 }
1295         }
1296         spin_unlock_irqrestore(&conf->device_lock, flags);
1297         if (unplug)
1298                 unplug_slaves(mddev);
1299 }
1300
1301
1302 static int init_resync(conf_t *conf)
1303 {
1304         int buffs;
1305
1306         buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
1307         if (conf->r10buf_pool)
1308                 BUG();
1309         conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
1310         if (!conf->r10buf_pool)
1311                 return -ENOMEM;
1312         conf->next_resync = 0;
1313         return 0;
1314 }
1315
1316 /*
1317  * perform a "sync" on one "block"
1318  *
1319  * We need to make sure that no normal I/O request - particularly write
1320  * requests - conflict with active sync requests.
1321  *
1322  * This is achieved by tracking pending requests and a 'barrier' concept
1323  * that can be installed to exclude normal IO requests.
1324  *
1325  * Resync and recovery are handled very differently.
1326  * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
1327  *
1328  * For resync, we iterate over virtual addresses, read all copies,
1329  * and update if there are differences.  If only one copy is live,
1330  * skip it.
1331  * For recovery, we iterate over physical addresses, read a good
1332  * value for each non-in_sync drive, and over-write.
1333  *
1334  * So, for recovery we may have several outstanding complex requests for a
1335  * given address, one for each out-of-sync device.  We model this by allocating
1336  * a number of r10_bio structures, one for each out-of-sync device.
1337  * As we setup these structures, we collect all bio's together into a list
1338  * which we then process collectively to add pages, and then process again
1339  * to pass to generic_make_request.
1340  *
1341  * The r10_bio structures are linked using a borrowed master_bio pointer.
1342  * This link is counted in ->remaining.  When the r10_bio that points to NULL
1343  * has its remaining count decremented to 0, the whole complex operation
1344  * is complete.
1345  *
1346  */
1347
1348 static sector_t sync_request(mddev_t *mddev, sector_t sector_nr, int *skipped, int go_faster)
1349 {
1350         conf_t *conf = mddev_to_conf(mddev);
1351         r10bio_t *r10_bio;
1352         struct bio *biolist = NULL, *bio;
1353         sector_t max_sector, nr_sectors;
1354         int disk;
1355         int i;
1356
1357         sector_t sectors_skipped = 0;
1358         int chunks_skipped = 0;
1359
1360         if (!conf->r10buf_pool)
1361                 if (init_resync(conf))
1362                         return 0;
1363
1364  skipped:
1365         max_sector = mddev->size << 1;
1366         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
1367                 max_sector = mddev->resync_max_sectors;
1368         if (sector_nr >= max_sector) {
1369                 close_sync(conf);
1370                 *skipped = 1;
1371                 return sectors_skipped;
1372         }
1373         if (chunks_skipped >= conf->raid_disks) {
1374                 /* if there has been nothing to do on any drive,
1375                  * then there is nothing to do at all..
1376                  */
1377                 *skipped = 1;
1378                 return (max_sector - sector_nr) + sectors_skipped;
1379         }
1380
1381         /* make sure whole request will fit in a chunk - if chunks
1382          * are meaningful
1383          */
1384         if (conf->near_copies < conf->raid_disks &&
1385             max_sector > (sector_nr | conf->chunk_mask))
1386                 max_sector = (sector_nr | conf->chunk_mask) + 1;
1387         /*
1388          * If there is non-resync activity waiting for us then
1389          * put in a delay to throttle resync.
1390          */
1391         if (!go_faster && waitqueue_active(&conf->wait_resume))
1392                 msleep_interruptible(1000);
1393         device_barrier(conf, sector_nr + RESYNC_SECTORS);
1394
1395         /* Again, very different code for resync and recovery.
1396          * Both must result in an r10bio with a list of bios that
1397          * have bi_end_io, bi_sector, bi_bdev set,
1398          * and bi_private set to the r10bio.
1399          * For recovery, we may actually create several r10bios
1400          * with 2 bios in each, that correspond to the bios in the main one.
1401          * In this case, the subordinate r10bios link back through a
1402          * borrowed master_bio pointer, and the counter in the master
1403          * includes a ref from each subordinate.
1404          */
1405         /* First, we decide what to do and set ->bi_end_io
1406          * To end_sync_read if we want to read, and
1407          * end_sync_write if we will want to write.
1408          */
1409
1410         if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
1411                 /* recovery... the complicated one */
1412                 int i, j, k;
1413                 r10_bio = NULL;
1414
1415                 for (i=0 ; i<conf->raid_disks; i++)
1416                         if (conf->mirrors[i].rdev &&
1417                             !conf->mirrors[i].rdev->in_sync) {
1418                                 /* want to reconstruct this device */
1419                                 r10bio_t *rb2 = r10_bio;
1420
1421                                 r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1422                                 spin_lock_irq(&conf->resync_lock);
1423                                 conf->nr_pending++;
1424                                 if (rb2) conf->barrier++;
1425                                 spin_unlock_irq(&conf->resync_lock);
1426                                 atomic_set(&r10_bio->remaining, 0);
1427
1428                                 r10_bio->master_bio = (struct bio*)rb2;
1429                                 if (rb2)
1430                                         atomic_inc(&rb2->remaining);
1431                                 r10_bio->mddev = mddev;
1432                                 set_bit(R10BIO_IsRecover, &r10_bio->state);
1433                                 r10_bio->sector = raid10_find_virt(conf, sector_nr, i);
1434                                 raid10_find_phys(conf, r10_bio);
1435                                 for (j=0; j<conf->copies;j++) {
1436                                         int d = r10_bio->devs[j].devnum;
1437                                         if (conf->mirrors[d].rdev &&
1438                                             conf->mirrors[d].rdev->in_sync) {
1439                                                 /* This is where we read from */
1440                                                 bio = r10_bio->devs[0].bio;
1441                                                 bio->bi_next = biolist;
1442                                                 biolist = bio;
1443                                                 bio->bi_private = r10_bio;
1444                                                 bio->bi_end_io = end_sync_read;
1445                                                 bio->bi_rw = 0;
1446                                                 bio->bi_sector = r10_bio->devs[j].addr +
1447                                                         conf->mirrors[d].rdev->data_offset;
1448                                                 bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1449                                                 atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1450                                                 atomic_inc(&r10_bio->remaining);
1451                                                 /* and we write to 'i' */
1452
1453                                                 for (k=0; k<conf->copies; k++)
1454                                                         if (r10_bio->devs[k].devnum == i)
1455                                                                 break;
1456                                                 bio = r10_bio->devs[1].bio;
1457                                                 bio->bi_next = biolist;
1458                                                 biolist = bio;
1459                                                 bio->bi_private = r10_bio;
1460                                                 bio->bi_end_io = end_sync_write;
1461                                                 bio->bi_rw = 1;
1462                                                 bio->bi_sector = r10_bio->devs[k].addr +
1463                                                         conf->mirrors[i].rdev->data_offset;
1464                                                 bio->bi_bdev = conf->mirrors[i].rdev->bdev;
1465
1466                                                 r10_bio->devs[0].devnum = d;
1467                                                 r10_bio->devs[1].devnum = i;
1468
1469                                                 break;
1470                                         }
1471                                 }
1472                                 if (j == conf->copies) {
1473                                         /* Cannot recover, so abort the recovery */
1474                                         put_buf(r10_bio);
1475                                         r10_bio = rb2;
1476                                         if (!test_and_set_bit(MD_RECOVERY_ERR, &mddev->recovery))
1477                                                 printk(KERN_INFO "raid10: %s: insufficient working devices for recovery.\n",
1478                                                        mdname(mddev));
1479                                         break;
1480                                 }
1481                         }
1482                 if (biolist == NULL) {
1483                         while (r10_bio) {
1484                                 r10bio_t *rb2 = r10_bio;
1485                                 r10_bio = (r10bio_t*) rb2->master_bio;
1486                                 rb2->master_bio = NULL;
1487                                 put_buf(rb2);
1488                         }
1489                         goto giveup;
1490                 }
1491         } else {
1492                 /* resync. Schedule a read for every block at this virt offset */
1493                 int count = 0;
1494                 r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
1495
1496                 spin_lock_irq(&conf->resync_lock);
1497                 conf->nr_pending++;
1498                 spin_unlock_irq(&conf->resync_lock);
1499
1500                 r10_bio->mddev = mddev;
1501                 atomic_set(&r10_bio->remaining, 0);
1502
1503                 r10_bio->master_bio = NULL;
1504                 r10_bio->sector = sector_nr;
1505                 set_bit(R10BIO_IsSync, &r10_bio->state);
1506                 raid10_find_phys(conf, r10_bio);
1507                 r10_bio->sectors = (sector_nr | conf->chunk_mask) - sector_nr +1;
1508
1509                 for (i=0; i<conf->copies; i++) {
1510                         int d = r10_bio->devs[i].devnum;
1511                         bio = r10_bio->devs[i].bio;
1512                         bio->bi_end_io = NULL;
1513                         if (conf->mirrors[d].rdev == NULL ||
1514                             conf->mirrors[d].rdev->faulty)
1515                                 continue;
1516                         atomic_inc(&conf->mirrors[d].rdev->nr_pending);
1517                         atomic_inc(&r10_bio->remaining);
1518                         bio->bi_next = biolist;
1519                         biolist = bio;
1520                         bio->bi_private = r10_bio;
1521                         bio->bi_end_io = end_sync_read;
1522                         bio->bi_rw = 0;
1523                         bio->bi_sector = r10_bio->devs[i].addr +
1524                                 conf->mirrors[d].rdev->data_offset;
1525                         bio->bi_bdev = conf->mirrors[d].rdev->bdev;
1526                         count++;
1527                 }
1528
1529                 if (count < 2) {
1530                         for (i=0; i<conf->copies; i++) {
1531                                 int d = r10_bio->devs[i].devnum;
1532                                 if (r10_bio->devs[i].bio->bi_end_io)
1533                                         rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1534                         }
1535                         put_buf(r10_bio);
1536                         biolist = NULL;
1537                         goto giveup;
1538                 }
1539         }
1540
1541         for (bio = biolist; bio ; bio=bio->bi_next) {
1542
1543                 bio->bi_flags &= ~(BIO_POOL_MASK - 1);
1544                 if (bio->bi_end_io)
1545                         bio->bi_flags |= 1 << BIO_UPTODATE;
1546                 bio->bi_vcnt = 0;
1547                 bio->bi_idx = 0;
1548                 bio->bi_phys_segments = 0;
1549                 bio->bi_hw_segments = 0;
1550                 bio->bi_size = 0;
1551         }
1552
1553         nr_sectors = 0;
1554         do {
1555                 struct page *page;
1556                 int len = PAGE_SIZE;
1557                 disk = 0;
1558                 if (sector_nr + (len>>9) > max_sector)
1559                         len = (max_sector - sector_nr) << 9;
1560                 if (len == 0)
1561                         break;
1562                 for (bio= biolist ; bio ; bio=bio->bi_next) {
1563                         page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
1564                         if (bio_add_page(bio, page, len, 0) == 0) {
1565                                 /* stop here */
1566                                 struct bio *bio2;
1567                                 bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
1568                                 for (bio2 = biolist; bio2 && bio2 != bio; bio2 = bio2->bi_next) {
1569                                         /* remove last page from this bio */
1570                                         bio2->bi_vcnt--;
1571                                         bio2->bi_size -= len;
1572                                         bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
1573                                 }
1574                                 goto bio_full;
1575                         }
1576                         disk = i;
1577                 }
1578                 nr_sectors += len>>9;
1579                 sector_nr += len>>9;
1580         } while (biolist->bi_vcnt < RESYNC_PAGES);
1581  bio_full:
1582         r10_bio->sectors = nr_sectors;
1583
1584         while (biolist) {
1585                 bio = biolist;
1586                 biolist = biolist->bi_next;
1587
1588                 bio->bi_next = NULL;
1589                 r10_bio = bio->bi_private;
1590                 r10_bio->sectors = nr_sectors;
1591
1592                 if (bio->bi_end_io == end_sync_read) {
1593                         md_sync_acct(bio->bi_bdev, nr_sectors);
1594                         generic_make_request(bio);
1595                 }
1596         }
1597
1598         if (sectors_skipped)
1599                 /* pretend they weren't skipped, it makes
1600                  * no important difference in this case
1601                  */
1602                 md_done_sync(mddev, sectors_skipped, 1);
1603
1604         return sectors_skipped + nr_sectors;
1605  giveup:
1606         /* There is nowhere to write, so all non-sync
1607          * drives must be failed, so try the next chunk...
1608          */
1609         {
1610         sector_t sec = max_sector - sector_nr;
1611         sectors_skipped += sec;
1612         chunks_skipped ++;
1613         sector_nr = max_sector;
1614         goto skipped;
1615         }
1616 }
1617
1618 static int run(mddev_t *mddev)
1619 {
1620         conf_t *conf;
1621         int i, disk_idx;
1622         mirror_info_t *disk;
1623         mdk_rdev_t *rdev;
1624         struct list_head *tmp;
1625         int nc, fc;
1626         sector_t stride, size;
1627
1628         if (mddev->level != 10) {
1629                 printk(KERN_ERR "raid10: %s: raid level not set correctly... (%d)\n",
1630                        mdname(mddev), mddev->level);
1631                 goto out;
1632         }
1633         nc = mddev->layout & 255;
1634         fc = (mddev->layout >> 8) & 255;
1635         if ((nc*fc) <2 || (nc*fc) > mddev->raid_disks ||
1636             (mddev->layout >> 16)) {
1637                 printk(KERN_ERR "raid10: %s: unsupported raid10 layout: 0x%8x\n",
1638                        mdname(mddev), mddev->layout);
1639                 goto out;
1640         }
1641         /*
1642          * copy the already verified devices into our private RAID10
1643          * bookkeeping area. [whatever we allocate in run(),
1644          * should be freed in stop()]
1645          */
1646         conf = kmalloc(sizeof(conf_t), GFP_KERNEL);
1647         mddev->private = conf;
1648         if (!conf) {
1649                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1650                         mdname(mddev));
1651                 goto out;
1652         }
1653         memset(conf, 0, sizeof(*conf));
1654         conf->mirrors = kmalloc(sizeof(struct mirror_info)*mddev->raid_disks,
1655                                  GFP_KERNEL);
1656         if (!conf->mirrors) {
1657                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1658                        mdname(mddev));
1659                 goto out_free_conf;
1660         }
1661         memset(conf->mirrors, 0, sizeof(struct mirror_info)*mddev->raid_disks);
1662
1663         conf->near_copies = nc;
1664         conf->far_copies = fc;
1665         conf->copies = nc*fc;
1666         conf->chunk_mask = (sector_t)(mddev->chunk_size>>9)-1;
1667         conf->chunk_shift = ffz(~mddev->chunk_size) - 9;
1668         stride = mddev->size >> (conf->chunk_shift-1);
1669         sector_div(stride, fc);
1670         conf->stride = stride << conf->chunk_shift;
1671
1672         conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
1673                                                 r10bio_pool_free, conf);
1674         if (!conf->r10bio_pool) {
1675                 printk(KERN_ERR "raid10: couldn't allocate memory for %s\n",
1676                         mdname(mddev));
1677                 goto out_free_conf;
1678         }
1679
1680         ITERATE_RDEV(mddev, rdev, tmp) {
1681                 disk_idx = rdev->raid_disk;
1682                 if (disk_idx >= mddev->raid_disks
1683                     || disk_idx < 0)
1684                         continue;
1685                 disk = conf->mirrors + disk_idx;
1686
1687                 disk->rdev = rdev;
1688
1689                 blk_queue_stack_limits(mddev->queue,
1690                                        rdev->bdev->bd_disk->queue);
1691                 /* as we don't honour merge_bvec_fn, we must never risk
1692                  * violating it, so limit ->max_sector to one PAGE, as
1693                  * a one page request is never in violation.
1694                  */
1695                 if (rdev->bdev->bd_disk->queue->merge_bvec_fn &&
1696                     mddev->queue->max_sectors > (PAGE_SIZE>>9))
1697                         mddev->queue->max_sectors = (PAGE_SIZE>>9);
1698
1699                 disk->head_position = 0;
1700                 if (!rdev->faulty && rdev->in_sync)
1701                         conf->working_disks++;
1702         }
1703         conf->raid_disks = mddev->raid_disks;
1704         conf->mddev = mddev;
1705         spin_lock_init(&conf->device_lock);
1706         INIT_LIST_HEAD(&conf->retry_list);
1707
1708         spin_lock_init(&conf->resync_lock);
1709         init_waitqueue_head(&conf->wait_idle);
1710         init_waitqueue_head(&conf->wait_resume);
1711
1712         /* need to check that every block has at least one working mirror */
1713         if (!enough(conf)) {
1714                 printk(KERN_ERR "raid10: not enough operational mirrors for %s\n",
1715                        mdname(mddev));
1716                 goto out_free_conf;
1717         }
1718
1719         mddev->degraded = 0;
1720         for (i = 0; i < conf->raid_disks; i++) {
1721
1722                 disk = conf->mirrors + i;
1723
1724                 if (!disk->rdev) {
1725                         disk->head_position = 0;
1726                         mddev->degraded++;
1727                 }
1728         }
1729
1730
1731         mddev->thread = md_register_thread(raid10d, mddev, "%s_raid10");
1732         if (!mddev->thread) {
1733                 printk(KERN_ERR
1734                        "raid10: couldn't allocate thread for %s\n",
1735                        mdname(mddev));
1736                 goto out_free_conf;
1737         }
1738
1739         printk(KERN_INFO
1740                 "raid10: raid set %s active with %d out of %d devices\n",
1741                 mdname(mddev), mddev->raid_disks - mddev->degraded,
1742                 mddev->raid_disks);
1743         /*
1744          * Ok, everything is just fine now
1745          */
1746         size = conf->stride * conf->raid_disks;
1747         sector_div(size, conf->near_copies);
1748         mddev->array_size = size/2;
1749         mddev->resync_max_sectors = size;
1750
1751         mddev->queue->unplug_fn = raid10_unplug;
1752         mddev->queue->issue_flush_fn = raid10_issue_flush;
1753
1754         /* Calculate max read-ahead size.
1755          * We need to readahead at least twice a whole stripe....
1756          * maybe...
1757          */
1758         {
1759                 int stripe = conf->raid_disks * mddev->chunk_size / PAGE_CACHE_SIZE;
1760                 stripe /= conf->near_copies;
1761                 if (mddev->queue->backing_dev_info.ra_pages < 2* stripe)
1762                         mddev->queue->backing_dev_info.ra_pages = 2* stripe;
1763         }
1764
1765         if (conf->near_copies < mddev->raid_disks)
1766                 blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
1767         return 0;
1768
1769 out_free_conf:
1770         if (conf->r10bio_pool)
1771                 mempool_destroy(conf->r10bio_pool);
1772         kfree(conf->mirrors);
1773         kfree(conf);
1774         mddev->private = NULL;
1775 out:
1776         return -EIO;
1777 }
1778
1779 static int stop(mddev_t *mddev)
1780 {
1781         conf_t *conf = mddev_to_conf(mddev);
1782
1783         md_unregister_thread(mddev->thread);
1784         mddev->thread = NULL;
1785         blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
1786         if (conf->r10bio_pool)
1787                 mempool_destroy(conf->r10bio_pool);
1788         kfree(conf->mirrors);
1789         kfree(conf);
1790         mddev->private = NULL;
1791         return 0;
1792 }
1793
1794
1795 static mdk_personality_t raid10_personality =
1796 {
1797         .name           = "raid10",
1798         .owner          = THIS_MODULE,
1799         .make_request   = make_request,
1800         .run            = run,
1801         .stop           = stop,
1802         .status         = status,
1803         .error_handler  = error,
1804         .hot_add_disk   = raid10_add_disk,
1805         .hot_remove_disk= raid10_remove_disk,
1806         .spare_active   = raid10_spare_active,
1807         .sync_request   = sync_request,
1808 };
1809
1810 static int __init raid_init(void)
1811 {
1812         return register_md_personality(RAID10, &raid10_personality);
1813 }
1814
1815 static void raid_exit(void)
1816 {
1817         unregister_md_personality(RAID10);
1818 }
1819
1820 module_init(raid_init);
1821 module_exit(raid_exit);
1822 MODULE_LICENSE("GPL");
1823 MODULE_ALIAS("md-personality-9"); /* RAID10 */