virtio/blk: Set VIRTIO_BLK_F_RO when the disk is read-only

Since we don't currently tell the guest when the disk backend is
read-only, it will report any inconsistent read after write as an error.
An image may be read-only either because user requested it on the
command-line, or because write support isn't implemented. Pass the
read-only attribute using the VIRTIO_BLK_F_RO feature.

Reviewed-by: Andre Przywara <andre.przywara@arm.com>
Signed-off-by: Jean-Philippe Brucker <jean-philippe.brucker@arm.com>
Signed-off-by: Will Deacon <will.deacon@arm.com>
diff --git a/disk/core.c b/disk/core.c
index dd2f258..4c7c4f0 100644
--- a/disk/core.c
+++ b/disk/core.c
@@ -139,8 +139,10 @@
 
 	/* blk device ?*/
 	disk = blkdev__probe(filename, flags, &st);
-	if (!IS_ERR_OR_NULL(disk))
+	if (!IS_ERR_OR_NULL(disk)) {
+		disk->readonly = readonly;
 		return disk;
+	}
 
 	fd = open(filename, flags);
 	if (fd < 0)
@@ -150,13 +152,16 @@
 	disk = qcow_probe(fd, true);
 	if (!IS_ERR_OR_NULL(disk)) {
 		pr_warning("Forcing read-only support for QCOW");
+		disk->readonly = true;
 		return disk;
 	}
 
 	/* raw image ?*/
 	disk = raw_image__probe(fd, &st, readonly);
-	if (!IS_ERR_OR_NULL(disk))
+	if (!IS_ERR_OR_NULL(disk)) {
+		disk->readonly = readonly;
 		return disk;
+	}
 
 	if (close(fd) < 0)
 		pr_warning("close() failed");
diff --git a/include/kvm/disk-image.h b/include/kvm/disk-image.h
index b728052..4746e88 100644
--- a/include/kvm/disk-image.h
+++ b/include/kvm/disk-image.h
@@ -59,6 +59,7 @@
 	void				*priv;
 	void				*disk_req_cb_param;
 	void				(*disk_req_cb)(void *param, long len);
+	bool				readonly;
 	bool				async;
 	int				evt;
 #ifdef CONFIG_HAS_AIO
diff --git a/virtio/blk.c b/virtio/blk.c
index a57df2e..6e7a1ee 100644
--- a/virtio/blk.c
+++ b/virtio/blk.c
@@ -148,10 +148,13 @@
 
 static u32 get_host_features(struct kvm *kvm, void *dev)
 {
+	struct blk_dev *bdev = dev;
+
 	return	1UL << VIRTIO_BLK_F_SEG_MAX
 		| 1UL << VIRTIO_BLK_F_FLUSH
 		| 1UL << VIRTIO_RING_F_EVENT_IDX
-		| 1UL << VIRTIO_RING_F_INDIRECT_DESC;
+		| 1UL << VIRTIO_RING_F_INDIRECT_DESC
+		| (bdev->disk->readonly ? 1UL << VIRTIO_BLK_F_RO : 0);
 }
 
 static void set_guest_features(struct kvm *kvm, void *dev, u32 features)