linux/drivers/md/raid5.c
<<
>>
Prefs
   1/*
   2 * raid5.c : Multiple Devices driver for Linux
   3 *         Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
   4 *         Copyright (C) 1999, 2000 Ingo Molnar
   5 *         Copyright (C) 2002, 2003 H. Peter Anvin
   6 *
   7 * RAID-4/5/6 management functions.
   8 * Thanks to Penguin Computing for making the RAID-6 development possible
   9 * by donating a test server!
  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/*
  22 * BITMAP UNPLUGGING:
  23 *
  24 * The sequencing for updating the bitmap reliably is a little
  25 * subtle (and I got it wrong the first time) so it deserves some
  26 * explanation.
  27 *
  28 * We group bitmap updates into batches.  Each batch has a number.
  29 * We may write out several batches at once, but that isn't very important.
  30 * conf->seq_write is the number of the last batch successfully written.
  31 * conf->seq_flush is the number of the last batch that was closed to
  32 *    new additions.
  33 * When we discover that we will need to write to any block in a stripe
  34 * (in add_stripe_bio) we update the in-memory bitmap and record in sh->bm_seq
  35 * the number of the batch it will be in. This is seq_flush+1.
  36 * When we are ready to do a write, if that batch hasn't been written yet,
  37 *   we plug the array and queue the stripe for later.
  38 * When an unplug happens, we increment bm_flush, thus closing the current
  39 *   batch.
  40 * When we notice that bm_flush > bm_write, we write out all pending updates
  41 * to the bitmap, and advance bm_write to where bm_flush was.
  42 * This may occasionally write a bit out twice, but is sure never to
  43 * miss any bits.
  44 */
  45
  46#include <linux/blkdev.h>
  47#include <linux/kthread.h>
  48#include <linux/raid/pq.h>
  49#include <linux/async_tx.h>
  50#include <linux/module.h>
  51#include <linux/async.h>
  52#include <linux/seq_file.h>
  53#include <linux/cpu.h>
  54#include <linux/slab.h>
  55#include <linux/ratelimit.h>
  56#include <trace/events/block.h>
  57
  58#include "md.h"
  59#include "raid5.h"
  60#include "raid0.h"
  61#include "bitmap.h"
  62
  63/*
  64 * Stripe cache
  65 */
  66
  67#define NR_STRIPES              256
  68#define STRIPE_SIZE             PAGE_SIZE
  69#define STRIPE_SHIFT            (PAGE_SHIFT - 9)
  70#define STRIPE_SECTORS          (STRIPE_SIZE>>9)
  71#define IO_THRESHOLD            1
  72#define BYPASS_THRESHOLD        1
  73#define NR_HASH                 (PAGE_SIZE / sizeof(struct hlist_head))
  74#define HASH_MASK               (NR_HASH - 1)
  75
  76static inline struct hlist_head *stripe_hash(struct r5conf *conf, sector_t sect)
  77{
  78        int hash = (sect >> STRIPE_SHIFT) & HASH_MASK;
  79        return &conf->stripe_hashtbl[hash];
  80}
  81
  82/* bio's attached to a stripe+device for I/O are linked together in bi_sector
  83 * order without overlap.  There may be several bio's per stripe+device, and
  84 * a bio could span several devices.
  85 * When walking this list for a particular stripe+device, we must never proceed
  86 * beyond a bio that extends past this device, as the next bio might no longer
  87 * be valid.
  88 * This function is used to determine the 'next' bio in the list, given the sector
  89 * of the current stripe+device
  90 */
  91static inline struct bio *r5_next_bio(struct bio *bio, sector_t sector)
  92{
  93        int sectors = bio->bi_size >> 9;
  94        if (bio->bi_sector + sectors < sector + STRIPE_SECTORS)
  95                return bio->bi_next;
  96        else
  97                return NULL;
  98}
  99
 100/*
 101 * We maintain a biased count of active stripes in the bottom 16 bits of
 102 * bi_phys_segments, and a count of processed stripes in the upper 16 bits
 103 */
 104static inline int raid5_bi_processed_stripes(struct bio *bio)
 105{
 106        atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
 107        return (atomic_read(segments) >> 16) & 0xffff;
 108}
 109
 110static inline int raid5_dec_bi_active_stripes(struct bio *bio)
 111{
 112        atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
 113        return atomic_sub_return(1, segments) & 0xffff;
 114}
 115
 116static inline void raid5_inc_bi_active_stripes(struct bio *bio)
 117{
 118        atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
 119        atomic_inc(segments);
 120}
 121
 122static inline void raid5_set_bi_processed_stripes(struct bio *bio,
 123        unsigned int cnt)
 124{
 125        atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
 126        int old, new;
 127
 128        do {
 129                old = atomic_read(segments);
 130                new = (old & 0xffff) | (cnt << 16);
 131        } while (atomic_cmpxchg(segments, old, new) != old);
 132}
 133
 134static inline void raid5_set_bi_stripes(struct bio *bio, unsigned int cnt)
 135{
 136        atomic_t *segments = (atomic_t *)&bio->bi_phys_segments;
 137        atomic_set(segments, cnt);
 138}
 139
 140/* Find first data disk in a raid6 stripe */
 141static inline int raid6_d0(struct stripe_head *sh)
 142{
 143        if (sh->ddf_layout)
 144                /* ddf always start from first device */
 145                return 0;
 146        /* md starts just after Q block */
 147        if (sh->qd_idx == sh->disks - 1)
 148                return 0;
 149        else
 150                return sh->qd_idx + 1;
 151}
 152static inline int raid6_next_disk(int disk, int raid_disks)
 153{
 154        disk++;
 155        return (disk < raid_disks) ? disk : 0;
 156}
 157
 158/* When walking through the disks in a raid5, starting at raid6_d0,
 159 * We need to map each disk to a 'slot', where the data disks are slot
 160 * 0 .. raid_disks-3, the parity disk is raid_disks-2 and the Q disk
 161 * is raid_disks-1.  This help does that mapping.
 162 */
 163static int raid6_idx_to_slot(int idx, struct stripe_head *sh,
 164                             int *count, int syndrome_disks)
 165{
 166        int slot = *count;
 167
 168        if (sh->ddf_layout)
 169                (*count)++;
 170        if (idx == sh->pd_idx)
 171                return syndrome_disks;
 172        if (idx == sh->qd_idx)
 173                return syndrome_disks + 1;
 174        if (!sh->ddf_layout)
 175                (*count)++;
 176        return slot;
 177}
 178
 179static void return_io(struct bio *return_bi)
 180{
 181        struct bio *bi = return_bi;
 182        while (bi) {
 183
 184                return_bi = bi->bi_next;
 185                bi->bi_next = NULL;
 186                bi->bi_size = 0;
 187                trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
 188                                         bi, 0);
 189                bio_endio(bi, 0);
 190                bi = return_bi;
 191        }
 192}
 193
 194static void print_raid5_conf (struct r5conf *conf);
 195
 196static int stripe_operations_active(struct stripe_head *sh)
 197{
 198        return sh->check_state || sh->reconstruct_state ||
 199               test_bit(STRIPE_BIOFILL_RUN, &sh->state) ||
 200               test_bit(STRIPE_COMPUTE_RUN, &sh->state);
 201}
 202
 203static void do_release_stripe(struct r5conf *conf, struct stripe_head *sh)
 204{
 205        BUG_ON(!list_empty(&sh->lru));
 206        BUG_ON(atomic_read(&conf->active_stripes)==0);
 207        if (test_bit(STRIPE_HANDLE, &sh->state)) {
 208                if (test_bit(STRIPE_DELAYED, &sh->state) &&
 209                    !test_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
 210                        list_add_tail(&sh->lru, &conf->delayed_list);
 211                else if (test_bit(STRIPE_BIT_DELAY, &sh->state) &&
 212                           sh->bm_seq - conf->seq_write > 0)
 213                        list_add_tail(&sh->lru, &conf->bitmap_list);
 214                else {
 215                        clear_bit(STRIPE_DELAYED, &sh->state);
 216                        clear_bit(STRIPE_BIT_DELAY, &sh->state);
 217                        list_add_tail(&sh->lru, &conf->handle_list);
 218                }
 219                md_wakeup_thread(conf->mddev->thread);
 220        } else {
 221                BUG_ON(stripe_operations_active(sh));
 222                if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
 223                        if (atomic_dec_return(&conf->preread_active_stripes)
 224                            < IO_THRESHOLD)
 225                                md_wakeup_thread(conf->mddev->thread);
 226                atomic_dec(&conf->active_stripes);
 227                if (!test_bit(STRIPE_EXPANDING, &sh->state)) {
 228                        list_add_tail(&sh->lru, &conf->inactive_list);
 229                        wake_up(&conf->wait_for_stripe);
 230                        if (conf->retry_read_aligned)
 231                                md_wakeup_thread(conf->mddev->thread);
 232                }
 233        }
 234}
 235
 236static void __release_stripe(struct r5conf *conf, struct stripe_head *sh)
 237{
 238        if (atomic_dec_and_test(&sh->count))
 239                do_release_stripe(conf, sh);
 240}
 241
 242static void release_stripe(struct stripe_head *sh)
 243{
 244        struct r5conf *conf = sh->raid_conf;
 245        unsigned long flags;
 246
 247        local_irq_save(flags);
 248        if (atomic_dec_and_lock(&sh->count, &conf->device_lock)) {
 249                do_release_stripe(conf, sh);
 250                spin_unlock(&conf->device_lock);
 251        }
 252        local_irq_restore(flags);
 253}
 254
 255static inline void remove_hash(struct stripe_head *sh)
 256{
 257        pr_debug("remove_hash(), stripe %llu\n",
 258                (unsigned long long)sh->sector);
 259
 260        hlist_del_init(&sh->hash);
 261}
 262
 263static inline void insert_hash(struct r5conf *conf, struct stripe_head *sh)
 264{
 265        struct hlist_head *hp = stripe_hash(conf, sh->sector);
 266
 267        pr_debug("insert_hash(), stripe %llu\n",
 268                (unsigned long long)sh->sector);
 269
 270        hlist_add_head(&sh->hash, hp);
 271}
 272
 273
 274/* find an idle stripe, make sure it is unhashed, and return it. */
 275static struct stripe_head *get_free_stripe(struct r5conf *conf)
 276{
 277        struct stripe_head *sh = NULL;
 278        struct list_head *first;
 279
 280        if (list_empty(&conf->inactive_list))
 281                goto out;
 282        first = conf->inactive_list.next;
 283        sh = list_entry(first, struct stripe_head, lru);
 284        list_del_init(first);
 285        remove_hash(sh);
 286        atomic_inc(&conf->active_stripes);
 287out:
 288        return sh;
 289}
 290
 291static void shrink_buffers(struct stripe_head *sh)
 292{
 293        struct page *p;
 294        int i;
 295        int num = sh->raid_conf->pool_size;
 296
 297        for (i = 0; i < num ; i++) {
 298                p = sh->dev[i].page;
 299                if (!p)
 300                        continue;
 301                sh->dev[i].page = NULL;
 302                put_page(p);
 303        }
 304}
 305
 306static int grow_buffers(struct stripe_head *sh)
 307{
 308        int i;
 309        int num = sh->raid_conf->pool_size;
 310
 311        for (i = 0; i < num; i++) {
 312                struct page *page;
 313
 314                if (!(page = alloc_page(GFP_KERNEL))) {
 315                        return 1;
 316                }
 317                sh->dev[i].page = page;
 318        }
 319        return 0;
 320}
 321
 322static void raid5_build_block(struct stripe_head *sh, int i, int previous);
 323static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
 324                            struct stripe_head *sh);
 325
 326static void init_stripe(struct stripe_head *sh, sector_t sector, int previous)
 327{
 328        struct r5conf *conf = sh->raid_conf;
 329        int i;
 330
 331        BUG_ON(atomic_read(&sh->count) != 0);
 332        BUG_ON(test_bit(STRIPE_HANDLE, &sh->state));
 333        BUG_ON(stripe_operations_active(sh));
 334
 335        pr_debug("init_stripe called, stripe %llu\n",
 336                (unsigned long long)sh->sector);
 337
 338        remove_hash(sh);
 339
 340        sh->generation = conf->generation - previous;
 341        sh->disks = previous ? conf->previous_raid_disks : conf->raid_disks;
 342        sh->sector = sector;
 343        stripe_set_idx(sector, conf, previous, sh);
 344        sh->state = 0;
 345
 346
 347        for (i = sh->disks; i--; ) {
 348                struct r5dev *dev = &sh->dev[i];
 349
 350                if (dev->toread || dev->read || dev->towrite || dev->written ||
 351                    test_bit(R5_LOCKED, &dev->flags)) {
 352                        printk(KERN_ERR "sector=%llx i=%d %p %p %p %p %d\n",
 353                               (unsigned long long)sh->sector, i, dev->toread,
 354                               dev->read, dev->towrite, dev->written,
 355                               test_bit(R5_LOCKED, &dev->flags));
 356                        WARN_ON(1);
 357                }
 358                dev->flags = 0;
 359                raid5_build_block(sh, i, previous);
 360        }
 361        insert_hash(conf, sh);
 362}
 363
 364static struct stripe_head *__find_stripe(struct r5conf *conf, sector_t sector,
 365                                         short generation)
 366{
 367        struct stripe_head *sh;
 368        struct hlist_node *hn;
 369
 370        pr_debug("__find_stripe, sector %llu\n", (unsigned long long)sector);
 371        hlist_for_each_entry(sh, hn, stripe_hash(conf, sector), hash)
 372                if (sh->sector == sector && sh->generation == generation)
 373                        return sh;
 374        pr_debug("__stripe %llu not in cache\n", (unsigned long long)sector);
 375        return NULL;
 376}
 377
 378/*
 379 * Need to check if array has failed when deciding whether to:
 380 *  - start an array
 381 *  - remove non-faulty devices
 382 *  - add a spare
 383 *  - allow a reshape
 384 * This determination is simple when no reshape is happening.
 385 * However if there is a reshape, we need to carefully check
 386 * both the before and after sections.
 387 * This is because some failed devices may only affect one
 388 * of the two sections, and some non-in_sync devices may
 389 * be insync in the section most affected by failed devices.
 390 */
 391static int calc_degraded(struct r5conf *conf)
 392{
 393        int degraded, degraded2;
 394        int i;
 395
 396        rcu_read_lock();
 397        degraded = 0;
 398        for (i = 0; i < conf->previous_raid_disks; i++) {
 399                struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
 400                if (rdev && test_bit(Faulty, &rdev->flags))
 401                        rdev = rcu_dereference(conf->disks[i].replacement);
 402                if (!rdev || test_bit(Faulty, &rdev->flags))
 403                        degraded++;
 404                else if (test_bit(In_sync, &rdev->flags))
 405                        ;
 406                else
 407                        /* not in-sync or faulty.
 408                         * If the reshape increases the number of devices,
 409                         * this is being recovered by the reshape, so
 410                         * this 'previous' section is not in_sync.
 411                         * If the number of devices is being reduced however,
 412                         * the device can only be part of the array if
 413                         * we are reverting a reshape, so this section will
 414                         * be in-sync.
 415                         */
 416                        if (conf->raid_disks >= conf->previous_raid_disks)
 417                                degraded++;
 418        }
 419        rcu_read_unlock();
 420        if (conf->raid_disks == conf->previous_raid_disks)
 421                return degraded;
 422        rcu_read_lock();
 423        degraded2 = 0;
 424        for (i = 0; i < conf->raid_disks; i++) {
 425                struct md_rdev *rdev = rcu_dereference(conf->disks[i].rdev);
 426                if (rdev && test_bit(Faulty, &rdev->flags))
 427                        rdev = rcu_dereference(conf->disks[i].replacement);
 428                if (!rdev || test_bit(Faulty, &rdev->flags))
 429                        degraded2++;
 430                else if (test_bit(In_sync, &rdev->flags))
 431                        ;
 432                else
 433                        /* not in-sync or faulty.
 434                         * If reshape increases the number of devices, this
 435                         * section has already been recovered, else it
 436                         * almost certainly hasn't.
 437                         */
 438                        if (conf->raid_disks <= conf->previous_raid_disks)
 439                                degraded2++;
 440        }
 441        rcu_read_unlock();
 442        if (degraded2 > degraded)
 443                return degraded2;
 444        return degraded;
 445}
 446
 447static int has_failed(struct r5conf *conf)
 448{
 449        int degraded;
 450
 451        if (conf->mddev->reshape_position == MaxSector)
 452                return conf->mddev->degraded > conf->max_degraded;
 453
 454        degraded = calc_degraded(conf);
 455        if (degraded > conf->max_degraded)
 456                return 1;
 457        return 0;
 458}
 459
 460static struct stripe_head *
 461get_active_stripe(struct r5conf *conf, sector_t sector,
 462                  int previous, int noblock, int noquiesce)
 463{
 464        struct stripe_head *sh;
 465
 466        pr_debug("get_stripe, sector %llu\n", (unsigned long long)sector);
 467
 468        spin_lock_irq(&conf->device_lock);
 469
 470        do {
 471                wait_event_lock_irq(conf->wait_for_stripe,
 472                                    conf->quiesce == 0 || noquiesce,
 473                                    conf->device_lock);
 474                sh = __find_stripe(conf, sector, conf->generation - previous);
 475                if (!sh) {
 476                        if (!conf->inactive_blocked)
 477                                sh = get_free_stripe(conf);
 478                        if (noblock && sh == NULL)
 479                                break;
 480                        if (!sh) {
 481                                conf->inactive_blocked = 1;
 482                                wait_event_lock_irq(conf->wait_for_stripe,
 483                                                    !list_empty(&conf->inactive_list) &&
 484                                                    (atomic_read(&conf->active_stripes)
 485                                                     < (conf->max_nr_stripes *3/4)
 486                                                     || !conf->inactive_blocked),
 487                                                    conf->device_lock);
 488                                conf->inactive_blocked = 0;
 489                        } else
 490                                init_stripe(sh, sector, previous);
 491                } else {
 492                        if (atomic_read(&sh->count)) {
 493                                BUG_ON(!list_empty(&sh->lru)
 494                                    && !test_bit(STRIPE_EXPANDING, &sh->state)
 495                                    && !test_bit(STRIPE_ON_UNPLUG_LIST, &sh->state));
 496                        } else {
 497                                if (!test_bit(STRIPE_HANDLE, &sh->state))
 498                                        atomic_inc(&conf->active_stripes);
 499                                if (list_empty(&sh->lru) &&
 500                                    !test_bit(STRIPE_EXPANDING, &sh->state))
 501                                        BUG();
 502                                list_del_init(&sh->lru);
 503                        }
 504                }
 505        } while (sh == NULL);
 506
 507        if (sh)
 508                atomic_inc(&sh->count);
 509
 510        spin_unlock_irq(&conf->device_lock);
 511        return sh;
 512}
 513
 514/* Determine if 'data_offset' or 'new_data_offset' should be used
 515 * in this stripe_head.
 516 */
 517static int use_new_offset(struct r5conf *conf, struct stripe_head *sh)
 518{
 519        sector_t progress = conf->reshape_progress;
 520        /* Need a memory barrier to make sure we see the value
 521         * of conf->generation, or ->data_offset that was set before
 522         * reshape_progress was updated.
 523         */
 524        smp_rmb();
 525        if (progress == MaxSector)
 526                return 0;
 527        if (sh->generation == conf->generation - 1)
 528                return 0;
 529        /* We are in a reshape, and this is a new-generation stripe,
 530         * so use new_data_offset.
 531         */
 532        return 1;
 533}
 534
 535static void
 536raid5_end_read_request(struct bio *bi, int error);
 537static void
 538raid5_end_write_request(struct bio *bi, int error);
 539
 540static void ops_run_io(struct stripe_head *sh, struct stripe_head_state *s)
 541{
 542        struct r5conf *conf = sh->raid_conf;
 543        int i, disks = sh->disks;
 544
 545        might_sleep();
 546
 547        for (i = disks; i--; ) {
 548                int rw;
 549                int replace_only = 0;
 550                struct bio *bi, *rbi;
 551                struct md_rdev *rdev, *rrdev = NULL;
 552                if (test_and_clear_bit(R5_Wantwrite, &sh->dev[i].flags)) {
 553                        if (test_and_clear_bit(R5_WantFUA, &sh->dev[i].flags))
 554                                rw = WRITE_FUA;
 555                        else
 556                                rw = WRITE;
 557                        if (test_bit(R5_Discard, &sh->dev[i].flags))
 558                                rw |= REQ_DISCARD;
 559                } else if (test_and_clear_bit(R5_Wantread, &sh->dev[i].flags))
 560                        rw = READ;
 561                else if (test_and_clear_bit(R5_WantReplace,
 562                                            &sh->dev[i].flags)) {
 563                        rw = WRITE;
 564                        replace_only = 1;
 565                } else
 566                        continue;
 567                if (test_and_clear_bit(R5_SyncIO, &sh->dev[i].flags))
 568                        rw |= REQ_SYNC;
 569
 570                bi = &sh->dev[i].req;
 571                rbi = &sh->dev[i].rreq; /* For writing to replacement */
 572
 573                bi->bi_rw = rw;
 574                rbi->bi_rw = rw;
 575                if (rw & WRITE) {
 576                        bi->bi_end_io = raid5_end_write_request;
 577                        rbi->bi_end_io = raid5_end_write_request;
 578                } else
 579                        bi->bi_end_io = raid5_end_read_request;
 580
 581                rcu_read_lock();
 582                rrdev = rcu_dereference(conf->disks[i].replacement);
 583                smp_mb(); /* Ensure that if rrdev is NULL, rdev won't be */
 584                rdev = rcu_dereference(conf->disks[i].rdev);
 585                if (!rdev) {
 586                        rdev = rrdev;
 587                        rrdev = NULL;
 588                }
 589                if (rw & WRITE) {
 590                        if (replace_only)
 591                                rdev = NULL;
 592                        if (rdev == rrdev)
 593                                /* We raced and saw duplicates */
 594                                rrdev = NULL;
 595                } else {
 596                        if (test_bit(R5_ReadRepl, &sh->dev[i].flags) && rrdev)
 597                                rdev = rrdev;
 598                        rrdev = NULL;
 599                }
 600
 601                if (rdev && test_bit(Faulty, &rdev->flags))
 602                        rdev = NULL;
 603                if (rdev)
 604                        atomic_inc(&rdev->nr_pending);
 605                if (rrdev && test_bit(Faulty, &rrdev->flags))
 606                        rrdev = NULL;
 607                if (rrdev)
 608                        atomic_inc(&rrdev->nr_pending);
 609                rcu_read_unlock();
 610
 611                /* We have already checked bad blocks for reads.  Now
 612                 * need to check for writes.  We never accept write errors
 613                 * on the replacement, so we don't to check rrdev.
 614                 */
 615                while ((rw & WRITE) && rdev &&
 616                       test_bit(WriteErrorSeen, &rdev->flags)) {
 617                        sector_t first_bad;
 618                        int bad_sectors;
 619                        int bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
 620                                              &first_bad, &bad_sectors);
 621                        if (!bad)
 622                                break;
 623
 624                        if (bad < 0) {
 625                                set_bit(BlockedBadBlocks, &rdev->flags);
 626                                if (!conf->mddev->external &&
 627                                    conf->mddev->flags) {
 628                                        /* It is very unlikely, but we might
 629                                         * still need to write out the
 630                                         * bad block log - better give it
 631                                         * a chance*/
 632                                        md_check_recovery(conf->mddev);
 633                                }
 634                                /*
 635                                 * Because md_wait_for_blocked_rdev
 636                                 * will dec nr_pending, we must
 637                                 * increment it first.
 638                                 */
 639                                atomic_inc(&rdev->nr_pending);
 640                                md_wait_for_blocked_rdev(rdev, conf->mddev);
 641                        } else {
 642                                /* Acknowledged bad block - skip the write */
 643                                rdev_dec_pending(rdev, conf->mddev);
 644                                rdev = NULL;
 645                        }
 646                }
 647
 648                if (rdev) {
 649                        if (s->syncing || s->expanding || s->expanded
 650                            || s->replacing)
 651                                md_sync_acct(rdev->bdev, STRIPE_SECTORS);
 652
 653                        set_bit(STRIPE_IO_STARTED, &sh->state);
 654
 655                        bi->bi_bdev = rdev->bdev;
 656                        pr_debug("%s: for %llu schedule op %ld on disc %d\n",
 657                                __func__, (unsigned long long)sh->sector,
 658                                bi->bi_rw, i);
 659                        atomic_inc(&sh->count);
 660                        if (use_new_offset(conf, sh))
 661                                bi->bi_sector = (sh->sector
 662                                                 + rdev->new_data_offset);
 663                        else
 664                                bi->bi_sector = (sh->sector
 665                                                 + rdev->data_offset);
 666                        if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
 667                                bi->bi_rw |= REQ_FLUSH;
 668
 669                        bi->bi_flags = 1 << BIO_UPTODATE;
 670                        bi->bi_idx = 0;
 671                        bi->bi_io_vec[0].bv_len = STRIPE_SIZE;
 672                        bi->bi_io_vec[0].bv_offset = 0;
 673                        bi->bi_size = STRIPE_SIZE;
 674                        bi->bi_next = NULL;
 675                        if (rrdev)
 676                                set_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags);
 677
 678                        if (conf->mddev->gendisk)
 679                                trace_block_bio_remap(bdev_get_queue(bi->bi_bdev),
 680                                                      bi, disk_devt(conf->mddev->gendisk),
 681                                                      sh->dev[i].sector);
 682                        generic_make_request(bi);
 683                }
 684                if (rrdev) {
 685                        if (s->syncing || s->expanding || s->expanded
 686                            || s->replacing)
 687                                md_sync_acct(rrdev->bdev, STRIPE_SECTORS);
 688
 689                        set_bit(STRIPE_IO_STARTED, &sh->state);
 690
 691                        rbi->bi_bdev = rrdev->bdev;
 692                        pr_debug("%s: for %llu schedule op %ld on "
 693                                 "replacement disc %d\n",
 694                                __func__, (unsigned long long)sh->sector,
 695                                rbi->bi_rw, i);
 696                        atomic_inc(&sh->count);
 697                        if (use_new_offset(conf, sh))
 698                                rbi->bi_sector = (sh->sector
 699                                                  + rrdev->new_data_offset);
 700                        else
 701                                rbi->bi_sector = (sh->sector
 702                                                  + rrdev->data_offset);
 703                        rbi->bi_flags = 1 << BIO_UPTODATE;
 704                        rbi->bi_idx = 0;
 705                        rbi->bi_io_vec[0].bv_len = STRIPE_SIZE;
 706                        rbi->bi_io_vec[0].bv_offset = 0;
 707                        rbi->bi_size = STRIPE_SIZE;
 708                        rbi->bi_next = NULL;
 709                        if (conf->mddev->gendisk)
 710                                trace_block_bio_remap(bdev_get_queue(rbi->bi_bdev),
 711                                                      rbi, disk_devt(conf->mddev->gendisk),
 712                                                      sh->dev[i].sector);
 713                        generic_make_request(rbi);
 714                }
 715                if (!rdev && !rrdev) {
 716                        if (rw & WRITE)
 717                                set_bit(STRIPE_DEGRADED, &sh->state);
 718                        pr_debug("skip op %ld on disc %d for sector %llu\n",
 719                                bi->bi_rw, i, (unsigned long long)sh->sector);
 720                        clear_bit(R5_LOCKED, &sh->dev[i].flags);
 721                        set_bit(STRIPE_HANDLE, &sh->state);
 722                }
 723        }
 724}
 725
 726static struct dma_async_tx_descriptor *
 727async_copy_data(int frombio, struct bio *bio, struct page *page,
 728        sector_t sector, struct dma_async_tx_descriptor *tx)
 729{
 730        struct bio_vec *bvl;
 731        struct page *bio_page;
 732        int i;
 733        int page_offset;
 734        struct async_submit_ctl submit;
 735        enum async_tx_flags flags = 0;
 736
 737        if (bio->bi_sector >= sector)
 738                page_offset = (signed)(bio->bi_sector - sector) * 512;
 739        else
 740                page_offset = (signed)(sector - bio->bi_sector) * -512;
 741
 742        if (frombio)
 743                flags |= ASYNC_TX_FENCE;
 744        init_async_submit(&submit, flags, tx, NULL, NULL, NULL);
 745
 746        bio_for_each_segment(bvl, bio, i) {
 747                int len = bvl->bv_len;
 748                int clen;
 749                int b_offset = 0;
 750
 751                if (page_offset < 0) {
 752                        b_offset = -page_offset;
 753                        page_offset += b_offset;
 754                        len -= b_offset;
 755                }
 756
 757                if (len > 0 && page_offset + len > STRIPE_SIZE)
 758                        clen = STRIPE_SIZE - page_offset;
 759                else
 760                        clen = len;
 761
 762                if (clen > 0) {
 763                        b_offset += bvl->bv_offset;
 764                        bio_page = bvl->bv_page;
 765                        if (frombio)
 766                                tx = async_memcpy(page, bio_page, page_offset,
 767                                                  b_offset, clen, &submit);
 768                        else
 769                                tx = async_memcpy(bio_page, page, b_offset,
 770                                                  page_offset, clen, &submit);
 771                }
 772                /* chain the operations */
 773                submit.depend_tx = tx;
 774
 775                if (clen < len) /* hit end of page */
 776                        break;
 777                page_offset +=  len;
 778        }
 779
 780        return tx;
 781}
 782
 783static void ops_complete_biofill(void *stripe_head_ref)
 784{
 785        struct stripe_head *sh = stripe_head_ref;
 786        struct bio *return_bi = NULL;
 787        int i;
 788
 789        pr_debug("%s: stripe %llu\n", __func__,
 790                (unsigned long long)sh->sector);
 791
 792        /* clear completed biofills */
 793        for (i = sh->disks; i--; ) {
 794                struct r5dev *dev = &sh->dev[i];
 795
 796                /* acknowledge completion of a biofill operation */
 797                /* and check if we need to reply to a read request,
 798                 * new R5_Wantfill requests are held off until
 799                 * !STRIPE_BIOFILL_RUN
 800                 */
 801                if (test_and_clear_bit(R5_Wantfill, &dev->flags)) {
 802                        struct bio *rbi, *rbi2;
 803
 804                        BUG_ON(!dev->read);
 805                        rbi = dev->read;
 806                        dev->read = NULL;
 807                        while (rbi && rbi->bi_sector <
 808                                dev->sector + STRIPE_SECTORS) {
 809                                rbi2 = r5_next_bio(rbi, dev->sector);
 810                                if (!raid5_dec_bi_active_stripes(rbi)) {
 811                                        rbi->bi_next = return_bi;
 812                                        return_bi = rbi;
 813                                }
 814                                rbi = rbi2;
 815                        }
 816                }
 817        }
 818        clear_bit(STRIPE_BIOFILL_RUN, &sh->state);
 819
 820        return_io(return_bi);
 821
 822        set_bit(STRIPE_HANDLE, &sh->state);
 823        release_stripe(sh);
 824}
 825
 826static void ops_run_biofill(struct stripe_head *sh)
 827{
 828        struct dma_async_tx_descriptor *tx = NULL;
 829        struct async_submit_ctl submit;
 830        int i;
 831
 832        pr_debug("%s: stripe %llu\n", __func__,
 833                (unsigned long long)sh->sector);
 834
 835        for (i = sh->disks; i--; ) {
 836                struct r5dev *dev = &sh->dev[i];
 837                if (test_bit(R5_Wantfill, &dev->flags)) {
 838                        struct bio *rbi;
 839                        spin_lock_irq(&sh->stripe_lock);
 840                        dev->read = rbi = dev->toread;
 841                        dev->toread = NULL;
 842                        spin_unlock_irq(&sh->stripe_lock);
 843                        while (rbi && rbi->bi_sector <
 844                                dev->sector + STRIPE_SECTORS) {
 845                                tx = async_copy_data(0, rbi, dev->page,
 846                                        dev->sector, tx);
 847                                rbi = r5_next_bio(rbi, dev->sector);
 848                        }
 849                }
 850        }
 851
 852        atomic_inc(&sh->count);
 853        init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_biofill, sh, NULL);
 854        async_trigger_callback(&submit);
 855}
 856
 857static void mark_target_uptodate(struct stripe_head *sh, int target)
 858{
 859        struct r5dev *tgt;
 860
 861        if (target < 0)
 862                return;
 863
 864        tgt = &sh->dev[target];
 865        set_bit(R5_UPTODATE, &tgt->flags);
 866        BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
 867        clear_bit(R5_Wantcompute, &tgt->flags);
 868}
 869
 870static void ops_complete_compute(void *stripe_head_ref)
 871{
 872        struct stripe_head *sh = stripe_head_ref;
 873
 874        pr_debug("%s: stripe %llu\n", __func__,
 875                (unsigned long long)sh->sector);
 876
 877        /* mark the computed target(s) as uptodate */
 878        mark_target_uptodate(sh, sh->ops.target);
 879        mark_target_uptodate(sh, sh->ops.target2);
 880
 881        clear_bit(STRIPE_COMPUTE_RUN, &sh->state);
 882        if (sh->check_state == check_state_compute_run)
 883                sh->check_state = check_state_compute_result;
 884        set_bit(STRIPE_HANDLE, &sh->state);
 885        release_stripe(sh);
 886}
 887
 888/* return a pointer to the address conversion region of the scribble buffer */
 889static addr_conv_t *to_addr_conv(struct stripe_head *sh,
 890                                 struct raid5_percpu *percpu)
 891{
 892        return percpu->scribble + sizeof(struct page *) * (sh->disks + 2);
 893}
 894
 895static struct dma_async_tx_descriptor *
 896ops_run_compute5(struct stripe_head *sh, struct raid5_percpu *percpu)
 897{
 898        int disks = sh->disks;
 899        struct page **xor_srcs = percpu->scribble;
 900        int target = sh->ops.target;
 901        struct r5dev *tgt = &sh->dev[target];
 902        struct page *xor_dest = tgt->page;
 903        int count = 0;
 904        struct dma_async_tx_descriptor *tx;
 905        struct async_submit_ctl submit;
 906        int i;
 907
 908        pr_debug("%s: stripe %llu block: %d\n",
 909                __func__, (unsigned long long)sh->sector, target);
 910        BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
 911
 912        for (i = disks; i--; )
 913                if (i != target)
 914                        xor_srcs[count++] = sh->dev[i].page;
 915
 916        atomic_inc(&sh->count);
 917
 918        init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST, NULL,
 919                          ops_complete_compute, sh, to_addr_conv(sh, percpu));
 920        if (unlikely(count == 1))
 921                tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
 922        else
 923                tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
 924
 925        return tx;
 926}
 927
 928/* set_syndrome_sources - populate source buffers for gen_syndrome
 929 * @srcs - (struct page *) array of size sh->disks
 930 * @sh - stripe_head to parse
 931 *
 932 * Populates srcs in proper layout order for the stripe and returns the
 933 * 'count' of sources to be used in a call to async_gen_syndrome.  The P
 934 * destination buffer is recorded in srcs[count] and the Q destination
 935 * is recorded in srcs[count+1]].
 936 */
 937static int set_syndrome_sources(struct page **srcs, struct stripe_head *sh)
 938{
 939        int disks = sh->disks;
 940        int syndrome_disks = sh->ddf_layout ? disks : (disks - 2);
 941        int d0_idx = raid6_d0(sh);
 942        int count;
 943        int i;
 944
 945        for (i = 0; i < disks; i++)
 946                srcs[i] = NULL;
 947
 948        count = 0;
 949        i = d0_idx;
 950        do {
 951                int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
 952
 953                srcs[slot] = sh->dev[i].page;
 954                i = raid6_next_disk(i, disks);
 955        } while (i != d0_idx);
 956
 957        return syndrome_disks;
 958}
 959
 960static struct dma_async_tx_descriptor *
 961ops_run_compute6_1(struct stripe_head *sh, struct raid5_percpu *percpu)
 962{
 963        int disks = sh->disks;
 964        struct page **blocks = percpu->scribble;
 965        int target;
 966        int qd_idx = sh->qd_idx;
 967        struct dma_async_tx_descriptor *tx;
 968        struct async_submit_ctl submit;
 969        struct r5dev *tgt;
 970        struct page *dest;
 971        int i;
 972        int count;
 973
 974        if (sh->ops.target < 0)
 975                target = sh->ops.target2;
 976        else if (sh->ops.target2 < 0)
 977                target = sh->ops.target;
 978        else
 979                /* we should only have one valid target */
 980                BUG();
 981        BUG_ON(target < 0);
 982        pr_debug("%s: stripe %llu block: %d\n",
 983                __func__, (unsigned long long)sh->sector, target);
 984
 985        tgt = &sh->dev[target];
 986        BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
 987        dest = tgt->page;
 988
 989        atomic_inc(&sh->count);
 990
 991        if (target == qd_idx) {
 992                count = set_syndrome_sources(blocks, sh);
 993                blocks[count] = NULL; /* regenerating p is not necessary */
 994                BUG_ON(blocks[count+1] != dest); /* q should already be set */
 995                init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
 996                                  ops_complete_compute, sh,
 997                                  to_addr_conv(sh, percpu));
 998                tx = async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE, &submit);
 999        } else {
1000                /* Compute any data- or p-drive using XOR */
1001                count = 0;
1002                for (i = disks; i-- ; ) {
1003                        if (i == target || i == qd_idx)
1004                                continue;
1005                        blocks[count++] = sh->dev[i].page;
1006                }
1007
1008                init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1009                                  NULL, ops_complete_compute, sh,
1010                                  to_addr_conv(sh, percpu));
1011                tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE, &submit);
1012        }
1013
1014        return tx;
1015}
1016
1017static struct dma_async_tx_descriptor *
1018ops_run_compute6_2(struct stripe_head *sh, struct raid5_percpu *percpu)
1019{
1020        int i, count, disks = sh->disks;
1021        int syndrome_disks = sh->ddf_layout ? disks : disks-2;
1022        int d0_idx = raid6_d0(sh);
1023        int faila = -1, failb = -1;
1024        int target = sh->ops.target;
1025        int target2 = sh->ops.target2;
1026        struct r5dev *tgt = &sh->dev[target];
1027        struct r5dev *tgt2 = &sh->dev[target2];
1028        struct dma_async_tx_descriptor *tx;
1029        struct page **blocks = percpu->scribble;
1030        struct async_submit_ctl submit;
1031
1032        pr_debug("%s: stripe %llu block1: %d block2: %d\n",
1033                 __func__, (unsigned long long)sh->sector, target, target2);
1034        BUG_ON(target < 0 || target2 < 0);
1035        BUG_ON(!test_bit(R5_Wantcompute, &tgt->flags));
1036        BUG_ON(!test_bit(R5_Wantcompute, &tgt2->flags));
1037
1038        /* we need to open-code set_syndrome_sources to handle the
1039         * slot number conversion for 'faila' and 'failb'
1040         */
1041        for (i = 0; i < disks ; i++)
1042                blocks[i] = NULL;
1043        count = 0;
1044        i = d0_idx;
1045        do {
1046                int slot = raid6_idx_to_slot(i, sh, &count, syndrome_disks);
1047
1048                blocks[slot] = sh->dev[i].page;
1049
1050                if (i == target)
1051                        faila = slot;
1052                if (i == target2)
1053                        failb = slot;
1054                i = raid6_next_disk(i, disks);
1055        } while (i != d0_idx);
1056
1057        BUG_ON(faila == failb);
1058        if (failb < faila)
1059                swap(faila, failb);
1060        pr_debug("%s: stripe: %llu faila: %d failb: %d\n",
1061                 __func__, (unsigned long long)sh->sector, faila, failb);
1062
1063        atomic_inc(&sh->count);
1064
1065        if (failb == syndrome_disks+1) {
1066                /* Q disk is one of the missing disks */
1067                if (faila == syndrome_disks) {
1068                        /* Missing P+Q, just recompute */
1069                        init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1070                                          ops_complete_compute, sh,
1071                                          to_addr_conv(sh, percpu));
1072                        return async_gen_syndrome(blocks, 0, syndrome_disks+2,
1073                                                  STRIPE_SIZE, &submit);
1074                } else {
1075                        struct page *dest;
1076                        int data_target;
1077                        int qd_idx = sh->qd_idx;
1078
1079                        /* Missing D+Q: recompute D from P, then recompute Q */
1080                        if (target == qd_idx)
1081                                data_target = target2;
1082                        else
1083                                data_target = target;
1084
1085                        count = 0;
1086                        for (i = disks; i-- ; ) {
1087                                if (i == data_target || i == qd_idx)
1088                                        continue;
1089                                blocks[count++] = sh->dev[i].page;
1090                        }
1091                        dest = sh->dev[data_target].page;
1092                        init_async_submit(&submit,
1093                                          ASYNC_TX_FENCE|ASYNC_TX_XOR_ZERO_DST,
1094                                          NULL, NULL, NULL,
1095                                          to_addr_conv(sh, percpu));
1096                        tx = async_xor(dest, blocks, 0, count, STRIPE_SIZE,
1097                                       &submit);
1098
1099                        count = set_syndrome_sources(blocks, sh);
1100                        init_async_submit(&submit, ASYNC_TX_FENCE, tx,
1101                                          ops_complete_compute, sh,
1102                                          to_addr_conv(sh, percpu));
1103                        return async_gen_syndrome(blocks, 0, count+2,
1104                                                  STRIPE_SIZE, &submit);
1105                }
1106        } else {
1107                init_async_submit(&submit, ASYNC_TX_FENCE, NULL,
1108                                  ops_complete_compute, sh,
1109                                  to_addr_conv(sh, percpu));
1110                if (failb == syndrome_disks) {
1111                        /* We're missing D+P. */
1112                        return async_raid6_datap_recov(syndrome_disks+2,
1113                                                       STRIPE_SIZE, faila,
1114                                                       blocks, &submit);
1115                } else {
1116                        /* We're missing D+D. */
1117                        return async_raid6_2data_recov(syndrome_disks+2,
1118                                                       STRIPE_SIZE, faila, failb,
1119                                                       blocks, &submit);
1120                }
1121        }
1122}
1123
1124
1125static void ops_complete_prexor(void *stripe_head_ref)
1126{
1127        struct stripe_head *sh = stripe_head_ref;
1128
1129        pr_debug("%s: stripe %llu\n", __func__,
1130                (unsigned long long)sh->sector);
1131}
1132
1133static struct dma_async_tx_descriptor *
1134ops_run_prexor(struct stripe_head *sh, struct raid5_percpu *percpu,
1135               struct dma_async_tx_descriptor *tx)
1136{
1137        int disks = sh->disks;
1138        struct page **xor_srcs = percpu->scribble;
1139        int count = 0, pd_idx = sh->pd_idx, i;
1140        struct async_submit_ctl submit;
1141
1142        /* existing parity data subtracted */
1143        struct page *xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1144
1145        pr_debug("%s: stripe %llu\n", __func__,
1146                (unsigned long long)sh->sector);
1147
1148        for (i = disks; i--; ) {
1149                struct r5dev *dev = &sh->dev[i];
1150                /* Only process blocks that are known to be uptodate */
1151                if (test_bit(R5_Wantdrain, &dev->flags))
1152                        xor_srcs[count++] = dev->page;
1153        }
1154
1155        init_async_submit(&submit, ASYNC_TX_FENCE|ASYNC_TX_XOR_DROP_DST, tx,
1156                          ops_complete_prexor, sh, to_addr_conv(sh, percpu));
1157        tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1158
1159        return tx;
1160}
1161
1162static struct dma_async_tx_descriptor *
1163ops_run_biodrain(struct stripe_head *sh, struct dma_async_tx_descriptor *tx)
1164{
1165        int disks = sh->disks;
1166        int i;
1167
1168        pr_debug("%s: stripe %llu\n", __func__,
1169                (unsigned long long)sh->sector);
1170
1171        for (i = disks; i--; ) {
1172                struct r5dev *dev = &sh->dev[i];
1173                struct bio *chosen;
1174
1175                if (test_and_clear_bit(R5_Wantdrain, &dev->flags)) {
1176                        struct bio *wbi;
1177
1178                        spin_lock_irq(&sh->stripe_lock);
1179                        chosen = dev->towrite;
1180                        dev->towrite = NULL;
1181                        BUG_ON(dev->written);
1182                        wbi = dev->written = chosen;
1183                        spin_unlock_irq(&sh->stripe_lock);
1184
1185                        while (wbi && wbi->bi_sector <
1186                                dev->sector + STRIPE_SECTORS) {
1187                                if (wbi->bi_rw & REQ_FUA)
1188                                        set_bit(R5_WantFUA, &dev->flags);
1189                                if (wbi->bi_rw & REQ_SYNC)
1190                                        set_bit(R5_SyncIO, &dev->flags);
1191                                if (wbi->bi_rw & REQ_DISCARD)
1192                                        set_bit(R5_Discard, &dev->flags);
1193                                else
1194                                        tx = async_copy_data(1, wbi, dev->page,
1195                                                dev->sector, tx);
1196                                wbi = r5_next_bio(wbi, dev->sector);
1197                        }
1198                }
1199        }
1200
1201        return tx;
1202}
1203
1204static void ops_complete_reconstruct(void *stripe_head_ref)
1205{
1206        struct stripe_head *sh = stripe_head_ref;
1207        int disks = sh->disks;
1208        int pd_idx = sh->pd_idx;
1209        int qd_idx = sh->qd_idx;
1210        int i;
1211        bool fua = false, sync = false, discard = false;
1212
1213        pr_debug("%s: stripe %llu\n", __func__,
1214                (unsigned long long)sh->sector);
1215
1216        for (i = disks; i--; ) {
1217                fua |= test_bit(R5_WantFUA, &sh->dev[i].flags);
1218                sync |= test_bit(R5_SyncIO, &sh->dev[i].flags);
1219                discard |= test_bit(R5_Discard, &sh->dev[i].flags);
1220        }
1221
1222        for (i = disks; i--; ) {
1223                struct r5dev *dev = &sh->dev[i];
1224
1225                if (dev->written || i == pd_idx || i == qd_idx) {
1226                        if (!discard)
1227                                set_bit(R5_UPTODATE, &dev->flags);
1228                        if (fua)
1229                                set_bit(R5_WantFUA, &dev->flags);
1230                        if (sync)
1231                                set_bit(R5_SyncIO, &dev->flags);
1232                }
1233        }
1234
1235        if (sh->reconstruct_state == reconstruct_state_drain_run)
1236                sh->reconstruct_state = reconstruct_state_drain_result;
1237        else if (sh->reconstruct_state == reconstruct_state_prexor_drain_run)
1238                sh->reconstruct_state = reconstruct_state_prexor_drain_result;
1239        else {
1240                BUG_ON(sh->reconstruct_state != reconstruct_state_run);
1241                sh->reconstruct_state = reconstruct_state_result;
1242        }
1243
1244        set_bit(STRIPE_HANDLE, &sh->state);
1245        release_stripe(sh);
1246}
1247
1248static void
1249ops_run_reconstruct5(struct stripe_head *sh, struct raid5_percpu *percpu,
1250                     struct dma_async_tx_descriptor *tx)
1251{
1252        int disks = sh->disks;
1253        struct page **xor_srcs = percpu->scribble;
1254        struct async_submit_ctl submit;
1255        int count = 0, pd_idx = sh->pd_idx, i;
1256        struct page *xor_dest;
1257        int prexor = 0;
1258        unsigned long flags;
1259
1260        pr_debug("%s: stripe %llu\n", __func__,
1261                (unsigned long long)sh->sector);
1262
1263        for (i = 0; i < sh->disks; i++) {
1264                if (pd_idx == i)
1265                        continue;
1266                if (!test_bit(R5_Discard, &sh->dev[i].flags))
1267                        break;
1268        }
1269        if (i >= sh->disks) {
1270                atomic_inc(&sh->count);
1271                set_bit(R5_Discard, &sh->dev[pd_idx].flags);
1272                ops_complete_reconstruct(sh);
1273                return;
1274        }
1275        /* check if prexor is active which means only process blocks
1276         * that are part of a read-modify-write (written)
1277         */
1278        if (sh->reconstruct_state == reconstruct_state_prexor_drain_run) {
1279                prexor = 1;
1280                xor_dest = xor_srcs[count++] = sh->dev[pd_idx].page;
1281                for (i = disks; i--; ) {
1282                        struct r5dev *dev = &sh->dev[i];
1283                        if (dev->written)
1284                                xor_srcs[count++] = dev->page;
1285                }
1286        } else {
1287                xor_dest = sh->dev[pd_idx].page;
1288                for (i = disks; i--; ) {
1289                        struct r5dev *dev = &sh->dev[i];
1290                        if (i != pd_idx)
1291                                xor_srcs[count++] = dev->page;
1292                }
1293        }
1294
1295        /* 1/ if we prexor'd then the dest is reused as a source
1296         * 2/ if we did not prexor then we are redoing the parity
1297         * set ASYNC_TX_XOR_DROP_DST and ASYNC_TX_XOR_ZERO_DST
1298         * for the synchronous xor case
1299         */
1300        flags = ASYNC_TX_ACK |
1301                (prexor ? ASYNC_TX_XOR_DROP_DST : ASYNC_TX_XOR_ZERO_DST);
1302
1303        atomic_inc(&sh->count);
1304
1305        init_async_submit(&submit, flags, tx, ops_complete_reconstruct, sh,
1306                          to_addr_conv(sh, percpu));
1307        if (unlikely(count == 1))
1308                tx = async_memcpy(xor_dest, xor_srcs[0], 0, 0, STRIPE_SIZE, &submit);
1309        else
1310                tx = async_xor(xor_dest, xor_srcs, 0, count, STRIPE_SIZE, &submit);
1311}
1312
1313static void
1314ops_run_reconstruct6(struct stripe_head *sh, struct raid5_percpu *percpu,
1315                     struct dma_async_tx_descriptor *tx)
1316{
1317        struct async_submit_ctl submit;
1318        struct page **blocks = percpu->scribble;
1319        int count, i;
1320
1321        pr_debug("%s: stripe %llu\n", __func__, (unsigned long long)sh->sector);
1322
1323        for (i = 0; i < sh->disks; i++) {
1324                if (sh->pd_idx == i || sh->qd_idx == i)
1325                        continue;
1326                if (!test_bit(R5_Discard, &sh->dev[i].flags))
1327                        break;
1328        }
1329        if (i >= sh->disks) {
1330                atomic_inc(&sh->count);
1331                set_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
1332                set_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
1333                ops_complete_reconstruct(sh);
1334                return;
1335        }
1336
1337        count = set_syndrome_sources(blocks, sh);
1338
1339        atomic_inc(&sh->count);
1340
1341        init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_reconstruct,
1342                          sh, to_addr_conv(sh, percpu));
1343        async_gen_syndrome(blocks, 0, count+2, STRIPE_SIZE,  &submit);
1344}
1345
1346static void ops_complete_check(void *stripe_head_ref)
1347{
1348        struct stripe_head *sh = stripe_head_ref;
1349
1350        pr_debug("%s: stripe %llu\n", __func__,
1351                (unsigned long long)sh->sector);
1352
1353        sh->check_state = check_state_check_result;
1354        set_bit(STRIPE_HANDLE, &sh->state);
1355        release_stripe(sh);
1356}
1357
1358static void ops_run_check_p(struct stripe_head *sh, struct raid5_percpu *percpu)
1359{
1360        int disks = sh->disks;
1361        int pd_idx = sh->pd_idx;
1362        int qd_idx = sh->qd_idx;
1363        struct page *xor_dest;
1364        struct page **xor_srcs = percpu->scribble;
1365        struct dma_async_tx_descriptor *tx;
1366        struct async_submit_ctl submit;
1367        int count;
1368        int i;
1369
1370        pr_debug("%s: stripe %llu\n", __func__,
1371                (unsigned long long)sh->sector);
1372
1373        count = 0;
1374        xor_dest = sh->dev[pd_idx].page;
1375        xor_srcs[count++] = xor_dest;
1376        for (i = disks; i--; ) {
1377                if (i == pd_idx || i == qd_idx)
1378                        continue;
1379                xor_srcs[count++] = sh->dev[i].page;
1380        }
1381
1382        init_async_submit(&submit, 0, NULL, NULL, NULL,
1383                          to_addr_conv(sh, percpu));
1384        tx = async_xor_val(xor_dest, xor_srcs, 0, count, STRIPE_SIZE,
1385                           &sh->ops.zero_sum_result, &submit);
1386
1387        atomic_inc(&sh->count);
1388        init_async_submit(&submit, ASYNC_TX_ACK, tx, ops_complete_check, sh, NULL);
1389        tx = async_trigger_callback(&submit);
1390}
1391
1392static void ops_run_check_pq(struct stripe_head *sh, struct raid5_percpu *percpu, int checkp)
1393{
1394        struct page **srcs = percpu->scribble;
1395        struct async_submit_ctl submit;
1396        int count;
1397
1398        pr_debug("%s: stripe %llu checkp: %d\n", __func__,
1399                (unsigned long long)sh->sector, checkp);
1400
1401        count = set_syndrome_sources(srcs, sh);
1402        if (!checkp)
1403                srcs[count] = NULL;
1404
1405        atomic_inc(&sh->count);
1406        init_async_submit(&submit, ASYNC_TX_ACK, NULL, ops_complete_check,
1407                          sh, to_addr_conv(sh, percpu));
1408        async_syndrome_val(srcs, 0, count+2, STRIPE_SIZE,
1409                           &sh->ops.zero_sum_result, percpu->spare_page, &submit);
1410}
1411
1412static void __raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1413{
1414        int overlap_clear = 0, i, disks = sh->disks;
1415        struct dma_async_tx_descriptor *tx = NULL;
1416        struct r5conf *conf = sh->raid_conf;
1417        int level = conf->level;
1418        struct raid5_percpu *percpu;
1419        unsigned long cpu;
1420
1421        cpu = get_cpu();
1422        percpu = per_cpu_ptr(conf->percpu, cpu);
1423        if (test_bit(STRIPE_OP_BIOFILL, &ops_request)) {
1424                ops_run_biofill(sh);
1425                overlap_clear++;
1426        }
1427
1428        if (test_bit(STRIPE_OP_COMPUTE_BLK, &ops_request)) {
1429                if (level < 6)
1430                        tx = ops_run_compute5(sh, percpu);
1431                else {
1432                        if (sh->ops.target2 < 0 || sh->ops.target < 0)
1433                                tx = ops_run_compute6_1(sh, percpu);
1434                        else
1435                                tx = ops_run_compute6_2(sh, percpu);
1436                }
1437                /* terminate the chain if reconstruct is not set to be run */
1438                if (tx && !test_bit(STRIPE_OP_RECONSTRUCT, &ops_request))
1439                        async_tx_ack(tx);
1440        }
1441
1442        if (test_bit(STRIPE_OP_PREXOR, &ops_request))
1443                tx = ops_run_prexor(sh, percpu, tx);
1444
1445        if (test_bit(STRIPE_OP_BIODRAIN, &ops_request)) {
1446                tx = ops_run_biodrain(sh, tx);
1447                overlap_clear++;
1448        }
1449
1450        if (test_bit(STRIPE_OP_RECONSTRUCT, &ops_request)) {
1451                if (level < 6)
1452                        ops_run_reconstruct5(sh, percpu, tx);
1453                else
1454                        ops_run_reconstruct6(sh, percpu, tx);
1455        }
1456
1457        if (test_bit(STRIPE_OP_CHECK, &ops_request)) {
1458                if (sh->check_state == check_state_run)
1459                        ops_run_check_p(sh, percpu);
1460                else if (sh->check_state == check_state_run_q)
1461                        ops_run_check_pq(sh, percpu, 0);
1462                else if (sh->check_state == check_state_run_pq)
1463                        ops_run_check_pq(sh, percpu, 1);
1464                else
1465                        BUG();
1466        }
1467
1468        if (overlap_clear)
1469                for (i = disks; i--; ) {
1470                        struct r5dev *dev = &sh->dev[i];
1471                        if (test_and_clear_bit(R5_Overlap, &dev->flags))
1472                                wake_up(&sh->raid_conf->wait_for_overlap);
1473                }
1474        put_cpu();
1475}
1476
1477#ifdef CONFIG_MULTICORE_RAID456
1478static void async_run_ops(void *param, async_cookie_t cookie)
1479{
1480        struct stripe_head *sh = param;
1481        unsigned long ops_request = sh->ops.request;
1482
1483        clear_bit_unlock(STRIPE_OPS_REQ_PENDING, &sh->state);
1484        wake_up(&sh->ops.wait_for_ops);
1485
1486        __raid_run_ops(sh, ops_request);
1487        release_stripe(sh);
1488}
1489
1490static void raid_run_ops(struct stripe_head *sh, unsigned long ops_request)
1491{
1492        /* since handle_stripe can be called outside of raid5d context
1493         * we need to ensure sh->ops.request is de-staged before another
1494         * request arrives
1495         */
1496        wait_event(sh->ops.wait_for_ops,
1497                   !test_and_set_bit_lock(STRIPE_OPS_REQ_PENDING, &sh->state));
1498        sh->ops.request = ops_request;
1499
1500        atomic_inc(&sh->count);
1501        async_schedule(async_run_ops, sh);
1502}
1503#else
1504#define raid_run_ops __raid_run_ops
1505#endif
1506
1507static int grow_one_stripe(struct r5conf *conf)
1508{
1509        struct stripe_head *sh;
1510        sh = kmem_cache_zalloc(conf->slab_cache, GFP_KERNEL);
1511        if (!sh)
1512                return 0;
1513
1514        sh->raid_conf = conf;
1515        #ifdef CONFIG_MULTICORE_RAID456
1516        init_waitqueue_head(&sh->ops.wait_for_ops);
1517        #endif
1518
1519        spin_lock_init(&sh->stripe_lock);
1520
1521        if (grow_buffers(sh)) {
1522                shrink_buffers(sh);
1523                kmem_cache_free(conf->slab_cache, sh);
1524                return 0;
1525        }
1526        /* we just created an active stripe so... */
1527        atomic_set(&sh->count, 1);
1528        atomic_inc(&conf->active_stripes);
1529        INIT_LIST_HEAD(&sh->lru);
1530        release_stripe(sh);
1531        return 1;
1532}
1533
1534static int grow_stripes(struct r5conf *conf, int num)
1535{
1536        struct kmem_cache *sc;
1537        int devs = max(conf->raid_disks, conf->previous_raid_disks);
1538
1539        if (conf->mddev->gendisk)
1540                sprintf(conf->cache_name[0],
1541                        "raid%d-%s", conf->level, mdname(conf->mddev));
1542        else
1543                sprintf(conf->cache_name[0],
1544                        "raid%d-%p", conf->level, conf->mddev);
1545        sprintf(conf->cache_name[1], "%s-alt", conf->cache_name[0]);
1546
1547        conf->active_name = 0;
1548        sc = kmem_cache_create(conf->cache_name[conf->active_name],
1549                               sizeof(struct stripe_head)+(devs-1)*sizeof(struct r5dev),
1550                               0, 0, NULL);
1551        if (!sc)
1552                return 1;
1553        conf->slab_cache = sc;
1554        conf->pool_size = devs;
1555        while (num--)
1556                if (!grow_one_stripe(conf))
1557                        return 1;
1558        return 0;
1559}
1560
1561/**
1562 * scribble_len - return the required size of the scribble region
1563 * @num - total number of disks in the array
1564 *
1565 * The size must be enough to contain:
1566 * 1/ a struct page pointer for each device in the array +2
1567 * 2/ room to convert each entry in (1) to its corresponding dma
1568 *    (dma_map_page()) or page (page_address()) address.
1569 *
1570 * Note: the +2 is for the destination buffers of the ddf/raid6 case where we
1571 * calculate over all devices (not just the data blocks), using zeros in place
1572 * of the P and Q blocks.
1573 */
1574static size_t scribble_len(int num)
1575{
1576        size_t len;
1577
1578        len = sizeof(struct page *) * (num+2) + sizeof(addr_conv_t) * (num+2);
1579
1580        return len;
1581}
1582
1583static int resize_stripes(struct r5conf *conf, int newsize)
1584{
1585        /* Make all the stripes able to hold 'newsize' devices.
1586         * New slots in each stripe get 'page' set to a new page.
1587         *
1588         * This happens in stages:
1589         * 1/ create a new kmem_cache and allocate the required number of
1590         *    stripe_heads.
1591         * 2/ gather all the old stripe_heads and transfer the pages across
1592         *    to the new stripe_heads.  This will have the side effect of
1593         *    freezing the array as once all stripe_heads have been collected,
1594         *    no IO will be possible.  Old stripe heads are freed once their
1595         *    pages have been transferred over, and the old kmem_cache is
1596         *    freed when all stripes are done.
1597         * 3/ reallocate conf->disks to be suitable bigger.  If this fails,
1598         *    we simple return a failre status - no need to clean anything up.
1599         * 4/ allocate new pages for the new slots in the new stripe_heads.
1600         *    If this fails, we don't bother trying the shrink the
1601         *    stripe_heads down again, we just leave them as they are.
1602         *    As each stripe_head is processed the new one is released into
1603         *    active service.
1604         *
1605         * Once step2 is started, we cannot afford to wait for a write,
1606         * so we use GFP_NOIO allocations.
1607         */
1608        struct stripe_head *osh, *nsh;
1609        LIST_HEAD(newstripes);
1610        struct disk_info *ndisks;
1611        unsigned long cpu;
1612        int err;
1613        struct kmem_cache *sc;
1614        int i;
1615
1616        if (newsize <= conf->pool_size)
1617                return 0; /* never bother to shrink */
1618
1619        err = md_allow_write(conf->mddev);
1620        if (err)
1621                return err;
1622
1623        /* Step 1 */
1624        sc = kmem_cache_create(conf->cache_name[1-conf->active_name],
1625                               sizeof(struct stripe_head)+(newsize-1)*sizeof(struct r5dev),
1626                               0, 0, NULL);
1627        if (!sc)
1628                return -ENOMEM;
1629
1630        for (i = conf->max_nr_stripes; i; i--) {
1631                nsh = kmem_cache_zalloc(sc, GFP_KERNEL);
1632                if (!nsh)
1633                        break;
1634
1635                nsh->raid_conf = conf;
1636                #ifdef CONFIG_MULTICORE_RAID456
1637                init_waitqueue_head(&nsh->ops.wait_for_ops);
1638                #endif
1639                spin_lock_init(&nsh->stripe_lock);
1640
1641                list_add(&nsh->lru, &newstripes);
1642        }
1643        if (i) {
1644                /* didn't get enough, give up */
1645                while (!list_empty(&newstripes)) {
1646                        nsh = list_entry(newstripes.next, struct stripe_head, lru);
1647                        list_del(&nsh->lru);
1648                        kmem_cache_free(sc, nsh);
1649                }
1650                kmem_cache_destroy(sc);
1651                return -ENOMEM;
1652        }
1653        /* Step 2 - Must use GFP_NOIO now.
1654         * OK, we have enough stripes, start collecting inactive
1655         * stripes and copying them over
1656         */
1657        list_for_each_entry(nsh, &newstripes, lru) {
1658                spin_lock_irq(&conf->device_lock);
1659                wait_event_lock_irq(conf->wait_for_stripe,
1660                                    !list_empty(&conf->inactive_list),
1661                                    conf->device_lock);
1662                osh = get_free_stripe(conf);
1663                spin_unlock_irq(&conf->device_lock);
1664                atomic_set(&nsh->count, 1);
1665                for(i=0; i<conf->pool_size; i++)
1666                        nsh->dev[i].page = osh->dev[i].page;
1667                for( ; i<newsize; i++)
1668                        nsh->dev[i].page = NULL;
1669                kmem_cache_free(conf->slab_cache, osh);
1670        }
1671        kmem_cache_destroy(conf->slab_cache);
1672
1673        /* Step 3.
1674         * At this point, we are holding all the stripes so the array
1675         * is completely stalled, so now is a good time to resize
1676         * conf->disks and the scribble region
1677         */
1678        ndisks = kzalloc(newsize * sizeof(struct disk_info), GFP_NOIO);
1679        if (ndisks) {
1680                for (i=0; i<conf->raid_disks; i++)
1681                        ndisks[i] = conf->disks[i];
1682                kfree(conf->disks);
1683                conf->disks = ndisks;
1684        } else
1685                err = -ENOMEM;
1686
1687        get_online_cpus();
1688        conf->scribble_len = scribble_len(newsize);
1689        for_each_present_cpu(cpu) {
1690                struct raid5_percpu *percpu;
1691                void *scribble;
1692
1693                percpu = per_cpu_ptr(conf->percpu, cpu);
1694                scribble = kmalloc(conf->scribble_len, GFP_NOIO);
1695
1696                if (scribble) {
1697                        kfree(percpu->scribble);
1698                        percpu->scribble = scribble;
1699                } else {
1700                        err = -ENOMEM;
1701                        break;
1702                }
1703        }
1704        put_online_cpus();
1705
1706        /* Step 4, return new stripes to service */
1707        while(!list_empty(&newstripes)) {
1708                nsh = list_entry(newstripes.next, struct stripe_head, lru);
1709                list_del_init(&nsh->lru);
1710
1711                for (i=conf->raid_disks; i < newsize; i++)
1712                        if (nsh->dev[i].page == NULL) {
1713                                struct page *p = alloc_page(GFP_NOIO);
1714                                nsh->dev[i].page = p;
1715                                if (!p)
1716                                        err = -ENOMEM;
1717                        }
1718                release_stripe(nsh);
1719        }
1720        /* critical section pass, GFP_NOIO no longer needed */
1721
1722        conf->slab_cache = sc;
1723        conf->active_name = 1-conf->active_name;
1724        conf->pool_size = newsize;
1725        return err;
1726}
1727
1728static int drop_one_stripe(struct r5conf *conf)
1729{
1730        struct stripe_head *sh;
1731
1732        spin_lock_irq(&conf->device_lock);
1733        sh = get_free_stripe(conf);
1734        spin_unlock_irq(&conf->device_lock);
1735        if (!sh)
1736                return 0;
1737        BUG_ON(atomic_read(&sh->count));
1738        shrink_buffers(sh);
1739        kmem_cache_free(conf->slab_cache, sh);
1740        atomic_dec(&conf->active_stripes);
1741        return 1;
1742}
1743
1744static void shrink_stripes(struct r5conf *conf)
1745{
1746        while (drop_one_stripe(conf))
1747                ;
1748
1749        if (conf->slab_cache)
1750                kmem_cache_destroy(conf->slab_cache);
1751        conf->slab_cache = NULL;
1752}
1753
1754static void raid5_end_read_request(struct bio * bi, int error)
1755{
1756        struct stripe_head *sh = bi->bi_private;
1757        struct r5conf *conf = sh->raid_conf;
1758        int disks = sh->disks, i;
1759        int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1760        char b[BDEVNAME_SIZE];
1761        struct md_rdev *rdev = NULL;
1762        sector_t s;
1763
1764        for (i=0 ; i<disks; i++)
1765                if (bi == &sh->dev[i].req)
1766                        break;
1767
1768        pr_debug("end_read_request %llu/%d, count: %d, uptodate %d.\n",
1769                (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1770                uptodate);
1771        if (i == disks) {
1772                BUG();
1773                return;
1774        }
1775        if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1776                /* If replacement finished while this request was outstanding,
1777                 * 'replacement' might be NULL already.
1778                 * In that case it moved down to 'rdev'.
1779                 * rdev is not removed until all requests are finished.
1780                 */
1781                rdev = conf->disks[i].replacement;
1782        if (!rdev)
1783                rdev = conf->disks[i].rdev;
1784
1785        if (use_new_offset(conf, sh))
1786                s = sh->sector + rdev->new_data_offset;
1787        else
1788                s = sh->sector + rdev->data_offset;
1789        if (uptodate) {
1790                set_bit(R5_UPTODATE, &sh->dev[i].flags);
1791                if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
1792                        /* Note that this cannot happen on a
1793                         * replacement device.  We just fail those on
1794                         * any error
1795                         */
1796                        printk_ratelimited(
1797                                KERN_INFO
1798                                "md/raid:%s: read error corrected"
1799                                " (%lu sectors at %llu on %s)\n",
1800                                mdname(conf->mddev), STRIPE_SECTORS,
1801                                (unsigned long long)s,
1802                                bdevname(rdev->bdev, b));
1803                        atomic_add(STRIPE_SECTORS, &rdev->corrected_errors);
1804                        clear_bit(R5_ReadError, &sh->dev[i].flags);
1805                        clear_bit(R5_ReWrite, &sh->dev[i].flags);
1806                } else if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags))
1807                        clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1808
1809                if (atomic_read(&rdev->read_errors))
1810                        atomic_set(&rdev->read_errors, 0);
1811        } else {
1812                const char *bdn = bdevname(rdev->bdev, b);
1813                int retry = 0;
1814                int set_bad = 0;
1815
1816                clear_bit(R5_UPTODATE, &sh->dev[i].flags);
1817                atomic_inc(&rdev->read_errors);
1818                if (test_bit(R5_ReadRepl, &sh->dev[i].flags))
1819                        printk_ratelimited(
1820                                KERN_WARNING
1821                                "md/raid:%s: read error on replacement device "
1822                                "(sector %llu on %s).\n",
1823                                mdname(conf->mddev),
1824                                (unsigned long long)s,
1825                                bdn);
1826                else if (conf->mddev->degraded >= conf->max_degraded) {
1827                        set_bad = 1;
1828                        printk_ratelimited(
1829                                KERN_WARNING
1830                                "md/raid:%s: read error not correctable "
1831                                "(sector %llu on %s).\n",
1832                                mdname(conf->mddev),
1833                                (unsigned long long)s,
1834                                bdn);
1835                } else if (test_bit(R5_ReWrite, &sh->dev[i].flags)) {
1836                        /* Oh, no!!! */
1837                        set_bad = 1;
1838                        printk_ratelimited(
1839                                KERN_WARNING
1840                                "md/raid:%s: read error NOT corrected!! "
1841                                "(sector %llu on %s).\n",
1842                                mdname(conf->mddev),
1843                                (unsigned long long)s,
1844                                bdn);
1845                } else if (atomic_read(&rdev->read_errors)
1846                         > conf->max_nr_stripes)
1847                        printk(KERN_WARNING
1848                               "md/raid:%s: Too many read errors, failing device %s.\n",
1849                               mdname(conf->mddev), bdn);
1850                else
1851                        retry = 1;
1852                if (retry)
1853                        if (test_bit(R5_ReadNoMerge, &sh->dev[i].flags)) {
1854                                set_bit(R5_ReadError, &sh->dev[i].flags);
1855                                clear_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1856                        } else
1857                                set_bit(R5_ReadNoMerge, &sh->dev[i].flags);
1858                else {
1859                        clear_bit(R5_ReadError, &sh->dev[i].flags);
1860                        clear_bit(R5_ReWrite, &sh->dev[i].flags);
1861                        if (!(set_bad
1862                              && test_bit(In_sync, &rdev->flags)
1863                              && rdev_set_badblocks(
1864                                      rdev, sh->sector, STRIPE_SECTORS, 0)))
1865                                md_error(conf->mddev, rdev);
1866                }
1867        }
1868        rdev_dec_pending(rdev, conf->mddev);
1869        clear_bit(R5_LOCKED, &sh->dev[i].flags);
1870        set_bit(STRIPE_HANDLE, &sh->state);
1871        release_stripe(sh);
1872}
1873
1874static void raid5_end_write_request(struct bio *bi, int error)
1875{
1876        struct stripe_head *sh = bi->bi_private;
1877        struct r5conf *conf = sh->raid_conf;
1878        int disks = sh->disks, i;
1879        struct md_rdev *uninitialized_var(rdev);
1880        int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
1881        sector_t first_bad;
1882        int bad_sectors;
1883        int replacement = 0;
1884
1885        for (i = 0 ; i < disks; i++) {
1886                if (bi == &sh->dev[i].req) {
1887                        rdev = conf->disks[i].rdev;
1888                        break;
1889                }
1890                if (bi == &sh->dev[i].rreq) {
1891                        rdev = conf->disks[i].replacement;
1892                        if (rdev)
1893                                replacement = 1;
1894                        else
1895                                /* rdev was removed and 'replacement'
1896                                 * replaced it.  rdev is not removed
1897                                 * until all requests are finished.
1898                                 */
1899                                rdev = conf->disks[i].rdev;
1900                        break;
1901                }
1902        }
1903        pr_debug("end_write_request %llu/%d, count %d, uptodate: %d.\n",
1904                (unsigned long long)sh->sector, i, atomic_read(&sh->count),
1905                uptodate);
1906        if (i == disks) {
1907                BUG();
1908                return;
1909        }
1910
1911        if (replacement) {
1912                if (!uptodate)
1913                        md_error(conf->mddev, rdev);
1914                else if (is_badblock(rdev, sh->sector,
1915                                     STRIPE_SECTORS,
1916                                     &first_bad, &bad_sectors))
1917                        set_bit(R5_MadeGoodRepl, &sh->dev[i].flags);
1918        } else {
1919                if (!uptodate) {
1920                        set_bit(WriteErrorSeen, &rdev->flags);
1921                        set_bit(R5_WriteError, &sh->dev[i].flags);
1922                        if (!test_and_set_bit(WantReplacement, &rdev->flags))
1923                                set_bit(MD_RECOVERY_NEEDED,
1924                                        &rdev->mddev->recovery);
1925                } else if (is_badblock(rdev, sh->sector,
1926                                       STRIPE_SECTORS,
1927                                       &first_bad, &bad_sectors))
1928                        set_bit(R5_MadeGood, &sh->dev[i].flags);
1929        }
1930        rdev_dec_pending(rdev, conf->mddev);
1931
1932        if (!test_and_clear_bit(R5_DOUBLE_LOCKED, &sh->dev[i].flags))
1933                clear_bit(R5_LOCKED, &sh->dev[i].flags);
1934        set_bit(STRIPE_HANDLE, &sh->state);
1935        release_stripe(sh);
1936}
1937
1938static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous);
1939        
1940static void raid5_build_block(struct stripe_head *sh, int i, int previous)
1941{
1942        struct r5dev *dev = &sh->dev[i];
1943
1944        bio_init(&dev->req);
1945        dev->req.bi_io_vec = &dev->vec;
1946        dev->req.bi_vcnt++;
1947        dev->req.bi_max_vecs++;
1948        dev->req.bi_private = sh;
1949        dev->vec.bv_page = dev->page;
1950
1951        bio_init(&dev->rreq);
1952        dev->rreq.bi_io_vec = &dev->rvec;
1953        dev->rreq.bi_vcnt++;
1954        dev->rreq.bi_max_vecs++;
1955        dev->rreq.bi_private = sh;
1956        dev->rvec.bv_page = dev->page;
1957
1958        dev->flags = 0;
1959        dev->sector = compute_blocknr(sh, i, previous);
1960}
1961
1962static void error(struct mddev *mddev, struct md_rdev *rdev)
1963{
1964        char b[BDEVNAME_SIZE];
1965        struct r5conf *conf = mddev->private;
1966        unsigned long flags;
1967        pr_debug("raid456: error called\n");
1968
1969        spin_lock_irqsave(&conf->device_lock, flags);
1970        clear_bit(In_sync, &rdev->flags);
1971        mddev->degraded = calc_degraded(conf);
1972        spin_unlock_irqrestore(&conf->device_lock, flags);
1973        set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1974
1975        set_bit(Blocked, &rdev->flags);
1976        set_bit(Faulty, &rdev->flags);
1977        set_bit(MD_CHANGE_DEVS, &mddev->flags);
1978        printk(KERN_ALERT
1979               "md/raid:%s: Disk failure on %s, disabling device.\n"
1980               "md/raid:%s: Operation continuing on %d devices.\n",
1981               mdname(mddev),
1982               bdevname(rdev->bdev, b),
1983               mdname(mddev),
1984               conf->raid_disks - mddev->degraded);
1985}
1986
1987/*
1988 * Input: a 'big' sector number,
1989 * Output: index of the data and parity disk, and the sector # in them.
1990 */
1991static sector_t raid5_compute_sector(struct r5conf *conf, sector_t r_sector,
1992                                     int previous, int *dd_idx,
1993                                     struct stripe_head *sh)
1994{
1995        sector_t stripe, stripe2;
1996        sector_t chunk_number;
1997        unsigned int chunk_offset;
1998        int pd_idx, qd_idx;
1999        int ddf_layout = 0;
2000        sector_t new_sector;
2001        int algorithm = previous ? conf->prev_algo
2002                                 : conf->algorithm;
2003        int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2004                                         : conf->chunk_sectors;
2005        int raid_disks = previous ? conf->previous_raid_disks
2006                                  : conf->raid_disks;
2007        int data_disks = raid_disks - conf->max_degraded;
2008
2009        /* First compute the information on this sector */
2010
2011        /*
2012         * Compute the chunk number and the sector offset inside the chunk
2013         */
2014        chunk_offset = sector_div(r_sector, sectors_per_chunk);
2015        chunk_number = r_sector;
2016
2017        /*
2018         * Compute the stripe number
2019         */
2020        stripe = chunk_number;
2021        *dd_idx = sector_div(stripe, data_disks);
2022        stripe2 = stripe;
2023        /*
2024         * Select the parity disk based on the user selected algorithm.
2025         */
2026        pd_idx = qd_idx = -1;
2027        switch(conf->level) {
2028        case 4:
2029                pd_idx = data_disks;
2030                break;
2031        case 5:
2032                switch (algorithm) {
2033                case ALGORITHM_LEFT_ASYMMETRIC:
2034                        pd_idx = data_disks - sector_div(stripe2, raid_disks);
2035                        if (*dd_idx >= pd_idx)
2036                                (*dd_idx)++;
2037                        break;
2038                case ALGORITHM_RIGHT_ASYMMETRIC:
2039                        pd_idx = sector_div(stripe2, raid_disks);
2040                        if (*dd_idx >= pd_idx)
2041                                (*dd_idx)++;
2042                        break;
2043                case ALGORITHM_LEFT_SYMMETRIC:
2044                        pd_idx = data_disks - sector_div(stripe2, raid_disks);
2045                        *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2046                        break;
2047                case ALGORITHM_RIGHT_SYMMETRIC:
2048                        pd_idx = sector_div(stripe2, raid_disks);
2049                        *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2050                        break;
2051                case ALGORITHM_PARITY_0:
2052                        pd_idx = 0;
2053                        (*dd_idx)++;
2054                        break;
2055                case ALGORITHM_PARITY_N:
2056                        pd_idx = data_disks;
2057                        break;
2058                default:
2059                        BUG();
2060                }
2061                break;
2062        case 6:
2063
2064                switch (algorithm) {
2065                case ALGORITHM_LEFT_ASYMMETRIC:
2066                        pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2067                        qd_idx = pd_idx + 1;
2068                        if (pd_idx == raid_disks-1) {
2069                                (*dd_idx)++;    /* Q D D D P */
2070                                qd_idx = 0;
2071                        } else if (*dd_idx >= pd_idx)
2072                                (*dd_idx) += 2; /* D D P Q D */
2073                        break;
2074                case ALGORITHM_RIGHT_ASYMMETRIC:
2075                        pd_idx = sector_div(stripe2, raid_disks);
2076                        qd_idx = pd_idx + 1;
2077                        if (pd_idx == raid_disks-1) {
2078                                (*dd_idx)++;    /* Q D D D P */
2079                                qd_idx = 0;
2080                        } else if (*dd_idx >= pd_idx)
2081                                (*dd_idx) += 2; /* D D P Q D */
2082                        break;
2083                case ALGORITHM_LEFT_SYMMETRIC:
2084                        pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2085                        qd_idx = (pd_idx + 1) % raid_disks;
2086                        *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2087                        break;
2088                case ALGORITHM_RIGHT_SYMMETRIC:
2089                        pd_idx = sector_div(stripe2, raid_disks);
2090                        qd_idx = (pd_idx + 1) % raid_disks;
2091                        *dd_idx = (pd_idx + 2 + *dd_idx) % raid_disks;
2092                        break;
2093
2094                case ALGORITHM_PARITY_0:
2095                        pd_idx = 0;
2096                        qd_idx = 1;
2097                        (*dd_idx) += 2;
2098                        break;
2099                case ALGORITHM_PARITY_N:
2100                        pd_idx = data_disks;
2101                        qd_idx = data_disks + 1;
2102                        break;
2103
2104                case ALGORITHM_ROTATING_ZERO_RESTART:
2105                        /* Exactly the same as RIGHT_ASYMMETRIC, but or
2106                         * of blocks for computing Q is different.
2107                         */
2108                        pd_idx = sector_div(stripe2, raid_disks);
2109                        qd_idx = pd_idx + 1;
2110                        if (pd_idx == raid_disks-1) {
2111                                (*dd_idx)++;    /* Q D D D P */
2112                                qd_idx = 0;
2113                        } else if (*dd_idx >= pd_idx)
2114                                (*dd_idx) += 2; /* D D P Q D */
2115                        ddf_layout = 1;
2116                        break;
2117
2118                case ALGORITHM_ROTATING_N_RESTART:
2119                        /* Same a left_asymmetric, by first stripe is
2120                         * D D D P Q  rather than
2121                         * Q D D D P
2122                         */
2123                        stripe2 += 1;
2124                        pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2125                        qd_idx = pd_idx + 1;
2126                        if (pd_idx == raid_disks-1) {
2127                                (*dd_idx)++;    /* Q D D D P */
2128                                qd_idx = 0;
2129                        } else if (*dd_idx >= pd_idx)
2130                                (*dd_idx) += 2; /* D D P Q D */
2131                        ddf_layout = 1;
2132                        break;
2133
2134                case ALGORITHM_ROTATING_N_CONTINUE:
2135                        /* Same as left_symmetric but Q is before P */
2136                        pd_idx = raid_disks - 1 - sector_div(stripe2, raid_disks);
2137                        qd_idx = (pd_idx + raid_disks - 1) % raid_disks;
2138                        *dd_idx = (pd_idx + 1 + *dd_idx) % raid_disks;
2139                        ddf_layout = 1;
2140                        break;
2141
2142                case ALGORITHM_LEFT_ASYMMETRIC_6:
2143                        /* RAID5 left_asymmetric, with Q on last device */
2144                        pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2145                        if (*dd_idx >= pd_idx)
2146                                (*dd_idx)++;
2147                        qd_idx = raid_disks - 1;
2148                        break;
2149
2150                case ALGORITHM_RIGHT_ASYMMETRIC_6:
2151                        pd_idx = sector_div(stripe2, raid_disks-1);
2152                        if (*dd_idx >= pd_idx)
2153                                (*dd_idx)++;
2154                        qd_idx = raid_disks - 1;
2155                        break;
2156
2157                case ALGORITHM_LEFT_SYMMETRIC_6:
2158                        pd_idx = data_disks - sector_div(stripe2, raid_disks-1);
2159                        *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2160                        qd_idx = raid_disks - 1;
2161                        break;
2162
2163                case ALGORITHM_RIGHT_SYMMETRIC_6:
2164                        pd_idx = sector_div(stripe2, raid_disks-1);
2165                        *dd_idx = (pd_idx + 1 + *dd_idx) % (raid_disks-1);
2166                        qd_idx = raid_disks - 1;
2167                        break;
2168
2169                case ALGORITHM_PARITY_0_6:
2170                        pd_idx = 0;
2171                        (*dd_idx)++;
2172                        qd_idx = raid_disks - 1;
2173                        break;
2174
2175                default:
2176                        BUG();
2177                }
2178                break;
2179        }
2180
2181        if (sh) {
2182                sh->pd_idx = pd_idx;
2183                sh->qd_idx = qd_idx;
2184                sh->ddf_layout = ddf_layout;
2185        }
2186        /*
2187         * Finally, compute the new sector number
2188         */
2189        new_sector = (sector_t)stripe * sectors_per_chunk + chunk_offset;
2190        return new_sector;
2191}
2192
2193
2194static sector_t compute_blocknr(struct stripe_head *sh, int i, int previous)
2195{
2196        struct r5conf *conf = sh->raid_conf;
2197        int raid_disks = sh->disks;
2198        int data_disks = raid_disks - conf->max_degraded;
2199        sector_t new_sector = sh->sector, check;
2200        int sectors_per_chunk = previous ? conf->prev_chunk_sectors
2201                                         : conf->chunk_sectors;
2202        int algorithm = previous ? conf->prev_algo
2203                                 : conf->algorithm;
2204        sector_t stripe;
2205        int chunk_offset;
2206        sector_t chunk_number;
2207        int dummy1, dd_idx = i;
2208        sector_t r_sector;
2209        struct stripe_head sh2;
2210
2211
2212        chunk_offset = sector_div(new_sector, sectors_per_chunk);
2213        stripe = new_sector;
2214
2215        if (i == sh->pd_idx)
2216                return 0;
2217        switch(conf->level) {
2218        case 4: break;
2219        case 5:
2220                switch (algorithm) {
2221                case ALGORITHM_LEFT_ASYMMETRIC:
2222                case ALGORITHM_RIGHT_ASYMMETRIC:
2223                        if (i > sh->pd_idx)
2224                                i--;
2225                        break;
2226                case ALGORITHM_LEFT_SYMMETRIC:
2227                case ALGORITHM_RIGHT_SYMMETRIC:
2228                        if (i < sh->pd_idx)
2229                                i += raid_disks;
2230                        i -= (sh->pd_idx + 1);
2231                        break;
2232                case ALGORITHM_PARITY_0:
2233                        i -= 1;
2234                        break;
2235                case ALGORITHM_PARITY_N:
2236                        break;
2237                default:
2238                        BUG();
2239                }
2240                break;
2241        case 6:
2242                if (i == sh->qd_idx)
2243                        return 0; /* It is the Q disk */
2244                switch (algorithm) {
2245                case ALGORITHM_LEFT_ASYMMETRIC:
2246                case ALGORITHM_RIGHT_ASYMMETRIC:
2247                case ALGORITHM_ROTATING_ZERO_RESTART:
2248                case ALGORITHM_ROTATING_N_RESTART:
2249                        if (sh->pd_idx == raid_disks-1)
2250                                i--;    /* Q D D D P */
2251                        else if (i > sh->pd_idx)
2252                                i -= 2; /* D D P Q D */
2253                        break;
2254                case ALGORITHM_LEFT_SYMMETRIC:
2255                case ALGORITHM_RIGHT_SYMMETRIC:
2256                        if (sh->pd_idx == raid_disks-1)
2257                                i--; /* Q D D D P */
2258                        else {
2259                                /* D D P Q D */
2260                                if (i < sh->pd_idx)
2261                                        i += raid_disks;
2262                                i -= (sh->pd_idx + 2);
2263                        }
2264                        break;
2265                case ALGORITHM_PARITY_0:
2266                        i -= 2;
2267                        break;
2268                case ALGORITHM_PARITY_N:
2269                        break;
2270                case ALGORITHM_ROTATING_N_CONTINUE:
2271                        /* Like left_symmetric, but P is before Q */
2272                        if (sh->pd_idx == 0)
2273                                i--;    /* P D D D Q */
2274                        else {
2275                                /* D D Q P D */
2276                                if (i < sh->pd_idx)
2277                                        i += raid_disks;
2278                                i -= (sh->pd_idx + 1);
2279                        }
2280                        break;
2281                case ALGORITHM_LEFT_ASYMMETRIC_6:
2282                case ALGORITHM_RIGHT_ASYMMETRIC_6:
2283                        if (i > sh->pd_idx)
2284                                i--;
2285                        break;
2286                case ALGORITHM_LEFT_SYMMETRIC_6:
2287                case ALGORITHM_RIGHT_SYMMETRIC_6:
2288                        if (i < sh->pd_idx)
2289                                i += data_disks + 1;
2290                        i -= (sh->pd_idx + 1);
2291                        break;
2292                case ALGORITHM_PARITY_0_6:
2293                        i -= 1;
2294                        break;
2295                default:
2296                        BUG();
2297                }
2298                break;
2299        }
2300
2301        chunk_number = stripe * data_disks + i;
2302        r_sector = chunk_number * sectors_per_chunk + chunk_offset;
2303
2304        check = raid5_compute_sector(conf, r_sector,
2305                                     previous, &dummy1, &sh2);
2306        if (check != sh->sector || dummy1 != dd_idx || sh2.pd_idx != sh->pd_idx
2307                || sh2.qd_idx != sh->qd_idx) {
2308                printk(KERN_ERR "md/raid:%s: compute_blocknr: map not correct\n",
2309                       mdname(conf->mddev));
2310                return 0;
2311        }
2312        return r_sector;
2313}
2314
2315
2316static void
2317schedule_reconstruction(struct stripe_head *sh, struct stripe_head_state *s,
2318                         int rcw, int expand)
2319{
2320        int i, pd_idx = sh->pd_idx, disks = sh->disks;
2321        struct r5conf *conf = sh->raid_conf;
2322        int level = conf->level;
2323
2324        if (rcw) {
2325
2326                for (i = disks; i--; ) {
2327                        struct r5dev *dev = &sh->dev[i];
2328
2329                        if (dev->towrite) {
2330                                set_bit(R5_LOCKED, &dev->flags);
2331                                set_bit(R5_Wantdrain, &dev->flags);
2332                                if (!expand)
2333                                        clear_bit(R5_UPTODATE, &dev->flags);
2334                                s->locked++;
2335                        }
2336                }
2337                /* if we are not expanding this is a proper write request, and
2338                 * there will be bios with new data to be drained into the
2339                 * stripe cache
2340                 */
2341                if (!expand) {
2342                        if (!s->locked)
2343                                /* False alarm, nothing to do */
2344                                return;
2345                        sh->reconstruct_state = reconstruct_state_drain_run;
2346                        set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2347                } else
2348                        sh->reconstruct_state = reconstruct_state_run;
2349
2350                set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2351
2352                if (s->locked + conf->max_degraded == disks)
2353                        if (!test_and_set_bit(STRIPE_FULL_WRITE, &sh->state))
2354                                atomic_inc(&conf->pending_full_writes);
2355        } else {
2356                BUG_ON(level == 6);
2357                BUG_ON(!(test_bit(R5_UPTODATE, &sh->dev[pd_idx].flags) ||
2358                        test_bit(R5_Wantcompute, &sh->dev[pd_idx].flags)));
2359
2360                for (i = disks; i--; ) {
2361                        struct r5dev *dev = &sh->dev[i];
2362                        if (i == pd_idx)
2363                                continue;
2364
2365                        if (dev->towrite &&
2366                            (test_bit(R5_UPTODATE, &dev->flags) ||
2367                             test_bit(R5_Wantcompute, &dev->flags))) {
2368                                set_bit(R5_Wantdrain, &dev->flags);
2369                                set_bit(R5_LOCKED, &dev->flags);
2370                                clear_bit(R5_UPTODATE, &dev->flags);
2371                                s->locked++;
2372                        }
2373                }
2374                if (!s->locked)
2375                        /* False alarm - nothing to do */
2376                        return;
2377                sh->reconstruct_state = reconstruct_state_prexor_drain_run;
2378                set_bit(STRIPE_OP_PREXOR, &s->ops_request);
2379                set_bit(STRIPE_OP_BIODRAIN, &s->ops_request);
2380                set_bit(STRIPE_OP_RECONSTRUCT, &s->ops_request);
2381        }
2382
2383        /* keep the parity disk(s) locked while asynchronous operations
2384         * are in flight
2385         */
2386        set_bit(R5_LOCKED, &sh->dev[pd_idx].flags);
2387        clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
2388        s->locked++;
2389
2390        if (level == 6) {
2391                int qd_idx = sh->qd_idx;
2392                struct r5dev *dev = &sh->dev[qd_idx];
2393
2394                set_bit(R5_LOCKED, &dev->flags);
2395                clear_bit(R5_UPTODATE, &dev->flags);
2396                s->locked++;
2397        }
2398
2399        pr_debug("%s: stripe %llu locked: %d ops_request: %lx\n",
2400                __func__, (unsigned long long)sh->sector,
2401                s->locked, s->ops_request);
2402}
2403
2404/*
2405 * Each stripe/dev can have one or more bion attached.
2406 * toread/towrite point to the first in a chain.
2407 * The bi_next chain must be in order.
2408 */
2409static int add_stripe_bio(struct stripe_head *sh, struct bio *bi, int dd_idx, int forwrite)
2410{
2411        struct bio **bip;
2412        struct r5conf *conf = sh->raid_conf;
2413        int firstwrite=0;
2414
2415        pr_debug("adding bi b#%llu to stripe s#%llu\n",
2416                (unsigned long long)bi->bi_sector,
2417                (unsigned long long)sh->sector);
2418
2419        /*
2420         * If several bio share a stripe. The bio bi_phys_segments acts as a
2421         * reference count to avoid race. The reference count should already be
2422         * increased before this function is called (for example, in
2423         * make_request()), so other bio sharing this stripe will not free the
2424         * stripe. If a stripe is owned by one stripe, the stripe lock will
2425         * protect it.
2426         */
2427        spin_lock_irq(&sh->stripe_lock);
2428        if (forwrite) {
2429                bip = &sh->dev[dd_idx].towrite;
2430                if (*bip == NULL)
2431                        firstwrite = 1;
2432        } else
2433                bip = &sh->dev[dd_idx].toread;
2434        while (*bip && (*bip)->bi_sector < bi->bi_sector) {
2435                if ((*bip)->bi_sector + ((*bip)->bi_size >> 9) > bi->bi_sector)
2436                        goto overlap;
2437                bip = & (*bip)->bi_next;
2438        }
2439        if (*bip && (*bip)->bi_sector < bi->bi_sector + ((bi->bi_size)>>9))
2440                goto overlap;
2441
2442        BUG_ON(*bip && bi->bi_next && (*bip) != bi->bi_next);
2443        if (*bip)
2444                bi->bi_next = *bip;
2445        *bip = bi;
2446        raid5_inc_bi_active_stripes(bi);
2447
2448        if (forwrite) {
2449                /* check if page is covered */
2450                sector_t sector = sh->dev[dd_idx].sector;
2451                for (bi=sh->dev[dd_idx].towrite;
2452                     sector < sh->dev[dd_idx].sector + STRIPE_SECTORS &&
2453                             bi && bi->bi_sector <= sector;
2454                     bi = r5_next_bio(bi, sh->dev[dd_idx].sector)) {
2455                        if (bi->bi_sector + (bi->bi_size>>9) >= sector)
2456                                sector = bi->bi_sector + (bi->bi_size>>9);
2457                }
2458                if (sector >= sh->dev[dd_idx].sector + STRIPE_SECTORS)
2459                        set_bit(R5_OVERWRITE, &sh->dev[dd_idx].flags);
2460        }
2461
2462        pr_debug("added bi b#%llu to stripe s#%llu, disk %d.\n",
2463                (unsigned long long)(*bip)->bi_sector,
2464                (unsigned long long)sh->sector, dd_idx);
2465        spin_unlock_irq(&sh->stripe_lock);
2466
2467        if (conf->mddev->bitmap && firstwrite) {
2468                bitmap_startwrite(conf->mddev->bitmap, sh->sector,
2469                                  STRIPE_SECTORS, 0);
2470                sh->bm_seq = conf->seq_flush+1;
2471                set_bit(STRIPE_BIT_DELAY, &sh->state);
2472        }
2473        return 1;
2474
2475 overlap:
2476        set_bit(R5_Overlap, &sh->dev[dd_idx].flags);
2477        spin_unlock_irq(&sh->stripe_lock);
2478        return 0;
2479}
2480
2481static void end_reshape(struct r5conf *conf);
2482
2483static void stripe_set_idx(sector_t stripe, struct r5conf *conf, int previous,
2484                            struct stripe_head *sh)
2485{
2486        int sectors_per_chunk =
2487                previous ? conf->prev_chunk_sectors : conf->chunk_sectors;
2488        int dd_idx;
2489        int chunk_offset = sector_div(stripe, sectors_per_chunk);
2490        int disks = previous ? conf->previous_raid_disks : conf->raid_disks;
2491
2492        raid5_compute_sector(conf,
2493                             stripe * (disks - conf->max_degraded)
2494                             *sectors_per_chunk + chunk_offset,
2495                             previous,
2496                             &dd_idx, sh);
2497}
2498
2499static void
2500handle_failed_stripe(struct r5conf *conf, struct stripe_head *sh,
2501                                struct stripe_head_state *s, int disks,
2502                                struct bio **return_bi)
2503{
2504        int i;
2505        for (i = disks; i--; ) {
2506                struct bio *bi;
2507                int bitmap_end = 0;
2508
2509                if (test_bit(R5_ReadError, &sh->dev[i].flags)) {
2510                        struct md_rdev *rdev;
2511                        rcu_read_lock();
2512                        rdev = rcu_dereference(conf->disks[i].rdev);
2513                        if (rdev && test_bit(In_sync, &rdev->flags))
2514                                atomic_inc(&rdev->nr_pending);
2515                        else
2516                                rdev = NULL;
2517                        rcu_read_unlock();
2518                        if (rdev) {
2519                                if (!rdev_set_badblocks(
2520                                            rdev,
2521                                            sh->sector,
2522                                            STRIPE_SECTORS, 0))
2523                                        md_error(conf->mddev, rdev);
2524                                rdev_dec_pending(rdev, conf->mddev);
2525                        }
2526                }
2527                spin_lock_irq(&sh->stripe_lock);
2528                /* fail all writes first */
2529                bi = sh->dev[i].towrite;
2530                sh->dev[i].towrite = NULL;
2531                spin_unlock_irq(&sh->stripe_lock);
2532                if (bi)
2533                        bitmap_end = 1;
2534
2535                if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2536                        wake_up(&conf->wait_for_overlap);
2537
2538                while (bi && bi->bi_sector <
2539                        sh->dev[i].sector + STRIPE_SECTORS) {
2540                        struct bio *nextbi = r5_next_bio(bi, sh->dev[i].sector);
2541                        clear_bit(BIO_UPTODATE, &bi->bi_flags);
2542                        if (!raid5_dec_bi_active_stripes(bi)) {
2543                                md_write_end(conf->mddev);
2544                                bi->bi_next = *return_bi;
2545                                *return_bi = bi;
2546                        }
2547                        bi = nextbi;
2548                }
2549                if (bitmap_end)
2550                        bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2551                                STRIPE_SECTORS, 0, 0);
2552                bitmap_end = 0;
2553                /* and fail all 'written' */
2554                bi = sh->dev[i].written;
2555                sh->dev[i].written = NULL;
2556                if (bi) bitmap_end = 1;
2557                while (bi && bi->bi_sector <
2558                       sh->dev[i].sector + STRIPE_SECTORS) {
2559                        struct bio *bi2 = r5_next_bio(bi, sh->dev[i].sector);
2560                        clear_bit(BIO_UPTODATE, &bi->bi_flags);
2561                        if (!raid5_dec_bi_active_stripes(bi)) {
2562                                md_write_end(conf->mddev);
2563                                bi->bi_next = *return_bi;
2564                                *return_bi = bi;
2565                        }
2566                        bi = bi2;
2567                }
2568
2569                /* fail any reads if this device is non-operational and
2570                 * the data has not reached the cache yet.
2571                 */
2572                if (!test_bit(R5_Wantfill, &sh->dev[i].flags) &&
2573                    (!test_bit(R5_Insync, &sh->dev[i].flags) ||
2574                      test_bit(R5_ReadError, &sh->dev[i].flags))) {
2575                        spin_lock_irq(&sh->stripe_lock);
2576                        bi = sh->dev[i].toread;
2577                        sh->dev[i].toread = NULL;
2578                        spin_unlock_irq(&sh->stripe_lock);
2579                        if (test_and_clear_bit(R5_Overlap, &sh->dev[i].flags))
2580                                wake_up(&conf->wait_for_overlap);
2581                        while (bi && bi->bi_sector <
2582                               sh->dev[i].sector + STRIPE_SECTORS) {
2583                                struct bio *nextbi =
2584                                        r5_next_bio(bi, sh->dev[i].sector);
2585                                clear_bit(BIO_UPTODATE, &bi->bi_flags);
2586                                if (!raid5_dec_bi_active_stripes(bi)) {
2587                                        bi->bi_next = *return_bi;
2588                                        *return_bi = bi;
2589                                }
2590                                bi = nextbi;
2591                        }
2592                }
2593                if (bitmap_end)
2594                        bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2595                                        STRIPE_SECTORS, 0, 0);
2596                /* If we were in the middle of a write the parity block might
2597                 * still be locked - so just clear all R5_LOCKED flags
2598                 */
2599                clear_bit(R5_LOCKED, &sh->dev[i].flags);
2600        }
2601
2602        if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2603                if (atomic_dec_and_test(&conf->pending_full_writes))
2604                        md_wakeup_thread(conf->mddev->thread);
2605}
2606
2607static void
2608handle_failed_sync(struct r5conf *conf, struct stripe_head *sh,
2609                   struct stripe_head_state *s)
2610{
2611        int abort = 0;
2612        int i;
2613
2614        clear_bit(STRIPE_SYNCING, &sh->state);
2615        if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
2616                wake_up(&conf->wait_for_overlap);
2617        s->syncing = 0;
2618        s->replacing = 0;
2619        /* There is nothing more to do for sync/check/repair.
2620         * Don't even need to abort as that is handled elsewhere
2621         * if needed, and not always wanted e.g. if there is a known
2622         * bad block here.
2623         * For recover/replace we need to record a bad block on all
2624         * non-sync devices, or abort the recovery
2625         */
2626        if (test_bit(MD_RECOVERY_RECOVER, &conf->mddev->recovery)) {
2627                /* During recovery devices cannot be removed, so
2628                 * locking and refcounting of rdevs is not needed
2629                 */
2630                for (i = 0; i < conf->raid_disks; i++) {
2631                        struct md_rdev *rdev = conf->disks[i].rdev;
2632                        if (rdev
2633                            && !test_bit(Faulty, &rdev->flags)
2634                            && !test_bit(In_sync, &rdev->flags)
2635                            && !rdev_set_badblocks(rdev, sh->sector,
2636                                                   STRIPE_SECTORS, 0))
2637                                abort = 1;
2638                        rdev = conf->disks[i].replacement;
2639                        if (rdev
2640                            && !test_bit(Faulty, &rdev->flags)
2641                            && !test_bit(In_sync, &rdev->flags)
2642                            && !rdev_set_badblocks(rdev, sh->sector,
2643                                                   STRIPE_SECTORS, 0))
2644                                abort = 1;
2645                }
2646                if (abort)
2647                        conf->recovery_disabled =
2648                                conf->mddev->recovery_disabled;
2649        }
2650        md_done_sync(conf->mddev, STRIPE_SECTORS, !abort);
2651}
2652
2653static int want_replace(struct stripe_head *sh, int disk_idx)
2654{
2655        struct md_rdev *rdev;
2656        int rv = 0;
2657        /* Doing recovery so rcu locking not required */
2658        rdev = sh->raid_conf->disks[disk_idx].replacement;
2659        if (rdev
2660            && !test_bit(Faulty, &rdev->flags)
2661            && !test_bit(In_sync, &rdev->flags)
2662            && (rdev->recovery_offset <= sh->sector
2663                || rdev->mddev->recovery_cp <= sh->sector))
2664                rv = 1;
2665
2666        return rv;
2667}
2668
2669/* fetch_block - checks the given member device to see if its data needs
2670 * to be read or computed to satisfy a request.
2671 *
2672 * Returns 1 when no more member devices need to be checked, otherwise returns
2673 * 0 to tell the loop in handle_stripe_fill to continue
2674 */
2675static int fetch_block(struct stripe_head *sh, struct stripe_head_state *s,
2676                       int disk_idx, int disks)
2677{
2678        struct r5dev *dev = &sh->dev[disk_idx];
2679        struct r5dev *fdev[2] = { &sh->dev[s->failed_num[0]],
2680                                  &sh->dev[s->failed_num[1]] };
2681
2682        /* is the data in this block needed, and can we get it? */
2683        if (!test_bit(R5_LOCKED, &dev->flags) &&
2684            !test_bit(R5_UPTODATE, &dev->flags) &&
2685            (dev->toread ||
2686             (dev->towrite && !test_bit(R5_OVERWRITE, &dev->flags)) ||
2687             s->syncing || s->expanding ||
2688             (s->replacing && want_replace(sh, disk_idx)) ||
2689             (s->failed >= 1 && fdev[0]->toread) ||
2690             (s->failed >= 2 && fdev[1]->toread) ||
2691             (sh->raid_conf->level <= 5 && s->failed && fdev[0]->towrite &&
2692              !test_bit(R5_OVERWRITE, &fdev[0]->flags)) ||
2693             (sh->raid_conf->level == 6 && s->failed && s->to_write))) {
2694                /* we would like to get this block, possibly by computing it,
2695                 * otherwise read it if the backing disk is insync
2696                 */
2697                BUG_ON(test_bit(R5_Wantcompute, &dev->flags));
2698                BUG_ON(test_bit(R5_Wantread, &dev->flags));
2699                if ((s->uptodate == disks - 1) &&
2700                    (s->failed && (disk_idx == s->failed_num[0] ||
2701                                   disk_idx == s->failed_num[1]))) {
2702                        /* have disk failed, and we're requested to fetch it;
2703                         * do compute it
2704                         */
2705                        pr_debug("Computing stripe %llu block %d\n",
2706                               (unsigned long long)sh->sector, disk_idx);
2707                        set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2708                        set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2709                        set_bit(R5_Wantcompute, &dev->flags);
2710                        sh->ops.target = disk_idx;
2711                        sh->ops.target2 = -1; /* no 2nd target */
2712                        s->req_compute = 1;
2713                        /* Careful: from this point on 'uptodate' is in the eye
2714                         * of raid_run_ops which services 'compute' operations
2715                         * before writes. R5_Wantcompute flags a block that will
2716                         * be R5_UPTODATE by the time it is needed for a
2717                         * subsequent operation.
2718                         */
2719                        s->uptodate++;
2720                        return 1;
2721                } else if (s->uptodate == disks-2 && s->failed >= 2) {
2722                        /* Computing 2-failure is *very* expensive; only
2723                         * do it if failed >= 2
2724                         */
2725                        int other;
2726                        for (other = disks; other--; ) {
2727                                if (other == disk_idx)
2728                                        continue;
2729                                if (!test_bit(R5_UPTODATE,
2730                                      &sh->dev[other].flags))
2731                                        break;
2732                        }
2733                        BUG_ON(other < 0);
2734                        pr_debug("Computing stripe %llu blocks %d,%d\n",
2735                               (unsigned long long)sh->sector,
2736                               disk_idx, other);
2737                        set_bit(STRIPE_COMPUTE_RUN, &sh->state);
2738                        set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
2739                        set_bit(R5_Wantcompute, &sh->dev[disk_idx].flags);
2740                        set_bit(R5_Wantcompute, &sh->dev[other].flags);
2741                        sh->ops.target = disk_idx;
2742                        sh->ops.target2 = other;
2743                        s->uptodate += 2;
2744                        s->req_compute = 1;
2745                        return 1;
2746                } else if (test_bit(R5_Insync, &dev->flags)) {
2747                        set_bit(R5_LOCKED, &dev->flags);
2748                        set_bit(R5_Wantread, &dev->flags);
2749                        s->locked++;
2750                        pr_debug("Reading block %d (sync=%d)\n",
2751                                disk_idx, s->syncing);
2752                }
2753        }
2754
2755        return 0;
2756}
2757
2758/**
2759 * handle_stripe_fill - read or compute data to satisfy pending requests.
2760 */
2761static void handle_stripe_fill(struct stripe_head *sh,
2762                               struct stripe_head_state *s,
2763                               int disks)
2764{
2765        int i;
2766
2767        /* look for blocks to read/compute, skip this if a compute
2768         * is already in flight, or if the stripe contents are in the
2769         * midst of changing due to a write
2770         */
2771        if (!test_bit(STRIPE_COMPUTE_RUN, &sh->state) && !sh->check_state &&
2772            !sh->reconstruct_state)
2773                for (i = disks; i--; )
2774                        if (fetch_block(sh, s, i, disks))
2775                                break;
2776        set_bit(STRIPE_HANDLE, &sh->state);
2777}
2778
2779
2780/* handle_stripe_clean_event
2781 * any written block on an uptodate or failed drive can be returned.
2782 * Note that if we 'wrote' to a failed drive, it will be UPTODATE, but
2783 * never LOCKED, so we don't need to test 'failed' directly.
2784 */
2785static void handle_stripe_clean_event(struct r5conf *conf,
2786        struct stripe_head *sh, int disks, struct bio **return_bi)
2787{
2788        int i;
2789        struct r5dev *dev;
2790        int discard_pending = 0;
2791
2792        for (i = disks; i--; )
2793                if (sh->dev[i].written) {
2794                        dev = &sh->dev[i];
2795                        if (!test_bit(R5_LOCKED, &dev->flags) &&
2796                            (test_bit(R5_UPTODATE, &dev->flags) ||
2797                             test_bit(R5_Discard, &dev->flags))) {
2798                                /* We can return any write requests */
2799                                struct bio *wbi, *wbi2;
2800                                pr_debug("Return write for disc %d\n", i);
2801                                if (test_and_clear_bit(R5_Discard, &dev->flags))
2802                                        clear_bit(R5_UPTODATE, &dev->flags);
2803                                wbi = dev->written;
2804                                dev->written = NULL;
2805                                while (wbi && wbi->bi_sector <
2806                                        dev->sector + STRIPE_SECTORS) {
2807                                        wbi2 = r5_next_bio(wbi, dev->sector);
2808                                        if (!raid5_dec_bi_active_stripes(wbi)) {
2809                                                md_write_end(conf->mddev);
2810                                                wbi->bi_next = *return_bi;
2811                                                *return_bi = wbi;
2812                                        }
2813                                        wbi = wbi2;
2814                                }
2815                                bitmap_endwrite(conf->mddev->bitmap, sh->sector,
2816                                                STRIPE_SECTORS,
2817                                         !test_bit(STRIPE_DEGRADED, &sh->state),
2818                                                0);
2819                        } else if (test_bit(R5_Discard, &dev->flags))
2820                                discard_pending = 1;
2821                }
2822        if (!discard_pending &&
2823            test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags)) {
2824                clear_bit(R5_Discard, &sh->dev[sh->pd_idx].flags);
2825                clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2826                if (sh->qd_idx >= 0) {
2827                        clear_bit(R5_Discard, &sh->dev[sh->qd_idx].flags);
2828                        clear_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags);
2829                }
2830                /* now that discard is done we can proceed with any sync */
2831                clear_bit(STRIPE_DISCARD, &sh->state);
2832                if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state))
2833                        set_bit(STRIPE_HANDLE, &sh->state);
2834
2835        }
2836
2837        if (test_and_clear_bit(STRIPE_FULL_WRITE, &sh->state))
2838                if (atomic_dec_and_test(&conf->pending_full_writes))
2839                        md_wakeup_thread(conf->mddev->thread);
2840}
2841
2842static void handle_stripe_dirtying(struct r5conf *conf,
2843                                   struct stripe_head *sh,
2844                                   struct stripe_head_state *s,
2845                                   int disks)
2846{
2847        int rmw = 0, rcw = 0, i;
2848        sector_t recovery_cp = conf->mddev->recovery_cp;
2849
2850        /* RAID6 requires 'rcw' in current implementation.
2851         * Otherwise, check whether resync is now happening or should start.
2852         * If yes, then the array is dirty (after unclean shutdown or
2853         * initial creation), so parity in some stripes might be inconsistent.
2854         * In this case, we need to always do reconstruct-write, to ensure
2855         * that in case of drive failure or read-error correction, we
2856         * generate correct data from the parity.
2857         */
2858        if (conf->max_degraded == 2 ||
2859            (recovery_cp < MaxSector && sh->sector >= recovery_cp)) {
2860                /* Calculate the real rcw later - for now make it
2861                 * look like rcw is cheaper
2862                 */
2863                rcw = 1; rmw = 2;
2864                pr_debug("force RCW max_degraded=%u, recovery_cp=%llu sh->sector=%llu\n",
2865                         conf->max_degraded, (unsigned long long)recovery_cp,
2866                         (unsigned long long)sh->sector);
2867        } else for (i = disks; i--; ) {
2868                /* would I have to read this buffer for read_modify_write */
2869                struct r5dev *dev = &sh->dev[i];
2870                if ((dev->towrite || i == sh->pd_idx) &&
2871                    !test_bit(R5_LOCKED, &dev->flags) &&
2872                    !(test_bit(R5_UPTODATE, &dev->flags) ||
2873                      test_bit(R5_Wantcompute, &dev->flags))) {
2874                        if (test_bit(R5_Insync, &dev->flags))
2875                                rmw++;
2876                        else
2877                                rmw += 2*disks;  /* cannot read it */
2878                }
2879                /* Would I have to read this buffer for reconstruct_write */
2880                if (!test_bit(R5_OVERWRITE, &dev->flags) && i != sh->pd_idx &&
2881                    !test_bit(R5_LOCKED, &dev->flags) &&
2882                    !(test_bit(R5_UPTODATE, &dev->flags) ||
2883                    test_bit(R5_Wantcompute, &dev->flags))) {
2884                        if (test_bit(R5_Insync, &dev->flags)) rcw++;
2885                        else
2886                                rcw += 2*disks;
2887                }
2888        }
2889        pr_debug("for sector %llu, rmw=%d rcw=%d\n",
2890                (unsigned long long)sh->sector, rmw, rcw);
2891        set_bit(STRIPE_HANDLE, &sh->state);
2892        if (rmw < rcw && rmw > 0) {
2893                /* prefer read-modify-write, but need to get some data */
2894                if (conf->mddev->queue)
2895                        blk_add_trace_msg(conf->mddev->queue,
2896                                          "raid5 rmw %llu %d",
2897                                          (unsigned long long)sh->sector, rmw);
2898                for (i = disks; i--; ) {
2899                        struct r5dev *dev = &sh->dev[i];
2900                        if ((dev->towrite || i == sh->pd_idx) &&
2901                            !test_bit(R5_LOCKED, &dev->flags) &&
2902                            !(test_bit(R5_UPTODATE, &dev->flags) ||
2903                            test_bit(R5_Wantcompute, &dev->flags)) &&
2904                            test_bit(R5_Insync, &dev->flags)) {
2905                                if (
2906                                  test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2907                                        pr_debug("Read_old block "
2908                                                 "%d for r-m-w\n", i);
2909                                        set_bit(R5_LOCKED, &dev->flags);
2910                                        set_bit(R5_Wantread, &dev->flags);
2911                                        s->locked++;
2912                                } else {
2913                                        set_bit(STRIPE_DELAYED, &sh->state);
2914                                        set_bit(STRIPE_HANDLE, &sh->state);
2915                                }
2916                        }
2917                }
2918        }
2919        if (rcw <= rmw && rcw > 0) {
2920                /* want reconstruct write, but need to get some data */
2921                int qread =0;
2922                rcw = 0;
2923                for (i = disks; i--; ) {
2924                        struct r5dev *dev = &sh->dev[i];
2925                        if (!test_bit(R5_OVERWRITE, &dev->flags) &&
2926                            i != sh->pd_idx && i != sh->qd_idx &&
2927                            !test_bit(R5_LOCKED, &dev->flags) &&
2928                            !(test_bit(R5_UPTODATE, &dev->flags) ||
2929                              test_bit(R5_Wantcompute, &dev->flags))) {
2930                                rcw++;
2931                                if (!test_bit(R5_Insync, &dev->flags))
2932                                        continue; /* it's a failed drive */
2933                                if (
2934                                  test_bit(STRIPE_PREREAD_ACTIVE, &sh->state)) {
2935                                        pr_debug("Read_old block "
2936                                                "%d for Reconstruct\n", i);
2937                                        set_bit(R5_LOCKED, &dev->flags);
2938                                        set_bit(R5_Wantread, &dev->flags);
2939                                        s->locked++;
2940                                        qread++;
2941                                } else {
2942                                        set_bit(STRIPE_DELAYED, &sh->state);
2943                                        set_bit(STRIPE_HANDLE, &sh->state);
2944                                }
2945                        }
2946                }
2947                if (rcw && conf->mddev->queue)
2948                        blk_add_trace_msg(conf->mddev->queue, "raid5 rcw %llu %d %d %d",
2949                                          (unsigned long long)sh->sector,
2950                                          rcw, qread, test_bit(STRIPE_DELAYED, &sh->state));
2951        }
2952        /* now if nothing is locked, and if we have enough data,
2953         * we can start a write request
2954         */
2955        /* since handle_stripe can be called at any time we need to handle the
2956         * case where a compute block operation has been submitted and then a
2957         * subsequent call wants to start a write request.  raid_run_ops only
2958         * handles the case where compute block and reconstruct are requested
2959         * simultaneously.  If this is not the case then new writes need to be
2960         * held off until the compute completes.
2961         */
2962        if ((s->req_compute || !test_bit(STRIPE_COMPUTE_RUN, &sh->state)) &&
2963            (s->locked == 0 && (rcw == 0 || rmw == 0) &&
2964            !test_bit(STRIPE_BIT_DELAY, &sh->state)))
2965                schedule_reconstruction(sh, s, rcw == 0, 0);
2966}
2967
2968static void handle_parity_checks5(struct r5conf *conf, struct stripe_head *sh,
2969                                struct stripe_head_state *s, int disks)
2970{
2971        struct r5dev *dev = NULL;
2972
2973        set_bit(STRIPE_HANDLE, &sh->state);
2974
2975        switch (sh->check_state) {
2976        case check_state_idle:
2977                /* start a new check operation if there are no failures */
2978                if (s->failed == 0) {
2979                        BUG_ON(s->uptodate != disks);
2980                        sh->check_state = check_state_run;
2981                        set_bit(STRIPE_OP_CHECK, &s->ops_request);
2982                        clear_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags);
2983                        s->uptodate--;
2984                        break;
2985                }
2986                dev = &sh->dev[s->failed_num[0]];
2987                /* fall through */
2988        case check_state_compute_result:
2989                sh->check_state = check_state_idle;
2990                if (!dev)
2991                        dev = &sh->dev[sh->pd_idx];
2992
2993                /* check that a write has not made the stripe insync */
2994                if (test_bit(STRIPE_INSYNC, &sh->state))
2995                        break;
2996
2997                /* either failed parity check, or recovery is happening */
2998                BUG_ON(!test_bit(R5_UPTODATE, &dev->flags));
2999                BUG_ON(s->uptodate != disks);
3000
3001                set_bit(R5_LOCKED, &dev->flags);
3002                s->locked++;
3003                set_bit(R5_Wantwrite, &dev->flags);
3004
3005                clear_bit(STRIPE_DEGRADED, &sh->state);
3006                set_bit(STRIPE_INSYNC, &sh->state);
3007                break;
3008        case check_state_run:
3009                break; /* we will be called again upon completion */
3010        case check_state_check_result:
3011                sh->check_state = check_state_idle;
3012
3013                /* if a failure occurred during the check operation, leave
3014                 * STRIPE_INSYNC not set and let the stripe be handled again
3015                 */
3016                if (s->failed)
3017                        break;
3018
3019                /* handle a successful check operation, if parity is correct
3020                 * we are done.  Otherwise update the mismatch count and repair
3021                 * parity if !MD_RECOVERY_CHECK
3022                 */
3023                if ((sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) == 0)
3024                        /* parity is correct (on disc,
3025                         * not in buffer any more)
3026                         */
3027                        set_bit(STRIPE_INSYNC, &sh->state);
3028                else {
3029                        atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3030                        if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3031                                /* don't try to repair!! */
3032                                set_bit(STRIPE_INSYNC, &sh->state);
3033                        else {
3034                                sh->check_state = check_state_compute_run;
3035                                set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3036                                set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3037                                set_bit(R5_Wantcompute,
3038                                        &sh->dev[sh->pd_idx].flags);
3039                                sh->ops.target = sh->pd_idx;
3040                                sh->ops.target2 = -1;
3041                                s->uptodate++;
3042                        }
3043                }
3044                break;
3045        case check_state_compute_run:
3046                break;
3047        default:
3048                printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3049                       __func__, sh->check_state,
3050                       (unsigned long long) sh->sector);
3051                BUG();
3052        }
3053}
3054
3055
3056static void handle_parity_checks6(struct r5conf *conf, struct stripe_head *sh,
3057                                  struct stripe_head_state *s,
3058                                  int disks)
3059{
3060        int pd_idx = sh->pd_idx;
3061        int qd_idx = sh->qd_idx;
3062        struct r5dev *dev;
3063
3064        set_bit(STRIPE_HANDLE, &sh->state);
3065
3066        BUG_ON(s->failed > 2);
3067
3068        /* Want to check and possibly repair P and Q.
3069         * However there could be one 'failed' device, in which
3070         * case we can only check one of them, possibly using the
3071         * other to generate missing data
3072         */
3073
3074        switch (sh->check_state) {
3075        case check_state_idle:
3076                /* start a new check operation if there are < 2 failures */
3077                if (s->failed == s->q_failed) {
3078                        /* The only possible failed device holds Q, so it
3079                         * makes sense to check P (If anything else were failed,
3080                         * we would have used P to recreate it).
3081                         */
3082                        sh->check_state = check_state_run;
3083                }
3084                if (!s->q_failed && s->failed < 2) {
3085                        /* Q is not failed, and we didn't use it to generate
3086                         * anything, so it makes sense to check it
3087                         */
3088                        if (sh->check_state == check_state_run)
3089                                sh->check_state = check_state_run_pq;
3090                        else
3091                                sh->check_state = check_state_run_q;
3092                }
3093
3094                /* discard potentially stale zero_sum_result */
3095                sh->ops.zero_sum_result = 0;
3096
3097                if (sh->check_state == check_state_run) {
3098                        /* async_xor_zero_sum destroys the contents of P */
3099                        clear_bit(R5_UPTODATE, &sh->dev[pd_idx].flags);
3100                        s->uptodate--;
3101                }
3102                if (sh->check_state >= check_state_run &&
3103                    sh->check_state <= check_state_run_pq) {
3104                        /* async_syndrome_zero_sum preserves P and Q, so
3105                         * no need to mark them !uptodate here
3106                         */
3107                        set_bit(STRIPE_OP_CHECK, &s->ops_request);
3108                        break;
3109                }
3110
3111                /* we have 2-disk failure */
3112                BUG_ON(s->failed != 2);
3113                /* fall through */
3114        case check_state_compute_result:
3115                sh->check_state = check_state_idle;
3116
3117                /* check that a write has not made the stripe insync */
3118                if (test_bit(STRIPE_INSYNC, &sh->state))
3119                        break;
3120
3121                /* now write out any block on a failed drive,
3122                 * or P or Q if they were recomputed
3123                 */
3124                BUG_ON(s->uptodate < disks - 1); /* We don't need Q to recover */
3125                if (s->failed == 2) {
3126                        dev = &sh->dev[s->failed_num[1]];
3127                        s->locked++;
3128                        set_bit(R5_LOCKED, &dev->flags);
3129                        set_bit(R5_Wantwrite, &dev->flags);
3130                }
3131                if (s->failed >= 1) {
3132                        dev = &sh->dev[s->failed_num[0]];
3133                        s->locked++;
3134                        set_bit(R5_LOCKED, &dev->flags);
3135                        set_bit(R5_Wantwrite, &dev->flags);
3136                }
3137                if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3138                        dev = &sh->dev[pd_idx];
3139                        s->locked++;
3140                        set_bit(R5_LOCKED, &dev->flags);
3141                        set_bit(R5_Wantwrite, &dev->flags);
3142                }
3143                if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3144                        dev = &sh->dev[qd_idx];
3145                        s->locked++;
3146                        set_bit(R5_LOCKED, &dev->flags);
3147                        set_bit(R5_Wantwrite, &dev->flags);
3148                }
3149                clear_bit(STRIPE_DEGRADED, &sh->state);
3150
3151                set_bit(STRIPE_INSYNC, &sh->state);
3152                break;
3153        case check_state_run:
3154        case check_state_run_q:
3155        case check_state_run_pq:
3156                break; /* we will be called again upon completion */
3157        case check_state_check_result:
3158                sh->check_state = check_state_idle;
3159
3160                /* handle a successful check operation, if parity is correct
3161                 * we are done.  Otherwise update the mismatch count and repair
3162                 * parity if !MD_RECOVERY_CHECK
3163                 */
3164                if (sh->ops.zero_sum_result == 0) {
3165                        /* both parities are correct */
3166                        if (!s->failed)
3167                                set_bit(STRIPE_INSYNC, &sh->state);
3168                        else {
3169                                /* in contrast to the raid5 case we can validate
3170                                 * parity, but still have a failure to write
3171                                 * back
3172                                 */
3173                                sh->check_state = check_state_compute_result;
3174                                /* Returning at this point means that we may go
3175                                 * off and bring p and/or q uptodate again so
3176                                 * we make sure to check zero_sum_result again
3177                                 * to verify if p or q need writeback
3178                                 */
3179                        }
3180                } else {
3181                        atomic64_add(STRIPE_SECTORS, &conf->mddev->resync_mismatches);
3182                        if (test_bit(MD_RECOVERY_CHECK, &conf->mddev->recovery))
3183                                /* don't try to repair!! */
3184                                set_bit(STRIPE_INSYNC, &sh->state);
3185                        else {
3186                                int *target = &sh->ops.target;
3187
3188                                sh->ops.target = -1;
3189                                sh->ops.target2 = -1;
3190                                sh->check_state = check_state_compute_run;
3191                                set_bit(STRIPE_COMPUTE_RUN, &sh->state);
3192                                set_bit(STRIPE_OP_COMPUTE_BLK, &s->ops_request);
3193                                if (sh->ops.zero_sum_result & SUM_CHECK_P_RESULT) {
3194                                        set_bit(R5_Wantcompute,
3195                                                &sh->dev[pd_idx].flags);
3196                                        *target = pd_idx;
3197                                        target = &sh->ops.target2;
3198                                        s->uptodate++;
3199                                }
3200                                if (sh->ops.zero_sum_result & SUM_CHECK_Q_RESULT) {
3201                                        set_bit(R5_Wantcompute,
3202                                                &sh->dev[qd_idx].flags);
3203                                        *target = qd_idx;
3204                                        s->uptodate++;
3205                                }
3206                        }
3207                }
3208                break;
3209        case check_state_compute_run:
3210                break;
3211        default:
3212                printk(KERN_ERR "%s: unknown check_state: %d sector: %llu\n",
3213                       __func__, sh->check_state,
3214                       (unsigned long long) sh->sector);
3215                BUG();
3216        }
3217}
3218
3219static void handle_stripe_expansion(struct r5conf *conf, struct stripe_head *sh)
3220{
3221        int i;
3222
3223        /* We have read all the blocks in this stripe and now we need to
3224         * copy some of them into a target stripe for expand.
3225         */
3226        struct dma_async_tx_descriptor *tx = NULL;
3227        clear_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3228        for (i = 0; i < sh->disks; i++)
3229                if (i != sh->pd_idx && i != sh->qd_idx) {
3230                        int dd_idx, j;
3231                        struct stripe_head *sh2;
3232                        struct async_submit_ctl submit;
3233
3234                        sector_t bn = compute_blocknr(sh, i, 1);
3235                        sector_t s = raid5_compute_sector(conf, bn, 0,
3236                                                          &dd_idx, NULL);
3237                        sh2 = get_active_stripe(conf, s, 0, 1, 1);
3238                        if (sh2 == NULL)
3239                                /* so far only the early blocks of this stripe
3240                                 * have been requested.  When later blocks
3241                                 * get requested, we will try again
3242                                 */
3243                                continue;
3244                        if (!test_bit(STRIPE_EXPANDING, &sh2->state) ||
3245                           test_bit(R5_Expanded, &sh2->dev[dd_idx].flags)) {
3246                                /* must have already done this block */
3247                                release_stripe(sh2);
3248                                continue;
3249                        }
3250
3251                        /* place all the copies on one channel */
3252                        init_async_submit(&submit, 0, tx, NULL, NULL, NULL);
3253                        tx = async_memcpy(sh2->dev[dd_idx].page,
3254                                          sh->dev[i].page, 0, 0, STRIPE_SIZE,
3255                                          &submit);
3256
3257                        set_bit(R5_Expanded, &sh2->dev[dd_idx].flags);
3258                        set_bit(R5_UPTODATE, &sh2->dev[dd_idx].flags);
3259                        for (j = 0; j < conf->raid_disks; j++)
3260                                if (j != sh2->pd_idx &&
3261                                    j != sh2->qd_idx &&
3262                                    !test_bit(R5_Expanded, &sh2->dev[j].flags))
3263                                        break;
3264                        if (j == conf->raid_disks) {
3265                                set_bit(STRIPE_EXPAND_READY, &sh2->state);
3266                                set_bit(STRIPE_HANDLE, &sh2->state);
3267                        }
3268                        release_stripe(sh2);
3269
3270                }
3271        /* done submitting copies, wait for them to complete */
3272        async_tx_quiesce(&tx);
3273}
3274
3275/*
3276 * handle_stripe - do things to a stripe.
3277 *
3278 * We lock the stripe by setting STRIPE_ACTIVE and then examine the
3279 * state of various bits to see what needs to be done.
3280 * Possible results:
3281 *    return some read requests which now have data
3282 *    return some write requests which are safely on storage
3283 *    schedule a read on some buffers
3284 *    schedule a write of some buffers
3285 *    return confirmation of parity correctness
3286 *
3287 */
3288
3289static void analyse_stripe(struct stripe_head *sh, struct stripe_head_state *s)
3290{
3291        struct r5conf *conf = sh->raid_conf;
3292        int disks = sh->disks;
3293        struct r5dev *dev;
3294        int i;
3295        int do_recovery = 0;
3296
3297        memset(s, 0, sizeof(*s));
3298
3299        s->expanding = test_bit(STRIPE_EXPAND_SOURCE, &sh->state);
3300        s->expanded = test_bit(STRIPE_EXPAND_READY, &sh->state);
3301        s->failed_num[0] = -1;
3302        s->failed_num[1] = -1;
3303
3304        /* Now to look around and see what can be done */
3305        rcu_read_lock();
3306        for (i=disks; i--; ) {
3307                struct md_rdev *rdev;
3308                sector_t first_bad;
3309                int bad_sectors;
3310                int is_bad = 0;
3311
3312                dev = &sh->dev[i];
3313
3314                pr_debug("check %d: state 0x%lx read %p write %p written %p\n",
3315                         i, dev->flags,
3316                         dev->toread, dev->towrite, dev->written);
3317                /* maybe we can reply to a read
3318                 *
3319                 * new wantfill requests are only permitted while
3320                 * ops_complete_biofill is guaranteed to be inactive
3321                 */
3322                if (test_bit(R5_UPTODATE, &dev->flags) && dev->toread &&
3323                    !test_bit(STRIPE_BIOFILL_RUN, &sh->state))
3324                        set_bit(R5_Wantfill, &dev->flags);
3325
3326                /* now count some things */
3327                if (test_bit(R5_LOCKED, &dev->flags))
3328                        s->locked++;
3329                if (test_bit(R5_UPTODATE, &dev->flags))
3330                        s->uptodate++;
3331                if (test_bit(R5_Wantcompute, &dev->flags)) {
3332                        s->compute++;
3333                        BUG_ON(s->compute > 2);
3334                }
3335
3336                if (test_bit(R5_Wantfill, &dev->flags))
3337                        s->to_fill++;
3338                else if (dev->toread)
3339                        s->to_read++;
3340                if (dev->towrite) {
3341                        s->to_write++;
3342                        if (!test_bit(R5_OVERWRITE, &dev->flags))
3343                                s->non_overwrite++;
3344                }
3345                if (dev->written)
3346                        s->written++;
3347                /* Prefer to use the replacement for reads, but only
3348                 * if it is recovered enough and has no bad blocks.
3349                 */
3350                rdev = rcu_dereference(conf->disks[i].replacement);
3351                if (rdev && !test_bit(Faulty, &rdev->flags) &&
3352                    rdev->recovery_offset >= sh->sector + STRIPE_SECTORS &&
3353                    !is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3354                                 &first_bad, &bad_sectors))
3355                        set_bit(R5_ReadRepl, &dev->flags);
3356                else {
3357                        if (rdev)
3358                                set_bit(R5_NeedReplace, &dev->flags);
3359                        rdev = rcu_dereference(conf->disks[i].rdev);
3360                        clear_bit(R5_ReadRepl, &dev->flags);
3361                }
3362                if (rdev && test_bit(Faulty, &rdev->flags))
3363                        rdev = NULL;
3364                if (rdev) {
3365                        is_bad = is_badblock(rdev, sh->sector, STRIPE_SECTORS,
3366                                             &first_bad, &bad_sectors);
3367                        if (s->blocked_rdev == NULL
3368                            && (test_bit(Blocked, &rdev->flags)
3369                                || is_bad < 0)) {
3370                                if (is_bad < 0)
3371                                        set_bit(BlockedBadBlocks,
3372                                                &rdev->flags);
3373                                s->blocked_rdev = rdev;
3374                                atomic_inc(&rdev->nr_pending);
3375                        }
3376                }
3377                clear_bit(R5_Insync, &dev->flags);
3378                if (!rdev)
3379                        /* Not in-sync */;
3380                else if (is_bad) {
3381                        /* also not in-sync */
3382                        if (!test_bit(WriteErrorSeen, &rdev->flags) &&
3383                            test_bit(R5_UPTODATE, &dev->flags)) {
3384                                /* treat as in-sync, but with a read error
3385                                 * which we can now try to correct
3386                                 */
3387                                set_bit(R5_Insync, &dev->flags);
3388                                set_bit(R5_ReadError, &dev->flags);
3389                        }
3390                } else if (test_bit(In_sync, &rdev->flags))
3391                        set_bit(R5_Insync, &dev->flags);
3392                else if (sh->sector + STRIPE_SECTORS <= rdev->recovery_offset)
3393                        /* in sync if before recovery_offset */
3394                        set_bit(R5_Insync, &dev->flags);
3395                else if (test_bit(R5_UPTODATE, &dev->flags) &&
3396                         test_bit(R5_Expanded, &dev->flags))
3397                        /* If we've reshaped into here, we assume it is Insync.
3398                         * We will shortly update recovery_offset to make
3399                         * it official.
3400                         */
3401                        set_bit(R5_Insync, &dev->flags);
3402
3403                if (rdev && test_bit(R5_WriteError, &dev->flags)) {
3404                        /* This flag does not apply to '.replacement'
3405                         * only to .rdev, so make sure to check that*/
3406                        struct md_rdev *rdev2 = rcu_dereference(
3407                                conf->disks[i].rdev);
3408                        if (rdev2 == rdev)
3409                                clear_bit(R5_Insync, &dev->flags);
3410                        if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3411                                s->handle_bad_blocks = 1;
3412                                atomic_inc(&rdev2->nr_pending);
3413                        } else
3414                                clear_bit(R5_WriteError, &dev->flags);
3415                }
3416                if (rdev && test_bit(R5_MadeGood, &dev->flags)) {
3417                        /* This flag does not apply to '.replacement'
3418                         * only to .rdev, so make sure to check that*/
3419                        struct md_rdev *rdev2 = rcu_dereference(
3420                                conf->disks[i].rdev);
3421                        if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3422                                s->handle_bad_blocks = 1;
3423                                atomic_inc(&rdev2->nr_pending);
3424                        } else
3425                                clear_bit(R5_MadeGood, &dev->flags);
3426                }
3427                if (test_bit(R5_MadeGoodRepl, &dev->flags)) {
3428                        struct md_rdev *rdev2 = rcu_dereference(
3429                                conf->disks[i].replacement);
3430                        if (rdev2 && !test_bit(Faulty, &rdev2->flags)) {
3431                                s->handle_bad_blocks = 1;
3432                                atomic_inc(&rdev2->nr_pending);
3433                        } else
3434                                clear_bit(R5_MadeGoodRepl, &dev->flags);
3435                }
3436                if (!test_bit(R5_Insync, &dev->flags)) {
3437                        /* The ReadError flag will just be confusing now */
3438                        clear_bit(R5_ReadError, &dev->flags);
3439                        clear_bit(R5_ReWrite, &dev->flags);
3440                }
3441                if (test_bit(R5_ReadError, &dev->flags))
3442                        clear_bit(R5_Insync, &dev->flags);
3443                if (!test_bit(R5_Insync, &dev->flags)) {
3444                        if (s->failed < 2)
3445                                s->failed_num[s->failed] = i;
3446                        s->failed++;
3447                        if (rdev && !test_bit(Faulty, &rdev->flags))
3448                                do_recovery = 1;
3449                }
3450        }
3451        if (test_bit(STRIPE_SYNCING, &sh->state)) {
3452                /* If there is a failed device being replaced,
3453                 *     we must be recovering.
3454                 * else if we are after recovery_cp, we must be syncing
3455                 * else if MD_RECOVERY_REQUESTED is set, we also are syncing.
3456                 * else we can only be replacing
3457                 * sync and recovery both need to read all devices, and so
3458                 * use the same flag.
3459                 */
3460                if (do_recovery ||
3461                    sh->sector >= conf->mddev->recovery_cp ||
3462                    test_bit(MD_RECOVERY_REQUESTED, &(conf->mddev->recovery)))
3463                        s->syncing = 1;
3464                else
3465                        s->replacing = 1;
3466        }
3467        rcu_read_unlock();
3468}
3469
3470static void handle_stripe(struct stripe_head *sh)
3471{
3472        struct stripe_head_state s;
3473        struct r5conf *conf = sh->raid_conf;
3474        int i;
3475        int prexor;
3476        int disks = sh->disks;
3477        struct r5dev *pdev, *qdev;
3478
3479        clear_bit(STRIPE_HANDLE, &sh->state);
3480        if (test_and_set_bit_lock(STRIPE_ACTIVE, &sh->state)) {
3481                /* already being handled, ensure it gets handled
3482                 * again when current action finishes */
3483                set_bit(STRIPE_HANDLE, &sh->state);
3484                return;
3485        }
3486
3487        if (test_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3488                spin_lock(&sh->stripe_lock);
3489                /* Cannot process 'sync' concurrently with 'discard' */
3490                if (!test_bit(STRIPE_DISCARD, &sh->state) &&
3491                    test_and_clear_bit(STRIPE_SYNC_REQUESTED, &sh->state)) {
3492                        set_bit(STRIPE_SYNCING, &sh->state);
3493                        clear_bit(STRIPE_INSYNC, &sh->state);
3494                }
3495                spin_unlock(&sh->stripe_lock);
3496        }
3497        clear_bit(STRIPE_DELAYED, &sh->state);
3498
3499        pr_debug("handling stripe %llu, state=%#lx cnt=%d, "
3500                "pd_idx=%d, qd_idx=%d\n, check:%d, reconstruct:%d\n",
3501               (unsigned long long)sh->sector, sh->state,
3502               atomic_read(&sh->count), sh->pd_idx, sh->qd_idx,
3503               sh->check_state, sh->reconstruct_state);
3504
3505        analyse_stripe(sh, &s);
3506
3507        if (s.handle_bad_blocks) {
3508                set_bit(STRIPE_HANDLE, &sh->state);
3509                goto finish;
3510        }
3511
3512        if (unlikely(s.blocked_rdev)) {
3513                if (s.syncing || s.expanding || s.expanded ||
3514                    s.replacing || s.to_write || s.written) {
3515                        set_bit(STRIPE_HANDLE, &sh->state);
3516                        goto finish;
3517                }
3518                /* There is nothing for the blocked_rdev to block */
3519                rdev_dec_pending(s.blocked_rdev, conf->mddev);
3520                s.blocked_rdev = NULL;
3521        }
3522
3523        if (s.to_fill && !test_bit(STRIPE_BIOFILL_RUN, &sh->state)) {
3524                set_bit(STRIPE_OP_BIOFILL, &s.ops_request);
3525                set_bit(STRIPE_BIOFILL_RUN, &sh->state);
3526        }
3527
3528        pr_debug("locked=%d uptodate=%d to_read=%d"
3529               " to_write=%d failed=%d failed_num=%d,%d\n",
3530               s.locked, s.uptodate, s.to_read, s.to_write, s.failed,
3531               s.failed_num[0], s.failed_num[1]);
3532        /* check if the array has lost more than max_degraded devices and,
3533         * if so, some requests might need to be failed.
3534         */
3535        if (s.failed > conf->max_degraded) {
3536                sh->check_state = 0;
3537                sh->reconstruct_state = 0;
3538                if (s.to_read+s.to_write+s.written)
3539                        handle_failed_stripe(conf, sh, &s, disks, &s.return_bi);
3540                if (s.syncing + s.replacing)
3541                        handle_failed_sync(conf, sh, &s);
3542        }
3543
3544        /* Now we check to see if any write operations have recently
3545         * completed
3546         */
3547        prexor = 0;
3548        if (sh->reconstruct_state == reconstruct_state_prexor_drain_result)
3549                prexor = 1;
3550        if (sh->reconstruct_state == reconstruct_state_drain_result ||
3551            sh->reconstruct_state == reconstruct_state_prexor_drain_result) {
3552                sh->reconstruct_state = reconstruct_state_idle;
3553
3554                /* All the 'written' buffers and the parity block are ready to
3555                 * be written back to disk
3556                 */
3557                BUG_ON(!test_bit(R5_UPTODATE, &sh->dev[sh->pd_idx].flags) &&
3558                       !test_bit(R5_Discard, &sh->dev[sh->pd_idx].flags));
3559                BUG_ON(sh->qd_idx >= 0 &&
3560                       !test_bit(R5_UPTODATE, &sh->dev[sh->qd_idx].flags) &&
3561                       !test_bit(R5_Discard, &sh->dev[sh->qd_idx].flags));
3562                for (i = disks; i--; ) {
3563                        struct r5dev *dev = &sh->dev[i];
3564                        if (test_bit(R5_LOCKED, &dev->flags) &&
3565                                (i == sh->pd_idx || i == sh->qd_idx ||
3566                                 dev->written)) {
3567                                pr_debug("Writing block %d\n", i);
3568                                set_bit(R5_Wantwrite, &dev->flags);
3569                                if (prexor)
3570                                        continue;
3571                                if (!test_bit(R5_Insync, &dev->flags) ||
3572                                    ((i == sh->pd_idx || i == sh->qd_idx)  &&
3573                                     s.failed == 0))
3574                                        set_bit(STRIPE_INSYNC, &sh->state);
3575                        }
3576                }
3577                if (test_and_clear_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3578                        s.dec_preread_active = 1;
3579        }
3580
3581        /*
3582         * might be able to return some write requests if the parity blocks
3583         * are safe, or on a failed drive
3584         */
3585        pdev = &sh->dev[sh->pd_idx];
3586        s.p_failed = (s.failed >= 1 && s.failed_num[0] == sh->pd_idx)
3587                || (s.failed >= 2 && s.failed_num[1] == sh->pd_idx);
3588        qdev = &sh->dev[sh->qd_idx];
3589        s.q_failed = (s.failed >= 1 && s.failed_num[0] == sh->qd_idx)
3590                || (s.failed >= 2 && s.failed_num[1] == sh->qd_idx)
3591                || conf->level < 6;
3592
3593        if (s.written &&
3594            (s.p_failed || ((test_bit(R5_Insync, &pdev->flags)
3595                             && !test_bit(R5_LOCKED, &pdev->flags)
3596                             && (test_bit(R5_UPTODATE, &pdev->flags) ||
3597                                 test_bit(R5_Discard, &pdev->flags))))) &&
3598            (s.q_failed || ((test_bit(R5_Insync, &qdev->flags)
3599                             && !test_bit(R5_LOCKED, &qdev->flags)
3600                             && (test_bit(R5_UPTODATE, &qdev->flags) ||
3601                                 test_bit(R5_Discard, &qdev->flags))))))
3602                handle_stripe_clean_event(conf, sh, disks, &s.return_bi);
3603
3604        /* Now we might consider reading some blocks, either to check/generate
3605         * parity, or to satisfy requests
3606         * or to load a block that is being partially written.
3607         */
3608        if (s.to_read || s.non_overwrite
3609            || (conf->level == 6 && s.to_write && s.failed)
3610            || (s.syncing && (s.uptodate + s.compute < disks))
3611            || s.replacing
3612            || s.expanding)
3613                handle_stripe_fill(sh, &s, disks);
3614
3615        /* Now to consider new write requests and what else, if anything
3616         * should be read.  We do not handle new writes when:
3617         * 1/ A 'write' operation (copy+xor) is already in flight.
3618         * 2/ A 'check' operation is in flight, as it may clobber the parity
3619         *    block.
3620         */
3621        if (s.to_write && !sh->reconstruct_state && !sh->check_state)
3622                handle_stripe_dirtying(conf, sh, &s, disks);
3623
3624        /* maybe we need to check and possibly fix the parity for this stripe
3625         * Any reads will already have been scheduled, so we just see if enough
3626         * data is available.  The parity check is held off while parity
3627         * dependent operations are in flight.
3628         */
3629        if (sh->check_state ||
3630            (s.syncing && s.locked == 0 &&
3631             !test_bit(STRIPE_COMPUTE_RUN, &sh->state) &&
3632             !test_bit(STRIPE_INSYNC, &sh->state))) {
3633                if (conf->level == 6)
3634                        handle_parity_checks6(conf, sh, &s, disks);
3635                else
3636                        handle_parity_checks5(conf, sh, &s, disks);
3637        }
3638
3639        if (s.replacing && s.locked == 0
3640            && !test_bit(STRIPE_INSYNC, &sh->state)) {
3641                /* Write out to replacement devices where possible */
3642                for (i = 0; i < conf->raid_disks; i++)
3643                        if (test_bit(R5_UPTODATE, &sh->dev[i].flags) &&
3644                            test_bit(R5_NeedReplace, &sh->dev[i].flags)) {
3645                                set_bit(R5_WantReplace, &sh->dev[i].flags);
3646                                set_bit(R5_LOCKED, &sh->dev[i].flags);
3647                                s.locked++;
3648                        }
3649                set_bit(STRIPE_INSYNC, &sh->state);
3650        }
3651        if ((s.syncing || s.replacing) && s.locked == 0 &&
3652            test_bit(STRIPE_INSYNC, &sh->state)) {
3653                md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3654                clear_bit(STRIPE_SYNCING, &sh->state);
3655                if (test_and_clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags))
3656                        wake_up(&conf->wait_for_overlap);
3657        }
3658
3659        /* If the failed drives are just a ReadError, then we might need
3660         * to progress the repair/check process
3661         */
3662        if (s.failed <= conf->max_degraded && !conf->mddev->ro)
3663                for (i = 0; i < s.failed; i++) {
3664                        struct r5dev *dev = &sh->dev[s.failed_num[i]];
3665                        if (test_bit(R5_ReadError, &dev->flags)
3666                            && !test_bit(R5_LOCKED, &dev->flags)
3667                            && test_bit(R5_UPTODATE, &dev->flags)
3668                                ) {
3669                                if (!test_bit(R5_ReWrite, &dev->flags)) {
3670                                        set_bit(R5_Wantwrite, &dev->flags);
3671                                        set_bit(R5_ReWrite, &dev->flags);
3672                                        set_bit(R5_LOCKED, &dev->flags);
3673                                        s.locked++;
3674                                } else {
3675                                        /* let's read it back */
3676                                        set_bit(R5_Wantread, &dev->flags);
3677                                        set_bit(R5_LOCKED, &dev->flags);
3678                                        s.locked++;
3679                                }
3680                        }
3681                }
3682
3683
3684        /* Finish reconstruct operations initiated by the expansion process */
3685        if (sh->reconstruct_state == reconstruct_state_result) {
3686                struct stripe_head *sh_src
3687                        = get_active_stripe(conf, sh->sector, 1, 1, 1);
3688                if (sh_src && test_bit(STRIPE_EXPAND_SOURCE, &sh_src->state)) {
3689                        /* sh cannot be written until sh_src has been read.
3690                         * so arrange for sh to be delayed a little
3691                         */
3692                        set_bit(STRIPE_DELAYED, &sh->state);
3693                        set_bit(STRIPE_HANDLE, &sh->state);
3694                        if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE,
3695                                              &sh_src->state))
3696                                atomic_inc(&conf->preread_active_stripes);
3697                        release_stripe(sh_src);
3698                        goto finish;
3699                }
3700                if (sh_src)
3701                        release_stripe(sh_src);
3702
3703                sh->reconstruct_state = reconstruct_state_idle;
3704                clear_bit(STRIPE_EXPANDING, &sh->state);
3705                for (i = conf->raid_disks; i--; ) {
3706                        set_bit(R5_Wantwrite, &sh->dev[i].flags);
3707                        set_bit(R5_LOCKED, &sh->dev[i].flags);
3708                        s.locked++;
3709                }
3710        }
3711
3712        if (s.expanded && test_bit(STRIPE_EXPANDING, &sh->state) &&
3713            !sh->reconstruct_state) {
3714                /* Need to write out all blocks after computing parity */
3715                sh->disks = conf->raid_disks;
3716                stripe_set_idx(sh->sector, conf, 0, sh);
3717                schedule_reconstruction(sh, &s, 1, 1);
3718        } else if (s.expanded && !sh->reconstruct_state && s.locked == 0) {
3719                clear_bit(STRIPE_EXPAND_READY, &sh->state);
3720                atomic_dec(&conf->reshape_stripes);
3721                wake_up(&conf->wait_for_overlap);
3722                md_done_sync(conf->mddev, STRIPE_SECTORS, 1);
3723        }
3724
3725        if (s.expanding && s.locked == 0 &&
3726            !test_bit(STRIPE_COMPUTE_RUN, &sh->state))
3727                handle_stripe_expansion(conf, sh);
3728
3729finish:
3730        /* wait for this device to become unblocked */
3731        if (unlikely(s.blocked_rdev)) {
3732                if (conf->mddev->external)
3733                        md_wait_for_blocked_rdev(s.blocked_rdev,
3734                                                 conf->mddev);
3735                else
3736                        /* Internal metadata will immediately
3737                         * be written by raid5d, so we don't
3738                         * need to wait here.
3739                         */
3740                        rdev_dec_pending(s.blocked_rdev,
3741                                         conf->mddev);
3742        }
3743
3744        if (s.handle_bad_blocks)
3745                for (i = disks; i--; ) {
3746                        struct md_rdev *rdev;
3747                        struct r5dev *dev = &sh->dev[i];
3748                        if (test_and_clear_bit(R5_WriteError, &dev->flags)) {
3749                                /* We own a safe reference to the rdev */
3750                                rdev = conf->disks[i].rdev;
3751                                if (!rdev_set_badblocks(rdev, sh->sector,
3752                                                        STRIPE_SECTORS, 0))
3753                                        md_error(conf->mddev, rdev);
3754                                rdev_dec_pending(rdev, conf->mddev);
3755                        }
3756                        if (test_and_clear_bit(R5_MadeGood, &dev->flags)) {
3757                                rdev = conf->disks[i].rdev;
3758                                rdev_clear_badblocks(rdev, sh->sector,
3759                                                     STRIPE_SECTORS, 0);
3760                                rdev_dec_pending(rdev, conf->mddev);
3761                        }
3762                        if (test_and_clear_bit(R5_MadeGoodRepl, &dev->flags)) {
3763                                rdev = conf->disks[i].replacement;
3764                                if (!rdev)
3765                                        /* rdev have been moved down */
3766                                        rdev = conf->disks[i].rdev;
3767                                rdev_clear_badblocks(rdev, sh->sector,
3768                                                     STRIPE_SECTORS, 0);
3769                                rdev_dec_pending(rdev, conf->mddev);
3770                        }
3771                }
3772
3773        if (s.ops_request)
3774                raid_run_ops(sh, s.ops_request);
3775
3776        ops_run_io(sh, &s);
3777
3778        if (s.dec_preread_active) {
3779                /* We delay this until after ops_run_io so that if make_request
3780                 * is waiting on a flush, it won't continue until the writes
3781                 * have actually been submitted.
3782                 */
3783                atomic_dec(&conf->preread_active_stripes);
3784                if (atomic_read(&conf->preread_active_stripes) <
3785                    IO_THRESHOLD)
3786                        md_wakeup_thread(conf->mddev->thread);
3787        }
3788
3789        return_io(s.return_bi);
3790
3791        clear_bit_unlock(STRIPE_ACTIVE, &sh->state);
3792}
3793
3794static void raid5_activate_delayed(struct r5conf *conf)
3795{
3796        if (atomic_read(&conf->preread_active_stripes) < IO_THRESHOLD) {
3797                while (!list_empty(&conf->delayed_list)) {
3798                        struct list_head *l = conf->delayed_list.next;
3799                        struct stripe_head *sh;
3800                        sh = list_entry(l, struct stripe_head, lru);
3801                        list_del_init(l);
3802                        clear_bit(STRIPE_DELAYED, &sh->state);
3803                        if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
3804                                atomic_inc(&conf->preread_active_stripes);
3805                        list_add_tail(&sh->lru, &conf->hold_list);
3806                }
3807        }
3808}
3809
3810static void activate_bit_delay(struct r5conf *conf)
3811{
3812        /* device_lock is held */
3813        struct list_head head;
3814        list_add(&head, &conf->bitmap_list);
3815        list_del_init(&conf->bitmap_list);
3816        while (!list_empty(&head)) {
3817                struct stripe_head *sh = list_entry(head.next, struct stripe_head, lru);
3818                list_del_init(&sh->lru);
3819                atomic_inc(&sh->count);
3820                __release_stripe(conf, sh);
3821        }
3822}
3823
3824int md_raid5_congested(struct mddev *mddev, int bits)
3825{
3826        struct r5conf *conf = mddev->private;
3827
3828        /* No difference between reads and writes.  Just check
3829         * how busy the stripe_cache is
3830         */
3831
3832        if (conf->inactive_blocked)
3833                return 1;
3834        if (conf->quiesce)
3835                return 1;
3836        if (list_empty_careful(&conf->inactive_list))
3837                return 1;
3838
3839        return 0;
3840}
3841EXPORT_SYMBOL_GPL(md_raid5_congested);
3842
3843static int raid5_congested(void *data, int bits)
3844{
3845        struct mddev *mddev = data;
3846
3847        return mddev_congested(mddev, bits) ||
3848                md_raid5_congested(mddev, bits);
3849}
3850
3851/* We want read requests to align with chunks where possible,
3852 * but write requests don't need to.
3853 */
3854static int raid5_mergeable_bvec(struct request_queue *q,
3855                                struct bvec_merge_data *bvm,
3856                                struct bio_vec *biovec)
3857{
3858        struct mddev *mddev = q->queuedata;
3859        sector_t sector = bvm->bi_sector + get_start_sect(bvm->bi_bdev);
3860        int max;
3861        unsigned int chunk_sectors = mddev->chunk_sectors;
3862        unsigned int bio_sectors = bvm->bi_size >> 9;
3863
3864        if ((bvm->bi_rw & 1) == WRITE)
3865                return biovec->bv_len; /* always allow writes to be mergeable */
3866
3867        if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3868                chunk_sectors = mddev->new_chunk_sectors;
3869        max =  (chunk_sectors - ((sector & (chunk_sectors - 1)) + bio_sectors)) << 9;
3870        if (max < 0) max = 0;
3871        if (max <= biovec->bv_len && bio_sectors == 0)
3872                return biovec->bv_len;
3873        else
3874                return max;
3875}
3876
3877
3878static int in_chunk_boundary(struct mddev *mddev, struct bio *bio)
3879{
3880        sector_t sector = bio->bi_sector + get_start_sect(bio->bi_bdev);
3881        unsigned int chunk_sectors = mddev->chunk_sectors;
3882        unsigned int bio_sectors = bio->bi_size >> 9;
3883
3884        if (mddev->new_chunk_sectors < mddev->chunk_sectors)
3885                chunk_sectors = mddev->new_chunk_sectors;
3886        return  chunk_sectors >=
3887                ((sector & (chunk_sectors - 1)) + bio_sectors);
3888}
3889
3890/*
3891 *  add bio to the retry LIFO  ( in O(1) ... we are in interrupt )
3892 *  later sampled by raid5d.
3893 */
3894static void add_bio_to_retry(struct bio *bi,struct r5conf *conf)
3895{
3896        unsigned long flags;
3897
3898        spin_lock_irqsave(&conf->device_lock, flags);
3899
3900        bi->bi_next = conf->retry_read_aligned_list;
3901        conf->retry_read_aligned_list = bi;
3902
3903        spin_unlock_irqrestore(&conf->device_lock, flags);
3904        md_wakeup_thread(conf->mddev->thread);
3905}
3906
3907
3908static struct bio *remove_bio_from_retry(struct r5conf *conf)
3909{
3910        struct bio *bi;
3911
3912        bi = conf->retry_read_aligned;
3913        if (bi) {
3914                conf->retry_read_aligned = NULL;
3915                return bi;
3916        }
3917        bi = conf->retry_read_aligned_list;
3918        if(bi) {
3919                conf->retry_read_aligned_list = bi->bi_next;
3920                bi->bi_next = NULL;
3921                /*
3922                 * this sets the active strip count to 1 and the processed
3923                 * strip count to zero (upper 8 bits)
3924                 */
3925                raid5_set_bi_stripes(bi, 1); /* biased count of active stripes */
3926        }
3927
3928        return bi;
3929}
3930
3931
3932/*
3933 *  The "raid5_align_endio" should check if the read succeeded and if it
3934 *  did, call bio_endio on the original bio (having bio_put the new bio
3935 *  first).
3936 *  If the read failed..
3937 */
3938static void raid5_align_endio(struct bio *bi, int error)
3939{
3940        struct bio* raid_bi  = bi->bi_private;
3941        struct mddev *mddev;
3942        struct r5conf *conf;
3943        int uptodate = test_bit(BIO_UPTODATE, &bi->bi_flags);
3944        struct md_rdev *rdev;
3945
3946        bio_put(bi);
3947
3948        rdev = (void*)raid_bi->bi_next;
3949        raid_bi->bi_next = NULL;
3950        mddev = rdev->mddev;
3951        conf = mddev->private;
3952
3953        rdev_dec_pending(rdev, conf->mddev);
3954
3955        if (!error && uptodate) {
3956                trace_block_bio_complete(bdev_get_queue(raid_bi->bi_bdev),
3957                                         raid_bi, 0);
3958                bio_endio(raid_bi, 0);
3959                if (atomic_dec_and_test(&conf->active_aligned_reads))
3960                        wake_up(&conf->wait_for_stripe);
3961                return;
3962        }
3963
3964
3965        pr_debug("raid5_align_endio : io error...handing IO for a retry\n");
3966
3967        add_bio_to_retry(raid_bi, conf);
3968}
3969
3970static int bio_fits_rdev(struct bio *bi)
3971{
3972        struct request_queue *q = bdev_get_queue(bi->bi_bdev);
3973
3974        if ((bi->bi_size>>9) > queue_max_sectors(q))
3975                return 0;
3976        blk_recount_segments(q, bi);
3977        if (bi->bi_phys_segments > queue_max_segments(q))
3978                return 0;
3979
3980        if (q->merge_bvec_fn)
3981                /* it's too hard to apply the merge_bvec_fn at this stage,
3982                 * just just give up
3983                 */
3984                return 0;
3985
3986        return 1;
3987}
3988
3989
3990static int chunk_aligned_read(struct mddev *mddev, struct bio * raid_bio)
3991{
3992        struct r5conf *conf = mddev->private;
3993        int dd_idx;
3994        struct bio* align_bi;
3995        struct md_rdev *rdev;
3996        sector_t end_sector;
3997
3998        if (!in_chunk_boundary(mddev, raid_bio)) {
3999                pr_debug("chunk_aligned_read : non aligned\n");
4000                return 0;
4001        }
4002        /*
4003         * use bio_clone_mddev to make a copy of the bio
4004         */
4005        align_bi = bio_clone_mddev(raid_bio, GFP_NOIO, mddev);
4006        if (!align_bi)
4007                return 0;
4008        /*
4009         *   set bi_end_io to a new function, and set bi_private to the
4010         *     original bio.
4011         */
4012        align_bi->bi_end_io  = raid5_align_endio;
4013        align_bi->bi_private = raid_bio;
4014        /*
4015         *      compute position
4016         */
4017        align_bi->bi_sector =  raid5_compute_sector(conf, raid_bio->bi_sector,
4018                                                    0,
4019                                                    &dd_idx, NULL);
4020
4021        end_sector = align_bi->bi_sector + (align_bi->bi_size >> 9);
4022        rcu_read_lock();
4023        rdev = rcu_dereference(conf->disks[dd_idx].replacement);
4024        if (!rdev || test_bit(Faulty, &rdev->flags) ||
4025            rdev->recovery_offset < end_sector) {
4026                rdev = rcu_dereference(conf->disks[dd_idx].rdev);
4027                if (rdev &&
4028                    (test_bit(Faulty, &rdev->flags) ||
4029                    !(test_bit(In_sync, &rdev->flags) ||
4030                      rdev->recovery_offset >= end_sector)))
4031                        rdev = NULL;
4032        }
4033        if (rdev) {
4034                sector_t first_bad;
4035                int bad_sectors;
4036
4037                atomic_inc(&rdev->nr_pending);
4038                rcu_read_unlock();
4039                raid_bio->bi_next = (void*)rdev;
4040                align_bi->bi_bdev =  rdev->bdev;
4041                align_bi->bi_flags &= ~(1 << BIO_SEG_VALID);
4042
4043                if (!bio_fits_rdev(align_bi) ||
4044                    is_badblock(rdev, align_bi->bi_sector, align_bi->bi_size>>9,
4045                                &first_bad, &bad_sectors)) {
4046                        /* too big in some way, or has a known bad block */
4047                        bio_put(align_bi);
4048                        rdev_dec_pending(rdev, mddev);
4049                        return 0;
4050                }
4051
4052                /* No reshape active, so we can trust rdev->data_offset */
4053                align_bi->bi_sector += rdev->data_offset;
4054
4055                spin_lock_irq(&conf->device_lock);
4056                wait_event_lock_irq(conf->wait_for_stripe,
4057                                    conf->quiesce == 0,
4058                                    conf->device_lock);
4059                atomic_inc(&conf->active_aligned_reads);
4060                spin_unlock_irq(&conf->device_lock);
4061
4062                if (mddev->gendisk)
4063                        trace_block_bio_remap(bdev_get_queue(align_bi->bi_bdev),
4064                                              align_bi, disk_devt(mddev->gendisk),
4065                                              raid_bio->bi_sector);
4066                generic_make_request(align_bi);
4067                return 1;
4068        } else {
4069                rcu_read_unlock();
4070                bio_put(align_bi);
4071                return 0;
4072        }
4073}
4074
4075/* __get_priority_stripe - get the next stripe to process
4076 *
4077 * Full stripe writes are allowed to pass preread active stripes up until
4078 * the bypass_threshold is exceeded.  In general the bypass_count
4079 * increments when the handle_list is handled before the hold_list; however, it
4080 * will not be incremented when STRIPE_IO_STARTED is sampled set signifying a
4081 * stripe with in flight i/o.  The bypass_count will be reset when the
4082 * head of the hold_list has changed, i.e. the head was promoted to the
4083 * handle_list.
4084 */
4085static struct stripe_head *__get_priority_stripe(struct r5conf *conf)
4086{
4087        struct stripe_head *sh;
4088
4089        pr_debug("%s: handle: %s hold: %s full_writes: %d bypass_count: %d\n",
4090                  __func__,
4091                  list_empty(&conf->handle_list) ? "empty" : "busy",
4092                  list_empty(&conf->hold_list) ? "empty" : "busy",
4093                  atomic_read(&conf->pending_full_writes), conf->bypass_count);
4094
4095        if (!list_empty(&conf->handle_list)) {
4096                sh = list_entry(conf->handle_list.next, typeof(*sh), lru);
4097
4098                if (list_empty(&conf->hold_list))
4099                        conf->bypass_count = 0;
4100                else if (!test_bit(STRIPE_IO_STARTED, &sh->state)) {
4101                        if (conf->hold_list.next == conf->last_hold)
4102                                conf->bypass_count++;
4103                        else {
4104                                conf->last_hold = conf->hold_list.next;
4105                                conf->bypass_count -= conf->bypass_threshold;
4106                                if (conf->bypass_count < 0)
4107                                        conf->bypass_count = 0;
4108                        }
4109                }
4110        } else if (!list_empty(&conf->hold_list) &&
4111                   ((conf->bypass_threshold &&
4112                     conf->bypass_count > conf->bypass_threshold) ||
4113                    atomic_read(&conf->pending_full_writes) == 0)) {
4114                sh = list_entry(conf->hold_list.next,
4115                                typeof(*sh), lru);
4116                conf->bypass_count -= conf->bypass_threshold;
4117                if (conf->bypass_count < 0)
4118                        conf->bypass_count = 0;
4119        } else
4120                return NULL;
4121
4122        list_del_init(&sh->lru);
4123        atomic_inc(&sh->count);
4124        BUG_ON(atomic_read(&sh->count) != 1);
4125        return sh;
4126}
4127
4128struct raid5_plug_cb {
4129        struct blk_plug_cb      cb;
4130        struct list_head        list;
4131};
4132
4133static void raid5_unplug(struct blk_plug_cb *blk_cb, bool from_schedule)
4134{
4135        struct raid5_plug_cb *cb = container_of(
4136                blk_cb, struct raid5_plug_cb, cb);
4137        struct stripe_head *sh;
4138        struct mddev *mddev = cb->cb.data;
4139        struct r5conf *conf = mddev->private;
4140        int cnt = 0;
4141
4142        if (cb->list.next && !list_empty(&cb->list)) {
4143                spin_lock_irq(&conf->device_lock);
4144                while (!list_empty(&cb->list)) {
4145                        sh = list_first_entry(&cb->list, struct stripe_head, lru);
4146                        list_del_init(&sh->lru);
4147                        /*
4148                         * avoid race release_stripe_plug() sees
4149                         * STRIPE_ON_UNPLUG_LIST clear but the stripe
4150                         * is still in our list
4151                         */
4152                        smp_mb__before_clear_bit();
4153                        clear_bit(STRIPE_ON_UNPLUG_LIST, &sh->state);
4154                        __release_stripe(conf, sh);
4155                        cnt++;
4156                }
4157                spin_unlock_irq(&conf->device_lock);
4158        }
4159        if (mddev->queue)
4160                trace_block_unplug(mddev->queue, cnt, !from_schedule);
4161        kfree(cb);
4162}
4163
4164static void release_stripe_plug(struct mddev *mddev,
4165                                struct stripe_head *sh)
4166{
4167        struct blk_plug_cb *blk_cb = blk_check_plugged(
4168                raid5_unplug, mddev,
4169                sizeof(struct raid5_plug_cb));
4170        struct raid5_plug_cb *cb;
4171
4172        if (!blk_cb) {
4173                release_stripe(sh);
4174                return;
4175        }
4176
4177        cb = container_of(blk_cb, struct raid5_plug_cb, cb);
4178
4179        if (cb->list.next == NULL)
4180                INIT_LIST_HEAD(&cb->list);
4181
4182        if (!test_and_set_bit(STRIPE_ON_UNPLUG_LIST, &sh->state))
4183                list_add_tail(&sh->lru, &cb->list);
4184        else
4185                release_stripe(sh);
4186}
4187
4188static void make_discard_request(struct mddev *mddev, struct bio *bi)
4189{
4190        struct r5conf *conf = mddev->private;
4191        sector_t logical_sector, last_sector;
4192        struct stripe_head *sh;
4193        int remaining;
4194        int stripe_sectors;
4195
4196        if (mddev->reshape_position != MaxSector)
4197                /* Skip discard while reshape is happening */
4198                return;
4199
4200        logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4201        last_sector = bi->bi_sector + (bi->bi_size>>9);
4202
4203        bi->bi_next = NULL;
4204        bi->bi_phys_segments = 1; /* over-loaded to count active stripes */
4205
4206        stripe_sectors = conf->chunk_sectors *
4207                (conf->raid_disks - conf->max_degraded);
4208        logical_sector = DIV_ROUND_UP_SECTOR_T(logical_sector,
4209                                               stripe_sectors);
4210        sector_div(last_sector, stripe_sectors);
4211
4212        logical_sector *= conf->chunk_sectors;
4213        last_sector *= conf->chunk_sectors;
4214
4215        for (; logical_sector < last_sector;
4216             logical_sector += STRIPE_SECTORS) {
4217                DEFINE_WAIT(w);
4218                int d;
4219        again:
4220                sh = get_active_stripe(conf, logical_sector, 0, 0, 0);
4221                prepare_to_wait(&conf->wait_for_overlap, &w,
4222                                TASK_UNINTERRUPTIBLE);
4223                set_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4224                if (test_bit(STRIPE_SYNCING, &sh->state)) {
4225                        release_stripe(sh);
4226                        schedule();
4227                        goto again;
4228                }
4229                clear_bit(R5_Overlap, &sh->dev[sh->pd_idx].flags);
4230                spin_lock_irq(&sh->stripe_lock);
4231                for (d = 0; d < conf->raid_disks; d++) {
4232                        if (d == sh->pd_idx || d == sh->qd_idx)
4233                                continue;
4234                        if (sh->dev[d].towrite || sh->dev[d].toread) {
4235                                set_bit(R5_Overlap, &sh->dev[d].flags);
4236                                spin_unlock_irq(&sh->stripe_lock);
4237                                release_stripe(sh);
4238                                schedule();
4239                                goto again;
4240                        }
4241                }
4242                set_bit(STRIPE_DISCARD, &sh->state);
4243                finish_wait(&conf->wait_for_overlap, &w);
4244                for (d = 0; d < conf->raid_disks; d++) {
4245                        if (d == sh->pd_idx || d == sh->qd_idx)
4246                                continue;
4247                        sh->dev[d].towrite = bi;
4248                        set_bit(R5_OVERWRITE, &sh->dev[d].flags);
4249                        raid5_inc_bi_active_stripes(bi);
4250                }
4251                spin_unlock_irq(&sh->stripe_lock);
4252                if (conf->mddev->bitmap) {
4253                        for (d = 0;
4254                             d < conf->raid_disks - conf->max_degraded;
4255                             d++)
4256                                bitmap_startwrite(mddev->bitmap,
4257                                                  sh->sector,
4258                                                  STRIPE_SECTORS,
4259                                                  0);
4260                        sh->bm_seq = conf->seq_flush + 1;
4261                        set_bit(STRIPE_BIT_DELAY, &sh->state);
4262                }
4263
4264                set_bit(STRIPE_HANDLE, &sh->state);
4265                clear_bit(STRIPE_DELAYED, &sh->state);
4266                if (!test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4267                        atomic_inc(&conf->preread_active_stripes);
4268                release_stripe_plug(mddev, sh);
4269        }
4270
4271        remaining = raid5_dec_bi_active_stripes(bi);
4272        if (remaining == 0) {
4273                md_write_end(mddev);
4274                bio_endio(bi, 0);
4275        }
4276}
4277
4278static void make_request(struct mddev *mddev, struct bio * bi)
4279{
4280        struct r5conf *conf = mddev->private;
4281        int dd_idx;
4282        sector_t new_sector;
4283        sector_t logical_sector, last_sector;
4284        struct stripe_head *sh;
4285        const int rw = bio_data_dir(bi);
4286        int remaining;
4287
4288        if (unlikely(bi->bi_rw & REQ_FLUSH)) {
4289                md_flush_request(mddev, bi);
4290                return;
4291        }
4292
4293        md_write_start(mddev, bi);
4294
4295        if (rw == READ &&
4296             mddev->reshape_position == MaxSector &&
4297             chunk_aligned_read(mddev,bi))
4298                return;
4299
4300        if (unlikely(bi->bi_rw & REQ_DISCARD)) {
4301                make_discard_request(mddev, bi);
4302                return;
4303        }
4304
4305        logical_sector = bi->bi_sector & ~((sector_t)STRIPE_SECTORS-1);
4306        last_sector = bi->bi_sector + (bi->bi_size>>9);
4307        bi->bi_next = NULL;
4308        bi->bi_phys_segments = 1;       /* over-loaded to count active stripes */
4309
4310        for (;logical_sector < last_sector; logical_sector += STRIPE_SECTORS) {
4311                DEFINE_WAIT(w);
4312                int previous;
4313
4314        retry:
4315                previous = 0;
4316                prepare_to_wait(&conf->wait_for_overlap, &w, TASK_UNINTERRUPTIBLE);
4317                if (unlikely(conf->reshape_progress != MaxSector)) {
4318                        /* spinlock is needed as reshape_progress may be
4319                         * 64bit on a 32bit platform, and so it might be
4320                         * possible to see a half-updated value
4321                         * Of course reshape_progress could change after
4322                         * the lock is dropped, so once we get a reference
4323                         * to the stripe that we think it is, we will have
4324                         * to check again.
4325                         */
4326                        spin_lock_irq(&conf->device_lock);
4327                        if (mddev->reshape_backwards
4328                            ? logical_sector < conf->reshape_progress
4329                            : logical_sector >= conf->reshape_progress) {
4330                                previous = 1;
4331                        } else {
4332                                if (mddev->reshape_backwards
4333                                    ? logical_sector < conf->reshape_safe
4334                                    : logical_sector >= conf->reshape_safe) {
4335                                        spin_unlock_irq(&conf->device_lock);
4336                                        schedule();
4337                                        goto retry;
4338                                }
4339                        }
4340                        spin_unlock_irq(&conf->device_lock);
4341                }
4342
4343                new_sector = raid5_compute_sector(conf, logical_sector,
4344                                                  previous,
4345                                                  &dd_idx, NULL);
4346                pr_debug("raid456: make_request, sector %llu logical %llu\n",
4347                        (unsigned long long)new_sector, 
4348                        (unsigned long long)logical_sector);
4349
4350                sh = get_active_stripe(conf, new_sector, previous,
4351                                       (bi->bi_rw&RWA_MASK), 0);
4352                if (sh) {
4353                        if (unlikely(previous)) {
4354                                /* expansion might have moved on while waiting for a
4355                                 * stripe, so we must do the range check again.
4356                                 * Expansion could still move past after this
4357                                 * test, but as we are holding a reference to
4358                                 * 'sh', we know that if that happens,
4359                                 *  STRIPE_EXPANDING will get set and the expansion
4360                                 * won't proceed until we finish with the stripe.
4361                                 */
4362                                int must_retry = 0;
4363                                spin_lock_irq(&conf->device_lock);
4364                                if (mddev->reshape_backwards
4365                                    ? logical_sector >= conf->reshape_progress
4366                                    : logical_sector < conf->reshape_progress)
4367                                        /* mismatch, need to try again */
4368                                        must_retry = 1;
4369                                spin_unlock_irq(&conf->device_lock);
4370                                if (must_retry) {
4371                                        release_stripe(sh);
4372                                        schedule();
4373                                        goto retry;
4374                                }
4375                        }
4376
4377                        if (rw == WRITE &&
4378                            logical_sector >= mddev->suspend_lo &&
4379                            logical_sector < mddev->suspend_hi) {
4380                                release_stripe(sh);
4381                                /* As the suspend_* range is controlled by
4382                                 * userspace, we want an interruptible
4383                                 * wait.
4384                                 */
4385                                flush_signals(current);
4386                                prepare_to_wait(&conf->wait_for_overlap,
4387                                                &w, TASK_INTERRUPTIBLE);
4388                                if (logical_sector >= mddev->suspend_lo &&
4389                                    logical_sector < mddev->suspend_hi)
4390                                        schedule();
4391                                goto retry;
4392                        }
4393
4394                        if (test_bit(STRIPE_EXPANDING, &sh->state) ||
4395                            !add_stripe_bio(sh, bi, dd_idx, rw)) {
4396                                /* Stripe is busy expanding or
4397                                 * add failed due to overlap.  Flush everything
4398                                 * and wait a while
4399                                 */
4400                                md_wakeup_thread(mddev->thread);
4401                                release_stripe(sh);
4402                                schedule();
4403                                goto retry;
4404                        }
4405                        finish_wait(&conf->wait_for_overlap, &w);
4406                        set_bit(STRIPE_HANDLE, &sh->state);
4407                        clear_bit(STRIPE_DELAYED, &sh->state);
4408                        if ((bi->bi_rw & REQ_SYNC) &&
4409                            !test_and_set_bit(STRIPE_PREREAD_ACTIVE, &sh->state))
4410                                atomic_inc(&conf->preread_active_stripes);
4411                        release_stripe_plug(mddev, sh);
4412                } else {
4413                        /* cannot get stripe for read-ahead, just give-up */
4414                        clear_bit(BIO_UPTODATE, &bi->bi_flags);
4415                        finish_wait(&conf->wait_for_overlap, &w);
4416                        break;
4417                }
4418        }
4419
4420        remaining = raid5_dec_bi_active_stripes(bi);
4421        if (remaining == 0) {
4422
4423                if ( rw == WRITE )
4424                        md_write_end(mddev);
4425
4426                trace_block_bio_complete(bdev_get_queue(bi->bi_bdev),
4427                                         bi, 0);
4428                bio_endio(bi, 0);
4429        }
4430}
4431
4432static sector_t raid5_size(struct mddev *mddev, sector_t sectors, int raid_disks);
4433
4434static sector_t reshape_request(struct mddev *mddev, sector_t sector_nr, int *skipped)
4435{
4436        /* reshaping is quite different to recovery/resync so it is
4437         * handled quite separately ... here.
4438         *
4439         * On each call to sync_request, we gather one chunk worth of
4440         * destination stripes and flag them as expanding.
4441         * Then we find all the source stripes and request reads.
4442         * As the reads complete, handle_stripe will copy the data
4443         * into the destination stripe and release that stripe.
4444         */
4445        struct r5conf *conf = mddev->private;
4446        struct stripe_head *sh;
4447        sector_t first_sector, last_sector;
4448        int raid_disks = conf->previous_raid_disks;
4449        int data_disks = raid_disks - conf->max_degraded;
4450        int new_data_disks = conf->raid_disks - conf->max_degraded;
4451        int i;
4452        int dd_idx;
4453        sector_t writepos, readpos, safepos;
4454        sector_t stripe_addr;
4455        int reshape_sectors;
4456        struct list_head stripes;
4457
4458        if (sector_nr == 0) {
4459                /* If restarting in the middle, skip the initial sectors */
4460                if (mddev->reshape_backwards &&
4461                    conf->reshape_progress < raid5_size(mddev, 0, 0)) {
4462                        sector_nr = raid5_size(mddev, 0, 0)
4463                                - conf->reshape_progress;
4464                } else if (!mddev->reshape_backwards &&
4465                           conf->reshape_progress > 0)
4466                        sector_nr = conf->reshape_progress;
4467                sector_div(sector_nr, new_data_disks);
4468                if (sector_nr) {
4469                        mddev->curr_resync_completed = sector_nr;
4470                        sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4471                        *skipped = 1;
4472                        return sector_nr;
4473                }
4474        }
4475
4476        /* We need to process a full chunk at a time.
4477         * If old and new chunk sizes differ, we need to process the
4478         * largest of these
4479         */
4480        if (mddev->new_chunk_sectors > mddev->chunk_sectors)
4481                reshape_sectors = mddev->new_chunk_sectors;
4482        else
4483                reshape_sectors = mddev->chunk_sectors;
4484
4485        /* We update the metadata at least every 10 seconds, or when
4486         * the data about to be copied would over-write the source of
4487         * the data at the front of the range.  i.e. one new_stripe
4488         * along from reshape_progress new_maps to after where
4489         * reshape_safe old_maps to
4490         */
4491        writepos = conf->reshape_progress;
4492        sector_div(writepos, new_data_disks);
4493        readpos = conf->reshape_progress;
4494        sector_div(readpos, data_disks);
4495        safepos = conf->reshape_safe;
4496        sector_div(safepos, data_disks);
4497        if (mddev->reshape_backwards) {
4498                writepos -= min_t(sector_t, reshape_sectors, writepos);
4499                readpos += reshape_sectors;
4500                safepos += reshape_sectors;
4501        } else {
4502                writepos += reshape_sectors;
4503                readpos -= min_t(sector_t, reshape_sectors, readpos);
4504                safepos -= min_t(sector_t, reshape_sectors, safepos);
4505        }
4506
4507        /* Having calculated the 'writepos' possibly use it
4508         * to set 'stripe_addr' which is where we will write to.
4509         */
4510        if (mddev->reshape_backwards) {
4511                BUG_ON(conf->reshape_progress == 0);
4512                stripe_addr = writepos;
4513                BUG_ON((mddev->dev_sectors &
4514                        ~((sector_t)reshape_sectors - 1))
4515                       - reshape_sectors - stripe_addr
4516                       != sector_nr);
4517        } else {
4518                BUG_ON(writepos != sector_nr + reshape_sectors);
4519                stripe_addr = sector_nr;
4520        }
4521
4522        /* 'writepos' is the most advanced device address we might write.
4523         * 'readpos' is the least advanced device address we might read.
4524         * 'safepos' is the least address recorded in the metadata as having
4525         *     been reshaped.
4526         * If there is a min_offset_diff, these are adjusted either by
4527         * increasing the safepos/readpos if diff is negative, or
4528         * increasing writepos if diff is positive.
4529         * If 'readpos' is then behind 'writepos', there is no way that we can
4530         * ensure safety in the face of a crash - that must be done by userspace
4531         * making a backup of the data.  So in that case there is no particular
4532         * rush to update metadata.
4533         * Otherwise if 'safepos' is behind 'writepos', then we really need to
4534         * update the metadata to advance 'safepos' to match 'readpos' so that
4535         * we can be safe in the event of a crash.
4536         * So we insist on updating metadata if safepos is behind writepos and
4537         * readpos is beyond writepos.
4538         * In any case, update the metadata every 10 seconds.
4539         * Maybe that number should be configurable, but I'm not sure it is
4540         * worth it.... maybe it could be a multiple of safemode_delay???
4541         */
4542        if (conf->min_offset_diff < 0) {
4543                safepos += -conf->min_offset_diff;
4544                readpos += -conf->min_offset_diff;
4545        } else
4546                writepos += conf->min_offset_diff;
4547
4548        if ((mddev->reshape_backwards
4549             ? (safepos > writepos && readpos < writepos)
4550             : (safepos < writepos && readpos > writepos)) ||
4551            time_after(jiffies, conf->reshape_checkpoint + 10*HZ)) {
4552                /* Cannot proceed until we've updated the superblock... */
4553                wait_event(conf->wait_for_overlap,
4554                           atomic_read(&conf->reshape_stripes)==0);
4555                mddev->reshape_position = conf->reshape_progress;
4556                mddev->curr_resync_completed = sector_nr;
4557                conf->reshape_checkpoint = jiffies;
4558                set_bit(MD_CHANGE_DEVS, &mddev->flags);
4559                md_wakeup_thread(mddev->thread);
4560                wait_event(mddev->sb_wait, mddev->flags == 0 ||
4561                           kthread_should_stop());
4562                spin_lock_irq(&conf->device_lock);
4563                conf->reshape_safe = mddev->reshape_position;
4564                spin_unlock_irq(&conf->device_lock);
4565                wake_up(&conf->wait_for_overlap);
4566                sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4567        }
4568
4569        INIT_LIST_HEAD(&stripes);
4570        for (i = 0; i < reshape_sectors; i += STRIPE_SECTORS) {
4571                int j;
4572                int skipped_disk = 0;
4573                sh = get_active_stripe(conf, stripe_addr+i, 0, 0, 1);
4574                set_bit(STRIPE_EXPANDING, &sh->state);
4575                atomic_inc(&conf->reshape_stripes);
4576                /* If any of this stripe is beyond the end of the old
4577                 * array, then we need to zero those blocks
4578                 */
4579                for (j=sh->disks; j--;) {
4580                        sector_t s;
4581                        if (j == sh->pd_idx)
4582                                continue;
4583                        if (conf->level == 6 &&
4584                            j == sh->qd_idx)
4585                                continue;
4586                        s = compute_blocknr(sh, j, 0);
4587                        if (s < raid5_size(mddev, 0, 0)) {
4588                                skipped_disk = 1;
4589                                continue;
4590                        }
4591                        memset(page_address(sh->dev[j].page), 0, STRIPE_SIZE);
4592                        set_bit(R5_Expanded, &sh->dev[j].flags);
4593                        set_bit(R5_UPTODATE, &sh->dev[j].flags);
4594                }
4595                if (!skipped_disk) {
4596                        set_bit(STRIPE_EXPAND_READY, &sh->state);
4597                        set_bit(STRIPE_HANDLE, &sh->state);
4598                }
4599                list_add(&sh->lru, &stripes);
4600        }
4601        spin_lock_irq(&conf->device_lock);
4602        if (mddev->reshape_backwards)
4603                conf->reshape_progress -= reshape_sectors * new_data_disks;
4604        else
4605                conf->reshape_progress += reshape_sectors * new_data_disks;
4606        spin_unlock_irq(&conf->device_lock);
4607        /* Ok, those stripe are ready. We can start scheduling
4608         * reads on the source stripes.
4609         * The source stripes are determined by mapping the first and last
4610         * block on the destination stripes.
4611         */
4612        first_sector =
4613                raid5_compute_sector(conf, stripe_addr*(new_data_disks),
4614                                     1, &dd_idx, NULL);
4615        last_sector =
4616                raid5_compute_sector(conf, ((stripe_addr+reshape_sectors)
4617                                            * new_data_disks - 1),
4618                                     1, &dd_idx, NULL);
4619        if (last_sector >= mddev->dev_sectors)
4620                last_sector = mddev->dev_sectors - 1;
4621        while (first_sector <= last_sector) {
4622                sh = get_active_stripe(conf, first_sector, 1, 0, 1);
4623                set_bit(STRIPE_EXPAND_SOURCE, &sh->state);
4624                set_bit(STRIPE_HANDLE, &sh->state);
4625                release_stripe(sh);
4626                first_sector += STRIPE_SECTORS;
4627        }
4628        /* Now that the sources are clearly marked, we can release
4629         * the destination stripes
4630         */
4631        while (!list_empty(&stripes)) {
4632                sh = list_entry(stripes.next, struct stripe_head, lru);
4633                list_del_init(&sh->lru);
4634                release_stripe(sh);
4635        }
4636        /* If this takes us to the resync_max point where we have to pause,
4637         * then we need to write out the superblock.
4638         */
4639        sector_nr += reshape_sectors;
4640        if ((sector_nr - mddev->curr_resync_completed) * 2
4641            >= mddev->resync_max - mddev->curr_resync_completed) {
4642                /* Cannot proceed until we've updated the superblock... */
4643                wait_event(conf->wait_for_overlap,
4644                           atomic_read(&conf->reshape_stripes) == 0);
4645                mddev->reshape_position = conf->reshape_progress;
4646                mddev->curr_resync_completed = sector_nr;
4647                conf->reshape_checkpoint = jiffies;
4648                set_bit(MD_CHANGE_DEVS, &mddev->flags);
4649                md_wakeup_thread(mddev->thread);
4650                wait_event(mddev->sb_wait,
4651                           !test_bit(MD_CHANGE_DEVS, &mddev->flags)
4652                           || kthread_should_stop());
4653                spin_lock_irq(&conf->device_lock);
4654                conf->reshape_safe = mddev->reshape_position;
4655                spin_unlock_irq(&conf->device_lock);
4656                wake_up(&conf->wait_for_overlap);
4657                sysfs_notify(&mddev->kobj, NULL, "sync_completed");
4658        }
4659        return reshape_sectors;
4660}
4661
4662/* FIXME go_faster isn't used */
4663static inline sector_t sync_request(struct mddev *mddev, sector_t sector_nr, int *skipped, int go_faster)
4664{
4665        struct r5conf *conf = mddev->private;
4666        struct stripe_head *sh;
4667        sector_t max_sector = mddev->dev_sectors;
4668        sector_t sync_blocks;
4669        int still_degraded = 0;
4670        int i;
4671
4672        if (sector_nr >= max_sector) {
4673                /* just being told to finish up .. nothing much to do */
4674
4675                if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)) {
4676                        end_reshape(conf);
4677                        return 0;
4678                }
4679
4680                if (mddev->curr_resync < max_sector) /* aborted */
4681                        bitmap_end_sync(mddev->bitmap, mddev->curr_resync,
4682                                        &sync_blocks, 1);
4683                else /* completed sync */
4684                        conf->fullsync = 0;
4685                bitmap_close_sync(mddev->bitmap);
4686
4687                return 0;
4688        }
4689
4690        /* Allow raid5_quiesce to complete */
4691        wait_event(conf->wait_for_overlap, conf->quiesce != 2);
4692
4693        if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4694                return reshape_request(mddev, sector_nr, skipped);
4695
4696        /* No need to check resync_max as we never do more than one
4697         * stripe, and as resync_max will always be on a chunk boundary,
4698         * if the check in md_do_sync didn't fire, there is no chance
4699         * of overstepping resync_max here
4700         */
4701
4702        /* if there is too many failed drives and we are trying
4703         * to resync, then assert that we are finished, because there is
4704         * nothing we can do.
4705         */
4706        if (mddev->degraded >= conf->max_degraded &&
4707            test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4708                sector_t rv = mddev->dev_sectors - sector_nr;
4709                *skipped = 1;
4710                return rv;
4711        }
4712        if (!bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, 1) &&
4713            !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery) &&
4714            !conf->fullsync && sync_blocks >= STRIPE_SECTORS) {
4715                /* we can skip this block, and probably more */
4716                sync_blocks /= STRIPE_SECTORS;
4717                *skipped = 1;
4718                return sync_blocks * STRIPE_SECTORS; /* keep things rounded to whole stripes */
4719        }
4720
4721        bitmap_cond_end_sync(mddev->bitmap, sector_nr);
4722
4723        sh = get_active_stripe(conf, sector_nr, 0, 1, 0);
4724        if (sh == NULL) {
4725                sh = get_active_stripe(conf, sector_nr, 0, 0, 0);
4726                /* make sure we don't swamp the stripe cache if someone else
4727                 * is trying to get access
4728                 */
4729                schedule_timeout_uninterruptible(1);
4730        }
4731        /* Need to check if array will still be degraded after recovery/resync
4732         * We don't need to check the 'failed' flag as when that gets set,
4733         * recovery aborts.
4734         */
4735        for (i = 0; i < conf->raid_disks; i++)
4736                if (conf->disks[i].rdev == NULL)
4737                        still_degraded = 1;
4738
4739        bitmap_start_sync(mddev->bitmap, sector_nr, &sync_blocks, still_degraded);
4740
4741        set_bit(STRIPE_SYNC_REQUESTED, &sh->state);
4742
4743        handle_stripe(sh);
4744        release_stripe(sh);
4745
4746        return STRIPE_SECTORS;
4747}
4748
4749static int  retry_aligned_read(struct r5conf *conf, struct bio *raid_bio)
4750{
4751        /* We may not be able to submit a whole bio at once as there
4752         * may not be enough stripe_heads available.
4753         * We cannot pre-allocate enough stripe_heads as we may need
4754         * more than exist in the cache (if we allow ever large chunks).
4755         * So we do one stripe head at a time and record in
4756         * ->bi_hw_segments how many have been done.
4757         *
4758         * We *know* that this entire raid_bio is in one chunk, so
4759         * it will be only one 'dd_idx' and only need one call to raid5_compute_sector.
4760         */
4761        struct stripe_head *sh;
4762        int dd_idx;
4763        sector_t sector, logical_sector, last_sector;
4764        int scnt = 0;
4765        int remaining;
4766        int handled = 0;
4767
4768        logical_sector =