--- drivers/md/raid1.c
+++ drivers/md/raid1.c
@@ -618,7 +623,9 @@
 		struct bio *bio;
 		bio = bio_list_get(&conf->pending_bio_list);
 		blk_remove_plug(conf->mddev->queue);
+		conf->pending_count = 0;
 		spin_unlock_irq(&conf->device_lock);
+		wake_up(&conf->wait_barrier);
 		/* flush any pending bitmap writes to
 		 * disk before proceeding w/ I/O */
 		bitmap_unplug(conf->mddev->bitmap);
@@ -788,6 +795,7 @@
 	struct bitmap *bitmap;
 	unsigned long flags;
 	struct bio_list bl;
+	int bl_count;
 	struct page **behind_pages = NULL;
 	const int rw = bio_data_dir(bio);
 	const bool do_sync = bio_rw_flagged(bio, BIO_RW_SYNCIO);
@@ -878,6 +886,11 @@
 	/*
 	 * WRITE:
 	 */
+	if (conf->pending_count >= max_queued) {
+		md_wakeup_thread(mddev->thread);
+		wait_event(conf->wait_barrier,
+			   conf->pending_count < max_queued);
+	}
 	/* first select target devices under spinlock and
 	 * inc refcount on their rdev.  Record them by setting
 	 * bios[x] to bio
@@ -954,6 +967,7 @@
 		set_bit(R1BIO_Barrier, &r1_bio->state);
 
 	bio_list_init(&bl);
+	bl_count = 0;
 	for (i = 0; i < disks; i++) {
 		struct bio *mbio;
 		if (!r1_bio->bios[i])
@@ -989,6 +1003,7 @@
 		atomic_inc(&r1_bio->remaining);
 
 		bio_list_add(&bl, mbio);
+		bl_count++;
 	}
 	kfree(behind_pages); /* the behind pages are attached to the bios now */
 
@@ -996,6 +1011,7 @@
 				test_bit(R1BIO_BehindIO, &r1_bio->state));
 	spin_lock_irqsave(&conf->device_lock, flags);
 	bio_list_merge(&conf->pending_bio_list, &bl);
+	conf->pending_count += bl_count;
 	bio_list_init(&bl);
 
 	blk_plug_device(mddev->queue);
@@ -2040,6 +2056,7 @@
 	init_waitqueue_head(&conf->wait_barrier);
 
 	bio_list_init(&conf->pending_bio_list);
+	conf->pending_count = 0;
 	bio_list_init(&conf->flushing_bio_list);
 
 
