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