{
        struct bio *bio = r1_bio->master_bio;
        struct r1conf *conf = r1_bio->mddev->private;
+       sector_t sector = r1_bio->sector;
 
        /* if nobody has done the final endio yet, do it now */
        if (!test_and_set_bit(R1BIO_Returned, &r1_bio->state)) {
 
                call_bio_endio(r1_bio);
        }
+
+       free_r1bio(r1_bio);
        /*
         * Wake up any possible resync thread that waits for the device
         * to go idle.  All I/Os, even write-behind writes, are done.
         */
-       allow_barrier(conf, r1_bio->sector);
-
-       free_r1bio(r1_bio);
+       allow_barrier(conf, sector);
 }
 
 /*