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