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