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