From 3921178a2eef5bcce147e8291bff46ff24370497 Mon Sep 17 00:00:00 2001
From: Kevin Wolf <kwolf@redhat.com>
Date: Wed, 26 May 2010 11:21:23 -0300
Subject: [PATCH 8/9] block: fix sector comparism in multiwrite_req_compare

RH-Author: Kevin Wolf <kwolf@redhat.com>
Message-id: <1274872884-23841-2-git-send-email-kwolf@redhat.com>
Patchwork-id: 9569
O-Subject: [RHEL-6 qemu-kvm PATCH 1/2] block: fix sector comparism in
	multiwrite_req_compare
Bugzilla: 596119
RH-Acked-by: Juan Quintela <quintela@redhat.com>
RH-Acked-by: Jes Sorensen <Jes.Sorensen@redhat.com>
RH-Acked-by: Christoph Hellwig <chellwig@redhat.com>

From: Christoph Hellwig <hch@lst.de>

Bugzilla: 596119

The difference between the start sectors of two requests can be larger
than the size of the "int" type, which can lead to a not correctly
sorted multiwrite array and thus spurious I/O errors and filesystem
corruption due to incorrect request merges.

So instead of doing the cute sector arithmetics trick spell out the
exact comparisms.

Spotted by Kevin Wolf based on a testcase from Michael Tokarev.

Signed-off-by: Christoph Hellwig <hch@lst.de>
Signed-off-by: Kevin Wolf <kwolf@redhat.com>
(cherry picked from commit 77be4366baface6613cfc312ba281f8e5860997c)
---
 block.c |   14 +++++++++++++-
 1 files changed, 13 insertions(+), 1 deletions(-)

Signed-off-by: Eduardo Habkost <ehabkost@redhat.com>
---
 block.c |   14 +++++++++++++-
 1 files changed, 13 insertions(+), 1 deletions(-)

diff --git a/block.c b/block.c
index 1475ea0..98fe44e 100644
--- a/block.c
+++ b/block.c
@@ -1891,7 +1891,19 @@ static void multiwrite_cb(void *opaque, int ret)
 
 static int multiwrite_req_compare(const void *a, const void *b)
 {
-    return (((BlockRequest*) a)->sector - ((BlockRequest*) b)->sector);
+    const BlockRequest *req1 = a, *req2 = b;
+
+    /*
+     * Note that we can't simply subtract req2->sector from req1->sector
+     * here as that could overflow the return value.
+     */
+    if (req1->sector > req2->sector) {
+        return 1;
+    } else if (req1->sector < req2->sector) {
+        return -1;
+    } else {
+        return 0;
+    }
 }
 
 /*
-- 
1.7.0.3

