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