linux/drivers/md/raid10.c
<<
>>
Prefs
   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/module.h>
  25#include <linux/seq_file.h>
  26#include <linux/ratelimit.h>
  27#include <linux/kthread.h>
  28#include "md.h"
  29#include "raid10.h"
  30#include "raid0.h"
  31#include "bitmap.h"
  32
  33/*
  34 * RAID10 provides a combination of RAID0 and RAID1 functionality.
  35 * The layout of data is defined by
  36 *    chunk_size
  37 *    raid_disks
  38 *    near_copies (stored in low byte of layout)
  39 *    far_copies (stored in second byte of layout)
  40 *    far_offset (stored in bit 16 of layout )
  41 *
  42 * The data to be stored is divided into chunks using chunksize.
  43 * Each device is divided into far_copies sections.
  44 * In each section, chunks are laid out in a style similar to raid0, but
  45 * near_copies copies of each chunk is stored (each on a different drive).
  46 * The starting device for each section is offset near_copies from the starting
  47 * device of the previous section.
  48 * Thus they are (near_copies*far_copies) of each chunk, and each is on a different
  49 * drive.
  50 * near_copies and far_copies must be at least one, and their product is at most
  51 * raid_disks.
  52 *
  53 * If far_offset is true, then the far_copies are handled a bit differently.
  54 * The copies are still in different stripes, but instead of be very far apart
  55 * on disk, there are adjacent stripes.
  56 */
  57
  58/*
  59 * Number of guaranteed r10bios in case of extreme VM load:
  60 */
  61#define NR_RAID10_BIOS 256
  62
  63/* when we get a read error on a read-only array, we redirect to another
  64 * device without failing the first device, or trying to over-write to
  65 * correct the read error.  To keep track of bad blocks on a per-bio
  66 * level, we store IO_BLOCKED in the appropriate 'bios' pointer
  67 */
  68#define IO_BLOCKED ((struct bio *)1)
  69/* When we successfully write to a known bad-block, we need to remove the
  70 * bad-block marking which must be done from process context.  So we record
  71 * the success by setting devs[n].bio to IO_MADE_GOOD
  72 */
  73#define IO_MADE_GOOD ((struct bio *)2)
  74
  75#define BIO_SPECIAL(bio) ((unsigned long)bio <= 2)
  76
  77/* When there are this many requests queued to be written by
  78 * the raid10 thread, we become 'congested' to provide back-pressure
  79 * for writeback.
  80 */
  81static int max_queued_requests = 1024;
  82
  83static void allow_barrier(struct r10conf *conf);
  84static void lower_barrier(struct r10conf *conf);
  85static int enough(struct r10conf *conf, int ignore);
  86static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
  87                                int *skipped);
  88static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio);
  89static void end_reshape_write(struct bio *bio, int error);
  90static void end_reshape(struct r10conf *conf);
  91
  92static void * r10bio_pool_alloc(gfp_t gfp_flags, void *data)
  93{
  94        struct r10conf *conf = data;
  95        int size = offsetof(struct r10bio, devs[conf->copies]);
  96
  97        /* allocate a r10bio with room for raid_disks entries in the
  98         * bios array */
  99        return kzalloc(size, gfp_flags);
 100}
 101
 102static void r10bio_pool_free(void *r10_bio, void *data)
 103{
 104        kfree(r10_bio);
 105}
 106
 107/* Maximum size of each resync request */
 108#define RESYNC_BLOCK_SIZE (64*1024)
 109#define RESYNC_PAGES ((RESYNC_BLOCK_SIZE + PAGE_SIZE-1) / PAGE_SIZE)
 110/* amount of memory to reserve for resync requests */
 111#define RESYNC_WINDOW (1024*1024)
 112/* maximum number of concurrent requests, memory permitting */
 113#define RESYNC_DEPTH (32*1024*1024/RESYNC_BLOCK_SIZE)
 114
 115/*
 116 * When performing a resync, we need to read and compare, so
 117 * we need as many pages are there are copies.
 118 * When performing a recovery, we need 2 bios, one for read,
 119 * one for write (we recover only one drive per r10buf)
 120 *
 121 */
 122static void * r10buf_pool_alloc(gfp_t gfp_flags, void *data)
 123{
 124        struct r10conf *conf = data;
 125        struct page *page;
 126        struct r10bio *r10_bio;
 127        struct bio *bio;
 128        int i, j;
 129        int nalloc;
 130
 131        r10_bio = r10bio_pool_alloc(gfp_flags, conf);
 132        if (!r10_bio)
 133                return NULL;
 134
 135        if (test_bit(MD_RECOVERY_SYNC, &conf->mddev->recovery) ||
 136            test_bit(MD_RECOVERY_RESHAPE, &conf->mddev->recovery))
 137                nalloc = conf->copies; /* resync */
 138        else
 139                nalloc = 2; /* recovery */
 140
 141        /*
 142         * Allocate bios.
 143         */
 144        for (j = nalloc ; j-- ; ) {
 145                bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
 146                if (!bio)
 147                        goto out_free_bio;
 148                r10_bio->devs[j].bio = bio;
 149                if (!conf->have_replacement)
 150                        continue;
 151                bio = bio_kmalloc(gfp_flags, RESYNC_PAGES);
 152                if (!bio)
 153                        goto out_free_bio;
 154                r10_bio->devs[j].repl_bio = bio;
 155        }
 156        /*
 157         * Allocate RESYNC_PAGES data pages and attach them
 158         * where needed.
 159         */
 160        for (j = 0 ; j < nalloc; j++) {
 161                struct bio *rbio = r10_bio->devs[j].repl_bio;
 162                bio = r10_bio->devs[j].bio;
 163                for (i = 0; i < RESYNC_PAGES; i++) {
 164                        if (j > 0 && !test_bit(MD_RECOVERY_SYNC,
 165                                               &conf->mddev->recovery)) {
 166                                /* we can share bv_page's during recovery
 167                                 * and reshape */
 168                                struct bio *rbio = r10_bio->devs[0].bio;
 169                                page = rbio->bi_io_vec[i].bv_page;
 170                                get_page(page);
 171                        } else
 172                                page = alloc_page(gfp_flags);
 173                        if (unlikely(!page))
 174                                goto out_free_pages;
 175
 176                        bio->bi_io_vec[i].bv_page = page;
 177                        if (rbio)
 178                                rbio->bi_io_vec[i].bv_page = page;
 179                }
 180        }
 181
 182        return r10_bio;
 183
 184out_free_pages:
 185        for ( ; i > 0 ; i--)
 186                safe_put_page(bio->bi_io_vec[i-1].bv_page);
 187        while (j--)
 188                for (i = 0; i < RESYNC_PAGES ; i++)
 189                        safe_put_page(r10_bio->devs[j].bio->bi_io_vec[i].bv_page);
 190        j = 0;
 191out_free_bio:
 192        for ( ; j < nalloc; j++) {
 193                if (r10_bio->devs[j].bio)
 194                        bio_put(r10_bio->devs[j].bio);
 195                if (r10_bio->devs[j].repl_bio)
 196                        bio_put(r10_bio->devs[j].repl_bio);
 197        }
 198        r10bio_pool_free(r10_bio, conf);
 199        return NULL;
 200}
 201
 202static void r10buf_pool_free(void *__r10_bio, void *data)
 203{
 204        int i;
 205        struct r10conf *conf = data;
 206        struct r10bio *r10bio = __r10_bio;
 207        int j;
 208
 209        for (j=0; j < conf->copies; j++) {
 210                struct bio *bio = r10bio->devs[j].bio;
 211                if (bio) {
 212                        for (i = 0; i < RESYNC_PAGES; i++) {
 213                                safe_put_page(bio->bi_io_vec[i].bv_page);
 214                                bio->bi_io_vec[i].bv_page = NULL;
 215                        }
 216                        bio_put(bio);
 217                }
 218                bio = r10bio->devs[j].repl_bio;
 219                if (bio)
 220                        bio_put(bio);
 221        }
 222        r10bio_pool_free(r10bio, conf);
 223}
 224
 225static void put_all_bios(struct r10conf *conf, struct r10bio *r10_bio)
 226{
 227        int i;
 228
 229        for (i = 0; i < conf->copies; i++) {
 230                struct bio **bio = & r10_bio->devs[i].bio;
 231                if (!BIO_SPECIAL(*bio))
 232                        bio_put(*bio);
 233                *bio = NULL;
 234                bio = &r10_bio->devs[i].repl_bio;
 235                if (r10_bio->read_slot < 0 && !BIO_SPECIAL(*bio))
 236                        bio_put(*bio);
 237                *bio = NULL;
 238        }
 239}
 240
 241static void free_r10bio(struct r10bio *r10_bio)
 242{
 243        struct r10conf *conf = r10_bio->mddev->private;
 244
 245        put_all_bios(conf, r10_bio);
 246        mempool_free(r10_bio, conf->r10bio_pool);
 247}
 248
 249static void put_buf(struct r10bio *r10_bio)
 250{
 251        struct r10conf *conf = r10_bio->mddev->private;
 252
 253        mempool_free(r10_bio, conf->r10buf_pool);
 254
 255        lower_barrier(conf);
 256}
 257
 258static void reschedule_retry(struct r10bio *r10_bio)
 259{
 260        unsigned long flags;
 261        struct mddev *mddev = r10_bio->mddev;
 262        struct r10conf *conf = mddev->private;
 263
 264        spin_lock_irqsave(&conf->device_lock, flags);
 265        list_add(&r10_bio->retry_list, &conf->retry_list);
 266        conf->nr_queued ++;
 267        spin_unlock_irqrestore(&conf->device_lock, flags);
 268
 269        /* wake up frozen array... */
 270        wake_up(&conf->wait_barrier);
 271
 272        md_wakeup_thread(mddev->thread);
 273}
 274
 275/*
 276 * raid_end_bio_io() is called when we have finished servicing a mirrored
 277 * operation and are ready to return a success/failure code to the buffer
 278 * cache layer.
 279 */
 280static void raid_end_bio_io(struct r10bio *r10_bio)
 281{
 282        struct bio *bio = r10_bio->master_bio;
 283        int done;
 284        struct r10conf *conf = r10_bio->mddev->private;
 285
 286        if (bio->bi_phys_segments) {
 287                unsigned long flags;
 288                spin_lock_irqsave(&conf->device_lock, flags);
 289                bio->bi_phys_segments--;
 290                done = (bio->bi_phys_segments == 0);
 291                spin_unlock_irqrestore(&conf->device_lock, flags);
 292        } else
 293                done = 1;
 294        if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
 295                clear_bit(BIO_UPTODATE, &bio->bi_flags);
 296        if (done) {
 297                bio_endio(bio, 0);
 298                /*
 299                 * Wake up any possible resync thread that waits for the device
 300                 * to go idle.
 301                 */
 302                allow_barrier(conf);
 303        }
 304        free_r10bio(r10_bio);
 305}
 306
 307/*
 308 * Update disk head position estimator based on IRQ completion info.
 309 */
 310static inline void update_head_pos(int slot, struct r10bio *r10_bio)
 311{
 312        struct r10conf *conf = r10_bio->mddev->private;
 313
 314        conf->mirrors[r10_bio->devs[slot].devnum].head_position =
 315                r10_bio->devs[slot].addr + (r10_bio->sectors);
 316}
 317
 318/*
 319 * Find the disk number which triggered given bio
 320 */
 321static int find_bio_disk(struct r10conf *conf, struct r10bio *r10_bio,
 322                         struct bio *bio, int *slotp, int *replp)
 323{
 324        int slot;
 325        int repl = 0;
 326
 327        for (slot = 0; slot < conf->copies; slot++) {
 328                if (r10_bio->devs[slot].bio == bio)
 329                        break;
 330                if (r10_bio->devs[slot].repl_bio == bio) {
 331                        repl = 1;
 332                        break;
 333                }
 334        }
 335
 336        BUG_ON(slot == conf->copies);
 337        update_head_pos(slot, r10_bio);
 338
 339        if (slotp)
 340                *slotp = slot;
 341        if (replp)
 342                *replp = repl;
 343        return r10_bio->devs[slot].devnum;
 344}
 345
 346static void raid10_end_read_request(struct bio *bio, int error)
 347{
 348        int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 349        struct r10bio *r10_bio = bio->bi_private;
 350        int slot, dev;
 351        struct md_rdev *rdev;
 352        struct r10conf *conf = r10_bio->mddev->private;
 353
 354
 355        slot = r10_bio->read_slot;
 356        dev = r10_bio->devs[slot].devnum;
 357        rdev = r10_bio->devs[slot].rdev;
 358        /*
 359         * this branch is our 'one mirror IO has finished' event handler:
 360         */
 361        update_head_pos(slot, r10_bio);
 362
 363        if (uptodate) {
 364                /*
 365                 * Set R10BIO_Uptodate in our master bio, so that
 366                 * we will return a good error code to the higher
 367                 * levels even if IO on some other mirrored buffer fails.
 368                 *
 369                 * The 'master' represents the composite IO operation to
 370                 * user-side. So if something waits for IO, then it will
 371                 * wait for the 'master' bio.
 372                 */
 373                set_bit(R10BIO_Uptodate, &r10_bio->state);
 374        } else {
 375                /* If all other devices that store this block have
 376                 * failed, we want to return the error upwards rather
 377                 * than fail the last device.  Here we redefine
 378                 * "uptodate" to mean "Don't want to retry"
 379                 */
 380                unsigned long flags;
 381                spin_lock_irqsave(&conf->device_lock, flags);
 382                if (!enough(conf, rdev->raid_disk))
 383                        uptodate = 1;
 384                spin_unlock_irqrestore(&conf->device_lock, flags);
 385        }
 386        if (uptodate) {
 387                raid_end_bio_io(r10_bio);
 388                rdev_dec_pending(rdev, conf->mddev);
 389        } else {
 390                /*
 391                 * oops, read error - keep the refcount on the rdev
 392                 */
 393                char b[BDEVNAME_SIZE];
 394                printk_ratelimited(KERN_ERR
 395                                   "md/raid10:%s: %s: rescheduling sector %llu\n",
 396                                   mdname(conf->mddev),
 397                                   bdevname(rdev->bdev, b),
 398                                   (unsigned long long)r10_bio->sector);
 399                set_bit(R10BIO_ReadError, &r10_bio->state);
 400                reschedule_retry(r10_bio);
 401        }
 402}
 403
 404static void close_write(struct r10bio *r10_bio)
 405{
 406        /* clear the bitmap if all writes complete successfully */
 407        bitmap_endwrite(r10_bio->mddev->bitmap, r10_bio->sector,
 408                        r10_bio->sectors,
 409                        !test_bit(R10BIO_Degraded, &r10_bio->state),
 410                        0);
 411        md_write_end(r10_bio->mddev);
 412}
 413
 414static void one_write_done(struct r10bio *r10_bio)
 415{
 416        if (atomic_dec_and_test(&r10_bio->remaining)) {
 417                if (test_bit(R10BIO_WriteError, &r10_bio->state))
 418                        reschedule_retry(r10_bio);
 419                else {
 420                        close_write(r10_bio);
 421                        if (test_bit(R10BIO_MadeGood, &r10_bio->state))
 422                                reschedule_retry(r10_bio);
 423                        else
 424                                raid_end_bio_io(r10_bio);
 425                }
 426        }
 427}
 428
 429static void raid10_end_write_request(struct bio *bio, int error)
 430{
 431        int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
 432        struct r10bio *r10_bio = bio->bi_private;
 433        int dev;
 434        int dec_rdev = 1;
 435        struct r10conf *conf = r10_bio->mddev->private;
 436        int slot, repl;
 437        struct md_rdev *rdev = NULL;
 438
 439        dev = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
 440
 441        if (repl)
 442                rdev = conf->mirrors[dev].replacement;
 443        if (!rdev) {
 444                smp_rmb();
 445                repl = 0;
 446                rdev = conf->mirrors[dev].rdev;
 447        }
 448        /*
 449         * this branch is our 'one mirror IO has finished' event handler:
 450         */
 451        if (!uptodate) {
 452                if (repl)
 453                        /* Never record new bad blocks to replacement,
 454                         * just fail it.
 455                         */
 456                        md_error(rdev->mddev, rdev);
 457                else {
 458                        set_bit(WriteErrorSeen, &rdev->flags);
 459                        if (!test_and_set_bit(WantReplacement, &rdev->flags))
 460                                set_bit(MD_RECOVERY_NEEDED,
 461                                        &rdev->mddev->recovery);
 462                        set_bit(R10BIO_WriteError, &r10_bio->state);
 463                        dec_rdev = 0;
 464                }
 465        } else {
 466                /*
 467                 * Set R10BIO_Uptodate in our master bio, so that
 468                 * we will return a good error code for to the higher
 469                 * levels even if IO on some other mirrored buffer fails.
 470                 *
 471                 * The 'master' represents the composite IO operation to
 472                 * user-side. So if something waits for IO, then it will
 473                 * wait for the 'master' bio.
 474                 */
 475                sector_t first_bad;
 476                int bad_sectors;
 477
 478                set_bit(R10BIO_Uptodate, &r10_bio->state);
 479
 480                /* Maybe we can clear some bad blocks. */
 481                if (is_badblock(rdev,
 482                                r10_bio->devs[slot].addr,
 483                                r10_bio->sectors,
 484                                &first_bad, &bad_sectors)) {
 485                        bio_put(bio);
 486                        if (repl)
 487                                r10_bio->devs[slot].repl_bio = IO_MADE_GOOD;
 488                        else
 489                                r10_bio->devs[slot].bio = IO_MADE_GOOD;
 490                        dec_rdev = 0;
 491                        set_bit(R10BIO_MadeGood, &r10_bio->state);
 492                }
 493        }
 494
 495        /*
 496         *
 497         * Let's see if all mirrored write operations have finished
 498         * already.
 499         */
 500        one_write_done(r10_bio);
 501        if (dec_rdev)
 502                rdev_dec_pending(rdev, conf->mddev);
 503}
 504
 505/*
 506 * RAID10 layout manager
 507 * As well as the chunksize and raid_disks count, there are two
 508 * parameters: near_copies and far_copies.
 509 * near_copies * far_copies must be <= raid_disks.
 510 * Normally one of these will be 1.
 511 * If both are 1, we get raid0.
 512 * If near_copies == raid_disks, we get raid1.
 513 *
 514 * Chunks are laid out in raid0 style with near_copies copies of the
 515 * first chunk, followed by near_copies copies of the next chunk and
 516 * so on.
 517 * If far_copies > 1, then after 1/far_copies of the array has been assigned
 518 * as described above, we start again with a device offset of near_copies.
 519 * So we effectively have another copy of the whole array further down all
 520 * the drives, but with blocks on different drives.
 521 * With this layout, and block is never stored twice on the one device.
 522 *
 523 * raid10_find_phys finds the sector offset of a given virtual sector
 524 * on each device that it is on.
 525 *
 526 * raid10_find_virt does the reverse mapping, from a device and a
 527 * sector offset to a virtual address
 528 */
 529
 530static void __raid10_find_phys(struct geom *geo, struct r10bio *r10bio)
 531{
 532        int n,f;
 533        sector_t sector;
 534        sector_t chunk;
 535        sector_t stripe;
 536        int dev;
 537        int slot = 0;
 538
 539        /* now calculate first sector/dev */
 540        chunk = r10bio->sector >> geo->chunk_shift;
 541        sector = r10bio->sector & geo->chunk_mask;
 542
 543        chunk *= geo->near_copies;
 544        stripe = chunk;
 545        dev = sector_div(stripe, geo->raid_disks);
 546        if (geo->far_offset)
 547                stripe *= geo->far_copies;
 548
 549        sector += stripe << geo->chunk_shift;
 550
 551        /* and calculate all the others */
 552        for (n = 0; n < geo->near_copies; n++) {
 553                int d = dev;
 554                sector_t s = sector;
 555                r10bio->devs[slot].addr = sector;
 556                r10bio->devs[slot].devnum = d;
 557                slot++;
 558
 559                for (f = 1; f < geo->far_copies; f++) {
 560                        d += geo->near_copies;
 561                        if (d >= geo->raid_disks)
 562                                d -= geo->raid_disks;
 563                        s += geo->stride;
 564                        r10bio->devs[slot].devnum = d;
 565                        r10bio->devs[slot].addr = s;
 566                        slot++;
 567                }
 568                dev++;
 569                if (dev >= geo->raid_disks) {
 570                        dev = 0;
 571                        sector += (geo->chunk_mask + 1);
 572                }
 573        }
 574}
 575
 576static void raid10_find_phys(struct r10conf *conf, struct r10bio *r10bio)
 577{
 578        struct geom *geo = &conf->geo;
 579
 580        if (conf->reshape_progress != MaxSector &&
 581            ((r10bio->sector >= conf->reshape_progress) !=
 582             conf->mddev->reshape_backwards)) {
 583                set_bit(R10BIO_Previous, &r10bio->state);
 584                geo = &conf->prev;
 585        } else
 586                clear_bit(R10BIO_Previous, &r10bio->state);
 587
 588        __raid10_find_phys(geo, r10bio);
 589}
 590
 591static sector_t raid10_find_virt(struct r10conf *conf, sector_t sector, int dev)
 592{
 593        sector_t offset, chunk, vchunk;
 594        /* Never use conf->prev as this is only called during resync
 595         * or recovery, so reshape isn't happening
 596         */
 597        struct geom *geo = &conf->geo;
 598
 599        offset = sector & geo->chunk_mask;
 600        if (geo->far_offset) {
 601                int fc;
 602                chunk = sector >> geo->chunk_shift;
 603                fc = sector_div(chunk, geo->far_copies);
 604                dev -= fc * geo->near_copies;
 605                if (dev < 0)
 606                        dev += geo->raid_disks;
 607        } else {
 608                while (sector >= geo->stride) {
 609                        sector -= geo->stride;
 610                        if (dev < geo->near_copies)
 611                                dev += geo->raid_disks - geo->near_copies;
 612                        else
 613                                dev -= geo->near_copies;
 614                }
 615                chunk = sector >> geo->chunk_shift;
 616        }
 617        vchunk = chunk * geo->raid_disks + dev;
 618        sector_div(vchunk, geo->near_copies);
 619        return (vchunk << geo->chunk_shift) + offset;
 620}
 621
 622/**
 623 *      raid10_mergeable_bvec -- tell bio layer if a two requests can be merged
 624 *      @q: request queue
 625 *      @bvm: properties of new bio
 626 *      @biovec: the request that could be merged to it.
 627 *
 628 *      Return amount of bytes we can accept at this offset
 629 *      This requires checking for end-of-chunk if near_copies != raid_disks,
 630 *      and for subordinate merge_bvec_fns if merge_check_needed.
 631 */
 632static int raid10_mergeable_bvec(struct request_queue *q,
 633                                 struct bvec_merge_data *bvm,
 634                                 struct bio_vec *biovec)
 635{
 636        struct mddev *mddev = q->queuedata;
 637        struct r10conf *conf = mddev->private;
 638        sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
 639        int max;
 640        unsigned int chunk_sectors;
 641        unsigned int bio_sectors = bvm->bi_size >> 9;
 642        struct geom *geo = &conf->geo;
 643
 644        chunk_sectors = (conf->geo.chunk_mask & conf->prev.chunk_mask) + 1;
 645        if (conf->reshape_progress != MaxSector &&
 646            ((sector >= conf->reshape_progress) !=
 647             conf->mddev->reshape_backwards))
 648                geo = &conf->prev;
 649
 650        if (geo->near_copies < geo->raid_disks) {
 651                max = (chunk_sectors - ((sector & (chunk_sectors - 1))
 652                                        + bio_sectors)) << 9;
 653                if (max < 0)
 654                        /* bio_add cannot handle a negative return */
 655                        max = 0;
 656                if (max <= biovec->bv_len && bio_sectors == 0)
 657                        return biovec->bv_len;
 658        } else
 659                max = biovec->bv_len;
 660
 661        if (mddev->merge_check_needed) {
 662                struct {
 663                        struct r10bio r10_bio;
 664                        struct r10dev devs[conf->copies];
 665                } on_stack;
 666                struct r10bio *r10_bio = &on_stack.r10_bio;
 667                int s;
 668                if (conf->reshape_progress != MaxSector) {
 669                        /* Cannot give any guidance during reshape */
 670                        if (max <= biovec->bv_len && bio_sectors == 0)
 671                                return biovec->bv_len;
 672                        return 0;
 673                }
 674                r10_bio->sector = sector;
 675                raid10_find_phys(conf, r10_bio);
 676                rcu_read_lock();
 677                for (s = 0; s < conf->copies; s++) {
 678                        int disk = r10_bio->devs[s].devnum;
 679                        struct md_rdev *rdev = rcu_dereference(
 680                                conf->mirrors[disk].rdev);
 681                        if (rdev && !test_bit(Faulty, &rdev->flags)) {
 682                                struct request_queue *q =
 683                                        bdev_get_queue(rdev->bdev);
 684                                if (q->merge_bvec_fn) {
 685                                        bvm->bi_sector = r10_bio->devs[s].addr
 686                                                + rdev->data_offset;
 687                                        bvm->bi_bdev = rdev->bdev;
 688                                        max = min(max, q->merge_bvec_fn(
 689                                                          q, bvm, biovec));
 690                                }
 691                        }
 692                        rdev = rcu_dereference(conf->mirrors[disk].replacement);
 693                        if (rdev && !test_bit(Faulty, &rdev->flags)) {
 694                                struct request_queue *q =
 695                                        bdev_get_queue(rdev->bdev);
 696                                if (q->merge_bvec_fn) {
 697                                        bvm->bi_sector = r10_bio->devs[s].addr
 698                                                + rdev->data_offset;
 699                                        bvm->bi_bdev = rdev->bdev;
 700                                        max = min(max, q->merge_bvec_fn(
 701                                                          q, bvm, biovec));
 702                                }
 703                        }
 704                }
 705                rcu_read_unlock();
 706        }
 707        return max;
 708}
 709
 710/*
 711 * This routine returns the disk from which the requested read should
 712 * be done. There is a per-array 'next expected sequential IO' sector
 713 * number - if this matches on the next IO then we use the last disk.
 714 * There is also a per-disk 'last know head position' sector that is
 715 * maintained from IRQ contexts, both the normal and the resync IO
 716 * completion handlers update this position correctly. If there is no
 717 * perfect sequential match then we pick the disk whose head is closest.
 718 *
 719 * If there are 2 mirrors in the same 2 devices, performance degrades
 720 * because position is mirror, not device based.
 721 *
 722 * The rdev for the device selected will have nr_pending incremented.
 723 */
 724
 725/*
 726 * FIXME: possibly should rethink readbalancing and do it differently
 727 * depending on near_copies / far_copies geometry.
 728 */
 729static struct md_rdev *read_balance(struct r10conf *conf,
 730                                    struct r10bio *r10_bio,
 731                                    int *max_sectors)
 732{
 733        const sector_t this_sector = r10_bio->sector;
 734        int disk, slot;
 735        int sectors = r10_bio->sectors;
 736        int best_good_sectors;
 737        sector_t new_distance, best_dist;
 738        struct md_rdev *best_rdev, *rdev = NULL;
 739        int do_balance;
 740        int best_slot;
 741        struct geom *geo = &conf->geo;
 742
 743        raid10_find_phys(conf, r10_bio);
 744        rcu_read_lock();
 745retry:
 746        sectors = r10_bio->sectors;
 747        best_slot = -1;
 748        best_rdev = NULL;
 749        best_dist = MaxSector;
 750        best_good_sectors = 0;
 751        do_balance = 1;
 752        /*
 753         * Check if we can balance. We can balance on the whole
 754         * device if no resync is going on (recovery is ok), or below
 755         * the resync window. We take the first readable disk when
 756         * above the resync window.
 757         */
 758        if (conf->mddev->recovery_cp < MaxSector
 759            && (this_sector + sectors >= conf->next_resync))
 760                do_balance = 0;
 761
 762        for (slot = 0; slot < conf->copies ; slot++) {
 763                sector_t first_bad;
 764                int bad_sectors;
 765                sector_t dev_sector;
 766
 767                if (r10_bio->devs[slot].bio == IO_BLOCKED)
 768                        continue;
 769                disk = r10_bio->devs[slot].devnum;
 770                rdev = rcu_dereference(conf->mirrors[disk].replacement);
 771                if (rdev == NULL || test_bit(Faulty, &rdev->flags) ||
 772                    test_bit(Unmerged, &rdev->flags) ||
 773                    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
 774                        rdev = rcu_dereference(conf->mirrors[disk].rdev);
 775                if (rdev == NULL ||
 776                    test_bit(Faulty, &rdev->flags) ||
 777                    test_bit(Unmerged, &rdev->flags))
 778                        continue;
 779                if (!test_bit(In_sync, &rdev->flags) &&
 780                    r10_bio->devs[slot].addr + sectors > rdev->recovery_offset)
 781                        continue;
 782
 783                dev_sector = r10_bio->devs[slot].addr;
 784                if (is_badblock(rdev, dev_sector, sectors,
 785                                &first_bad, &bad_sectors)) {
 786                        if (best_dist < MaxSector)
 787                                /* Already have a better slot */
 788                                continue;
 789                        if (first_bad <= dev_sector) {
 790                                /* Cannot read here.  If this is the
 791                                 * 'primary' device, then we must not read
 792                                 * beyond 'bad_sectors' from another device.
 793                                 */
 794                                bad_sectors -= (dev_sector - first_bad);
 795                                if (!do_balance && sectors > bad_sectors)
 796                                        sectors = bad_sectors;
 797                                if (best_good_sectors > sectors)
 798                                        best_good_sectors = sectors;
 799                        } else {
 800                                sector_t good_sectors =
 801                                        first_bad - dev_sector;
 802                                if (good_sectors > best_good_sectors) {
 803                                        best_good_sectors = good_sectors;
 804                                        best_slot = slot;
 805                                        best_rdev = rdev;
 806                                }
 807                                if (!do_balance)
 808                                        /* Must read from here */
 809                                        break;
 810                        }
 811                        continue;
 812                } else
 813                        best_good_sectors = sectors;
 814
 815                if (!do_balance)
 816                        break;
 817
 818                /* This optimisation is debatable, and completely destroys
 819                 * sequential read speed for 'far copies' arrays.  So only
 820                 * keep it for 'near' arrays, and review those later.
 821                 */
 822                if (geo->near_copies > 1 && !atomic_read(&rdev->nr_pending))
 823                        break;
 824
 825                /* for far > 1 always use the lowest address */
 826                if (geo->far_copies > 1)
 827                        new_distance = r10_bio->devs[slot].addr;
 828                else
 829                        new_distance = abs(r10_bio->devs[slot].addr -
 830                                           conf->mirrors[disk].head_position);
 831                if (new_distance < best_dist) {
 832                        best_dist = new_distance;
 833                        best_slot = slot;
 834                        best_rdev = rdev;
 835                }
 836        }
 837        if (slot >= conf->copies) {
 838                slot = best_slot;
 839                rdev = best_rdev;
 840        }
 841
 842        if (slot >= 0) {
 843                atomic_inc(&rdev->nr_pending);
 844                if (test_bit(Faulty, &rdev->flags)) {
 845                        /* Cannot risk returning a device that failed
 846                         * before we inc'ed nr_pending
 847                         */
 848                        rdev_dec_pending(rdev, conf->mddev);
 849                        goto retry;
 850                }
 851                r10_bio->read_slot = slot;
 852        } else
 853                rdev = NULL;
 854        rcu_read_unlock();
 855        *max_sectors = best_good_sectors;
 856
 857        return rdev;
 858}
 859
 860int md_raid10_congested(struct mddev *mddev, int bits)
 861{
 862        struct r10conf *conf = mddev->private;
 863        int i, ret = 0;
 864
 865        if ((bits & (1 << BDI_async_congested)) &&
 866            conf->pending_count >= max_queued_requests)
 867                return 1;
 868
 869        rcu_read_lock();
 870        for (i = 0;
 871             (i < conf->geo.raid_disks || i < conf->prev.raid_disks)
 872                     && ret == 0;
 873             i++) {
 874                struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
 875                if (rdev && !test_bit(Faulty, &rdev->flags)) {
 876                        struct request_queue *q = bdev_get_queue(rdev->bdev);
 877
 878                        ret |= bdi_congested(&q->backing_dev_info, bits);
 879                }
 880        }
 881        rcu_read_unlock();
 882        return ret;
 883}
 884EXPORT_SYMBOL_GPL(md_raid10_congested);
 885
 886static int raid10_congested(void *data, int bits)
 887{
 888        struct mddev *mddev = data;
 889
 890        return mddev_congested(mddev, bits) ||
 891                md_raid10_congested(mddev, bits);
 892}
 893
 894static void flush_pending_writes(struct r10conf *conf)
 895{
 896        /* Any writes that have been queued but are awaiting
 897         * bitmap updates get flushed here.
 898         */
 899        spin_lock_irq(&conf->device_lock);
 900
 901        if (conf->pending_bio_list.head) {
 902                struct bio *bio;
 903                bio = bio_list_get(&conf->pending_bio_list);
 904                conf->pending_count = 0;
 905                spin_unlock_irq(&conf->device_lock);
 906                /* flush any pending bitmap writes to disk
 907                 * before proceeding w/ I/O */
 908                bitmap_unplug(conf->mddev->bitmap);
 909                wake_up(&conf->wait_barrier);
 910
 911                while (bio) { /* submit pending writes */
 912                        struct bio *next = bio->bi_next;
 913                        bio->bi_next = NULL;
 914                        if (unlikely((bio->bi_rw & REQ_DISCARD) &&
 915                            !blk_queue_discard(bdev_get_queue(bio->bi_bdev))))
 916                                /* Just ignore it */
 917                                bio_endio(bio, 0);
 918                        else
 919                                generic_make_request(bio);
 920                        bio = next;
 921                }
 922        } else
 923                spin_unlock_irq(&conf->device_lock);
 924}
 925
 926/* Barriers....
 927 * Sometimes we need to suspend IO while we do something else,
 928 * either some resync/recovery, or reconfigure the array.
 929 * To do this we raise a 'barrier'.
 930 * The 'barrier' is a counter that can be raised multiple times
 931 * to count how many activities are happening which preclude
 932 * normal IO.
 933 * We can only raise the barrier if there is no pending IO.
 934 * i.e. if nr_pending == 0.
 935 * We choose only to raise the barrier if no-one is waiting for the
 936 * barrier to go down.  This means that as soon as an IO request
 937 * is ready, no other operations which require a barrier will start
 938 * until the IO request has had a chance.
 939 *
 940 * So: regular IO calls 'wait_barrier'.  When that returns there
 941 *    is no backgroup IO happening,  It must arrange to call
 942 *    allow_barrier when it has finished its IO.
 943 * backgroup IO calls must call raise_barrier.  Once that returns
 944 *    there is no normal IO happeing.  It must arrange to call
 945 *    lower_barrier when the particular background IO completes.
 946 */
 947
 948static void raise_barrier(struct r10conf *conf, int force)
 949{
 950        BUG_ON(force && !conf->barrier);
 951        spin_lock_irq(&conf->resync_lock);
 952
 953        /* Wait until no block IO is waiting (unless 'force') */
 954        wait_event_lock_irq(conf->wait_barrier, force || !conf->nr_waiting,
 955                            conf->resync_lock);
 956
 957        /* block any new IO from starting */
 958        conf->barrier++;
 959
 960        /* Now wait for all pending IO to complete */
 961        wait_event_lock_irq(conf->wait_barrier,
 962                            !conf->nr_pending && conf->barrier < RESYNC_DEPTH,
 963                            conf->resync_lock);
 964
 965        spin_unlock_irq(&conf->resync_lock);
 966}
 967
 968static void lower_barrier(struct r10conf *conf)
 969{
 970        unsigned long flags;
 971        spin_lock_irqsave(&conf->resync_lock, flags);
 972        conf->barrier--;
 973        spin_unlock_irqrestore(&conf->resync_lock, flags);
 974        wake_up(&conf->wait_barrier);
 975}
 976
 977static void wait_barrier(struct r10conf *conf)
 978{
 979        spin_lock_irq(&conf->resync_lock);
 980        if (conf->barrier) {
 981                conf->nr_waiting++;
 982                /* Wait for the barrier to drop.
 983                 * However if there are already pending
 984                 * requests (preventing the barrier from
 985                 * rising completely), and the
 986                 * pre-process bio queue isn't empty,
 987                 * then don't wait, as we need to empty
 988                 * that queue to get the nr_pending
 989                 * count down.
 990                 */
 991                wait_event_lock_irq(conf->wait_barrier,
 992                                    !conf->barrier ||
 993                                    (conf->nr_pending &&
 994                                     current->bio_list &&
 995                                     !bio_list_empty(current->bio_list)),
 996                                    conf->resync_lock);
 997                conf->nr_waiting--;
 998        }
 999        conf->nr_pending++;
1000        spin_unlock_irq(&conf->resync_lock);
1001}
1002
1003static void allow_barrier(struct r10conf *conf)
1004{
1005        unsigned long flags;
1006        spin_lock_irqsave(&conf->resync_lock, flags);
1007        conf->nr_pending--;
1008        spin_unlock_irqrestore(&conf->resync_lock, flags);
1009        wake_up(&conf->wait_barrier);
1010}
1011
1012static void freeze_array(struct r10conf *conf)
1013{
1014        /* stop syncio and normal IO and wait for everything to
1015         * go quiet.
1016         * We increment barrier and nr_waiting, and then
1017         * wait until nr_pending match nr_queued+1
1018         * This is called in the context of one normal IO request
1019         * that has failed. Thus any sync request that might be pending
1020         * will be blocked by nr_pending, and we need to wait for
1021         * pending IO requests to complete or be queued for re-try.
1022         * Thus the number queued (nr_queued) plus this request (1)
1023         * must match the number of pending IOs (nr_pending) before
1024         * we continue.
1025         */
1026        spin_lock_irq(&conf->resync_lock);
1027        conf->barrier++;
1028        conf->nr_waiting++;
1029        wait_event_lock_irq_cmd(conf->wait_barrier,
1030                                conf->nr_pending == conf->nr_queued+1,
1031                                conf->resync_lock,
1032                                flush_pending_writes(conf));
1033
1034        spin_unlock_irq(&conf->resync_lock);
1035}
1036
1037static void unfreeze_array(struct r10conf *conf)
1038{
1039        /* reverse the effect of the freeze */
1040        spin_lock_irq(&conf->resync_lock);
1041        conf->barrier--;
1042        conf->nr_waiting--;
1043        wake_up(&conf->wait_barrier);
1044        spin_unlock_irq(&conf->resync_lock);
1045}
1046
1047static sector_t choose_data_offset(struct r10bio *r10_bio,
1048                                   struct md_rdev *rdev)
1049{
1050        if (!test_bit(MD_RECOVERY_RESHAPE, &rdev->mddev->recovery) ||
1051            test_bit(R10BIO_Previous, &r10_bio->state))
1052                return rdev->data_offset;
1053        else
1054                return rdev->new_data_offset;
1055}
1056
1057struct raid10_plug_cb {
1058        struct blk_plug_cb      cb;
1059        struct bio_list         pending;
1060        int                     pending_cnt;
1061};
1062
1063static void raid10_unplug(struct blk_plug_cb *cb, bool from_schedule)
1064{
1065        struct raid10_plug_cb *plug = container_of(cb, struct raid10_plug_cb,
1066                                                   cb);
1067        struct mddev *mddev = plug->cb.data;
1068        struct r10conf *conf = mddev->private;
1069        struct bio *bio;
1070
1071        if (from_schedule || current->bio_list) {
1072                spin_lock_irq(&conf->device_lock);
1073                bio_list_merge(&conf->pending_bio_list, &plug->pending);
1074                conf->pending_count += plug->pending_cnt;
1075                spin_unlock_irq(&conf->device_lock);
1076                wake_up(&conf->wait_barrier);
1077                md_wakeup_thread(mddev->thread);
1078                kfree(plug);
1079                return;
1080        }
1081
1082        /* we aren't scheduling, so we can do the write-out directly. */
1083        bio = bio_list_get(&plug->pending);
1084        bitmap_unplug(mddev->bitmap);
1085        wake_up(&conf->wait_barrier);
1086
1087        while (bio) { /* submit pending writes */
1088                struct bio *next = bio->bi_next;
1089                bio->bi_next = NULL;
1090                generic_make_request(bio);
1091                bio = next;
1092        }
1093        kfree(plug);
1094}
1095
1096static void make_request(struct mddev *mddev, struct bio * bio)
1097{
1098        struct r10conf *conf = mddev->private;
1099        struct r10bio *r10_bio;
1100        struct bio *read_bio;
1101        int i;
1102        sector_t chunk_mask = (conf->geo.chunk_mask & conf->prev.chunk_mask);
1103        int chunk_sects = chunk_mask + 1;
1104        const int rw = bio_data_dir(bio);
1105        const unsigned long do_sync = (bio->bi_rw & REQ_SYNC);
1106        const unsigned long do_fua = (bio->bi_rw & REQ_FUA);
1107        const unsigned long do_discard = (bio->bi_rw
1108                                          & (REQ_DISCARD | REQ_SECURE));
1109        const unsigned long do_same = (bio->bi_rw & REQ_WRITE_SAME);
1110        unsigned long flags;
1111        struct md_rdev *blocked_rdev;
1112        struct blk_plug_cb *cb;
1113        struct raid10_plug_cb *plug = NULL;
1114        int sectors_handled;
1115        int max_sectors;
1116        int sectors;
1117
1118        if (unlikely(bio->bi_rw & REQ_FLUSH)) {
1119                md_flush_request(mddev, bio);
1120                return;
1121        }
1122
1123        /* If this request crosses a chunk boundary, we need to
1124         * split it.  This will only happen for 1 PAGE (or less) requests.
1125         */
1126        if (unlikely((bio->bi_sector & chunk_mask) + (bio->bi_size >> 9)
1127                     > chunk_sects
1128                     && (conf->geo.near_copies < conf->geo.raid_disks
1129                         || conf->prev.near_copies < conf->prev.raid_disks))) {
1130                struct bio_pair *bp;
1131                /* Sanity check -- queue functions should prevent this happening */
1132                if ((bio->bi_vcnt != 1 && bio->bi_vcnt != 0) ||
1133                    bio->bi_idx != 0)
1134                        goto bad_map;
1135                /* This is a one page bio that upper layers
1136                 * refuse to split for us, so we need to split it.
1137                 */
1138                bp = bio_split(bio,
1139                               chunk_sects - (bio->bi_sector & (chunk_sects - 1)) );
1140
1141                /* Each of these 'make_request' calls will call 'wait_barrier'.
1142                 * If the first succeeds but the second blocks due to the resync
1143                 * thread raising the barrier, we will deadlock because the
1144                 * IO to the underlying device will be queued in generic_make_request
1145                 * and will never complete, so will never reduce nr_pending.
1146                 * So increment nr_waiting here so no new raise_barriers will
1147                 * succeed, and so the second wait_barrier cannot block.
1148                 */
1149                spin_lock_irq(&conf->resync_lock);
1150                conf->nr_waiting++;
1151                spin_unlock_irq(&conf->resync_lock);
1152
1153                make_request(mddev, &bp->bio1);
1154                make_request(mddev, &bp->bio2);
1155
1156                spin_lock_irq(&conf->resync_lock);
1157                conf->nr_waiting--;
1158                wake_up(&conf->wait_barrier);
1159                spin_unlock_irq(&conf->resync_lock);
1160
1161                bio_pair_release(bp);
1162                return;
1163        bad_map:
1164                printk("md/raid10:%s: make_request bug: can't convert block across chunks"
1165                       " or bigger than %dk %llu %d\n", mdname(mddev), chunk_sects/2,
1166                       (unsigned long long)bio->bi_sector, bio->bi_size >> 10);
1167
1168                bio_io_error(bio);
1169                return;
1170        }
1171
1172        md_write_start(mddev, bio);
1173
1174        /*
1175         * Register the new request and wait if the reconstruction
1176         * thread has put up a bar for new requests.
1177         * Continue immediately if no resync is active currently.
1178         */
1179        wait_barrier(conf);
1180
1181        sectors = bio->bi_size >> 9;
1182        while (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1183            bio->bi_sector < conf->reshape_progress &&
1184            bio->bi_sector + sectors > conf->reshape_progress) {
1185                /* IO spans the reshape position.  Need to wait for
1186                 * reshape to pass
1187                 */
1188                allow_barrier(conf);
1189                wait_event(conf->wait_barrier,
1190                           conf->reshape_progress <= bio->bi_sector ||
1191                           conf->reshape_progress >= bio->bi_sector + sectors);
1192                wait_barrier(conf);
1193        }
1194        if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
1195            bio_data_dir(bio) == WRITE &&
1196            (mddev->reshape_backwards
1197             ? (bio->bi_sector < conf->reshape_safe &&
1198                bio->bi_sector + sectors > conf->reshape_progress)
1199             : (bio->bi_sector + sectors > conf->reshape_safe &&
1200                bio->bi_sector < conf->reshape_progress))) {
1201                /* Need to update reshape_position in metadata */
1202                mddev->reshape_position = conf->reshape_progress;
1203                set_bit(MD_CHANGE_DEVS, &mddev->flags);
1204                set_bit(MD_CHANGE_PENDING, &mddev->flags);
1205                md_wakeup_thread(mddev->thread);
1206                wait_event(mddev->sb_wait,
1207                           !test_bit(MD_CHANGE_PENDING, &mddev->flags));
1208
1209                conf->reshape_safe = mddev->reshape_position;
1210        }
1211
1212        r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1213
1214        r10_bio->master_bio = bio;
1215        r10_bio->sectors = sectors;
1216
1217        r10_bio->mddev = mddev;
1218        r10_bio->sector = bio->bi_sector;
1219        r10_bio->state = 0;
1220
1221        /* We might need to issue multiple reads to different
1222         * devices if there are bad blocks around, so we keep
1223         * track of the number of reads in bio->bi_phys_segments.
1224         * If this is 0, there is only one r10_bio and no locking
1225         * will be needed when the request completes.  If it is
1226         * non-zero, then it is the number of not-completed requests.
1227         */
1228        bio->bi_phys_segments = 0;
1229        clear_bit(BIO_SEG_VALID, &bio->bi_flags);
1230
1231        if (rw == READ) {
1232                /*
1233                 * read balancing logic:
1234                 */
1235                struct md_rdev *rdev;
1236                int slot;
1237
1238read_again:
1239                rdev = read_balance(conf, r10_bio, &max_sectors);
1240                if (!rdev) {
1241                        raid_end_bio_io(r10_bio);
1242                        return;
1243                }
1244                slot = r10_bio->read_slot;
1245
1246                read_bio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1247                md_trim_bio(read_bio, r10_bio->sector - bio->bi_sector,
1248                            max_sectors);
1249
1250                r10_bio->devs[slot].bio = read_bio;
1251                r10_bio->devs[slot].rdev = rdev;
1252
1253                read_bio->bi_sector = r10_bio->devs[slot].addr +
1254                        choose_data_offset(r10_bio, rdev);
1255                read_bio->bi_bdev = rdev->bdev;
1256                read_bio->bi_end_io = raid10_end_read_request;
1257                read_bio->bi_rw = READ | do_sync;
1258                read_bio->bi_private = r10_bio;
1259
1260                if (max_sectors < r10_bio->sectors) {
1261                        /* Could not read all from this device, so we will
1262                         * need another r10_bio.
1263                         */
1264                        sectors_handled = (r10_bio->sectors + max_sectors
1265                                           - bio->bi_sector);
1266                        r10_bio->sectors = max_sectors;
1267                        spin_lock_irq(&conf->device_lock);
1268                        if (bio->bi_phys_segments == 0)
1269                                bio->bi_phys_segments = 2;
1270                        else
1271                                bio->bi_phys_segments++;
1272                        spin_unlock(&conf->device_lock);
1273                        /* Cannot call generic_make_request directly
1274                         * as that will be queued in __generic_make_request
1275                         * and subsequent mempool_alloc might block
1276                         * waiting for it.  so hand bio over to raid10d.
1277                         */
1278                        reschedule_retry(r10_bio);
1279
1280                        r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1281
1282                        r10_bio->master_bio = bio;
1283                        r10_bio->sectors = ((bio->bi_size >> 9)
1284                                            - sectors_handled);
1285                        r10_bio->state = 0;
1286                        r10_bio->mddev = mddev;
1287                        r10_bio->sector = bio->bi_sector + sectors_handled;
1288                        goto read_again;
1289                } else
1290                        generic_make_request(read_bio);
1291                return;
1292        }
1293
1294        /*
1295         * WRITE:
1296         */
1297        if (conf->pending_count >= max_queued_requests) {
1298                md_wakeup_thread(mddev->thread);
1299                wait_event(conf->wait_barrier,
1300                           conf->pending_count < max_queued_requests);
1301        }
1302        /* first select target devices under rcu_lock and
1303         * inc refcount on their rdev.  Record them by setting
1304         * bios[x] to bio
1305         * If there are known/acknowledged bad blocks on any device
1306         * on which we have seen a write error, we want to avoid
1307         * writing to those blocks.  This potentially requires several
1308         * writes to write around the bad blocks.  Each set of writes
1309         * gets its own r10_bio with a set of bios attached.  The number
1310         * of r10_bios is recored in bio->bi_phys_segments just as with
1311         * the read case.
1312         */
1313
1314        r10_bio->read_slot = -1; /* make sure repl_bio gets freed */
1315        raid10_find_phys(conf, r10_bio);
1316retry_write:
1317        blocked_rdev = NULL;
1318        rcu_read_lock();
1319        max_sectors = r10_bio->sectors;
1320
1321        for (i = 0;  i < conf->copies; i++) {
1322                int d = r10_bio->devs[i].devnum;
1323                struct md_rdev *rdev = rcu_dereference(conf->mirrors[d].rdev);
1324                struct md_rdev *rrdev = rcu_dereference(
1325                        conf->mirrors[d].replacement);
1326                if (rdev == rrdev)
1327                        rrdev = NULL;
1328                if (rdev && unlikely(test_bit(Blocked, &rdev->flags))) {
1329                        atomic_inc(&rdev->nr_pending);
1330                        blocked_rdev = rdev;
1331                        break;
1332                }
1333                if (rrdev && unlikely(test_bit(Blocked, &rrdev->flags))) {
1334                        atomic_inc(&rrdev->nr_pending);
1335                        blocked_rdev = rrdev;
1336                        break;
1337                }
1338                if (rdev && (test_bit(Faulty, &rdev->flags)
1339                             || test_bit(Unmerged, &rdev->flags)))
1340                        rdev = NULL;
1341                if (rrdev && (test_bit(Faulty, &rrdev->flags)
1342                              || test_bit(Unmerged, &rrdev->flags)))
1343                        rrdev = NULL;
1344
1345                r10_bio->devs[i].bio = NULL;
1346                r10_bio->devs[i].repl_bio = NULL;
1347
1348                if (!rdev && !rrdev) {
1349                        set_bit(R10BIO_Degraded, &r10_bio->state);
1350                        continue;
1351                }
1352                if (rdev && test_bit(WriteErrorSeen, &rdev->flags)) {
1353                        sector_t first_bad;
1354                        sector_t dev_sector = r10_bio->devs[i].addr;
1355                        int bad_sectors;
1356                        int is_bad;
1357
1358                        is_bad = is_badblock(rdev, dev_sector,
1359                                             max_sectors,
1360                                             &first_bad, &bad_sectors);
1361                        if (is_bad < 0) {
1362                                /* Mustn't write here until the bad block
1363                                 * is acknowledged
1364                                 */
1365                                atomic_inc(&rdev->nr_pending);
1366                                set_bit(BlockedBadBlocks, &rdev->flags);
1367                                blocked_rdev = rdev;
1368                                break;
1369                        }
1370                        if (is_bad && first_bad <= dev_sector) {
1371                                /* Cannot write here at all */
1372                                bad_sectors -= (dev_sector - first_bad);
1373                                if (bad_sectors < max_sectors)
1374                                        /* Mustn't write more than bad_sectors
1375                                         * to other devices yet
1376                                         */
1377                                        max_sectors = bad_sectors;
1378                                /* We don't set R10BIO_Degraded as that
1379                                 * only applies if the disk is missing,
1380                                 * so it might be re-added, and we want to
1381                                 * know to recover this chunk.
1382                                 * In this case the device is here, and the
1383                                 * fact that this chunk is not in-sync is
1384                                 * recorded in the bad block log.
1385                                 */
1386                                continue;
1387                        }
1388                        if (is_bad) {
1389                                int good_sectors = first_bad - dev_sector;
1390                                if (good_sectors < max_sectors)
1391                                        max_sectors = good_sectors;
1392                        }
1393                }
1394                if (rdev) {
1395                        r10_bio->devs[i].bio = bio;
1396                        atomic_inc(&rdev->nr_pending);
1397                }
1398                if (rrdev) {
1399                        r10_bio->devs[i].repl_bio = bio;
1400                        atomic_inc(&rrdev->nr_pending);
1401                }
1402        }
1403        rcu_read_unlock();
1404
1405        if (unlikely(blocked_rdev)) {
1406                /* Have to wait for this device to get unblocked, then retry */
1407                int j;
1408                int d;
1409
1410                for (j = 0; j < i; j++) {
1411                        if (r10_bio->devs[j].bio) {
1412                                d = r10_bio->devs[j].devnum;
1413                                rdev_dec_pending(conf->mirrors[d].rdev, mddev);
1414                        }
1415                        if (r10_bio->devs[j].repl_bio) {
1416                                struct md_rdev *rdev;
1417                                d = r10_bio->devs[j].devnum;
1418                                rdev = conf->mirrors[d].replacement;
1419                                if (!rdev) {
1420                                        /* Race with remove_disk */
1421                                        smp_mb();
1422                                        rdev = conf->mirrors[d].rdev;
1423                                }
1424                                rdev_dec_pending(rdev, mddev);
1425                        }
1426                }
1427                allow_barrier(conf);
1428                md_wait_for_blocked_rdev(blocked_rdev, mddev);
1429                wait_barrier(conf);
1430                goto retry_write;
1431        }
1432
1433        if (max_sectors < r10_bio->sectors) {
1434                /* We are splitting this into multiple parts, so
1435                 * we need to prepare for allocating another r10_bio.
1436                 */
1437                r10_bio->sectors = max_sectors;
1438                spin_lock_irq(&conf->device_lock);
1439                if (bio->bi_phys_segments == 0)
1440                        bio->bi_phys_segments = 2;
1441                else
1442                        bio->bi_phys_segments++;
1443                spin_unlock_irq(&conf->device_lock);
1444        }
1445        sectors_handled = r10_bio->sector + max_sectors - bio->bi_sector;
1446
1447        atomic_set(&r10_bio->remaining, 1);
1448        bitmap_startwrite(mddev->bitmap, r10_bio->sector, r10_bio->sectors, 0);
1449
1450        for (i = 0; i < conf->copies; i++) {
1451                struct bio *mbio;
1452                int d = r10_bio->devs[i].devnum;
1453                if (r10_bio->devs[i].bio) {
1454                        struct md_rdev *rdev = conf->mirrors[d].rdev;
1455                        mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1456                        md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1457                                    max_sectors);
1458                        r10_bio->devs[i].bio = mbio;
1459
1460                        mbio->bi_sector = (r10_bio->devs[i].addr+
1461                                           choose_data_offset(r10_bio,
1462                                                              rdev));
1463                        mbio->bi_bdev = rdev->bdev;
1464                        mbio->bi_end_io = raid10_end_write_request;
1465                        mbio->bi_rw =
1466                                WRITE | do_sync | do_fua | do_discard | do_same;
1467                        mbio->bi_private = r10_bio;
1468
1469                        atomic_inc(&r10_bio->remaining);
1470
1471                        cb = blk_check_plugged(raid10_unplug, mddev,
1472                                               sizeof(*plug));
1473                        if (cb)
1474                                plug = container_of(cb, struct raid10_plug_cb,
1475                                                    cb);
1476                        else
1477                                plug = NULL;
1478                        spin_lock_irqsave(&conf->device_lock, flags);
1479                        if (plug) {
1480                                bio_list_add(&plug->pending, mbio);
1481                                plug->pending_cnt++;
1482                        } else {
1483                                bio_list_add(&conf->pending_bio_list, mbio);
1484                                conf->pending_count++;
1485                        }
1486                        spin_unlock_irqrestore(&conf->device_lock, flags);
1487                        if (!plug)
1488                                md_wakeup_thread(mddev->thread);
1489                }
1490
1491                if (r10_bio->devs[i].repl_bio) {
1492                        struct md_rdev *rdev = conf->mirrors[d].replacement;
1493                        if (rdev == NULL) {
1494                                /* Replacement just got moved to main 'rdev' */
1495                                smp_mb();
1496                                rdev = conf->mirrors[d].rdev;
1497                        }
1498                        mbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
1499                        md_trim_bio(mbio, r10_bio->sector - bio->bi_sector,
1500                                    max_sectors);
1501                        r10_bio->devs[i].repl_bio = mbio;
1502
1503                        mbio->bi_sector = (r10_bio->devs[i].addr +
1504                                           choose_data_offset(
1505                                                   r10_bio, rdev));
1506                        mbio->bi_bdev = rdev->bdev;
1507                        mbio->bi_end_io = raid10_end_write_request;
1508                        mbio->bi_rw =
1509                                WRITE | do_sync | do_fua | do_discard | do_same;
1510                        mbio->bi_private = r10_bio;
1511
1512                        atomic_inc(&r10_bio->remaining);
1513                        spin_lock_irqsave(&conf->device_lock, flags);
1514                        bio_list_add(&conf->pending_bio_list, mbio);
1515                        conf->pending_count++;
1516                        spin_unlock_irqrestore(&conf->device_lock, flags);
1517                        if (!mddev_check_plugged(mddev))
1518                                md_wakeup_thread(mddev->thread);
1519                }
1520        }
1521
1522        /* Don't remove the bias on 'remaining' (one_write_done) until
1523         * after checking if we need to go around again.
1524         */
1525
1526        if (sectors_handled < (bio->bi_size >> 9)) {
1527                one_write_done(r10_bio);
1528                /* We need another r10_bio.  It has already been counted
1529                 * in bio->bi_phys_segments.
1530                 */
1531                r10_bio = mempool_alloc(conf->r10bio_pool, GFP_NOIO);
1532
1533                r10_bio->master_bio = bio;
1534                r10_bio->sectors = (bio->bi_size >> 9) - sectors_handled;
1535
1536                r10_bio->mddev = mddev;
1537                r10_bio->sector = bio->bi_sector + sectors_handled;
1538                r10_bio->state = 0;
1539                goto retry_write;
1540        }
1541        one_write_done(r10_bio);
1542
1543        /* In case raid10d snuck in to freeze_array */
1544        wake_up(&conf->wait_barrier);
1545}
1546
1547static void status(struct seq_file *seq, struct mddev *mddev)
1548{
1549        struct r10conf *conf = mddev->private;
1550        int i;
1551
1552        if (conf->geo.near_copies < conf->geo.raid_disks)
1553                seq_printf(seq, " %dK chunks", mddev->chunk_sectors / 2);
1554        if (conf->geo.near_copies > 1)
1555                seq_printf(seq, " %d near-copies", conf->geo.near_copies);
1556        if (conf->geo.far_copies > 1) {
1557                if (conf->geo.far_offset)
1558                        seq_printf(seq, " %d offset-copies", conf->geo.far_copies);
1559                else
1560                        seq_printf(seq, " %d far-copies", conf->geo.far_copies);
1561        }
1562        seq_printf(seq, " [%d/%d] [", conf->geo.raid_disks,
1563                                        conf->geo.raid_disks - mddev->degraded);
1564        for (i = 0; i < conf->geo.raid_disks; i++)
1565                seq_printf(seq, "%s",
1566                              conf->mirrors[i].rdev &&
1567                              test_bit(In_sync, &conf->mirrors[i].rdev->flags) ? "U" : "_");
1568        seq_printf(seq, "]");
1569}
1570
1571/* check if there are enough drives for
1572 * every block to appear on atleast one.
1573 * Don't consider the device numbered 'ignore'
1574 * as we might be about to remove it.
1575 */
1576static int _enough(struct r10conf *conf, struct geom *geo, int ignore)
1577{
1578        int first = 0;
1579
1580        do {
1581                int n = conf->copies;
1582                int cnt = 0;
1583                int this = first;
1584                while (n--) {
1585                        if (conf->mirrors[this].rdev &&
1586                            this != ignore)
1587                                cnt++;
1588                        this = (this+1) % geo->raid_disks;
1589                }
1590                if (cnt == 0)
1591                        return 0;
1592                first = (first + geo->near_copies) % geo->raid_disks;
1593        } while (first != 0);
1594        return 1;
1595}
1596
1597static int enough(struct r10conf *conf, int ignore)
1598{
1599        return _enough(conf, &conf->geo, ignore) &&
1600                _enough(conf, &conf->prev, ignore);
1601}
1602
1603static void error(struct mddev *mddev, struct md_rdev *rdev)
1604{
1605        char b[BDEVNAME_SIZE];
1606        struct r10conf *conf = mddev->private;
1607
1608        /*
1609         * If it is not operational, then we have already marked it as dead
1610         * else if it is the last working disks, ignore the error, let the
1611         * next level up know.
1612         * else mark the drive as failed
1613         */
1614        if (test_bit(In_sync, &rdev->flags)
1615            && !enough(conf, rdev->raid_disk))
1616                /*
1617                 * Don't fail the drive, just return an IO error.
1618                 */
1619                return;
1620        if (test_and_clear_bit(In_sync, &rdev->flags)) {
1621                unsigned long flags;
1622                spin_lock_irqsave(&conf->device_lock, flags);
1623                mddev->degraded++;
1624                spin_unlock_irqrestore(&conf->device_lock, flags);
1625                /*
1626                 * if recovery is running, make sure it aborts.
1627                 */
1628                set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1629        }
1630        set_bit(Blocked, &rdev->flags);
1631        set_bit(Faulty, &rdev->flags);
1632        set_bit(MD_CHANGE_DEVS, &mddev->flags);
1633        printk(KERN_ALERT
1634               "md/raid10:%s: Disk failure on %s, disabling device.\n"
1635               "md/raid10:%s: Operation continuing on %d devices.\n",
1636               mdname(mddev), bdevname(rdev->bdev, b),
1637               mdname(mddev), conf->geo.raid_disks - mddev->degraded);
1638}
1639
1640static void print_conf(struct r10conf *conf)
1641{
1642        int i;
1643        struct raid10_info *tmp;
1644
1645        printk(KERN_DEBUG "RAID10 conf printout:\n");
1646        if (!conf) {
1647                printk(KERN_DEBUG "(!conf)\n");
1648                return;
1649        }
1650        printk(KERN_DEBUG " --- wd:%d rd:%d\n", conf->geo.raid_disks - conf->mddev->degraded,
1651                conf->geo.raid_disks);
1652
1653        for (i = 0; i < conf->geo.raid_disks; i++) {
1654                char b[BDEVNAME_SIZE];
1655                tmp = conf->mirrors + i;
1656                if (tmp->rdev)
1657                        printk(KERN_DEBUG " disk %d, wo:%d, o:%d, dev:%s\n",
1658                                i, !test_bit(In_sync, &tmp->rdev->flags),
1659                                !test_bit(Faulty, &tmp->rdev->flags),
1660                                bdevname(tmp->rdev->bdev,b));
1661        }
1662}
1663
1664static void close_sync(struct r10conf *conf)
1665{
1666        wait_barrier(conf);
1667        allow_barrier(conf);
1668
1669        mempool_destroy(conf->r10buf_pool);
1670        conf->r10buf_pool = NULL;
1671}
1672
1673static int raid10_spare_active(struct mddev *mddev)
1674{
1675        int i;
1676        struct r10conf *conf = mddev->private;
1677        struct raid10_info *tmp;
1678        int count = 0;
1679        unsigned long flags;
1680
1681        /*
1682         * Find all non-in_sync disks within the RAID10 configuration
1683         * and mark them in_sync
1684         */
1685        for (i = 0; i < conf->geo.raid_disks; i++) {
1686                tmp = conf->mirrors + i;
1687                if (tmp->replacement
1688                    && tmp->replacement->recovery_offset == MaxSector
1689                    && !test_bit(Faulty, &tmp->replacement->flags)
1690                    && !test_and_set_bit(In_sync, &tmp->replacement->flags)) {
1691                        /* Replacement has just become active */
1692                        if (!tmp->rdev
1693                            || !test_and_clear_bit(In_sync, &tmp->rdev->flags))
1694                                count++;
1695                        if (tmp->rdev) {
1696                                /* Replaced device not technically faulty,
1697                                 * but we need to be sure it gets removed
1698                                 * and never re-added.
1699                                 */
1700                                set_bit(Faulty, &tmp->rdev->flags);
1701                                sysfs_notify_dirent_safe(
1702                                        tmp->rdev->sysfs_state);
1703                        }
1704                        sysfs_notify_dirent_safe(tmp->replacement->sysfs_state);
1705                } else if (tmp->rdev
1706                           && !test_bit(Faulty, &tmp->rdev->flags)
1707                           && !test_and_set_bit(In_sync, &tmp->rdev->flags)) {
1708                        count++;
1709                        sysfs_notify_dirent_safe(tmp->rdev->sysfs_state);
1710                }
1711        }
1712        spin_lock_irqsave(&conf->device_lock, flags);
1713        mddev->degraded -= count;
1714        spin_unlock_irqrestore(&conf->device_lock, flags);
1715
1716        print_conf(conf);
1717        return count;
1718}
1719
1720
1721static int raid10_add_disk(struct mddev *mddev, struct md_rdev *rdev)
1722{
1723        struct r10conf *conf = mddev->private;
1724        int err = -EEXIST;
1725        int mirror;
1726        int first = 0;
1727        int last = conf->geo.raid_disks - 1;
1728        struct request_queue *q = bdev_get_queue(rdev->bdev);
1729
1730        if (mddev->recovery_cp < MaxSector)
1731                /* only hot-add to in-sync arrays, as recovery is
1732                 * very different from resync
1733                 */
1734                return -EBUSY;
1735        if (rdev->saved_raid_disk < 0 && !_enough(conf, &conf->prev, -1))
1736                return -EINVAL;
1737
1738        if (rdev->raid_disk >= 0)
1739                first = last = rdev->raid_disk;
1740
1741        if (q->merge_bvec_fn) {
1742                set_bit(Unmerged, &rdev->flags);
1743                mddev->merge_check_needed = 1;
1744        }
1745
1746        if (rdev->saved_raid_disk >= first &&
1747            conf->mirrors[rdev->saved_raid_disk].rdev == NULL)
1748                mirror = rdev->saved_raid_disk;
1749        else
1750                mirror = first;
1751        for ( ; mirror <= last ; mirror++) {
1752                struct raid10_info *p = &conf->mirrors[mirror];
1753                if (p->recovery_disabled == mddev->recovery_disabled)
1754                        continue;
1755                if (p->rdev) {
1756                        if (!test_bit(WantReplacement, &p->rdev->flags) ||
1757                            p->replacement != NULL)
1758                                continue;
1759                        clear_bit(In_sync, &rdev->flags);
1760                        set_bit(Replacement, &rdev->flags);
1761                        rdev->raid_disk = mirror;
1762                        err = 0;
1763                        disk_stack_limits(mddev->gendisk, rdev->bdev,
1764                                          rdev->data_offset << 9);
1765                        conf->fullsync = 1;
1766                        rcu_assign_pointer(p->replacement, rdev);
1767                        break;
1768                }
1769
1770                disk_stack_limits(mddev->gendisk, rdev->bdev,
1771                                  rdev->data_offset << 9);
1772
1773                p->head_position = 0;
1774                p->recovery_disabled = mddev->recovery_disabled - 1;
1775                rdev->raid_disk = mirror;
1776                err = 0;
1777                if (rdev->saved_raid_disk != mirror)
1778                        conf->fullsync = 1;
1779                rcu_assign_pointer(p->rdev, rdev);
1780                break;
1781        }
1782        if (err == 0 && test_bit(Unmerged, &rdev->flags)) {
1783                /* Some requests might not have seen this new
1784                 * merge_bvec_fn.  We must wait for them to complete
1785                 * before merging the device fully.
1786                 * First we make sure any code which has tested
1787                 * our function has submitted the request, then
1788                 * we wait for all outstanding requests to complete.
1789                 */
1790                synchronize_sched();
1791                raise_barrier(conf, 0);
1792                lower_barrier(conf);
1793                clear_bit(Unmerged, &rdev->flags);
1794        }
1795        md_integrity_add_rdev(rdev, mddev);
1796        if (mddev->queue && blk_queue_discard(bdev_get_queue(rdev->bdev)))
1797                queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, mddev->queue);
1798
1799        print_conf(conf);
1800        return err;
1801}
1802
1803static int raid10_remove_disk(struct mddev *mddev, struct md_rdev *rdev)
1804{
1805        struct r10conf *conf = mddev->private;
1806        int err = 0;
1807        int number = rdev->raid_disk;
1808        struct md_rdev **rdevp;
1809        struct raid10_info *p = conf->mirrors + number;
1810
1811        print_conf(conf);
1812        if (rdev == p->rdev)
1813                rdevp = &p->rdev;
1814        else if (rdev == p->replacement)
1815                rdevp = &p->replacement;
1816        else
1817                return 0;
1818
1819        if (test_bit(In_sync, &rdev->flags) ||
1820            atomic_read(&rdev->nr_pending)) {
1821                err = -EBUSY;
1822                goto abort;
1823        }
1824        /* Only remove faulty devices if recovery
1825         * is not possible.
1826         */
1827        if (!test_bit(Faulty, &rdev->flags) &&
1828            mddev->recovery_disabled != p->recovery_disabled &&
1829            (!p->replacement || p->replacement == rdev) &&
1830            number < conf->geo.raid_disks &&
1831            enough(conf, -1)) {
1832                err = -EBUSY;
1833                goto abort;
1834        }
1835        *rdevp = NULL;
1836        synchronize_rcu();
1837        if (atomic_read(&rdev->nr_pending)) {
1838                /* lost the race, try later */
1839                err = -EBUSY;
1840                *rdevp = rdev;
1841                goto abort;
1842        } else if (p->replacement) {
1843                /* We must have just cleared 'rdev' */
1844                p->rdev = p->replacement;
1845                clear_bit(Replacement, &p->replacement->flags);
1846                smp_mb(); /* Make sure other CPUs may see both as identical
1847                           * but will never see neither -- if they are careful.
1848                           */
1849                p->replacement = NULL;
1850                clear_bit(WantReplacement, &rdev->flags);
1851        } else
1852                /* We might have just remove the Replacement as faulty
1853                 * Clear the flag just in case
1854                 */
1855                clear_bit(WantReplacement, &rdev->flags);
1856
1857        err = md_integrity_register(mddev);
1858
1859abort:
1860
1861        print_conf(conf);
1862        return err;
1863}
1864
1865
1866static void end_sync_read(struct bio *bio, int error)
1867{
1868        struct r10bio *r10_bio = bio->bi_private;
1869        struct r10conf *conf = r10_bio->mddev->private;
1870        int d;
1871
1872        if (bio == r10_bio->master_bio) {
1873                /* this is a reshape read */
1874                d = r10_bio->read_slot; /* really the read dev */
1875        } else
1876                d = find_bio_disk(conf, r10_bio, bio, NULL, NULL);
1877
1878        if (test_bit(BIO_UPTODATE, &bio->bi_flags))
1879                set_bit(R10BIO_Uptodate, &r10_bio->state);
1880        else
1881                /* The write handler will notice the lack of
1882                 * R10BIO_Uptodate and record any errors etc
1883                 */
1884                atomic_add(r10_bio->sectors,
1885                           &conf->mirrors[d].rdev->corrected_errors);
1886
1887        /* for reconstruct, we always reschedule after a read.
1888         * for resync, only after all reads
1889         */
1890        rdev_dec_pending(conf->mirrors[d].rdev, conf->mddev);
1891        if (test_bit(R10BIO_IsRecover, &r10_bio->state) ||
1892            atomic_dec_and_test(&r10_bio->remaining)) {
1893                /* we have read all the blocks,
1894                 * do the comparison in process context in raid10d
1895                 */
1896                reschedule_retry(r10_bio);
1897        }
1898}
1899
1900static void end_sync_request(struct r10bio *r10_bio)
1901{
1902        struct mddev *mddev = r10_bio->mddev;
1903
1904        while (atomic_dec_and_test(&r10_bio->remaining)) {
1905                if (r10_bio->master_bio == NULL) {
1906                        /* the primary of several recovery bios */
1907                        sector_t s = r10_bio->sectors;
1908                        if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1909                            test_bit(R10BIO_WriteError, &r10_bio->state))
1910                                reschedule_retry(r10_bio);
1911                        else
1912                                put_buf(r10_bio);
1913                        md_done_sync(mddev, s, 1);
1914                        break;
1915                } else {
1916                        struct r10bio *r10_bio2 = (struct r10bio *)r10_bio->master_bio;
1917                        if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
1918                            test_bit(R10BIO_WriteError, &r10_bio->state))
1919                                reschedule_retry(r10_bio);
1920                        else
1921                                put_buf(r10_bio);
1922                        r10_bio = r10_bio2;
1923                }
1924        }
1925}
1926
1927static void end_sync_write(struct bio *bio, int error)
1928{
1929        int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
1930        struct r10bio *r10_bio = bio->bi_private;
1931        struct mddev *mddev = r10_bio->mddev;
1932        struct r10conf *conf = mddev->private;
1933        int d;
1934        sector_t first_bad;
1935        int bad_sectors;
1936        int slot;
1937        int repl;
1938        struct md_rdev *rdev = NULL;
1939
1940        d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
1941        if (repl)
1942                rdev = conf->mirrors[d].replacement;
1943        else
1944                rdev = conf->mirrors[d].rdev;
1945
1946        if (!uptodate) {
1947                if (repl)
1948                        md_error(mddev, rdev);
1949                else {
1950                        set_bit(WriteErrorSeen, &rdev->flags);
1951                        if (!test_and_set_bit(WantReplacement, &rdev->flags))
1952                                set_bit(MD_RECOVERY_NEEDED,
1953                                        &rdev->mddev->recovery);
1954                        set_bit(R10BIO_WriteError, &r10_bio->state);
1955                }
1956        } else if (is_badblock(rdev,
1957                             r10_bio->devs[slot].addr,
1958                             r10_bio->sectors,
1959                             &first_bad, &bad_sectors))
1960                set_bit(R10BIO_MadeGood, &r10_bio->state);
1961
1962        rdev_dec_pending(rdev, mddev);
1963
1964        end_sync_request(r10_bio);
1965}
1966
1967/*
1968 * Note: sync and recover and handled very differently for raid10
1969 * This code is for resync.
1970 * For resync, we read through virtual addresses and read all blocks.
1971 * If there is any error, we schedule a write.  The lowest numbered
1972 * drive is authoritative.
1973 * However requests come for physical address, so we need to map.
1974 * For every physical address there are raid_disks/copies virtual addresses,
1975 * which is always are least one, but is not necessarly an integer.
1976 * This means that a physical address can span multiple chunks, so we may
1977 * have to submit multiple io requests for a single sync request.
1978 */
1979/*
1980 * We check if all blocks are in-sync and only write to blocks that
1981 * aren't in sync
1982 */
1983static void sync_request_write(struct mddev *mddev, struct r10bio *r10_bio)
1984{
1985        struct r10conf *conf = mddev->private;
1986        int i, first;
1987        struct bio *tbio, *fbio;
1988        int vcnt;
1989
1990        atomic_set(&r10_bio->remaining, 1);
1991
1992        /* find the first device with a block */
1993        for (i=0; i<conf->copies; i++)
1994                if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags))
1995                        break;
1996
1997        if (i == conf->copies)
1998                goto done;
1999
2000        first = i;
2001        fbio = r10_bio->devs[i].bio;
2002
2003        vcnt = (r10_bio->sectors + (PAGE_SIZE >> 9) - 1) >> (PAGE_SHIFT - 9);
2004        /* now find blocks with errors */
2005        for (i=0 ; i < conf->copies ; i++) {
2006                int  j, d;
2007
2008                tbio = r10_bio->devs[i].bio;
2009
2010                if (tbio->bi_end_io != end_sync_read)
2011                        continue;
2012                if (i == first)
2013                        continue;
2014                if (test_bit(BIO_UPTODATE, &r10_bio->devs[i].bio->bi_flags)) {
2015                        /* We know that the bi_io_vec layout is the same for
2016                         * both 'first' and 'i', so we just compare them.
2017                         * All vec entries are PAGE_SIZE;
2018                         */
2019                        for (j = 0; j < vcnt; j++)
2020                                if (memcmp(page_address(fbio->bi_io_vec[j].bv_page),
2021                                           page_address(tbio->bi_io_vec[j].bv_page),
2022                                           fbio->bi_io_vec[j].bv_len))
2023                                        break;
2024                        if (j == vcnt)
2025                                continue;
2026                        atomic64_add(r10_bio->sectors, &mddev->resync_mismatches);
2027                        if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
2028                                /* Don't fix anything. */
2029                                continue;
2030                }
2031                /* Ok, we need to write this bio, either to correct an
2032                 * inconsistency or to correct an unreadable block.
2033                 * First we need to fixup bv_offset, bv_len and
2034                 * bi_vecs, as the read request might have corrupted these
2035                 */
2036                tbio->bi_vcnt = vcnt;
2037                tbio->bi_size = r10_bio->sectors << 9;
2038                tbio->bi_idx = 0;
2039                tbio->bi_phys_segments = 0;
2040                tbio->bi_flags &= ~(BIO_POOL_MASK - 1);
2041                tbio->bi_flags |= 1 << BIO_UPTODATE;
2042                tbio->bi_next = NULL;
2043                tbio->bi_rw = WRITE;
2044                tbio->bi_private = r10_bio;
2045                tbio->bi_sector = r10_bio->devs[i].addr;
2046
2047                for (j=0; j < vcnt ; j++) {
2048                        tbio->bi_io_vec[j].bv_offset = 0;
2049                        tbio->bi_io_vec[j].bv_len = PAGE_SIZE;
2050
2051                        memcpy(page_address(tbio->bi_io_vec[j].bv_page),
2052                               page_address(fbio->bi_io_vec[j].bv_page),
2053                               PAGE_SIZE);
2054                }
2055                tbio->bi_end_io = end_sync_write;
2056
2057                d = r10_bio->devs[i].devnum;
2058                atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2059                atomic_inc(&r10_bio->remaining);
2060                md_sync_acct(conf->mirrors[d].rdev->bdev, tbio->bi_size >> 9);
2061
2062                tbio->bi_sector += conf->mirrors[d].rdev->data_offset;
2063                tbio->bi_bdev = conf->mirrors[d].rdev->bdev;
2064                generic_make_request(tbio);
2065        }
2066
2067        /* Now write out to any replacement devices
2068         * that are active
2069         */
2070        for (i = 0; i < conf->copies; i++) {
2071                int j, d;
2072
2073                tbio = r10_bio->devs[i].repl_bio;
2074                if (!tbio || !tbio->bi_end_io)
2075                        continue;
2076                if (r10_bio->devs[i].bio->bi_end_io != end_sync_write
2077                    && r10_bio->devs[i].bio != fbio)
2078                        for (j = 0; j < vcnt; j++)
2079                                memcpy(page_address(tbio->bi_io_vec[j].bv_page),
2080                                       page_address(fbio->bi_io_vec[j].bv_page),
2081                                       PAGE_SIZE);
2082                d = r10_bio->devs[i].devnum;
2083                atomic_inc(&r10_bio->remaining);
2084                md_sync_acct(conf->mirrors[d].replacement->bdev,
2085                             tbio->bi_size >> 9);
2086                generic_make_request(tbio);
2087        }
2088
2089done:
2090        if (atomic_dec_and_test(&r10_bio->remaining)) {
2091                md_done_sync(mddev, r10_bio->sectors, 1);
2092                put_buf(r10_bio);
2093        }
2094}
2095
2096/*
2097 * Now for the recovery code.
2098 * Recovery happens across physical sectors.
2099 * We recover all non-is_sync drives by finding the virtual address of
2100 * each, and then choose a working drive that also has that virt address.
2101 * There is a separate r10_bio for each non-in_sync drive.
2102 * Only the first two slots are in use. The first for reading,
2103 * The second for writing.
2104 *
2105 */
2106static void fix_recovery_read_error(struct r10bio *r10_bio)
2107{
2108        /* We got a read error during recovery.
2109         * We repeat the read in smaller page-sized sections.
2110         * If a read succeeds, write it to the new device or record
2111         * a bad block if we cannot.
2112         * If a read fails, record a bad block on both old and
2113         * new devices.
2114         */
2115        struct mddev *mddev = r10_bio->mddev;
2116        struct r10conf *conf = mddev->private;
2117        struct bio *bio = r10_bio->devs[0].bio;
2118        sector_t sect = 0;
2119        int sectors = r10_bio->sectors;
2120        int idx = 0;
2121        int dr = r10_bio->devs[0].devnum;
2122        int dw = r10_bio->devs[1].devnum;
2123
2124        while (sectors) {
2125                int s = sectors;
2126                struct md_rdev *rdev;
2127                sector_t addr;
2128                int ok;
2129
2130                if (s > (PAGE_SIZE>>9))
2131                        s = PAGE_SIZE >> 9;
2132
2133                rdev = conf->mirrors[dr].rdev;
2134                addr = r10_bio->devs[0].addr + sect,
2135                ok = sync_page_io(rdev,
2136                                  addr,
2137                                  s << 9,
2138                                  bio->bi_io_vec[idx].bv_page,
2139                                  READ, false);
2140                if (ok) {
2141                        rdev = conf->mirrors[dw].rdev;
2142                        addr = r10_bio->devs[1].addr + sect;
2143                        ok = sync_page_io(rdev,
2144                                          addr,
2145                                          s << 9,
2146                                          bio->bi_io_vec[idx].bv_page,
2147                                          WRITE, false);
2148                        if (!ok) {
2149                                set_bit(WriteErrorSeen, &rdev->flags);
2150                                if (!test_and_set_bit(WantReplacement,
2151                                                      &rdev->flags))
2152                                        set_bit(MD_RECOVERY_NEEDED,
2153                                                &rdev->mddev->recovery);
2154                        }
2155                }
2156                if (!ok) {
2157                        /* We don't worry if we cannot set a bad block -
2158                         * it really is bad so there is no loss in not
2159                         * recording it yet
2160                         */
2161                        rdev_set_badblocks(rdev, addr, s, 0);
2162
2163                        if (rdev != conf->mirrors[dw].rdev) {
2164                                /* need bad block on destination too */
2165                                struct md_rdev *rdev2 = conf->mirrors[dw].rdev;
2166                                addr = r10_bio->devs[1].addr + sect;
2167                                ok = rdev_set_badblocks(rdev2, addr, s, 0);
2168                                if (!ok) {
2169                                        /* just abort the recovery */
2170                                        printk(KERN_NOTICE
2171                                               "md/raid10:%s: recovery aborted"
2172                                               " due to read error\n",
2173                                               mdname(mddev));
2174
2175                                        conf->mirrors[dw].recovery_disabled
2176                                                = mddev->recovery_disabled;
2177                                        set_bit(MD_RECOVERY_INTR,
2178                                                &mddev->recovery);
2179                                        break;
2180                                }
2181                        }
2182                }
2183
2184                sectors -= s;
2185                sect += s;
2186                idx++;
2187        }
2188}
2189
2190static void recovery_request_write(struct mddev *mddev, struct r10bio *r10_bio)
2191{
2192        struct r10conf *conf = mddev->private;
2193        int d;
2194        struct bio *wbio, *wbio2;
2195
2196        if (!test_bit(R10BIO_Uptodate, &r10_bio->state)) {
2197                fix_recovery_read_error(r10_bio);
2198                end_sync_request(r10_bio);
2199                return;
2200        }
2201
2202        /*
2203         * share the pages with the first bio
2204         * and submit the write request
2205         */
2206        d = r10_bio->devs[1].devnum;
2207        wbio = r10_bio->devs[1].bio;
2208        wbio2 = r10_bio->devs[1].repl_bio;
2209        if (wbio->bi_end_io) {
2210                atomic_inc(&conf->mirrors[d].rdev->nr_pending);
2211                md_sync_acct(conf->mirrors[d].rdev->bdev, wbio->bi_size >> 9);
2212                generic_make_request(wbio);
2213        }
2214        if (wbio2 && wbio2->bi_end_io) {
2215                atomic_inc(&conf->mirrors[d].replacement->nr_pending);
2216                md_sync_acct(conf->mirrors[d].replacement->bdev,
2217                             wbio2->bi_size >> 9);
2218                generic_make_request(wbio2);
2219        }
2220}
2221
2222
2223/*
2224 * Used by fix_read_error() to decay the per rdev read_errors.
2225 * We halve the read error count for every hour that has elapsed
2226 * since the last recorded read error.
2227 *
2228 */
2229static void check_decay_read_errors(struct mddev *mddev, struct md_rdev *rdev)
2230{
2231        struct timespec cur_time_mon;
2232        unsigned long hours_since_last;
2233        unsigned int read_errors = atomic_read(&rdev->read_errors);
2234
2235        ktime_get_ts(&cur_time_mon);
2236
2237        if (rdev->last_read_error.tv_sec == 0 &&
2238            rdev->last_read_error.tv_nsec == 0) {
2239                /* first time we've seen a read error */
2240                rdev->last_read_error = cur_time_mon;
2241                return;
2242        }
2243
2244        hours_since_last = (cur_time_mon.tv_sec -
2245                            rdev->last_read_error.tv_sec) / 3600;
2246
2247        rdev->last_read_error = cur_time_mon;
2248
2249        /*
2250         * if hours_since_last is > the number of bits in read_errors
2251         * just set read errors to 0. We do this to avoid
2252         * overflowing the shift of read_errors by hours_since_last.
2253         */
2254        if (hours_since_last >= 8 * sizeof(read_errors))
2255                atomic_set(&rdev->read_errors, 0);
2256        else
2257                atomic_set(&rdev->read_errors, read_errors >> hours_since_last);
2258}
2259
2260static int r10_sync_page_io(struct md_rdev *rdev, sector_t sector,
2261                            int sectors, struct page *page, int rw)
2262{
2263        sector_t first_bad;
2264        int bad_sectors;
2265
2266        if (is_badblock(rdev, sector, sectors, &first_bad, &bad_sectors)
2267            && (rw == READ || test_bit(WriteErrorSeen, &rdev->flags)))
2268                return -1;
2269        if (sync_page_io(rdev, sector, sectors << 9, page, rw, false))
2270                /* success */
2271                return 1;
2272        if (rw == WRITE) {
2273                set_bit(WriteErrorSeen, &rdev->flags);
2274                if (!test_and_set_bit(WantReplacement, &rdev->flags))
2275                        set_bit(MD_RECOVERY_NEEDED,
2276                                &rdev->mddev->recovery);
2277        }
2278        /* need to record an error - either for the block or the device */
2279        if (!rdev_set_badblocks(rdev, sector, sectors, 0))
2280                md_error(rdev->mddev, rdev);
2281        return 0;
2282}
2283
2284/*
2285 * This is a kernel thread which:
2286 *
2287 *      1.      Retries failed read operations on working mirrors.
2288 *      2.      Updates the raid superblock when problems encounter.
2289 *      3.      Performs writes following reads for array synchronising.
2290 */
2291
2292static void fix_read_error(struct r10conf *conf, struct mddev *mddev, struct r10bio *r10_bio)
2293{
2294        int sect = 0; /* Offset from r10_bio->sector */
2295        int sectors = r10_bio->sectors;
2296        struct md_rdev*rdev;
2297        int max_read_errors = atomic_read(&mddev->max_corr_read_errors);
2298        int d = r10_bio->devs[r10_bio->read_slot].devnum;
2299
2300        /* still own a reference to this rdev, so it cannot
2301         * have been cleared recently.
2302         */
2303        rdev = conf->mirrors[d].rdev;
2304
2305        if (test_bit(Faulty, &rdev->flags))
2306                /* drive has already been failed, just ignore any
2307                   more fix_read_error() attempts */
2308                return;
2309
2310        check_decay_read_errors(mddev, rdev);
2311        atomic_inc(&rdev->read_errors);
2312        if (atomic_read(&rdev->read_errors) > max_read_errors) {
2313                char b[BDEVNAME_SIZE];
2314                bdevname(rdev->bdev, b);
2315
2316                printk(KERN_NOTICE
2317                       "md/raid10:%s: %s: Raid device exceeded "
2318                       "read_error threshold [cur %d:max %d]\n",
2319                       mdname(mddev), b,
2320                       atomic_read(&rdev->read_errors), max_read_errors);
2321                printk(KERN_NOTICE
2322                       "md/raid10:%s: %s: Failing raid device\n",
2323                       mdname(mddev), b);
2324                md_error(mddev, conf->mirrors[d].rdev);
2325                r10_bio->devs[r10_bio->read_slot].bio = IO_BLOCKED;
2326                return;
2327        }
2328
2329        while(sectors) {
2330                int s = sectors;
2331                int sl = r10_bio->read_slot;
2332                int success = 0;
2333                int start;
2334
2335                if (s > (PAGE_SIZE>>9))
2336                        s = PAGE_SIZE >> 9;
2337
2338                rcu_read_lock();
2339                do {
2340                        sector_t first_bad;
2341                        int bad_sectors;
2342
2343                        d = r10_bio->devs[sl].devnum;
2344                        rdev = rcu_dereference(conf->mirrors[d].rdev);
2345                        if (rdev &&
2346                            !test_bit(Unmerged, &rdev->flags) &&
2347                            test_bit(In_sync, &rdev->flags) &&
2348                            is_badblock(rdev, r10_bio->devs[sl].addr + sect, s,
2349                                        &first_bad, &bad_sectors) == 0) {
2350                                atomic_inc(&rdev->nr_pending);
2351                                rcu_read_unlock();
2352                                success = sync_page_io(rdev,
2353                                                       r10_bio->devs[sl].addr +
2354                                                       sect,
2355                                                       s<<9,
2356                                                       conf->tmppage, READ, false);
2357                                rdev_dec_pending(rdev, mddev);
2358                                rcu_read_lock();
2359                                if (success)
2360                                        break;
2361                        }
2362                        sl++;
2363                        if (sl == conf->copies)
2364                                sl = 0;
2365                } while (!success && sl != r10_bio->read_slot);
2366                rcu_read_unlock();
2367
2368                if (!success) {
2369                        /* Cannot read from anywhere, just mark the block
2370                         * as bad on the first device to discourage future
2371                         * reads.
2372                         */
2373                        int dn = r10_bio->devs[r10_bio->read_slot].devnum;
2374                        rdev = conf->mirrors[dn].rdev;
2375
2376                        if (!rdev_set_badblocks(
2377                                    rdev,
2378                                    r10_bio->devs[r10_bio->read_slot].addr
2379                                    + sect,
2380                                    s, 0)) {
2381                                md_error(mddev, rdev);
2382                                r10_bio->devs[r10_bio->read_slot].bio
2383                                        = IO_BLOCKED;
2384                        }
2385                        break;
2386                }
2387
2388                start = sl;
2389                /* write it back and re-read */
2390                rcu_read_lock();
2391                while (sl != r10_bio->read_slot) {
2392                        char b[BDEVNAME_SIZE];
2393
2394                        if (sl==0)
2395                                sl = conf->copies;
2396                        sl--;
2397                        d = r10_bio->devs[sl].devnum;
2398                        rdev = rcu_dereference(conf->mirrors[d].rdev);
2399                        if (!rdev ||
2400                            test_bit(Unmerged, &rdev->flags) ||
2401                            !test_bit(In_sync, &rdev->flags))
2402                                continue;
2403
2404                        atomic_inc(&rdev->nr_pending);
2405                        rcu_read_unlock();
2406                        if (r10_sync_page_io(rdev,
2407                                             r10_bio->devs[sl].addr +
2408                                             sect,
2409                                             s, conf->tmppage, WRITE)
2410                            == 0) {
2411                                /* Well, this device is dead */
2412                                printk(KERN_NOTICE
2413                                       "md/raid10:%s: read correction "
2414                                       "write failed"
2415                                       " (%d sectors at %llu on %s)\n",
2416                                       mdname(mddev), s,
2417                                       (unsigned long long)(
2418                                               sect +
2419                                               choose_data_offset(r10_bio,
2420                                                                  rdev)),
2421                                       bdevname(rdev->bdev, b));
2422                                printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2423                                       "drive\n",
2424                                       mdname(mddev),
2425                                       bdevname(rdev->bdev, b));
2426                        }
2427                        rdev_dec_pending(rdev, mddev);
2428                        rcu_read_lock();
2429                }
2430                sl = start;
2431                while (sl != r10_bio->read_slot) {
2432                        char b[BDEVNAME_SIZE];
2433
2434                        if (sl==0)
2435                                sl = conf->copies;
2436                        sl--;
2437                        d = r10_bio->devs[sl].devnum;
2438                        rdev = rcu_dereference(conf->mirrors[d].rdev);
2439                        if (!rdev ||
2440                            !test_bit(In_sync, &rdev->flags))
2441                                continue;
2442
2443                        atomic_inc(&rdev->nr_pending);
2444                        rcu_read_unlock();
2445                        switch (r10_sync_page_io(rdev,
2446                                             r10_bio->devs[sl].addr +
2447                                             sect,
2448                                             s, conf->tmppage,
2449                                                 READ)) {
2450                        case 0:
2451                                /* Well, this device is dead */
2452                                printk(KERN_NOTICE
2453                                       "md/raid10:%s: unable to read back "
2454                                       "corrected sectors"
2455                                       " (%d sectors at %llu on %s)\n",
2456                                       mdname(mddev), s,
2457                                       (unsigned long long)(
2458                                               sect +
2459                                               choose_data_offset(r10_bio, rdev)),
2460                                       bdevname(rdev->bdev, b));
2461                                printk(KERN_NOTICE "md/raid10:%s: %s: failing "
2462                                       "drive\n",
2463                                       mdname(mddev),
2464                                       bdevname(rdev->bdev, b));
2465                                break;
2466                        case 1:
2467                                printk(KERN_INFO
2468                                       "md/raid10:%s: read error corrected"
2469                                       " (%d sectors at %llu on %s)\n",
2470                                       mdname(mddev), s,
2471                                       (unsigned long long)(
2472                                               sect +
2473                                               choose_data_offset(r10_bio, rdev)),
2474                                       bdevname(rdev->bdev, b));
2475                                atomic_add(s, &rdev->corrected_errors);
2476                        }
2477
2478                        rdev_dec_pending(rdev, mddev);
2479                        rcu_read_lock();
2480                }
2481                rcu_read_unlock();
2482
2483                sectors -= s;
2484                sect += s;
2485        }
2486}
2487
2488static void bi_complete(struct bio *bio, int error)
2489{
2490        complete((struct completion *)bio->bi_private);
2491}
2492
2493static int submit_bio_wait(int rw, struct bio *bio)
2494{
2495        struct completion event;
2496        rw |= REQ_SYNC;
2497
2498        init_completion(&event);
2499        bio->bi_private = &event;
2500        bio->bi_end_io = bi_complete;
2501        submit_bio(rw, bio);
2502        wait_for_completion(&event);
2503
2504        return test_bit(BIO_UPTODATE, &bio->bi_flags);
2505}
2506
2507static int narrow_write_error(struct r10bio *r10_bio, int i)
2508{
2509        struct bio *bio = r10_bio->master_bio;
2510        struct mddev *mddev = r10_bio->mddev;
2511        struct r10conf *conf = mddev->private;
2512        struct md_rdev *rdev = conf->mirrors[r10_bio->devs[i].devnum].rdev;
2513        /* bio has the data to be written to slot 'i' where
2514         * we just recently had a write error.
2515         * We repeatedly clone the bio and trim down to one block,
2516         * then try the write.  Where the write fails we record
2517         * a bad block.
2518         * It is conceivable that the bio doesn't exactly align with
2519         * blocks.  We must handle this.
2520         *
2521         * We currently own a reference to the rdev.
2522         */
2523
2524        int block_sectors;
2525        sector_t sector;
2526        int sectors;
2527        int sect_to_write = r10_bio->sectors;
2528        int ok = 1;
2529
2530        if (rdev->badblocks.shift < 0)
2531                return 0;
2532
2533        block_sectors = 1 << rdev->badblocks.shift;
2534        sector = r10_bio->sector;
2535        sectors = ((r10_bio->sector + block_sectors)
2536                   & ~(sector_t)(block_sectors - 1))
2537                - sector;
2538
2539        while (sect_to_write) {
2540                struct bio *wbio;
2541                if (sectors > sect_to_write)
2542                        sectors = sect_to_write;
2543                /* Write at 'sector' for 'sectors' */
2544                wbio = bio_clone_mddev(bio, GFP_NOIO, mddev);
2545                md_trim_bio(wbio, sector - bio->bi_sector, sectors);
2546                wbio->bi_sector = (r10_bio->devs[i].addr+
2547                                   choose_data_offset(r10_bio, rdev) +
2548                                   (sector - r10_bio->sector));
2549                wbio->bi_bdev = rdev->bdev;
2550                if (submit_bio_wait(WRITE, wbio) == 0)
2551                        /* Failure! */
2552                        ok = rdev_set_badblocks(rdev, sector,
2553                                                sectors, 0)
2554                                && ok;
2555
2556                bio_put(wbio);
2557                sect_to_write -= sectors;
2558                sector += sectors;
2559                sectors = block_sectors;
2560        }
2561        return ok;
2562}
2563
2564static void handle_read_error(struct mddev *mddev, struct r10bio *r10_bio)
2565{
2566        int slot = r10_bio->read_slot;
2567        struct bio *bio;
2568        struct r10conf *conf = mddev->private;
2569        struct md_rdev *rdev = r10_bio->devs[slot].rdev;
2570        char b[BDEVNAME_SIZE];
2571        unsigned long do_sync;
2572        int max_sectors;
2573
2574        /* we got a read error. Maybe the drive is bad.  Maybe just
2575         * the block and we can fix it.
2576         * We freeze all other IO, and try reading the block from
2577         * other devices.  When we find one, we re-write
2578         * and check it that fixes the read error.
2579         * This is all done synchronously while the array is
2580         * frozen.
2581         */
2582        bio = r10_bio->devs[slot].bio;
2583        bdevname(bio->bi_bdev, b);
2584        bio_put(bio);
2585        r10_bio->devs[slot].bio = NULL;
2586
2587        if (mddev->ro == 0) {
2588                freeze_array(conf);
2589                fix_read_error(conf, mddev, r10_bio);
2590                unfreeze_array(conf);
2591        } else
2592                r10_bio->devs[slot].bio = IO_BLOCKED;
2593
2594        rdev_dec_pending(rdev, mddev);
2595
2596read_more:
2597        rdev = read_balance(conf, r10_bio, &max_sectors);
2598        if (rdev == NULL) {
2599                printk(KERN_ALERT "md/raid10:%s: %s: unrecoverable I/O"
2600                       " read error for block %llu\n",
2601                       mdname(mddev), b,
2602                       (unsigned long long)r10_bio->sector);
2603                raid_end_bio_io(r10_bio);
2604                return;
2605        }
2606
2607        do_sync = (r10_bio->master_bio->bi_rw & REQ_SYNC);
2608        slot = r10_bio->read_slot;
2609        printk_ratelimited(
2610                KERN_ERR
2611                "md/raid10:%s: %s: redirecting "
2612                "sector %llu to another mirror\n",
2613                mdname(mddev),
2614                bdevname(rdev->bdev, b),
2615                (unsigned long long)r10_bio->sector);
2616        bio = bio_clone_mddev(r10_bio->master_bio,
2617                              GFP_NOIO, mddev);
2618        md_trim_bio(bio,
2619                    r10_bio->sector - bio->bi_sector,
2620                    max_sectors);
2621        r10_bio->devs[slot].bio = bio;
2622        r10_bio->devs[slot].rdev = rdev;
2623        bio->bi_sector = r10_bio->devs[slot].addr
2624                + choose_data_offset(r10_bio, rdev);
2625        bio->bi_bdev = rdev->bdev;
2626        bio->bi_rw = READ | do_sync;
2627        bio->bi_private = r10_bio;
2628        bio->bi_end_io = raid10_end_read_request;
2629        if (max_sectors < r10_bio->sectors) {
2630                /* Drat - have to split this up more */
2631                struct bio *mbio = r10_bio->master_bio;
2632                int sectors_handled =
2633                        r10_bio->sector + max_sectors
2634                        - mbio->bi_sector;
2635                r10_bio->sectors = max_sectors;
2636                spin_lock_irq(&conf->device_lock);
2637                if (mbio->bi_phys_segments == 0)
2638                        mbio->bi_phys_segments = 2;
2639                else
2640                        mbio->bi_phys_segments++;
2641                spin_unlock_irq(&conf->device_lock);
2642                generic_make_request(bio);
2643
2644                r10_bio = mempool_alloc(conf->r10bio_pool,
2645                                        GFP_NOIO);
2646                r10_bio->master_bio = mbio;
2647                r10_bio->sectors = (mbio->bi_size >> 9)
2648                        - sectors_handled;
2649                r10_bio->state = 0;
2650                set_bit(R10BIO_ReadError,
2651                        &r10_bio->state);
2652                r10_bio->mddev = mddev;
2653                r10_bio->sector = mbio->bi_sector
2654                        + sectors_handled;
2655
2656                goto read_more;
2657        } else
2658                generic_make_request(bio);
2659}
2660
2661static void handle_write_completed(struct r10conf *conf, struct r10bio *r10_bio)
2662{
2663        /* Some sort of write request has finished and it
2664         * succeeded in writing where we thought there was a
2665         * bad block.  So forget the bad block.
2666         * Or possibly if failed and we need to record
2667         * a bad block.
2668         */
2669        int m;
2670        struct md_rdev *rdev;
2671
2672        if (test_bit(R10BIO_IsSync, &r10_bio->state) ||
2673            test_bit(R10BIO_IsRecover, &r10_bio->state)) {
2674                for (m = 0; m < conf->copies; m++) {
2675                        int dev = r10_bio->devs[m].devnum;
2676                        rdev = conf->mirrors[dev].rdev;
2677                        if (r10_bio->devs[m].bio == NULL)
2678                                continue;
2679                        if (test_bit(BIO_UPTODATE,
2680                                     &r10_bio->devs[m].bio->bi_flags)) {
2681                                rdev_clear_badblocks(
2682                                        rdev,
2683                                        r10_bio->devs[m].addr,
2684                                        r10_bio->sectors, 0);
2685                        } else {
2686                                if (!rdev_set_badblocks(
2687                                            rdev,
2688                                            r10_bio->devs[m].addr,
2689                                            r10_bio->sectors, 0))
2690                                        md_error(conf->mddev, rdev);
2691                        }
2692                        rdev = conf->mirrors[dev].replacement;
2693                        if (r10_bio->devs[m].repl_bio == NULL)
2694                                continue;
2695                        if (test_bit(BIO_UPTODATE,
2696                                     &r10_bio->devs[m].repl_bio->bi_flags)) {
2697                                rdev_clear_badblocks(
2698                                        rdev,
2699                                        r10_bio->devs[m].addr,
2700                                        r10_bio->sectors, 0);
2701                        } else {
2702                                if (!rdev_set_badblocks(
2703                                            rdev,
2704                                            r10_bio->devs[m].addr,
2705                                            r10_bio->sectors, 0))
2706                                        md_error(conf->mddev, rdev);
2707                        }
2708                }
2709                put_buf(r10_bio);
2710        } else {
2711                for (m = 0; m < conf->copies; m++) {
2712                        int dev = r10_bio->devs[m].devnum;
2713                        struct bio *bio = r10_bio->devs[m].bio;
2714                        rdev = conf->mirrors[dev].rdev;
2715                        if (bio == IO_MADE_GOOD) {
2716                                rdev_clear_badblocks(
2717                                        rdev,
2718                                        r10_bio->devs[m].addr,
2719                                        r10_bio->sectors, 0);
2720                                rdev_dec_pending(rdev, conf->mddev);
2721                        } else if (bio != NULL &&
2722                                   !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
2723                                if (!narrow_write_error(r10_bio, m)) {
2724                                        md_error(conf->mddev, rdev);
2725                                        set_bit(R10BIO_Degraded,
2726                                                &r10_bio->state);
2727                                }
2728                                rdev_dec_pending(rdev, conf->mddev);
2729                        }
2730                        bio = r10_bio->devs[m].repl_bio;
2731                        rdev = conf->mirrors[dev].replacement;
2732                        if (rdev && bio == IO_MADE_GOOD) {
2733                                rdev_clear_badblocks(
2734                                        rdev,
2735                                        r10_bio->devs[m].addr,
2736                                        r10_bio->sectors, 0);
2737                                rdev_dec_pending(rdev, conf->mddev);
2738                        }
2739                }
2740                if (test_bit(R10BIO_WriteError,
2741                             &r10_bio->state))
2742                        close_write(r10_bio);
2743                raid_end_bio_io(r10_bio);
2744        }
2745}
2746
2747static void raid10d(struct md_thread *thread)
2748{
2749        struct mddev *mddev = thread->mddev;
2750        struct r10bio *r10_bio;
2751        unsigned long flags;
2752        struct r10conf *conf = mddev->private;
2753        struct list_head *head = &conf->retry_list;
2754        struct blk_plug plug;
2755
2756        md_check_recovery(mddev);
2757
2758        blk_start_plug(&plug);
2759        for (;;) {
2760
2761                flush_pending_writes(conf);
2762
2763                spin_lock_irqsave(&conf->device_lock, flags);
2764                if (list_empty(head)) {
2765                        spin_unlock_irqrestore(&conf->device_lock, flags);
2766                        break;
2767                }
2768                r10_bio = list_entry(head->prev, struct r10bio, retry_list);
2769                list_del(head->prev);
2770                conf->nr_queued--;
2771                spin_unlock_irqrestore(&conf->device_lock, flags);
2772
2773                mddev = r10_bio->mddev;
2774                conf = mddev->private;
2775                if (test_bit(R10BIO_MadeGood, &r10_bio->state) ||
2776                    test_bit(R10BIO_WriteError, &r10_bio->state))
2777                        handle_write_completed(conf, r10_bio);
2778                else if (test_bit(R10BIO_IsReshape, &r10_bio->state))
2779                        reshape_request_write(mddev, r10_bio);
2780                else if (test_bit(R10BIO_IsSync, &r10_bio->state))
2781                        sync_request_write(mddev, r10_bio);
2782                else if (test_bit(R10BIO_IsRecover, &r10_bio->state))
2783                        recovery_request_write(mddev, r10_bio);
2784                else if (test_bit(R10BIO_ReadError, &r10_bio->state))
2785                        handle_read_error(mddev, r10_bio);
2786                else {
2787                        /* just a partial read to be scheduled from a
2788                         * separate context
2789                         */
2790                        int slot = r10_bio->read_slot;
2791                        generic_make_request(r10_bio->devs[slot].bio);
2792                }
2793
2794                cond_resched();
2795                if (mddev->flags & ~(1<<MD_CHANGE_PENDING))
2796                        md_check_recovery(mddev);
2797        }
2798        blk_finish_plug(&plug);
2799}
2800
2801
2802static int init_resync(struct r10conf *conf)
2803{
2804        int buffs;
2805        int i;
2806
2807        buffs = RESYNC_WINDOW / RESYNC_BLOCK_SIZE;
2808        BUG_ON(conf->r10buf_pool);
2809        conf->have_replacement = 0;
2810        for (i = 0; i < conf->geo.raid_disks; i++)
2811                if (conf->mirrors[i].replacement)
2812                        conf->have_replacement = 1;
2813        conf->r10buf_pool = mempool_create(buffs, r10buf_pool_alloc, r10buf_pool_free, conf);
2814        if (!conf->r10buf_pool)
2815                return -ENOMEM;
2816        conf->next_resync = 0;
2817        return 0;
2818}
2819
2820/*
2821 * perform a "sync" on one "block"
2822 *
2823 * We need to make sure that no normal I/O request - particularly write
2824 * requests - conflict with active sync requests.
2825 *
2826 * This is achieved by tracking pending requests and a 'barrier' concept
2827 * that can be installed to exclude normal IO requests.
2828 *
2829 * Resync and recovery are handled very differently.
2830 * We differentiate by looking at MD_RECOVERY_SYNC in mddev->recovery.
2831 *
2832 * For resync, we iterate over virtual addresses, read all copies,
2833 * and update if there are differences.  If only one copy is live,
2834 * skip it.
2835 * For recovery, we iterate over physical addresses, read a good
2836 * value for each non-in_sync drive, and over-write.
2837 *
2838 * So, for recovery we may have several outstanding complex requests for a
2839 * given address, one for each out-of-sync device.  We model this by allocating
2840 * a number of r10_bio structures, one for each out-of-sync device.
2841 * As we setup these structures, we collect all bio's together into a list
2842 * which we then process collectively to add pages, and then process again
2843 * to pass to generic_make_request.
2844 *
2845 * The r10_bio structures are linked using a borrowed master_bio pointer.
2846 * This link is counted in ->remaining.  When the r10_bio that points to NULL
2847 * has its remaining count decremented to 0, the whole complex operation
2848 * is complete.
2849 *
2850 */
2851
2852static sector_t sync_request(struct mddev *mddev, sector_t sector_nr,
2853                             int *skipped, int go_faster)
2854{
2855        struct r10conf *conf = mddev->private;
2856        struct r10bio *r10_bio;
2857        struct bio *biolist = NULL, *bio;
2858        sector_t max_sector, nr_sectors;
2859        int i;
2860        int max_sync;
2861        sector_t sync_blocks;
2862        sector_t sectors_skipped = 0;
2863        int chunks_skipped = 0;
2864        sector_t chunk_mask = conf->geo.chunk_mask;
2865
2866        if (!conf->r10buf_pool)
2867                if (init_resync(conf))
2868                        return 0;
2869
2870 skipped:
2871        max_sector = mddev->dev_sectors;
2872        if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
2873            test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2874                max_sector = mddev->resync_max_sectors;
2875        if (sector_nr >= max_sector) {
2876                /* If we aborted, we need to abort the
2877                 * sync on the 'current' bitmap chucks (there can
2878                 * be several when recovering multiple devices).
2879                 * as we may have started syncing it but not finished.
2880                 * We can find the current address in
2881                 * mddev->curr_resync, but for recovery,
2882                 * we need to convert that to several
2883                 * virtual addresses.
2884                 */
2885                if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
2886                        end_reshape(conf);
2887                        return 0;
2888                }
2889
2890                if (mddev->curr_resync < max_sector) { /* aborted */
2891                        if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
2892                                bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
2893                                                &sync_blocks, 1);
2894                        else for (i = 0; i < conf->geo.raid_disks; i++) {
2895                                sector_t sect =
2896                                        raid10_find_virt(conf, mddev->curr_resync, i);
2897                                bitmap_end_sync(mddev->bitmap, sect,
2898                                                &sync_blocks, 1);
2899                        }
2900                } else {
2901                        /* completed sync */
2902                        if ((!mddev->bitmap || conf->fullsync)
2903                            && conf->have_replacement
2904                            && test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2905                                /* Completed a full sync so the replacements
2906                                 * are now fully recovered.
2907                                 */
2908                                for (i = 0; i < conf->geo.raid_disks; i++)
2909                                        if (conf->mirrors[i].replacement)
2910                                                conf->mirrors[i].replacement
2911                                                        ->recovery_offset
2912                                                        = MaxSector;
2913                        }
2914                        conf->fullsync = 0;
2915                }
2916                bitmap_close_sync(mddev->bitmap);
2917                close_sync(conf);
2918                *skipped = 1;
2919                return sectors_skipped;
2920        }
2921
2922        if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
2923                return reshape_request(mddev, sector_nr, skipped);
2924
2925        if (chunks_skipped >= conf->geo.raid_disks) {
2926                /* if there has been nothing to do on any drive,
2927                 * then there is nothing to do at all..
2928                 */
2929                *skipped = 1;
2930                return (max_sector - sector_nr) + sectors_skipped;
2931        }
2932
2933        if (max_sector > mddev->resync_max)
2934                max_sector = mddev->resync_max; /* Don't do IO beyond here */
2935
2936        /* make sure whole request will fit in a chunk - if chunks
2937         * are meaningful
2938         */
2939        if (conf->geo.near_copies < conf->geo.raid_disks &&
2940            max_sector > (sector_nr | chunk_mask))
2941                max_sector = (sector_nr | chunk_mask) + 1;
2942        /*
2943         * If there is non-resync activity waiting for us then
2944         * put in a delay to throttle resync.
2945         */
2946        if (!go_faster && conf->nr_waiting)
2947                msleep_interruptible(1000);
2948
2949        /* Again, very different code for resync and recovery.
2950         * Both must result in an r10bio with a list of bios that
2951         * have bi_end_io, bi_sector, bi_bdev set,
2952         * and bi_private set to the r10bio.
2953         * For recovery, we may actually create several r10bios
2954         * with 2 bios in each, that correspond to the bios in the main one.
2955         * In this case, the subordinate r10bios link back through a
2956         * borrowed master_bio pointer, and the counter in the master
2957         * includes a ref from each subordinate.
2958         */
2959        /* First, we decide what to do and set ->bi_end_io
2960         * To end_sync_read if we want to read, and
2961         * end_sync_write if we will want to write.
2962         */
2963
2964        max_sync = RESYNC_PAGES << (PAGE_SHIFT-9);
2965        if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
2966                /* recovery... the complicated one */
2967                int j;
2968                r10_bio = NULL;
2969
2970                for (i = 0 ; i < conf->geo.raid_disks; i++) {
2971                        int still_degraded;
2972                        struct r10bio *rb2;
2973                        sector_t sect;
2974                        int must_sync;
2975                        int any_working;
2976                        struct raid10_info *mirror = &conf->mirrors[i];
2977
2978                        if ((mirror->rdev == NULL ||
2979                             test_bit(In_sync, &mirror->rdev->flags))
2980                            &&
2981                            (mirror->replacement == NULL ||
2982                             test_bit(Faulty,
2983                                      &mirror->replacement->flags)))
2984                                continue;
2985
2986                        still_degraded = 0;
2987                        /* want to reconstruct this device */
2988                        rb2 = r10_bio;
2989                        sect = raid10_find_virt(conf, sector_nr, i);
2990                        if (sect >= mddev->resync_max_sectors) {
2991                                /* last stripe is not complete - don't
2992                                 * try to recover this sector.
2993                                 */
2994                                continue;
2995                        }
2996                        /* Unless we are doing a full sync, or a replacement
2997                         * we only need to recover the block if it is set in
2998                         * the bitmap
2999                         */
3000                        must_sync = bitmap_start_sync(mddev->bitmap, sect,
3001                                                      &sync_blocks, 1);
3002                        if (sync_blocks < max_sync)
3003                                max_sync = sync_blocks;
3004                        if (!must_sync &&
3005                            mirror->replacement == NULL &&
3006                            !conf->fullsync) {
3007                                /* yep, skip the sync_blocks here, but don't assume
3008                                 * that there will never be anything to do here
3009                                 */
3010                                chunks_skipped = -1;
3011                                continue;
3012                        }
3013
3014                        r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
3015                        raise_barrier(conf, rb2 != NULL);
3016                        atomic_set(&r10_bio->remaining, 0);
3017
3018                        r10_bio->master_bio = (struct bio*)rb2;
3019                        if (rb2)
3020                                atomic_inc(&rb2->remaining);
3021                        r10_bio->mddev = mddev;
3022                        set_bit(R10BIO_IsRecover, &r10_bio->state);
3023                        r10_bio->sector = sect;
3024
3025                        raid10_find_phys(conf, r10_bio);
3026
3027                        /* Need to check if the array will still be
3028                         * degraded
3029                         */
3030                        for (j = 0; j < conf->geo.raid_disks; j++)
3031                                if (conf->mirrors[j].rdev == NULL ||
3032                                    test_bit(Faulty, &conf->mirrors[j].rdev->flags)) {
3033                                        still_degraded = 1;
3034                                        break;
3035                                }
3036
3037                        must_sync = bitmap_start_sync(mddev->bitmap, sect,
3038                                                      &sync_blocks, still_degraded);
3039
3040                        any_working = 0;
3041                        for (j=0; j<conf->copies;j++) {
3042                                int k;
3043                                int d = r10_bio->devs[j].devnum;
3044                                sector_t from_addr, to_addr;
3045                                struct md_rdev *rdev;
3046                                sector_t sector, first_bad;
3047                                int bad_sectors;
3048                                if (!conf->mirrors[d].rdev ||
3049                                    !test_bit(In_sync, &conf->mirrors[d].rdev->flags))
3050                                        continue;
3051                                /* This is where we read from */
3052                                any_working = 1;
3053                                rdev = conf->mirrors[d].rdev;
3054                                sector = r10_bio->devs[j].addr;
3055
3056                                if (is_badblock(rdev, sector, max_sync,
3057                                                &first_bad, &bad_sectors)) {
3058                                        if (first_bad > sector)
3059                                                max_sync = first_bad - sector;
3060                                        else {
3061                                                bad_sectors -= (sector
3062                                                                - first_bad);
3063                                                if (max_sync > bad_sectors)
3064                                                        max_sync = bad_sectors;
3065                                                continue;
3066                                        }
3067                                }
3068                                bio = r10_bio->devs[0].bio;
3069                                bio->bi_next = biolist;
3070                                biolist = bio;
3071                                bio->bi_private = r10_bio;
3072                                bio->bi_end_io = end_sync_read;
3073                                bio->bi_rw = READ;
3074                                from_addr = r10_bio->devs[j].addr;
3075                                bio->bi_sector = from_addr + rdev->data_offset;
3076                                bio->bi_bdev = rdev->bdev;
3077                                atomic_inc(&rdev->nr_pending);
3078                                /* and we write to 'i' (if not in_sync) */
3079
3080                                for (k=0; k<conf->copies; k++)
3081                                        if (r10_bio->devs[k].devnum == i)
3082                                                break;
3083                                BUG_ON(k == conf->copies);
3084                                to_addr = r10_bio->devs[k].addr;
3085                                r10_bio->devs[0].devnum = d;
3086                                r10_bio->devs[0].addr = from_addr;
3087                                r10_bio->devs[1].devnum = i;
3088                                r10_bio->devs[1].addr = to_addr;
3089
3090                                rdev = mirror->rdev;
3091                                if (!test_bit(In_sync, &rdev->flags)) {
3092                                        bio = r10_bio->devs[1].bio;
3093                                        bio->bi_next = biolist;
3094                                        biolist = bio;
3095                                        bio->bi_private = r10_bio;
3096                                        bio->bi_end_io = end_sync_write;
3097                                        bio->bi_rw = WRITE;
3098                                        bio->bi_sector = to_addr
3099                                                + rdev->data_offset;
3100                                        bio->bi_bdev = rdev->bdev;
3101                                        atomic_inc(&r10_bio->remaining);
3102                                } else
3103                                        r10_bio->devs[1].bio->bi_end_io = NULL;
3104
3105                                /* and maybe write to replacement */
3106                                bio = r10_bio->devs[1].repl_bio;
3107                                if (bio)
3108                                        bio->bi_end_io = NULL;
3109                                rdev = mirror->replacement;
3110                                /* Note: if rdev != NULL, then bio
3111                                 * cannot be NULL as r10buf_pool_alloc will
3112                                 * have allocated it.
3113                                 * So the second test here is pointless.
3114                                 * But it keeps semantic-checkers happy, and
3115                                 * this comment keeps human reviewers
3116                                 * happy.
3117                                 */
3118                                if (rdev == NULL || bio == NULL ||
3119                                    test_bit(Faulty, &rdev->flags))
3120                                        break;
3121                                bio->bi_next = biolist;
3122                                biolist = bio;
3123                                bio->bi_private = r10_bio;
3124                                bio->bi_end_io = end_sync_write;
3125                                bio->bi_rw = WRITE;
3126                                bio->bi_sector = to_addr + rdev->data_offset;
3127                                bio->bi_bdev = rdev->bdev;
3128                                atomic_inc(&r10_bio->remaining);
3129                                break;
3130                        }
3131                        if (j == conf->copies) {
3132                                /* Cannot recover, so abort the recovery or
3133                                 * record a bad block */
3134                                put_buf(r10_bio);
3135                                if (rb2)
3136                                        atomic_dec(&rb2->remaining);
3137                                r10_bio = rb2;
3138                                if (any_working) {
3139                                        /* problem is that there are bad blocks
3140                                         * on other device(s)
3141                                         */
3142                                        int k;
3143                                        for (k = 0; k < conf->copies; k++)
3144                                                if (r10_bio->devs[k].devnum == i)
3145                                                        break;
3146                                        if (!test_bit(In_sync,
3147                                                      &mirror->rdev->flags)
3148                                            && !rdev_set_badblocks(
3149                                                    mirror->rdev,
3150                                                    r10_bio->devs[k].addr,
3151                                                    max_sync, 0))
3152                                                any_working = 0;
3153                                        if (mirror->replacement &&
3154                                            !rdev_set_badblocks(
3155                                                    mirror->replacement,
3156                                                    r10_bio->devs[k].addr,
3157                                                    max_sync, 0))
3158                                                any_working = 0;
3159                                }
3160                                if (!any_working)  {
3161                                        if (!test_and_set_bit(MD_RECOVERY_INTR,
3162                                                              &mddev->recovery))
3163                                                printk(KERN_INFO "md/raid10:%s: insufficient "
3164                                                       "working devices for recovery.\n",
3165                                                       mdname(mddev));
3166                                        mirror->recovery_disabled
3167                                                = mddev->recovery_disabled;
3168                                }
3169                                break;
3170                        }
3171                }
3172                if (biolist == NULL) {
3173                        while (r10_bio) {
3174                                struct r10bio *rb2 = r10_bio;
3175                                r10_bio = (struct r10bio*) rb2->master_bio;
3176                                rb2->master_bio = NULL;
3177                                put_buf(rb2);
3178                        }
3179                        goto giveup;
3180                }
3181        } else {
3182                /* resync. Schedule a read for every block at this virt offset */
3183                int count = 0;
3184
3185                bitmap_cond_end_sync(mddev->bitmap, sector_nr);
3186
3187                if (!bitmap_start_sync(mddev->bitmap, sector_nr,
3188                                       &sync_blocks, mddev->degraded) &&
3189                    !conf->fullsync && !test_bit(MD_RECOVERY_REQUESTED,
3190                                                 &mddev->recovery)) {
3191                        /* We can skip this block */
3192                        *skipped = 1;
3193                        return sync_blocks + sectors_skipped;
3194                }
3195                if (sync_blocks < max_sync)
3196                        max_sync = sync_blocks;
3197                r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
3198
3199                r10_bio->mddev = mddev;
3200                atomic_set(&r10_bio->remaining, 0);
3201                raise_barrier(conf, 0);
3202                conf->next_resync = sector_nr;
3203
3204                r10_bio->master_bio = NULL;
3205                r10_bio->sector = sector_nr;
3206                set_bit(R10BIO_IsSync, &r10_bio->state);
3207                raid10_find_phys(conf, r10_bio);
3208                r10_bio->sectors = (sector_nr | chunk_mask) - sector_nr + 1;
3209
3210                for (i = 0; i < conf->copies; i++) {
3211                        int d = r10_bio->devs[i].devnum;
3212                        sector_t first_bad, sector;
3213                        int bad_sectors;
3214
3215                        if (r10_bio->devs[i].repl_bio)
3216                                r10_bio->devs[i].repl_bio->bi_end_io = NULL;
3217
3218                        bio = r10_bio->devs[i].bio;
3219                        bio->bi_end_io = NULL;
3220                        clear_bit(BIO_UPTODATE, &bio->bi_flags);
3221                        if (conf->mirrors[d].rdev == NULL ||
3222                            test_bit(Faulty, &conf->mirrors[d].rdev->flags))
3223                                continue;
3224                        sector = r10_bio->devs[i].addr;
3225                        if (is_badblock(conf->mirrors[d].rdev,
3226                                        sector, max_sync,
3227                                        &first_bad, &bad_sectors)) {
3228                                if (first_bad > sector)
3229                                        max_sync = first_bad - sector;
3230                                else {
3231                                        bad_sectors -= (sector - first_bad);
3232                                        if (max_sync > bad_sectors)
3233                                                max_sync = bad_sectors;
3234                                        continue;
3235                                }
3236                        }
3237                        atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3238                        atomic_inc(&r10_bio->remaining);
3239                        bio->bi_next = biolist;
3240                        biolist = bio;
3241                        bio->bi_private = r10_bio;
3242                        bio->bi_end_io = end_sync_read;
3243                        bio->bi_rw = READ;
3244                        bio->bi_sector = sector +
3245                                conf->mirrors[d].rdev->data_offset;
3246                        bio->bi_bdev = conf->mirrors[d].rdev->bdev;
3247                        count++;
3248
3249                        if (conf->mirrors[d].replacement == NULL ||
3250                            test_bit(Faulty,
3251                                     &conf->mirrors[d].replacement->flags))
3252                                continue;
3253
3254                        /* Need to set up for writing to the replacement */
3255                        bio = r10_bio->devs[i].repl_bio;
3256                        clear_bit(BIO_UPTODATE, &bio->bi_flags);
3257
3258                        sector = r10_bio->devs[i].addr;
3259                        atomic_inc(&conf->mirrors[d].rdev->nr_pending);
3260                        bio->bi_next = biolist;
3261                        biolist = bio;
3262                        bio->bi_private = r10_bio;
3263                        bio->bi_end_io = end_sync_write;
3264                        bio->bi_rw = WRITE;
3265                        bio->bi_sector = sector +
3266                                conf->mirrors[d].replacement->data_offset;
3267                        bio->bi_bdev = conf->mirrors[d].replacement->bdev;
3268                        count++;
3269                }
3270
3271                if (count < 2) {
3272                        for (i=0; i<conf->copies; i++) {
3273                                int d = r10_bio->devs[i].devnum;
3274                                if (r10_bio->devs[i].bio->bi_end_io)
3275                                        rdev_dec_pending(conf->mirrors[d].rdev,
3276                                                         mddev);
3277                                if (r10_bio->devs[i].repl_bio &&
3278                                    r10_bio->devs[i].repl_bio->bi_end_io)
3279                                        rdev_dec_pending(
3280                                                conf->mirrors[d].replacement,
3281                                                mddev);
3282                        }
3283                        put_buf(r10_bio);
3284                        biolist = NULL;
3285                        goto giveup;
3286                }
3287        }
3288
3289        for (bio = biolist; bio ; bio=bio->bi_next) {
3290
3291                bio->bi_flags &= ~(BIO_POOL_MASK - 1);
3292                if (bio->bi_end_io)
3293                        bio->bi_flags |= 1 << BIO_UPTODATE;
3294                bio->bi_vcnt = 0;
3295                bio->bi_idx = 0;
3296                bio->bi_phys_segments = 0;
3297                bio->bi_size = 0;
3298        }
3299
3300        nr_sectors = 0;
3301        if (sector_nr + max_sync < max_sector)
3302                max_sector = sector_nr + max_sync;
3303        do {
3304                struct page *page;
3305                int len = PAGE_SIZE;
3306                if (sector_nr + (len>>9) > max_sector)
3307                        len = (max_sector - sector_nr) << 9;
3308                if (len == 0)
3309                        break;
3310                for (bio= biolist ; bio ; bio=bio->bi_next) {
3311                        struct bio *bio2;
3312                        page = bio->bi_io_vec[bio->bi_vcnt].bv_page;
3313                        if (bio_add_page(bio, page, len, 0))
3314                                continue;
3315
3316                        /* stop here */
3317                        bio->bi_io_vec[bio->bi_vcnt].bv_page = page;
3318                        for (bio2 = biolist;
3319                             bio2 && bio2 != bio;
3320                             bio2 = bio2->bi_next) {
3321                                /* remove last page from this bio */
3322                                bio2->bi_vcnt--;
3323                                bio2->bi_size -= len;
3324                                bio2->bi_flags &= ~(1<< BIO_SEG_VALID);
3325                        }
3326                        goto bio_full;
3327                }
3328                nr_sectors += len>>9;
3329                sector_nr += len>>9;
3330        } while (biolist->bi_vcnt < RESYNC_PAGES);
3331 bio_full:
3332        r10_bio->sectors = nr_sectors;
3333
3334        while (biolist) {
3335                bio = biolist;
3336                biolist = biolist->bi_next;
3337
3338                bio->bi_next = NULL;
3339                r10_bio = bio->bi_private;
3340                r10_bio->sectors = nr_sectors;
3341
3342                if (bio->bi_end_io == end_sync_read) {
3343                        md_sync_acct(bio->bi_bdev, nr_sectors);
3344                        generic_make_request(bio);
3345                }
3346        }
3347
3348        if (sectors_skipped)
3349                /* pretend they weren't skipped, it makes
3350                 * no important difference in this case
3351                 */
3352                md_done_sync(mddev, sectors_skipped, 1);
3353
3354        return sectors_skipped + nr_sectors;
3355 giveup:
3356        /* There is nowhere to write, so all non-sync
3357         * drives must be failed or in resync, all drives
3358         * have a bad block, so try the next chunk...
3359         */
3360        if (sector_nr + max_sync < max_sector)
3361                max_sector = sector_nr + max_sync;
3362
3363        sectors_skipped += (max_sector - sector_nr);
3364        chunks_skipped ++;
3365        sector_nr = max_sector;
3366        goto skipped;
3367}
3368
3369static sector_t
3370raid10_size(struct mddev *mddev, sector_t sectors, int raid_disks)
3371{
3372        sector_t size;
3373        struct r10conf *conf = mddev->private;
3374
3375        if (!raid_disks)
3376                raid_disks = min(conf->geo.raid_disks,
3377                                 conf->prev.raid_disks);
3378        if (!sectors)
3379                sectors = conf->dev_sectors;
3380
3381        size = sectors >> conf->geo.chunk_shift;
3382        sector_div(size, conf->geo.far_copies);
3383        size = size * raid_disks;
3384        sector_div(size, conf->geo.near_copies);
3385
3386        return size << conf->geo.chunk_shift;
3387}
3388
3389static void calc_sectors(struct r10conf *conf, sector_t size)
3390{
3391        /* Calculate the number of sectors-per-device that will
3392         * actually be used, and set conf->dev_sectors and
3393         * conf->stride
3394         */
3395
3396        size = size >> conf->geo.chunk_shift;
3397        sector_div(size, conf->geo.far_copies);
3398        size = size * conf->geo.raid_disks;
3399        sector_div(size, conf->geo.near_copies);
3400        /* 'size' is now the number of chunks in the array */
3401        /* calculate "used chunks per device" */
3402        size = size * conf->copies;
3403
3404        /* We need to round up when dividing by raid_disks to
3405         * get the stride size.
3406         */
3407        size = DIV_ROUND_UP_SECTOR_T(size, conf->geo.raid_disks);
3408
3409        conf->dev_sectors = size << conf->geo.chunk_shift;
3410
3411        if (conf->geo.far_offset)
3412                conf->geo.stride = 1 << conf->geo.chunk_shift;
3413        else {
3414                sector_div(size, conf->geo.far_copies);
3415                conf->geo.stride = size << conf->geo.chunk_shift;
3416        }
3417}
3418
3419enum geo_type {geo_new, geo_old, geo_start};
3420static int setup_geo(struct geom *geo, struct mddev *mddev, enum geo_type new)
3421{
3422        int nc, fc, fo;
3423        int layout, chunk, disks;
3424        switch (new) {
3425        case geo_old:
3426                layout = mddev->layout;
3427                chunk = mddev->chunk_sectors;
3428                disks = mddev->raid_disks - mddev->delta_disks;
3429                break;
3430        case geo_new:
3431                layout = mddev->new_layout;
3432                chunk = mddev->new_chunk_sectors;
3433                disks = mddev->raid_disks;
3434                break;
3435        default: /* avoid 'may be unused' warnings */
3436        case geo_start: /* new when starting reshape - raid_disks not
3437                         * updated yet. */
3438                layout = mddev->new_layout;
3439                chunk = mddev->new_chunk_sectors;
3440                disks = mddev->raid_disks + mddev->delta_disks;
3441                break;
3442        }
3443        if (layout >> 17)
3444                return -1;
3445        if (chunk < (PAGE_SIZE >> 9) ||
3446            !is_power_of_2(chunk))
3447                return -2;
3448        nc = layout & 255;
3449        fc = (layout >> 8) & 255;
3450        fo = layout & (1<<16);
3451        geo->raid_disks = disks;
3452        geo->near_copies = nc;
3453        geo->far_copies = fc;
3454        geo->far_offset = fo;
3455        geo->chunk_mask = chunk - 1;
3456        geo->chunk_shift = ffz(~chunk);
3457        return nc*fc;
3458}
3459
3460static struct r10conf *setup_conf(struct mddev *mddev)
3461{
3462        struct r10conf *conf = NULL;
3463        int err = -EINVAL;
3464        struct geom geo;
3465        int copies;
3466
3467        copies = setup_geo(&geo, mddev, geo_new);
3468
3469        if (copies == -2) {
3470                printk(KERN_ERR "md/raid10:%s: chunk size must be "
3471                       "at least PAGE_SIZE(%ld) and be a power of 2.\n",
3472                       mdname(mddev), PAGE_SIZE);
3473                goto out;
3474        }
3475
3476        if (copies < 2 || copies > mddev->raid_disks) {
3477                printk(KERN_ERR "md/raid10:%s: unsupported raid10 layout: 0x%8x\n",
3478                       mdname(mddev), mddev->new_layout);
3479                goto out;
3480        }
3481
3482        err = -ENOMEM;
3483        conf = kzalloc(sizeof(struct r10conf), GFP_KERNEL);
3484        if (!conf)
3485                goto out;
3486
3487        /* FIXME calc properly */
3488        conf->mirrors = kzalloc(sizeof(struct raid10_info)*(mddev->raid_disks +
3489                                                            max(0,mddev->delta_disks)),
3490                                GFP_KERNEL);
3491        if (!conf->mirrors)
3492                goto out;
3493
3494        conf->tmppage = alloc_page(GFP_KERNEL);
3495        if (!conf->tmppage)
3496                goto out;
3497
3498        conf->geo = geo;
3499        conf->copies = copies;
3500        conf->r10bio_pool = mempool_create(NR_RAID10_BIOS, r10bio_pool_alloc,
3501                                           r10bio_pool_free, conf);
3502        if (!conf->r10bio_pool)
3503                goto out;
3504
3505        calc_sectors(conf, mddev->dev_sectors);
3506        if (mddev->reshape_position == MaxSector) {
3507                conf->prev = conf->geo;
3508                conf->reshape_progress = MaxSector;
3509        } else {
3510                if (setup_geo(&conf->prev, mddev, geo_old) != conf->copies) {
3511                        err = -EINVAL;
3512                        goto out;
3513                }
3514                conf->reshape_progress = mddev->reshape_position;
3515                if (conf->prev.far_offset)
3516                        conf->prev.stride = 1 << conf->prev.chunk_shift;
3517                else
3518                        /* far_copies must be 1 */
3519                        conf->prev.stride = conf->dev_sectors;
3520        }
3521        spin_lock_init(&conf->device_lock);
3522        INIT_LIST_HEAD(&conf->retry_list);
3523
3524        spin_lock_init(&conf->resync_lock);
3525        init_waitqueue_head(&conf->wait_barrier);
3526
3527        conf->thread = md_register_thread(raid10d, mddev, "raid10");
3528        if (!conf->thread)
3529                goto out;
3530
3531        conf->mddev = mddev;
3532        return conf;
3533
3534 out:
3535        if (err == -ENOMEM)
3536                printk(KERN_ERR "md/raid10:%s: couldn't allocate memory.\n",
3537                       mdname(mddev));
3538        if (conf) {
3539                if (conf->r10bio_pool)
3540                        mempool_destroy(conf->r10bio_pool);
3541                kfree(conf->mirrors);
3542                safe_put_page(conf->tmppage);
3543                kfree(conf);
3544        }
3545        return ERR_PTR(err);
3546}
3547
3548static int run(struct mddev *mddev)
3549{
3550        struct r10conf *conf;
3551        int i, disk_idx, chunk_size;
3552        struct raid10_info *disk;
3553        struct md_rdev *rdev;
3554        sector_t size;
3555        sector_t min_offset_diff = 0;
3556        int first = 1;
3557        bool discard_supported = false;
3558
3559        if (mddev->private == NULL) {
3560                conf = setup_conf(mddev);
3561                if (IS_ERR(conf))
3562                        return PTR_ERR(conf);
3563                mddev->private = conf;
3564        }
3565        conf = mddev->private;
3566        if (!conf)
3567                goto out;
3568
3569        mddev->thread = conf->thread;
3570        conf->thread = NULL;
3571
3572        chunk_size = mddev->chunk_sectors << 9;
3573        if (mddev->queue) {
3574                blk_queue_max_discard_sectors(mddev->queue,
3575                                              mddev->chunk_sectors);
3576                blk_queue_max_write_same_sectors(mddev->queue,
3577                                                 mddev->chunk_sectors);
3578                blk_queue_io_min(mddev->queue, chunk_size);
3579                if (conf->geo.raid_disks % conf->geo.near_copies)
3580                        blk_queue_io_opt(mddev->queue, chunk_size * conf->geo.raid_disks);
3581                else
3582                        blk_queue_io_opt(mddev->queue, chunk_size *
3583                                         (conf->geo.raid_disks / conf->geo.near_copies));
3584        }
3585
3586        rdev_for_each(rdev, mddev) {
3587                long long diff;
3588                struct request_queue *q;
3589
3590                disk_idx = rdev->raid_disk;
3591                if (disk_idx < 0)
3592                        continue;
3593                if (disk_idx >= conf->geo.raid_disks &&
3594                    disk_idx >= conf->prev.raid_disks)
3595                        continue;
3596                disk = conf->mirrors + disk_idx;
3597
3598                if (test_bit(Replacement, &rdev->flags)) {
3599                        if (disk->replacement)
3600                                goto out_free_conf;
3601                        disk->replacement = rdev;
3602                } else {
3603                        if (disk->rdev)
3604                                goto out_free_conf;
3605                        disk->rdev = rdev;
3606                }
3607                q = bdev_get_queue(rdev->bdev);
3608                if (q->merge_bvec_fn)
3609                        mddev->merge_check_needed = 1;
3610                diff = (rdev->new_data_offset - rdev->data_offset);
3611                if (!mddev->reshape_backwards)
3612                        diff = -diff;
3613                if (diff < 0)
3614                        diff = 0;
3615                if (first || diff < min_offset_diff)
3616                        min_offset_diff = diff;
3617
3618                if (mddev->gendisk)
3619                        disk_stack_limits(mddev->gendisk, rdev->bdev,
3620                                          rdev->data_offset << 9);
3621
3622                disk->head_position = 0;
3623
3624                if (blk_queue_discard(bdev_get_queue(rdev->bdev)))
3625                        discard_supported = true;
3626        }
3627
3628        if (mddev->queue) {
3629                if (discard_supported)
3630                        queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
3631                                                mddev->queue);
3632                else
3633                        queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD,
3634                                                  mddev->queue);
3635        }
3636        /* need to check that every block has at least one working mirror */
3637        if (!enough(conf, -1)) {
3638                printk(KERN_ERR "md/raid10:%s: not enough operational mirrors.\n",
3639                       mdname(mddev));
3640                goto out_free_conf;
3641        }
3642
3643        if (conf->reshape_progress != MaxSector) {
3644                /* must ensure that shape change is supported */
3645                if (conf->geo.far_copies != 1 &&
3646                    conf->geo.far_offset == 0)
3647                        goto out_free_conf;
3648                if (conf->prev.far_copies != 1 &&
3649                    conf->geo.far_offset == 0)
3650                        goto out_free_conf;
3651        }
3652
3653        mddev->degraded = 0;
3654        for (i = 0;
3655             i < conf->geo.raid_disks
3656                     || i < conf->prev.raid_disks;
3657             i++) {
3658
3659                disk = conf->mirrors + i;
3660
3661                if (!disk->rdev && disk->replacement) {
3662                        /* The replacement is all we have - use it */
3663                        disk->rdev = disk->replacement;
3664                        disk->replacement = NULL;
3665                        clear_bit(Replacement, &disk->rdev->flags);
3666                }
3667
3668                if (!disk->rdev ||
3669                    !test_bit(In_sync, &disk->rdev->flags)) {
3670                        disk->head_position = 0;
3671                        mddev->degraded++;
3672                        if (disk->rdev)
3673                                conf->fullsync = 1;
3674                }
3675                disk->recovery_disabled = mddev->recovery_disabled - 1;
3676        }
3677
3678        if (mddev->recovery_cp != MaxSector)
3679                printk(KERN_NOTICE "md/raid10:%s: not clean"
3680                       " -- starting background reconstruction\n",
3681                       mdname(mddev));
3682        printk(KERN_INFO
3683                "md/raid10:%s: active with %d out of %d devices\n",
3684                mdname(mddev), conf->geo.raid_disks - mddev->degraded,
3685                conf->geo.raid_disks);
3686        /*
3687         * Ok, everything is just fine now
3688         */
3689        mddev->dev_sectors = conf->dev_sectors;
3690        size = raid10_size(mddev, 0, 0);
3691        md_set_array_sectors(mddev, size);
3692        mddev->resync_max_sectors = size;
3693
3694        if (mddev->queue) {
3695                int stripe = conf->geo.raid_disks *
3696                        ((mddev->chunk_sectors << 9) / PAGE_SIZE);
3697                mddev->queue->backing_dev_info.congested_fn = raid10_congested;
3698                mddev->queue->backing_dev_info.congested_data = mddev;
3699
3700                /* Calculate max read-ahead size.
3701                 * We need to readahead at least twice a whole stripe....
3702                 * maybe...
3703                 */
3704                stripe /= conf->geo.near_copies;
3705                if (mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
3706                        mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
3707                blk_queue_merge_bvec(mddev->queue, raid10_mergeable_bvec);
3708        }
3709
3710
3711        if (md_integrity_register(mddev))
3712                goto out_free_conf;
3713
3714        if (conf->reshape_progress != MaxSector) {
3715                unsigned long before_length, after_length;
3716
3717                before_length = ((1 << conf->prev.chunk_shift) *
3718                                 conf->prev.far_copies);
3719                after_length = ((1 << conf->geo.chunk_shift) *
3720                                conf->geo.far_copies);
3721
3722                if (max(before_length, after_length) > min_offset_diff) {
3723                        /* This cannot work */
3724                        printk("md/raid10: offset difference not enough to continue reshape\n");
3725                        goto out_free_conf;
3726                }
3727                conf->offset_diff = min_offset_diff;
3728
3729                conf->reshape_safe = conf->reshape_progress;
3730                clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3731                clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3732                set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
3733                set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3734                mddev->sync_thread = md_register_thread(md_do_sync, mddev,
3735                                                        "reshape");
3736        }
3737
3738        return 0;
3739
3740out_free_conf:
3741        md_unregister_thread(&mddev->thread);
3742        if (conf->r10bio_pool)
3743                mempool_destroy(conf->r10bio_pool);
3744        safe_put_page(conf->tmppage);
3745        kfree(conf->mirrors);
3746        kfree(conf);
3747        mddev->private = NULL;
3748out:
3749        return -EIO;
3750}
3751
3752static int stop(struct mddev *mddev)
3753{
3754        struct r10conf *conf = mddev->private;
3755
3756        raise_barrier(conf, 0);
3757        lower_barrier(conf);
3758
3759        md_unregister_thread(&mddev->thread);
3760        if (mddev->queue)
3761                /* the unplug fn references 'conf'*/
3762                blk_sync_queue(mddev->queue);
3763
3764        if (conf->r10bio_pool)
3765                mempool_destroy(conf->r10bio_pool);
3766        kfree(conf->mirrors);
3767        kfree(conf);
3768        mddev->private = NULL;
3769        return 0;
3770}
3771
3772static void raid10_quiesce(struct mddev *mddev, int state)
3773{
3774        struct r10conf *conf = mddev->private;
3775
3776        switch(state) {
3777        case 1:
3778                raise_barrier(conf, 0);
3779                break;
3780        case 0:
3781                lower_barrier(conf);
3782                break;
3783        }
3784}
3785
3786static int raid10_resize(struct mddev *mddev, sector_t sectors)
3787{
3788        /* Resize of 'far' arrays is not supported.
3789         * For 'near' and 'offset' arrays we can set the
3790         * number of sectors used to be an appropriate multiple
3791         * of the chunk size.
3792         * For 'offset', this is far_copies*chunksize.
3793         * For 'near' the multiplier is the LCM of
3794         * near_copies and raid_disks.
3795         * So if far_copies > 1 && !far_offset, fail.
3796         * Else find LCM(raid_disks, near_copy)*far_copies and
3797         * multiply by chunk_size.  Then round to this number.
3798         * This is mostly done by raid10_size()
3799         */
3800        struct r10conf *conf = mddev->private;
3801        sector_t oldsize, size;
3802
3803        if (mddev->reshape_position != MaxSector)
3804                return -EBUSY;
3805
3806        if (conf->geo.far_copies > 1 && !conf->geo.far_offset)
3807                return -EINVAL;
3808
3809        oldsize = raid10_size(mddev, 0, 0);
3810        size = raid10_size(mddev, sectors, 0);
3811        if (mddev->external_size &&
3812            mddev->array_sectors > size)
3813                return -EINVAL;
3814        if (mddev->bitmap) {
3815                int ret = bitmap_resize(mddev->bitmap, size, 0, 0);
3816                if (ret)
3817                        return ret;
3818        }
3819        md_set_array_sectors(mddev, size);
3820        set_capacity(mddev->gendisk, mddev->array_sectors);
3821        revalidate_disk(mddev->gendisk);
3822        if (sectors > mddev->dev_sectors &&
3823            mddev->recovery_cp > oldsize) {
3824                mddev->recovery_cp = oldsize;
3825                set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3826        }
3827        calc_sectors(conf, sectors);
3828        mddev->dev_sectors = conf->dev_sectors;
3829        mddev->resync_max_sectors = size;
3830        return 0;
3831}
3832
3833static void *raid10_takeover_raid0(struct mddev *mddev)
3834{
3835        struct md_rdev *rdev;
3836        struct r10conf *conf;
3837
3838        if (mddev->degraded > 0) {
3839                printk(KERN_ERR "md/raid10:%s: Error: degraded raid0!\n",
3840                       mdname(mddev));
3841                return ERR_PTR(-EINVAL);
3842        }
3843
3844        /* Set new parameters */
3845        mddev->new_level = 10;
3846        /* new layout: far_copies = 1, near_copies = 2 */
3847        mddev->new_layout = (1<<8) + 2;
3848        mddev->new_chunk_sectors = mddev->chunk_sectors;
3849        mddev->delta_disks = mddev->raid_disks;
3850        mddev->raid_disks *= 2;
3851        /* make sure it will be not marked as dirty */
3852        mddev->recovery_cp = MaxSector;
3853
3854        conf = setup_conf(mddev);
3855        if (!IS_ERR(conf)) {
3856                rdev_for_each(rdev, mddev)
3857                        if (rdev->raid_disk >= 0)
3858                                rdev->new_raid_disk = rdev->raid_disk * 2;
3859                conf->barrier = 1;
3860        }
3861
3862        return conf;
3863}
3864
3865static void *raid10_takeover(struct mddev *mddev)
3866{
3867        struct r0conf *raid0_conf;
3868
3869        /* raid10 can take over:
3870         *  raid0 - providing it has only two drives
3871         */
3872        if (mddev->level == 0) {
3873                /* for raid0 takeover only one zone is supported */
3874                raid0_conf = mddev->private;
3875                if (raid0_conf->nr_strip_zones > 1) {
3876                        printk(KERN_ERR "md/raid10:%s: cannot takeover raid 0"
3877                               " with more than one zone.\n",
3878                               mdname(mddev));
3879                        return ERR_PTR(-EINVAL);
3880                }
3881                return raid10_takeover_raid0(mddev);
3882        }
3883        return ERR_PTR(-EINVAL);
3884}
3885
3886static int raid10_check_reshape(struct mddev *mddev)
3887{
3888        /* Called when there is a request to change
3889         * - layout (to ->new_layout)
3890         * - chunk size (to ->new_chunk_sectors)
3891         * - raid_disks (by delta_disks)
3892         * or when trying to restart a reshape that was ongoing.
3893         *
3894         * We need to validate the request and possibly allocate
3895         * space if that might be an issue later.
3896         *
3897         * Currently we reject any reshape of a 'far' mode array,
3898         * allow chunk size to change if new is generally acceptable,
3899         * allow raid_disks to increase, and allow
3900         * a switch between 'near' mode and 'offset' mode.
3901         */
3902        struct r10conf *conf = mddev->private;
3903        struct geom geo;
3904
3905        if (conf->geo.far_copies != 1 && !conf->geo.far_offset)
3906                return -EINVAL;
3907
3908        if (setup_geo(&geo, mddev, geo_start) != conf->copies)
3909                /* mustn't change number of copies */
3910                return -EINVAL;
3911        if (geo.far_copies > 1 && !geo.far_offset)
3912                /* Cannot switch to 'far' mode */
3913                return -EINVAL;
3914
3915        if (mddev->array_sectors & geo.chunk_mask)
3916                        /* not factor of array size */
3917                        return -EINVAL;
3918
3919        if (!enough(conf, -1))
3920                return -EINVAL;
3921
3922        kfree(conf->mirrors_new);
3923        conf->mirrors_new = NULL;
3924        if (mddev->delta_disks > 0) {
3925                /* allocate new 'mirrors' list */
3926                conf->mirrors_new = kzalloc(
3927                        sizeof(struct raid10_info)
3928                        *(mddev->raid_disks +
3929                          mddev->delta_disks),
3930                        GFP_KERNEL);
3931                if (!conf->mirrors_new)
3932                        return -ENOMEM;
3933        }
3934        return 0;
3935}
3936
3937/*
3938 * Need to check if array has failed when deciding whether to:
3939 *  - start an array
3940 *  - remove non-faulty devices
3941 *  - add a spare
3942 *  - allow a reshape
3943 * This determination is simple when no reshape is happening.
3944 * However if there is a reshape, we need to carefully check
3945 * both the before and after sections.
3946 * This is because some failed devices may only affect one
3947 * of the two sections, and some non-in_sync devices may
3948 * be insync in the section most affected by failed devices.
3949 */
3950static int calc_degraded(struct r10conf *conf)
3951{
3952        int degraded, degraded2;
3953        int i;
3954
3955        rcu_read_lock();
3956        degraded = 0;
3957        /* 'prev' section first */
3958        for (i = 0; i < conf->prev.raid_disks; i++) {
3959                struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
3960                if (!rdev || test_bit(Faulty, &rdev->flags))
3961                        degraded++;
3962                else if (!test_bit(In_sync, &rdev->flags))
3963                        /* When we can reduce the number of devices in
3964                         * an array, this might not contribute to
3965                         * 'degraded'.  It does now.
3966                         */
3967                        degraded++;
3968        }
3969        rcu_read_unlock();
3970        if (conf->geo.raid_disks == conf->prev.raid_disks)
3971                return degraded;
3972        rcu_read_lock();
3973        degraded2 = 0;
3974        for (i = 0; i < conf->geo.raid_disks; i++) {
3975                struct md_rdev *rdev = rcu_dereference(conf->mirrors[i].rdev);
3976                if (!rdev || test_bit(Faulty, &rdev->flags))
3977                        degraded2++;
3978                else if (!test_bit(In_sync, &rdev->flags)) {
3979                        /* If reshape is increasing the number of devices,
3980                         * this section has already been recovered, so
3981                         * it doesn't contribute to degraded.
3982                         * else it does.
3983                         */
3984                        if (conf->geo.raid_disks <= conf->prev.raid_disks)
3985                                degraded2++;
3986                }
3987        }
3988        rcu_read_unlock();
3989        if (degraded2 > degraded)
3990                return degraded2;
3991        return degraded;
3992}
3993
3994static int raid10_start_reshape(struct mddev *mddev)
3995{
3996        /* A 'reshape' has been requested. This commits
3997         * the various 'new' fields and sets MD_RECOVER_RESHAPE
3998         * This also checks if there are enough spares and adds them
3999         * to the array.
4000         * We currently require enough spares to make the final
4001         * array non-degraded.  We also require that the difference
4002         * between old and new data_offset - on each device - is
4003         * enough that we never risk over-writing.
4004         */
4005
4006        unsigned long before_length, after_length;
4007        sector_t min_offset_diff = 0;
4008        int first = 1;
4009        struct geom new;
4010        struct r10conf *conf = mddev->private;
4011        struct md_rdev *rdev;
4012        int spares = 0;
4013        int ret;
4014
4015        if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4016                return -EBUSY;
4017
4018        if (setup_geo(&new, mddev, geo_start) != conf->copies)
4019                return -EINVAL;
4020
4021        before_length = ((1 << conf->prev.chunk_shift) *
4022                         conf->prev.far_copies);
4023        after_length = ((1 << conf->geo.chunk_shift) *
4024                        conf->geo.far_copies);
4025
4026        rdev_for_each(rdev, mddev) {
4027                if (!test_bit(In_sync, &rdev->flags)
4028                    && !test_bit(Faulty, &rdev->flags))
4029                        spares++;
4030                if (rdev->raid_disk >= 0) {
4031                        long long diff = (rdev->new_data_offset
4032                                          - rdev->data_offset);
4033                        if (!mddev->reshape_backwards)
4034                                diff = -diff;
4035                        if (diff < 0)
4036                                diff = 0;
4037                        if (first || diff < min_offset_diff)
4038                                min_offset_diff = diff;
4039                }
4040        }
4041
4042        if (max(before_length, after_length) > min_offset_diff)
4043                return -EINVAL;
4044
4045        if (spares < mddev->delta_disks)
4046                return -EINVAL;
4047
4048        conf->offset_diff = min_offset_diff;
4049        spin_lock_irq(&conf->device_lock);
4050        if (conf->mirrors_new) {
4051                memcpy(conf->mirrors_new, conf->mirrors,
4052                       sizeof(struct raid10_info)*conf->prev.raid_disks);
4053                smp_mb();
4054                kfree(conf->mirrors_old); /* FIXME and elsewhere */
4055                conf->mirrors_old = conf->mirrors;
4056                conf->mirrors = conf->mirrors_new;
4057                conf->mirrors_new = NULL;
4058        }
4059        setup_geo(&conf->geo, mddev, geo_start);
4060        smp_mb();
4061        if (mddev->reshape_backwards) {
4062                sector_t size = raid10_size(mddev, 0, 0);
4063                if (size < mddev->array_sectors) {
4064                        spin_unlock_irq(&conf->device_lock);
4065                        printk(KERN_ERR "md/raid10:%s: array size must be reduce before number of disks\n",
4066                               mdname(mddev));
4067                        return -EINVAL;
4068                }
4069                mddev->resync_max_sectors = size;
4070                conf->reshape_progress = size;
4071        } else
4072                conf->reshape_progress = 0;
4073        spin_unlock_irq(&conf->device_lock);
4074
4075        if (mddev->delta_disks && mddev->bitmap) {
4076                ret = bitmap_resize(mddev->bitmap,
4077                                    raid10_size(mddev, 0,
4078                                                conf->geo.raid_disks),
4079                                    0, 0);
4080                if (ret)
4081                        goto abort;
4082        }
4083        if (mddev->delta_disks > 0) {
4084                rdev_for_each(rdev, mddev)
4085                        if (rdev->raid_disk < 0 &&
4086                            !test_bit(Faulty, &rdev->flags)) {
4087                                if (raid10_add_disk(mddev, rdev) == 0) {
4088                                        if (rdev->raid_disk >=
4089                                            conf->prev.raid_disks)
4090                                                set_bit(In_sync, &rdev->flags);
4091                                        else
4092                                                rdev->recovery_offset = 0;
4093
4094                                        if (sysfs_link_rdev(mddev, rdev))
4095                                                /* Failure here  is OK */;
4096                                }
4097                        } else if (rdev->raid_disk >= conf->prev.raid_disks
4098                                   && !test_bit(Faulty, &rdev->flags)) {
4099                                /* This is a spare that was manually added */
4100                                set_bit(In_sync, &rdev->flags);
4101                        }
4102        }
4103        /* When a reshape changes the number of devices,
4104         * ->degraded is measured against the larger of the
4105         * pre and  post numbers.
4106         */
4107        spin_lock_irq(&conf->device_lock);
4108        mddev->degraded = calc_degraded(conf);
4109        spin_unlock_irq(&conf->device_lock);
4110        mddev->raid_disks = conf->geo.raid_disks;
4111        mddev->reshape_position = conf->reshape_progress;
4112        set_bit(MD_CHANGE_DEVS, &mddev->flags);
4113
4114        clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4115        clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4116        set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
4117        set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
4118
4119        mddev->sync_thread = md_register_thread(md_do_sync, mddev,
4120                                                "reshape");
4121        if (!mddev->sync_thread) {
4122                ret = -EAGAIN;
4123                goto abort;
4124        }
4125        conf->reshape_checkpoint = jiffies;
4126        md_wakeup_thread(mddev->sync_thread);
4127        md_new_event(mddev);
4128        return 0;
4129
4130abort:
4131        mddev->recovery = 0;
4132        spin_lock_irq(&conf->device_lock);
4133        conf->geo = conf->prev;
4134        mddev->raid_disks = conf->geo.raid_disks;
4135        rdev_for_each(rdev, mddev)
4136                rdev->new_data_offset = rdev->data_offset;
4137        smp_wmb();
4138        conf->reshape_progress = MaxSector;
4139        mddev->reshape_position = MaxSector;
4140        spin_unlock_irq(&conf->device_lock);
4141        return ret;
4142}
4143
4144/* Calculate the last device-address that could contain
4145 * any block from the chunk that includes the array-address 's'
4146 * and report the next address.
4147 * i.e. the address returned will be chunk-aligned and after
4148 * any data that is in the chunk containing 's'.
4149 */
4150static sector_t last_dev_address(sector_t s, struct geom *geo)
4151{
4152        s = (s | geo->chunk_mask) + 1;
4153        s >>= geo->chunk_shift;
4154        s *= geo->near_copies;
4155        s = DIV_ROUND_UP_SECTOR_T(s, geo->raid_disks);
4156        s *= geo->far_copies;
4157        s <<= geo->chunk_shift;
4158        return s;
4159}
4160
4161/* Calculate the first device-address that could contain
4162 * any block from the chunk that includes the array-address 's'.
4163 * This too will be the start of a chunk
4164 */
4165static sector_t first_dev_address(sector_t s, struct geom *geo)
4166{
4167        s >>= geo->chunk_shift;
4168        s *= geo->near_copies;
4169        sector_div(s, geo->raid_disks);
4170        s *= geo->far_copies;
4171        s <<= geo->chunk_shift;
4172        return s;
4173}
4174
4175static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr,
4176                                int *skipped)
4177{
4178        /* We simply copy at most one chunk (smallest of old and new)
4179         * at a time, possibly less if that exceeds RESYNC_PAGES,
4180         * or we hit a bad block or something.
4181         * This might mean we pause for normal IO in the middle of
4182         * a chunk, but that is not a problem was mddev->reshape_position
4183         * can record any location.
4184         *
4185         * If we will want to write to a location that isn't
4186         * yet recorded as 'safe' (i.e. in metadata on disk) then
4187         * we need to flush all reshape requests and update the metadata.
4188         *
4189         * When reshaping forwards (e.g. to more devices), we interpret
4190         * 'safe' as the earliest block which might not have been copied
4191         * down yet.  We divide this by previous stripe size and multiply
4192         * by previous stripe length to get lowest device offset that we
4193         * cannot write to yet.
4194         * We interpret 'sector_nr' as an address that we want to write to.
4195         * From this we use last_device_address() to find where we might
4196         * write to, and first_device_address on the  'safe' position.
4197         * If this 'next' write position is after the 'safe' position,
4198         * we must update the metadata to increase the 'safe' position.
4199         *
4200         * When reshaping backwards, we round in the opposite direction
4201         * and perform the reverse test:  next write position must not be
4202         * less than current safe position.
4203         *
4204         * In all this the minimum difference in data offsets
4205         * (conf->offset_diff - always positive) allows a bit of slack,
4206         * so next can be after 'safe', but not by more than offset_disk
4207         *
4208         * We need to prepare all the bios here before we start any IO
4209         * to ensure the size we choose is acceptable to all devices.
4210         * The means one for each copy for write-out and an extra one for
4211         * read-in.
4212         * We store the read-in bio in ->master_bio and the others in
4213         * ->devs[x].bio and ->devs[x].repl_bio.
4214         */
4215        struct r10conf *conf = mddev->private;
4216        struct r10bio *r10_bio;
4217        sector_t next, safe, last;
4218        int max_sectors;
4219        int nr_sectors;
4220        int s;
4221        struct md_rdev *rdev;
4222        int need_flush = 0;
4223        struct bio *blist;
4224        struct bio *bio, *read_bio;
4225        int sectors_done = 0;
4226
4227        if (sector_nr == 0) {
4228                /* If restarting in the middle, skip the initial sectors */
4229                if (mddev->reshape_backwards &&
4230                    conf->reshape_progress < raid10_size(mddev, 0, 0)) {
4231                        sector_nr = (raid10_size(mddev, 0, 0)
4232                                     - conf->reshape_progress);
4233                } else if (!mddev->reshape_backwards &&
4234                           conf->reshape_progress > 0)
4235                        sector_nr = conf->reshape_progress;
4236                if (sector_nr) {
4237                        mddev->curr_resync_completed = sector_nr;
4238                        sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4239                        *skipped = 1;
4240                        return sector_nr;
4241                }
4242        }
4243
4244        /* We don't use sector_nr to track where we are up to
4245         * as that doesn't work well for ->reshape_backwards.
4246         * So just use ->reshape_progress.
4247         */
4248        if (mddev->reshape_backwards) {
4249                /* 'next' is the earliest device address that we might
4250                 * write to for this chunk in the new layout
4251                 */
4252                next = first_dev_address(conf->reshape_progress - 1,
4253                                         &conf->geo);
4254
4255                /* 'safe' is the last device address that we might read from
4256                 * in the old layout after a restart
4257                 */
4258                safe = last_dev_address(conf->reshape_safe - 1,
4259                                        &conf->prev);
4260
4261                if (next + conf->offset_diff < safe)
4262                        need_flush = 1;
4263
4264                last = conf->reshape_progress - 1;
4265                sector_nr = last & ~(sector_t)(conf->geo.chunk_mask
4266                                               & conf->prev.chunk_mask);
4267                if (sector_nr + RESYNC_BLOCK_SIZE/512 < last)
4268                        sector_nr = last + 1 - RESYNC_BLOCK_SIZE/512;
4269        } else {
4270                /* 'next' is after the last device address that we
4271                 * might write to for this chunk in the new layout
4272                 */
4273                next = last_dev_address(conf->reshape_progress, &conf->geo);
4274
4275                /* 'safe' is the earliest device address that we might
4276                 * read from in the old layout after a restart
4277                 */
4278                safe = first_dev_address(conf->reshape_safe, &conf->prev);
4279
4280                /* Need to update metadata if 'next' might be beyond 'safe'
4281                 * as that would possibly corrupt data
4282                 */
4283                if (next > safe + conf->offset_diff)
4284                        need_flush = 1;
4285
4286                sector_nr = conf->reshape_progress;
4287                last  = sector_nr | (conf->geo.chunk_mask
4288                                     & conf->prev.chunk_mask);
4289
4290                if (sector_nr + RESYNC_BLOCK_SIZE/512 <= last)
4291                        last = sector_nr + RESYNC_BLOCK_SIZE/512 - 1;
4292        }
4293
4294        if (need_flush ||
4295            time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4296                /* Need to update reshape_position in metadata */
4297                wait_barrier(conf);
4298                mddev->reshape_position = conf->reshape_progress;
4299                if (mddev->reshape_backwards)
4300                        mddev->curr_resync_completed = raid10_size(mddev, 0, 0)
4301                                - conf->reshape_progress;
4302                else
4303                        mddev->curr_resync_completed = conf->reshape_progress;
4304                conf->reshape_checkpoint = jiffies;
4305                set_bit(MD_CHANGE_DEVS, &mddev->flags);
4306                md_wakeup_thread(mddev->thread);
4307                wait_event(mddev->sb_wait, mddev->flags == 0 ||
4308                           kthread_should_stop());
4309                conf->reshape_safe = mddev->reshape_position;
4310                allow_barrier(conf);
4311        }
4312
4313read_more:
4314        /* Now schedule reads for blocks from sector_nr to last */
4315        r10_bio = mempool_alloc(conf->r10buf_pool, GFP_NOIO);
4316        raise_barrier(conf, sectors_done != 0);
4317        atomic_set(&r10_bio->remaining, 0);
4318        r10_bio->mddev = mddev;
4319        r10_bio->sector = sector_nr;
4320        set_bit(R10BIO_IsReshape, &r10_bio->state);
4321        r10_bio->sectors = last - sector_nr + 1;
4322        rdev = read_balance(conf, r10_bio, &max_sectors);
4323        BUG_ON(!test_bit(R10BIO_Previous, &r10_bio->state));
4324
4325        if (!rdev) {
4326                /* Cannot read from here, so need to record bad blocks
4327                 * on all the target devices.
4328                 */
4329                // FIXME
4330                set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4331                return sectors_done;
4332        }
4333
4334        read_bio = bio_alloc_mddev(GFP_KERNEL, RESYNC_PAGES, mddev);
4335
4336        read_bio->bi_bdev = rdev->bdev;
4337        read_bio->bi_sector = (r10_bio->devs[r10_bio->read_slot].addr
4338                               + rdev->data_offset);
4339        read_bio->bi_private = r10_bio;
4340        read_bio->bi_end_io = end_sync_read;
4341        read_bio->bi_rw = READ;
4342        read_bio->bi_flags &= ~(BIO_POOL_MASK - 1);
4343        read_bio->bi_flags |= 1 << BIO_UPTODATE;
4344        read_bio->bi_vcnt = 0;
4345        read_bio->bi_idx = 0;
4346        read_bio->bi_size = 0;
4347        r10_bio->master_bio = read_bio;
4348        r10_bio->read_slot = r10_bio->devs[r10_bio->read_slot].devnum;
4349
4350        /* Now find the locations in the new layout */
4351        __raid10_find_phys(&conf->geo, r10_bio);
4352
4353        blist = read_bio;
4354        read_bio->bi_next = NULL;
4355
4356        for (s = 0; s < conf->copies*2; s++) {
4357                struct bio *b;
4358                int d = r10_bio->devs[s/2].devnum;
4359                struct md_rdev *rdev2;
4360                if (s&1) {
4361                        rdev2 = conf->mirrors[d].replacement;
4362                        b = r10_bio->devs[s/2].repl_bio;
4363                } else {
4364                        rdev2 = conf->mirrors[d].rdev;
4365                        b = r10_bio->devs[s/2].bio;
4366                }
4367                if (!rdev2 || test_bit(Faulty, &rdev2->flags))
4368                        continue;
4369                b->bi_bdev = rdev2->bdev;
4370                b->bi_sector = r10_bio->devs[s/2].addr + rdev2->new_data_offset;
4371                b->bi_private = r10_bio;
4372                b->bi_end_io = end_reshape_write;
4373                b->bi_rw = WRITE;
4374                b->bi_flags &= ~(BIO_POOL_MASK - 1);
4375                b->bi_flags |= 1 << BIO_UPTODATE;
4376                b->bi_next = blist;
4377                b->bi_vcnt = 0;
4378                b->bi_idx = 0;
4379                b->bi_size = 0;
4380                blist = b;
4381        }
4382
4383        /* Now add as many pages as possible to all of these bios. */
4384
4385        nr_sectors = 0;
4386        for (s = 0 ; s < max_sectors; s += PAGE_SIZE >> 9) {
4387                struct page *page = r10_bio->devs[0].bio->bi_io_vec[s/(PAGE_SIZE>>9)].bv_page;
4388                int len = (max_sectors - s) << 9;
4389                if (len > PAGE_SIZE)
4390                        len = PAGE_SIZE;
4391                for (bio = blist; bio ; bio = bio->bi_next) {
4392                        struct bio *bio2;
4393                        if (bio_add_page(bio, page, len, 0))
4394                                continue;
4395
4396                        /* Didn't fit, must stop */
4397                        for (bio2 = blist;
4398                             bio2 && bio2 != bio;
4399                             bio2 = bio2->bi_next) {
4400                                /* Remove last page from this bio */
4401                                bio2->bi_vcnt--;
4402                                bio2->bi_size -= len;
4403                                bio2->bi_flags &= ~(1<<BIO_SEG_VALID);
4404                        }
4405                        goto bio_full;
4406                }
4407                sector_nr += len >> 9;
4408                nr_sectors += len >> 9;
4409        }
4410bio_full:
4411        r10_bio->sectors = nr_sectors;
4412
4413        /* Now submit the read */
4414        md_sync_acct(read_bio->bi_bdev, r10_bio->sectors);
4415        atomic_inc(&r10_bio->remaining);
4416        read_bio->bi_next = NULL;
4417        generic_make_request(read_bio);
4418        sector_nr += nr_sectors;
4419        sectors_done += nr_sectors;
4420        if (sector_nr <= last)
4421                goto read_more;
4422
4423        /* Now that we have done the whole section we can
4424         * update reshape_progress
4425         */
4426        if (mddev->reshape_backwards)
4427                conf->reshape_progress -= sectors_done;
4428        else
4429                conf->reshape_progress += sectors_done;
4430
4431        return sectors_done;
4432}
4433
4434static void end_reshape_request(struct r10bio *r10_bio);
4435static int handle_reshape_read_error(struct mddev *mddev,
4436                                     struct r10bio *r10_bio);
4437static void reshape_request_write(struct mddev *mddev, struct r10bio *r10_bio)
4438{
4439        /* Reshape read completed.  Hopefully we have a block
4440         * to write out.
4441         * If we got a read error then we do sync 1-page reads from
4442         * elsewhere until we find the data - or give up.
4443         */
4444        struct r10conf *conf = mddev->private;
4445        int s;
4446
4447        if (!test_bit(R10BIO_Uptodate, &r10_bio->state))
4448                if (handle_reshape_read_error(mddev, r10_bio) < 0) {
4449                        /* Reshape has been aborted */
4450                        md_done_sync(mddev, r10_bio->sectors, 0);
4451                        return;
4452                }
4453
4454        /* We definitely have the data in the pages, schedule the
4455         * writes.
4456         */
4457        atomic_set(&r10_bio->remaining, 1);
4458        for (s = 0; s < conf->copies*2; s++) {
4459                struct bio *b;
4460                int d = r10_bio->devs[s/2].devnum;
4461                struct md_rdev *rdev;
4462                if (s&1) {
4463                        rdev = conf->mirrors[d].replacement;
4464                        b = r10_bio->devs[s/2].repl_bio;
4465                } else {
4466                        rdev = conf->mirrors[d].rdev;
4467                        b = r10_bio->devs[s/2].bio;
4468                }
4469                if (!rdev || test_bit(Faulty, &rdev->flags))
4470                        continue;
4471                atomic_inc(&rdev->nr_pending);
4472                md_sync_acct(b->bi_bdev, r10_bio->sectors);
4473                atomic_inc(&r10_bio->remaining);
4474                b->bi_next = NULL;
4475                generic_make_request(b);
4476        }
4477        end_reshape_request(r10_bio);
4478}
4479
4480static void end_reshape(struct r10conf *conf)
4481{
4482        if (test_bit(MD_RECOVERY_INTR, &conf->mddev->recovery))
4483                return;
4484
4485        spin_lock_irq(&conf->device_lock);
4486        conf->prev = conf->geo;
4487        md_finish_reshape(conf->mddev);
4488        smp_wmb();
4489        conf->reshape_progress = MaxSector;
4490        spin_unlock_irq(&conf->device_lock);
4491
4492        /* read-ahead size must cover two whole stripes, which is
4493         * 2 * (datadisks) * chunksize where 'n' is the number of raid devices
4494         */
4495        if (conf->mddev->queue) {
4496                int stripe = conf->geo.raid_disks *
4497                        ((conf->mddev->chunk_sectors << 9) / PAGE_SIZE);
4498                stripe /= conf->geo.near_copies;
4499                if (conf->mddev->queue->backing_dev_info.ra_pages < 2 * stripe)
4500                        conf->mddev->queue->backing_dev_info.ra_pages = 2 * stripe;
4501        }
4502        conf->fullsync = 0;
4503}
4504
4505
4506static int handle_reshape_read_error(struct mddev *mddev,
4507                                     struct r10bio *r10_bio)
4508{
4509        /* Use sync reads to get the blocks from somewhere else */
4510        int sectors = r10_bio->sectors;
4511        struct r10conf *conf = mddev->private;
4512        struct {
4513                struct r10bio r10_bio;
4514                struct r10dev devs[conf->copies];
4515        } on_stack;
4516        struct r10bio *r10b = &on_stack.r10_bio;
4517        int slot = 0;
4518        int idx = 0;
4519        struct bio_vec *bvec = r10_bio->master_bio->bi_io_vec;
4520
4521        r10b->sector = r10_bio->sector;
4522        __raid10_find_phys(&conf->prev, r10b);
4523
4524        while (sectors) {
4525                int s = sectors;
4526                int success = 0;
4527                int first_slot = slot;
4528
4529                if (s > (PAGE_SIZE >> 9))
4530                        s = PAGE_SIZE >> 9;
4531
4532                while (!success) {
4533                        int d = r10b->devs[slot].devnum;
4534                        struct md_rdev *rdev = conf->mirrors[d].rdev;
4535                        sector_t addr;
4536                        if (rdev == NULL ||
4537                            test_bit(Faulty, &rdev->flags) ||
4538                            !test_bit(In_sync, &rdev->flags))
4539                                goto failed;
4540
4541                        addr = r10b->devs[slot].addr + idx * PAGE_SIZE;
4542                        success = sync_page_io(rdev,
4543                                               addr,
4544                                               s << 9,
4545                                               bvec[idx].bv_page,
4546                                               READ, false);
4547                        if (success)
4548                                break;
4549                failed:
4550                        slot++;
4551                        if (slot >= conf->copies)
4552                                slot = 0;
4553                        if (slot == first_slot)
4554                                break;
4555                }
4556                if (!success) {
4557                        /* couldn't read this block, must give up */
4558                        set_bit(MD_RECOVERY_INTR,
4559                                &mddev->recovery);
4560                        return -EIO;
4561                }
4562                sectors -= s;
4563                idx++;
4564        }
4565        return 0;
4566}
4567
4568static void end_reshape_write(struct bio *bio, int error)
4569{
4570        int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
4571        struct r10bio *r10_bio = bio->bi_private;
4572        struct mddev *mddev = r10_bio->mddev;
4573        struct r10conf *conf = mddev->private;
4574        int d;
4575        int slot;
4576        int repl;
4577        struct md_rdev *rdev = NULL;
4578
4579        d = find_bio_disk(conf, r10_bio, bio, &slot, &repl);
4580        if (repl)
4581                rdev = conf->mirrors[d].replacement;
4582        if (!rdev) {
4583                smp_mb();
4584                rdev = conf->mirrors[d].rdev;
4585        }
4586
4587        if (!uptodate) {
4588                /* FIXME should record badblock */
4589                md_error(mddev, rdev);
4590        }
4591
4592        rdev_dec_pending(rdev, mddev);
4593        end_reshape_request(r10_bio);
4594}
4595
4596static void end_reshape_request(struct r10bio *r10_bio)
4597{
4598        if (!atomic_dec_and_test(&r10_bio->remaining))
4599                return;
4600        md_done_sync(r10_bio->mddev, r10_bio->sectors, 1);
4601        bio_put(r10_bio->master_bio);
4602        put_buf(r10_bio);
4603}
4604
4605static void raid10_finish_reshape(struct mddev *mddev)
4606{
4607        struct r10conf *conf = mddev->private;
4608
4609        if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
4610                return;
4611
4612        if (mddev->delta_disks > 0) {
4613                sector_t size = raid10_size(mddev, 0, 0);
4614                md_set_array_sectors(mddev, size);
4615                if (mddev->recovery_cp > mddev->resync_max_sectors) {
4616                        mddev->recovery_cp = mddev->resync_max_sectors;
4617                        set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4618                }
4619                mddev->resync_max_sectors = size;
4620                set_capacity(mddev->gendisk, mddev->array_sectors);
4621                revalidate_disk(mddev->gendisk);
4622        } else {
4623                int d;
4624                for (d = conf->geo.raid_disks ;
4625                     d < conf->geo.raid_disks - mddev->delta_disks;
4626                     d++) {
4627                        struct md_rdev *rdev = conf->mirrors[d].rdev;
4628                        if (rdev)
4629                                clear_bit(In_sync, &rdev->flags);
4630                        rdev = conf->mirrors[d].replacement;
4631                        if (rdev)
4632                                clear_bit(In_sync, &rdev->flags);
4633                }
4634        }
4635        mddev->layout = mddev->new_layout;
4636        mddev->chunk_sectors = 1 << conf->geo.chunk_shift;
4637        mddev->reshape_position = MaxSector;
4638        mddev->delta_disks = 0;
4639        mddev->reshape_backwards = 0;
4640}
4641
4642static struct md_personality raid10_personality =
4643{
4644        .name           = "raid10",
4645        .level          = 10,
4646        .owner          = THIS_MODULE,
4647        .make_request   = make_request,
4648        .run            = run,
4649        .stop           = stop,
4650        .status         = status,
4651        .error_handler  = error,
4652        .hot_add_disk   = raid10_add_disk,
4653        .hot_remove_disk= raid10_remove_disk,
4654        .spare_active   = raid10_spare_active,
4655        .sync_request   = sync_request,
4656        .quiesce        = raid10_quiesce,
4657        .size           = raid10_size,
4658        .resize         = raid10_resize,
4659        .takeover       = raid10_takeover,
4660        .check_reshape  = raid10_check_reshape,
4661        .start_reshape  = raid10_start_reshape,
4662        .finish_reshape = raid10_finish_reshape,
4663};
4664
4665static int __init raid_init(void)
4666{
4667        return register_md_personality(&raid10_personality);
4668}
4669
4670static void raid_exit(void)
4671{
4672        unregister_md_personality(&raid10_personality);
4673}
4674
4675module_init(raid_init);
4676module_exit(raid_exit);
4677MODULE_LICENSE("GPL");
4678MODULE_DESCRIPTION("RAID10 (striped mirror) personality for MD");
4679MODULE_ALIAS("md-personality-9"); /* RAID10 */
4680MODULE_ALIAS("md-raid10");
4681MODULE_ALIAS("md-level-10");
4682
4683module_param(max_queued_requests, int, S_IRUGO|S_IWUSR);
4684
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.