Skip to contentSkip to conversation

blksnap - block devices snapshots module

PATCH In review Sergei Shtepa 5 participants 23 messages Nov 24, 2023 – Dec 7, 2023

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

v6 cover blksnap - block devices snapshots module

From: Sergei Shtepa <[email protected]>

Hi all.

I am happy to offer an improved version of the Block Devices Snapshots Module. It allows creating non-persistent snapshots of any block devices. The main purpose of such snapshots is to provide backups of block devices. See more in Documentation/block/blksnap.rst.

The Block Device Filtering Mechanism is added to the block layer. This allows attaching and detaching block device filters to the block layer. Filters allow extending the functionality of the block layer. See more in Documentation/block/blkfilter.rst.

The tool, library and tests for working with blksnap can be found on github.

From the documentation, it is possible to learn how to manage the module using the library and console tool.

In the new version, the method of saving snapshot difference has been changed. Why this should have been done, Dave Chinner <[email protected]> described in detail in the comments to the previous version.

The module is incompatible with features hardware inline encryption and data integrity. Thanks to Eric Biggers <[email protected]>.

Unfortunately, I didn't have a chance to check it, since I don't have such equipment.

And it is impossible to determine the presence of a blk-crypto-fallback at the block layer filter level. The filter receives already encrypted data. The original device continues to work without problems, but the data in the snapshot is encrypted. Perhaps they can be decrypted if specify the correct key when mounting the file system for snapshot image.

Tested on amd64 and ppc64le with a page size of 64KiB and a storage block size of 4KiB.

Based on LK v6.7-rc2.
Compatible with branch 'for-next'.

P.S.
I'm sorry if I didn't add to 'CC' someone. Script get_maintainer.pl returns a very large list. I get "Error: too many recipients from 86.49.140.21" when trying to send an email from the smtp.migadu.com.

v6 changes:
- The difference storage has been changed.
In the previous version, the file was created only to reserve sector ranges on a block device. The data was stored directly to the block device in these sector ranges. Now saving and reading data is done using 'VFS' using vfs_iter_write() and vfs_iter_read() functions. This allows not to depend on the filesystem and use, for example, tmpfs. Using an unnamed temporary file allows hiding it from other processes and automatically release it when the snapshot is closed. However, now the module does not allow adding a block device to the snapshot on which the difference storage is located. There is no way to ensure the immutability of file metadata when writing data to a file. This means that the metadata of the filesystem may change, which may cause damage to the snapshot.
- _IOW and _IOR were mixed up - fixed.
- Protection against the use of the snapshots for block devices with hardware inline encryption and data integrity was implemented. Compatibility with them was not planned and has not been tested at the moment.

v5 changes:
- Rebase for "kernel/git/axboe/linux-block.git" branch "for-6.5/block".

v4 changes:
- Structures for describing the state of chunks are allocated dynamically. This reduces memory consumption, since the struct chunk is allocated only for those blocks for which the snapshot image state differs from the original block device.
- The algorithm for calculating the chunk size depending on the size of the block device has been changed. For large block devices, it is now possible to allocate a larger number of chunks, and their size is smaller.
- For block devices, a 'filter' file has been added to /sys/block/<device>. It displays the name of the filter that is attached to the block device.
- Fixed a problem with the lack of protection against re-adding a block device to a snapshot.
- Fixed a bug in the algorithm of allocating the next bio for a chunk. This problem was occurred on large disks, for which a chunk consists of at least two bio.
- The ownership mechanism of the diff_area structure has been changed. This fixed the error of prematurely releasing the diff_area structure when destroying the snapshot.
- Documentation corrected.
- The Sparse analyzer is passed.
- Use __u64 type instead pointers in UAPI.

v3 changes:
- New block device I/O controls BLKFILTER_ATTACH and BLKFILTER_DETACH allow to attach and detach filters.
- New block device I/O control BLKFILTER_CTL allow sending command to attached block device filter.
- The copy-on-write algorithm for processing I/O units has been optimized and has become asynchronous.
- The snapshot image reading algorithm has been optimized and has become asynchronous.
- Optimized the finite state machine for processing chunks.
- Fixed a tracking block size calculation bug.

v2 changes:
- Added documentation for Block Device Filtering Mechanism.
- Added documentation for Block Devices Snapshots Module (blksnap).
- The MAINTAINERS file has been updated.
- Optimized queue code for snapshot images.
- Fixed comments, log messages and code for better readability.

v1 changes:
- Forgotten "static" declarations have been added.
- The text of the comments has been corrected.
- It is possible to connect only one filter, since there are no others in upstream.
- Do not have additional locks for attach/detach filter.
- blksnap.h moved to include/uapi/.
- #pragma once and commented code removed.
- uuid_t removed from user API.
- Removed default values for module parameters from the configuration file.
- The debugging code for tracking memory leaks has been removed.
- Simplified Makefile.
- Optimized work with large memory buffers, CBT tables are now in virtual memory.
- The allocation code of minor numbers has been optimized.
- The implementation of the snapshot image block device has been simplified, now it is a bio-based block device.
- Removed initialization of global variables with null values.
- only one bio is used to copy one chunk.
- Checked on ppc64le.

Sergei Shtepa (11):
documentation: Block Device Filtering Mechanism
block: Block Device Filtering Mechanism
documentation: Block Devices Snapshots Module
blksnap: header file of the module interface
blksnap: module management interface functions
blksnap: handling and tracking I/O units
blksnap: difference storage and chunk
blksnap: event queue from the difference storage
blksnap: snapshot and snapshot image block device
blksnap: Kconfig and Makefile
blksnap: prevents using devices with data integrity or inline
encryption

 Documentation/block/blkfilter.rst             |  66 ++
 Documentation/block/blksnap.rst               | 352 +++++++++
 Documentation/block/index.rst                 |   2 +
 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 MAINTAINERS                                   |  17 +
 block/Makefile                                |   3 +-
 block/bdev.c                                  |   2 +
 block/blk-core.c                              |  35 +-
 block/blk-filter.c                            | 238 +++++++
 block/blk.h                                   |  11 +
 block/genhd.c                                 |  10 +
 block/ioctl.c                                 |   7 +
 block/partitions/core.c                       |   9 +
 drivers/block/Kconfig                         |   2 +
 drivers/block/Makefile                        |   2 +
 drivers/block/blksnap/Kconfig                 |  31 +
 drivers/block/blksnap/Makefile                |  15 +
 drivers/block/blksnap/cbt_map.c               | 228 ++++++
 drivers/block/blksnap/cbt_map.h               |  90 +++
 drivers/block/blksnap/chunk.c                 | 667 ++++++++++++++++++
 drivers/block/blksnap/chunk.h                 | 142 ++++
 drivers/block/blksnap/diff_area.c             | 601 ++++++++++++++++
 drivers/block/blksnap/diff_area.h             | 175 +++++
 drivers/block/blksnap/diff_buffer.c           | 115 +++
 drivers/block/blksnap/diff_buffer.h           |  37 +
 drivers/block/blksnap/diff_storage.c          | 291 ++++++++
 drivers/block/blksnap/diff_storage.h          | 104 +++
 drivers/block/blksnap/event_queue.c           |  81 +++
 drivers/block/blksnap/event_queue.h           |  64 ++
 drivers/block/blksnap/main.c                  | 475 +++++++++++++
 drivers/block/blksnap/params.h                |  16 +
 drivers/block/blksnap/snapimage.c             | 134 ++++
 drivers/block/blksnap/snapimage.h             |  10 +
 drivers/block/blksnap/snapshot.c              | 457 ++++++++++++
 drivers/block/blksnap/snapshot.h              |  64 ++
 drivers/block/blksnap/tracker.c               | 358 ++++++++++
 drivers/block/blksnap/tracker.h               |  78 ++
 include/linux/blk-filter.h                    |  51 ++
 include/linux/blk_types.h                     |   1 +
 include/linux/blkdev.h                        |   1 +
 include/linux/sched.h                         |   1 +
 include/uapi/linux/blk-filter.h               |  35 +
 include/uapi/linux/blksnap.h                  | 388 ++++++++++
 include/uapi/linux/fs.h                       |   3 +
 44 files changed, 5468 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/block/blkfilter.rst
 create mode 100644 Documentation/block/blksnap.rst
 create mode 100644 block/blk-filter.c
 create mode 100644 drivers/block/blksnap/Kconfig
 create mode 100644 drivers/block/blksnap/Makefile
 create mode 100644 drivers/block/blksnap/cbt_map.c
 create mode 100644 drivers/block/blksnap/cbt_map.h
 create mode 100644 drivers/block/blksnap/chunk.c
 create mode 100644 drivers/block/blksnap/chunk.h
 create mode 100644 drivers/block/blksnap/diff_area.c
 create mode 100644 drivers/block/blksnap/diff_area.h
 create mode 100644 drivers/block/blksnap/diff_buffer.c
 create mode 100644 drivers/block/blksnap/diff_buffer.h
 create mode 100644 drivers/block/blksnap/diff_storage.c
 create mode 100644 drivers/block/blksnap/diff_storage.h
 create mode 100644 drivers/block/blksnap/event_queue.c
 create mode 100644 drivers/block/blksnap/event_queue.h
 create mode 100644 drivers/block/blksnap/main.c
 create mode 100644 drivers/block/blksnap/params.h
 create mode 100644 drivers/block/blksnap/snapimage.c
 create mode 100644 drivers/block/blksnap/snapimage.h
 create mode 100644 drivers/block/blksnap/snapshot.c
 create mode 100644 drivers/block/blksnap/snapshot.h
 create mode 100644 drivers/block/blksnap/tracker.c
 create mode 100644 drivers/block/blksnap/tracker.h
 create mode 100644 include/linux/blk-filter.h
 create mode 100644 include/uapi/linux/blk-filter.h
 create mode 100644 include/uapi/linux/blksnap.h
Signature · 1 line
2.20.1
#1 lore raw

PATCH v6 1/11 documentation: Block Device Filtering Mechanism

From: Sergei Shtepa <[email protected]>

The document contains:
* Describes the purpose of the mechanism
* A little historical background on the capabilities of handling I/O units of the Linux kernel
* Brief description of the design
* Reference to interface description

---
 Documentation/block/blkfilter.rst | 66 +++++++++++++++++++++++++++++++
 Documentation/block/index.rst     |  1 +
 MAINTAINERS                       |  6 +++
 3 files changed, 73 insertions(+)
 create mode 100644 Documentation/block/blkfilter.rst
Documentation/block/blkfilter.rst new file +66 -0
new file mode 100644
index 000000000000..4e148e78f3d4
@@ -0,0 +1,66 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+================================
+Block Device Filtering Mechanism
+================================
+
+The block device filtering mechanism provides the ability to attach block
+device filters. Block device filters allow performing additional processing
+for I/O units.
+
+Introduction
+============
+
+The idea of handling I/O units on block devices is not new. Back in the
+2.6 kernel, there was an undocumented possibility of handling I/O units
+by substituting the make_request_fn() function, which belonged to the
+request_queue structure. But none of the in-tree kernel modules used this
+feature, and it was eliminated in the 5.10 kernel.
+
+The block device filtering mechanism returns the ability to handle I/O units.
+It is possible to safely attach a filter to a block device "on the fly" without
+changing the structure of the block device's stack.
+
+It supports attaching one filter to one block device, because there is only
+one filter implementation in the kernel yet.
+See Documentation/block/blksnap.rst.
+
+Design
+======
+
+The block device filtering mechanism provides registration and unregistration
+for filter operations. The struct blkfilter_operations contains a pointer to
+the callback functions for the filter. After registering the filter operations,
+the filter can be managed using block device ioctls BLKFILTER_ATTACH,
+BLKFILTER_DETACH and BLKFILTER_CTL.
+
+When the filter is attached, the callback function is called for each I/O unit
+for a block device, providing I/O unit filtering. Depending on the result of
+filtering the I/O unit, it can either be passed for subsequent processing by
+the block layer, or skipped.
+
+The filter can be implemented as a loadable module. In this case, the filter
+module cannot be unloaded while the filter is attached to at least one of the
+block devices.
+
+Interface description
+=====================
+
+The ioctl BLKFILTER_ATTACH allows user-space programs to attach a block device
+filter to a block device. The ioctl BLKFILTER_DETACH allows user-space programs
+to detach it. Both ioctls use &struct blkfilter_name. The ioctl BLKFILTER_CTL
+allows user-space programs to send a filter-specific command. It use &struct
+blkfilter_ctl.
+
+.. kernel-doc:: include/uapi/linux/blk-filter.h
+
+To register in the system, the filter uses the &struct blkfilter_operations,
+which contains callback functions, unique filter name and module owner. When
+attaching a filter to a block device, the filter creates a &struct blkfilter.
+The pointer to the &struct blkfilter allows the filter to determine for which
+block device the callback functions are being called.
+
+.. kernel-doc:: include/linux/blk-filter.h
+
+.. kernel-doc:: block/blk-filter.c
+   :export:
Documentation/block/index.rst +1 -0
index 9fea696f9daa..e9712f72cd6d 100644
@@ -10,6 +10,7 @@ Block
    bfq-iosched
    biovecs
    blk-mq
+   blkfilter
    cmdline-partition
    data-integrity
    deadline-iosched
MAINTAINERS +6 -0
index 97f51d5ec1cf..c20cbec81b58 100644
@@ -3584,6 +3584,12 @@ M:	Jan-Simon Moeller <[email protected]>
 S:	Maintained
 F:	drivers/leds/leds-blinkm.c
 
+BLOCK DEVICE FILTERING MECHANISM
+M:	Sergei Shtepa <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	Documentation/block/blkfilter.rst
+
 BLOCK LAYER
 M:	Jens Axboe <[email protected]>
 L:	[email protected]
Signature · 1 line
2.20.1
#2 lore raw

PATCH v6 2/11 block: Block Device Filtering Mechanism

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The block device filtering mechanism is an API that allows to attach block device filters. Block device filters allow perform additional processing for I/O units.

The idea of handling I/O units on block devices is not new. Back in the 2.6 kernel, there was an undocumented possibility of handling I/O units by substituting the make_request_fn() function, which belonged to the request_queue structure. But none of the in-tree kernel modules used this feature, and it was eliminated in the 5.10 kernel.

The block device filtering mechanism returns the ability to handle I/O units. It is possible to safely attach filter to a block device "on the fly" without changing the structure of block devices stack.

---
 MAINTAINERS                     |   3 +
 block/Makefile                  |   3 +-
 block/bdev.c                    |   2 +
 block/blk-core.c                |  35 ++++-
 block/blk-filter.c              | 238 ++++++++++++++++++++++++++++++++
 block/blk.h                     |  11 ++
 block/genhd.c                   |  10 ++
 block/ioctl.c                   |   7 +
 block/partitions/core.c         |   9 ++
 include/linux/blk-filter.h      |  51 +++++++
 include/linux/blk_types.h       |   1 +
 include/linux/blkdev.h          |   1 +
 include/linux/sched.h           |   1 +
 include/uapi/linux/blk-filter.h |  35 +++++
 include/uapi/linux/fs.h         |   3 +
 15 files changed, 408 insertions(+), 2 deletions(-)
 create mode 100644 block/blk-filter.c
 create mode 100644 include/linux/blk-filter.h
 create mode 100644 include/uapi/linux/blk-filter.h
MAINTAINERS +3 -0
index c20cbec81b58..ef90cd0fec9c 100644
@@ -3589,6 +3589,9 @@ M:	Sergei Shtepa <[email protected]>
 L:	[email protected]
 S:	Supported
 F:	Documentation/block/blkfilter.rst
+F:	block/blk-filter.c
+F:	include/linux/blk-filter.h
+F:	include/uapi/linux/blk-filter.h
 
 BLOCK LAYER
 M:	Jens Axboe <[email protected]>
block/Makefile +2 -1
index 46ada9dc8bbf..041c54eb0240 100644
@@ -9,7 +9,8 @@ obj-y		:= bdev.o fops.o bio.o elevator.o blk-core.o blk-sysfs.o \
 			blk-lib.o blk-mq.o blk-mq-tag.o blk-stat.o \
 			blk-mq-sysfs.o blk-mq-cpumap.o blk-mq-sched.o ioctl.o \
 			genhd.o ioprio.o badblocks.o partitions/ blk-rq-qos.o \
-			disk-events.o blk-ia-ranges.o early-lookup.o
+			disk-events.o blk-ia-ranges.o early-lookup.o \
+			blk-filter.o
 
 obj-$(CONFIG_BOUNCE)		+= bounce.o
 obj-$(CONFIG_BLK_DEV_BSG_COMMON) += bsg.o
block/bdev.c +2 -0
index e4cfb7adb645..6039d99b3a75 100644
@@ -412,6 +412,7 @@ struct block_device *bdev_alloc(struct gendisk *disk, u8 partno)
 		return NULL;
 	}
 	bdev->bd_disk = disk;
+	bdev->bd_filter = NULL;
 	return bdev;
 }
 
@@ -1018,6 +1019,7 @@ void bdev_mark_dead(struct block_device *bdev, bool surprise)
 	}
 
 	invalidate_bdev(bdev);
+	blkfilter_detach(bdev);
 }
 /*
  * New drivers should not use this directly.  There are some drivers however
block/blk-core.c +34 -1
index fdf25b8d6e78..1de74240892a 100644
@@ -18,6 +18,7 @@
 #include <linux/blkdev.h>
 #include <linux/blk-pm.h>
 #include <linux/blk-integrity.h>
+#include <linux/blk-filter.h>
 #include <linux/highmem.h>
 #include <linux/mm.h>
 #include <linux/pagemap.h>
@@ -592,12 +593,34 @@ static inline blk_status_t blk_check_zone_append(struct request_queue *q,
 
 static void __submit_bio(struct bio *bio)
 {
+	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
+	bool skip_bio = false;
+
+	if (unlikely(bio_queue_enter(bio)))
+		return;
+
+	if (bio->bi_bdev->bd_filter &&
+	    bio->bi_bdev->bd_filter != current->blk_filter) {
+		struct blkfilter *prev = current->blk_filter;
+
+		current->blk_filter = bio->bi_bdev->bd_filter;
+		skip_bio = bio->bi_bdev->bd_filter->ops->submit_bio(bio);
+		current->blk_filter = prev;
+	}
+
+	blk_queue_exit(q);
+	if (skip_bio)
+		return;
+
 	if (unlikely(!blk_crypto_bio_prep(&bio)))
 		return;
 
 	if (!bio->bi_bdev->bd_has_submit_bio) {
 		blk_mq_submit_bio(bio);
-	} else if (likely(bio_queue_enter(bio) == 0)) {
+		return;
+	}
+
+	if (likely(bio_queue_enter(bio) == 0)) {
 		struct gendisk *disk = bio->bi_bdev->bd_disk;
 
 		disk->fops->submit_bio(bio);
@@ -681,6 +704,15 @@ static void __submit_bio_noacct_mq(struct bio *bio)
 	current->bio_list = NULL;
 }
 
+/**
+ * submit_bio_noacct_nocheck - re-submit a bio to the block device layer for I/O
+ *	from block device filter.
+ * @bio:  The bio describing the location in memory and on the device.
+ *
+ * This is a version of submit_bio() that shall only be used for I/O that is
+ * resubmitted to lower level by block device filters.  All file  systems and
+ * other upper level users of the block layer should use submit_bio() instead.
+ */
 void submit_bio_noacct_nocheck(struct bio *bio)
 {
 	blk_cgroup_bio_start(bio);
@@ -708,6 +740,7 @@ void submit_bio_noacct_nocheck(struct bio *bio)
 	else
 		__submit_bio_noacct(bio);
 }
+EXPORT_SYMBOL_GPL(submit_bio_noacct_nocheck);
 
 /**
  * submit_bio_noacct - re-submit a bio to the block device layer for I/O
block/blk-filter.c new file +238 -0

238 lines not on this page · raw message

block/blk.h +11 -0
index 08a358bc0919..1f104f4865c3 100644
@@ -7,6 +7,8 @@
 #include <xen/xen.h>
 #include "blk-crypto-internal.h"
 
+struct blkfilter_ctl;
+struct blkfilter_name;
 struct elevator_type;
 
 /* Max future timer expiry for timeouts */
@@ -474,6 +476,15 @@ long compat_blkdev_ioctl(struct file *file, unsigned cmd, unsigned long arg);
 
 extern const struct address_space_operations def_blk_aops;
 
+int blkfilter_ioctl_attach(struct block_device *bdev,
+		    struct blkfilter_name __user *argp);
+int blkfilter_ioctl_detach(struct block_device *bdev,
+		    struct blkfilter_name __user *argp);
+int blkfilter_ioctl_ctl(struct block_device *bdev,
+		    struct blkfilter_ctl __user *argp);
+void blkfilter_detach(struct block_device *bdev);
+ssize_t blkfilter_show(struct block_device *bdev, char *buf);
+
 int disk_register_independent_access_ranges(struct gendisk *disk);
 void disk_unregister_independent_access_ranges(struct gendisk *disk);
 
block/genhd.c +10 -0
index c9d06f72c587..ba744e3fd581 100644
@@ -26,6 +26,7 @@
 #include <linux/badblocks.h>
 #include <linux/part_stat.h>
 #include <linux/blktrace_api.h>
+#include <linux/blk-filter.h>
 
 #include "blk-throttle.h"
 #include "blk.h"
@@ -654,6 +655,7 @@ void del_gendisk(struct gendisk *disk)
 	mutex_lock(&disk->open_mutex);
 	xa_for_each(&disk->part_tbl, idx, part)
 		remove_inode_hash(part->bd_inode);
+	blkfilter_detach(disk->part0);
 	mutex_unlock(&disk->open_mutex);
 
 	/*
@@ -1044,6 +1046,12 @@ static ssize_t diskseq_show(struct device *dev,
 	return sprintf(buf, "%llu\n", disk->diskseq);
 }
 
+static ssize_t disk_filter_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	return blkfilter_show(dev_to_bdev(dev), buf);
+}
+
 static DEVICE_ATTR(range, 0444, disk_range_show, NULL);
 static DEVICE_ATTR(ext_range, 0444, disk_ext_range_show, NULL);
 static DEVICE_ATTR(removable, 0444, disk_removable_show, NULL);
@@ -1057,6 +1065,7 @@ static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
 static DEVICE_ATTR(badblocks, 0644, disk_badblocks_show, disk_badblocks_store);
 static DEVICE_ATTR(diskseq, 0444, diskseq_show, NULL);
+static DEVICE_ATTR(filter, 0444, disk_filter_show, NULL);
 
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 ssize_t part_fail_show(struct device *dev,
@@ -1103,6 +1112,7 @@ static struct attribute *disk_attrs[] = {
 	&dev_attr_events_async.attr,
 	&dev_attr_events_poll_msecs.attr,
 	&dev_attr_diskseq.attr,
+	&dev_attr_filter.attr,
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 	&dev_attr_fail.attr,
 #endif
block/ioctl.c +7 -0
index 4160f4e6bd5b..1b11303e213b 100644
@@ -2,6 +2,7 @@
 #include <linux/capability.h>
 #include <linux/compat.h>
 #include <linux/blkdev.h>
+#include <linux/blk-filter.h>
 #include <linux/export.h>
 #include <linux/gfp.h>
 #include <linux/blkpg.h>
@@ -572,6 +573,12 @@ static int blkdev_common_ioctl(struct block_device *bdev, blk_mode_t mode,
 		return blkdev_pr_preempt(bdev, mode, argp, true);
 	case IOC_PR_CLEAR:
 		return blkdev_pr_clear(bdev, mode, argp);
+	case BLKFILTER_ATTACH:
+		return blkfilter_ioctl_attach(bdev, argp);
+	case BLKFILTER_DETACH:
+		return blkfilter_ioctl_detach(bdev, argp);
+	case BLKFILTER_CTL:
+		return blkfilter_ioctl_ctl(bdev, argp);
 	default:
 		return -ENOIOCTLCMD;
 	}
block/partitions/core.c +9 -0
index f47ffcfdfcec..19c69dc23d2c 100644
@@ -10,6 +10,7 @@
 #include <linux/ctype.h>
 #include <linux/vmalloc.h>
 #include <linux/raid/detect.h>
+#include <linux/blk-filter.h>
 #include "check.h"
 
 static int (*const check_part[])(struct parsed_partitions *) = {
@@ -200,6 +201,12 @@ static ssize_t part_discard_alignment_show(struct device *dev,
 	return sprintf(buf, "%u\n", bdev_discard_alignment(dev_to_bdev(dev)));
 }
 
+static ssize_t part_filter_show(struct device *dev,
+				struct device_attribute *attr, char *buf)
+{
+	return blkfilter_show(dev_to_bdev(dev), buf);
+}
+
 static DEVICE_ATTR(partition, 0444, part_partition_show, NULL);
 static DEVICE_ATTR(start, 0444, part_start_show, NULL);
 static DEVICE_ATTR(size, 0444, part_size_show, NULL);
@@ -208,6 +215,7 @@ static DEVICE_ATTR(alignment_offset, 0444, part_alignment_offset_show, NULL);
 static DEVICE_ATTR(discard_alignment, 0444, part_discard_alignment_show, NULL);
 static DEVICE_ATTR(stat, 0444, part_stat_show, NULL);
 static DEVICE_ATTR(inflight, 0444, part_inflight_show, NULL);
+static DEVICE_ATTR(filter, 0444, part_filter_show, NULL);
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 static struct device_attribute dev_attr_fail =
 	__ATTR(make-it-fail, 0644, part_fail_show, part_fail_store);
@@ -222,6 +230,7 @@ static struct attribute *part_attrs[] = {
 	&dev_attr_discard_alignment.attr,
 	&dev_attr_stat.attr,
 	&dev_attr_inflight.attr,
+	&dev_attr_filter.attr,
 #ifdef CONFIG_FAIL_MAKE_REQUEST
 	&dev_attr_fail.attr,
 #endif
include/linux/blk-filter.h new file +51 -0

51 lines not on this page · raw message

include/linux/blk_types.h +1 -0
index d5c5e59ddbd2..490865292fde 100644
@@ -74,6 +74,7 @@ struct block_device {
 	 * path
 	 */
 	struct device		bd_device;
+	struct blkfilter	*bd_filter;
 } __randomize_layout;
 
 #define bdev_whole(_bdev) \
include/linux/blkdev.h +1 -0
index 51fa7ffdee83..6a0754007d1d 100644
@@ -834,6 +834,7 @@ void blk_request_module(dev_t devt);
 
 extern int blk_register_queue(struct gendisk *disk);
 extern void blk_unregister_queue(struct gendisk *disk);
+void submit_bio_noacct_nocheck(struct bio *bio);
 void submit_bio_noacct(struct bio *bio);
 struct bio *bio_split_to_limits(struct bio *bio);
 
include/linux/sched.h +1 -0
index 292c31697248..e7c3cd490a80 100644
@@ -1190,6 +1190,7 @@ struct task_struct {
 
 	/* Stack plugging: */
 	struct blk_plug			*plug;
+	struct blkfilter		*blk_filter;
 
 	/* VM state: */
 	struct reclaim_state		*reclaim_state;
include/uapi/linux/blk-filter.h new file +35 -0
new file mode 100644
index 000000000000..18885dc1b717
@@ -0,0 +1,35 @@
+/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#ifndef _UAPI_LINUX_BLK_FILTER_H
+#define _UAPI_LINUX_BLK_FILTER_H
+
+#include <linux/types.h>
+
+#define BLKFILTER_NAME_LENGTH	32
+
+/**
+ * struct blkfilter_name - parameter for BLKFILTER_ATTACH and BLKFILTER_DETACH
+ *      ioctl.
+ *
+ * @name:       Name of block device filter.
+ */
+struct blkfilter_name {
+	__u8 name[BLKFILTER_NAME_LENGTH];
+};
+
+/**
+ * struct blkfilter_ctl - parameter for BLKFILTER_CTL ioctl
+ *
+ * @name:	Name of block device filter.
+ * @cmd:	The filter-specific operation code of the command.
+ * @optlen:	Size of data at @opt.
+ * @opt:	Userspace buffer with options.
+ */
+struct blkfilter_ctl {
+	__u8 name[BLKFILTER_NAME_LENGTH];
+	__u32 cmd;
+	__u32 optlen;
+	__u64 opt;
+};
+
+#endif /* _UAPI_LINUX_BLK_FILTER_H */
include/uapi/linux/fs.h +3 -0
index da43810b7485..f96809cd2f50 100644
@@ -189,6 +189,9 @@ struct fsxattr {
  * A jump here: 130-136 are reserved for zoned block devices
  * (see uapi/linux/blkzoned.h)
  */
+#define BLKFILTER_ATTACH	_IOWR(0x12, 140, struct blkfilter_name)
+#define BLKFILTER_DETACH	_IOWR(0x12, 141, struct blkfilter_name)
+#define BLKFILTER_CTL		_IOWR(0x12, 142, struct blkfilter_ctl)
 
 #define BMAP_IOCTL 1		/* obsolete - kept for compatibility */
 #define FIBMAP	   _IO(0x00,1)	/* bmap access */
Signature · 1 line
2.20.1
#3 lore raw

Re: [PATCH v6 02/11] block: Block Device Filtering Mechanism

Quoted 6 lines
block/blk-core.c +6 -0
+	struct request_queue *q = bdev_get_queue(bio->bi_bdev);
+	bool skip_bio = false;
+
+	if (unlikely(bio_queue_enter(bio)))
+		return;
+

block/blk-core.c static inline blk_status_t blk_check_zone_append(struct request_queue *q, · line 611

Quoted 10 lines
block/blk-core.c +10 -0
+	if (bio->bi_bdev->bd_filter &&
+	    bio->bi_bdev->bd_filter != current->blk_filter) {
+		struct blkfilter *prev = current->blk_filter;
+
+		current->blk_filter = bio->bi_bdev->bd_filter;
+		skip_bio = bio->bi_bdev->bd_filter->ops->submit_bio(bio);
+		current->blk_filter = prev;
+	}
+
+	blk_queue_exit(q);

This currently adds a queue enter/exit pair even if no filter driver is used, which іs probably not acceptable. We probably need some way to avoid the check in the fast path. In general an unlocked check for bio->bi_bdev->bd_filter outside the protection seems fine to here, we just need to find a good way to make sure it is visible by the time a filter is actually set and the filter driver initialization.

block/blk-core.c static inline blk_status_t blk_check_zone_append(struct request_queue *q, · line 623

Quoted 7 lines
block/blk-core.c +4 -1
 	if (!bio->bi_bdev->bd_has_submit_bio) {
 		blk_mq_submit_bio(bio);
-	} else if (likely(bio_queue_enter(bio) == 0)) {
+		return;
+	}
+
+	if (likely(bio_queue_enter(bio) == 0)) {

This is just stray reformatting and we can drop it.

#4 lore raw

Re: [PATCH v6 02/11] block: Block Device Filtering Mechanism

Hi Christoph.

Thanks for the review this patch set.
You've given me a good deal to think about.

#5 lore raw

PATCH v6 3/11 documentation: Block Devices Snapshots Module

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The document contains:
* Describes the purpose of the mechanism
* Description of features
* Description of algorithms
* Recommendations about using the module from the user-space side
* Reference to module interface description

---
 Documentation/block/blksnap.rst | 352 ++++++++++++++++++++++++++++++++
 Documentation/block/index.rst   |   1 +
 MAINTAINERS                     |   6 +
 3 files changed, 359 insertions(+)
 create mode 100644 Documentation/block/blksnap.rst
Documentation/block/blksnap.rst new file +352 -0
new file mode 100644
index 000000000000..ef6010e46858
@@ -0,0 +1,352 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+========================================
+Block Devices Snapshots Module (blksnap)
+========================================
+
+Introduction
+============
+
+At first glance, there is no novelty in the idea of creating snapshots for
+block devices. The Linux kernel already has mechanisms for creating snapshots.
+Device Mapper includes dm-snap, which allows to create snapshots of block
+devices. BTRFS supports snapshots at the filesystem level. However, both of
+these options have flaws that do not allow to use them as a universal tool for
+creating backups.
+
+The main properties that a backup tool should have are:
+
+- Simplicity and universality of use
+- Reliability
+- Minimal consumption of system resources during backup
+- Minimal time required for recovery or replication of the entire system
+
+Taking above properties into account, blksnap module features:
+
+- Change tracker
+- Snapshots at the block device level
+- Dynamic allocation of space for storing differences
+- Snapshot overflow resistance
+- Coherent snapshot of multiple block devices
+
+Features
+========
+
+Change tracker
+--------------
+
+The change tracker allows to determine which blocks were changed during the
+time between the last snapshot created and any of the previous snapshots.
+With a map of changes, it is enough to copy only the changed blocks, and no
+need to reread the entire block device completely. The change tracker allows
+to implement the logic of both incremental and differential backups.
+Incremental backup is critical for large file repositories whose size can be
+hundreds of terabytes and whose full backup time can take more than a day.
+On such servers, the use of backup tools without a change tracker becomes
+practically impossible.
+
+Snapshot at the block device level
+----------------------------------
+
+A snapshot at the block device level allows to simplify the backup algorithm
+and reduce consumption of system resources. It also allows to perform linear
+reading of disk space directly, which allows to achieve maximum reading speed
+with minimal use of processor time. At the same time, the universality of
+creating snapshots for any block device is achieved, regardless of the file
+system located on it. The exceptions are BTRFS, ZFS and cluster file systems.
+
+Dynamic allocation of storage space for differences
+---------------------------------------------------
+
+To store differences, the module does not require a pre-reserved space on
+filesystem. The space for storing differences can be allocated in file in any
+filesystem. In addition, the size of the difference storage can be increased
+after the snapshot is created, but only for a filesystem that supports
+fallocate. A shared difference storage for all images of snapshot block devices
+allows to optimize the use of storage space. However, there is one limitation.
+A snapshot cannot be taken from a block device on which the difference storage
+is located.
+
+Snapshot overflow resistance
+----------------------------
+
+To create images of snapshots of block devices, the module stores blocks
+of the original block device that have been changed since the snapshot
+was taken. To do this, the module handles write requests and reads blocks
+that need to be overwritten. This algorithm guarantees safety of the data
+of the original block device in the event of an overflow of the snapshot,
+and even in the case of unpredictable critical errors. If a problem occurs
+during backup, the difference storage is released, the snapshot is closed,
+no backup is created, but the server continues to work.
+
+Coherent snapshot of multiple block devices
+-------------------------------------------
+
+A snapshot is created simultaneously for all block devices for which a backup
+is being created, ensuring their coherent state.
+
+
+Algorithms
+==========
+
+Overview
+--------
+
+The blksnap module is a block-level filter. It handles all write I/O units.
+The filter is attached to the block device when the snapshot is created
+for the first time. The change tracker marks all overwritten blocks.
+Information about the history of changes on the block device is available
+while holding the snapshot. The module reads the blocks that need to be
+overwritten and stores them in the difference storage. When reading from
+a snapshot image, reading is performed either from the original device or
+from the difference storage.
+
+Change tracking
+---------------
+
+A change tracker map is created for each block device. One byte of this map
+corresponds to one block. The block size is set by the
+``tracking_block_minimum_shift`` and ``tracking_block_maximum_count``
+module parameters. The ``tracking_block_minimum_shift`` parameter limits
+the minimum block size for tracking, while ``tracking_block_maximum_count``
+defines the maximum allowed number of blocks. The size of the change tracker
+block is determined depending on the size of the block device when adding
+a tracking device, that is, when the snapshot is taken for the first time.
+The block size must be a power of two. The ``tracking_block_maximum_shift``
+module parameter allows to limit the maximum block size for tracking. If the
+block size reaches the allowable limit, the number of blocks will exceed the
+``tracking_block_maximum_count`` parameter.
+
+The byte of the change map stores a number from 0 to 255. This is the
+snapshot number, since the creation of which there have been changes in
+the block. Each time a snapshot is created, the number of the current
+snapshot is increased by one. This number is written to the cell of the
+change map when writing to the block. Thus, knowing the number of one of
+the previous snapshots and the number of the last snapshot, one can determine
+from the change map which blocks have been changed. When the number of the
+current change reaches the maximum allowed value for the map of 255, at the
+time when the next snapshot is created, the map of changes is reset to zero,
+and the number of the current snapshot is assigned the value 1. The change
+tracker is reset, and a new UUID is generated - a unique identifier of the
+snapshot generation. The snapshot generation identifier allows to identify
+that a change tracking reset has been performed.
+
+The change map has two copies. One copy is active, it tracks the current
+changes on the block device. The second copy is available for reading
+while the snapshot is being held, and contains the history up to the moment
+the snapshot is taken. Copies are synchronized at the moment of snapshot
+creation. After the snapshot is released, a second copy of the map is not
+needed, but it is not released, so as not to allocate memory for it again
+the next time the snapshot is created.
+
+Copy on write
+-------------
+
+Data is copied in blocks, or rather in chunks. The term "chunk" is used to
+avoid confusion with change tracker blocks and I/O blocks. In addition,
+the "chunk" in the blksnap module means about the same as the "chunk" in
+the dm-snap module.
+
+The size of the chunk is determined by the ``chunk_minimum_shift`` and
+``chunk_maximum_count`` module parameters. The ``chunk_minimum_shift``
+parameter limits the minimum size of the chunk, while ``chunk_maximum_count``
+defines the maximum allowed number of chunks. The size of the chunk is
+determined depending on the size of the block device at the time of taking the
+snapshot. The size of the chunk must be a power of two. The module parameter
+``chunk_maximum_shift`` allows to limit the maximum chunk size. If the chunk
+size reaches the allowable limit, the number of chunks will exceed the
+``chunk_maximum_count`` parameter.
+
+One chunk is described by the ``struct chunk`` structure. A map of structures
+is created for each block device. The structure contains all the necessary
+information to copy the chunks data from the original block device to the
+difference storage. This information allows to describe the snapshot image.
+A semaphore is located in the structure, which allows synchronization of threads
+accessing the chunk.
+
+The block level in Linux has a feature. If a read I/O unit was sent, and a
+write I/O unit was sent after it, then a write can be performed first, and only
+then a read. Therefore, the copy-on-write algorithm is executed synchronously.
+If the write request is handled, the execution of this I/O unit will be delayed
+until the overwritten chunks are read from the original device for later
+storing to the difference store. But if, when handling a write I/O unit, it
+turns out that the written range of sectors has already been prepared for
+storing to the difference storage, then the I/O unit is simply passed.
+
+This algorithm makes it possible to efficiently perform backup even systems
+with a Round-Robin databases. Such databases can be overwritten several times
+during the system backup. Of course, the value of a backup of the RRD monitoring
+system data can be questioned. However, it is often a task to make a backup
+of the entire enterprise infrastructure in order to restore or replicate it
+entirely in case of problems.
+
+There is also a flaw in the algorithm. When overwriting at least one sector,
+an entire chunk is copied. Thus, a situation of rapid filling of the difference
+storage when writing data to a block device in small portions in random order
+is possible. This situation is possible in case of strong fragmentation of
+data on the filesystem. But it must be borne in mind that with such data
+fragmentation, performance of systems usually degrades greatly. So, this
+problem does not occur on real servers, although it can easily be created
+by artificial tests.
+
+Difference storage
+------------------
+
+The difference storage can be a block device or it can be a file on a
+filesystem. Using a block device allows to achieve slightly higher performance,
+but in this case, the block device is used by the kernel module exclusively.
+Usually the disk space is marked up so that there is no available free space
+for backup purposes. Using a file allows to place the difference storage on a
+filesystem.
+
+The difference storage can be expanded already while the snapshot is being held,
+but only if the filesystem supports fallocate(). If the free space in the
+difference storage remains less than half of the value of the module parameter
+``diff_storage_minimum``, then the kernel module can expand the difference
+storage  file within the specified limits. This limit is set when creating a
+snapshot.
+
+If free space in the difference storage runs out, an event to user land is
+generated about the overflow of the snapshot. Such a snapshot is considered
+corrupted, and read I/O units to snapshot images will be terminated with an
+error code. The difference storage stores outdated data required for snapshot
+images, so when the snapshot is overflowed, the backup process is interrupted,
+but the system maintains its operability without data loss.
+
+The difference storage has a limitation. The device cannot be added to the
+snapshot where the difference storage is located. In this case, the difference
+storage can be located in virtual memory, which consists of RAM and a swap
+partition (or file). To do this, it is enough to use a file in /dev/shm, or a
+new tmpfs filesystem can be created for this purpose. Obviously, this variant
+can be useful if the system has a lot of RAM or a large swap. The good news is
+that the modern Linux kernel allows to increase the size of the swap file "on
+the fly" without changing the system configuration.
+
+A regular file or a block device file for the difference storage must be opened
+with the O_EXCL flag. If an unnamed file with the O_TMPFILE flag is created,
+then such a file will be automatically released when the snapshot is destroyed.
+In addition, the use of an unnamed temporary file ensures that no one can open
+this file and read its contents.
+
+Performing I/O for a snapshot image
+-----------------------------------
+
+To read snapshot data, when taking a snapshot, block devices of snapshot images
+are created. The snapshot image block devices support the write operation.
+This allows to perform additional data preparation on the filesystem before
+creating a backup.
+
+To process the I/O unit, clones of the I/O unit are created, which redirect
+the I/O unit either to the original block device or to the difference storage.
+When processing of cloned I/O units is completed, the original I/O unit is
+marked as completed too.
+
+An I/O unit can be partially processed without accessing to block devices if
+the I/O unit refers to a chunk that is in the queue for storing to the
+difference storage. In this case, the data is read or written in a buffer in
+memory.
+
+If, when processing the write I/O unit, it turns out that the data of the
+referred chunk has not yet been stored to the difference storage or has not
+even been read from the original device, then an I/O unit to read data from the
+original device is initiated beforehand. After the reading from original device
+is performed, their data from the I/O unit is partially overwritten directly in
+the buffer of the chunk in memory, and the chunk is scheduled to be saved to the
+difference storage.
+
+How to use
+==========
+
+Depending on the needs and the selected license, you can choose different
+options for managing the module:
+
+- Using ioctl directly
+- Using a static C++ library
+- Using the blksnap console tool
+
+Using a BLKFILTER_CTL for block device
+--------------------------------------
+
+BLKFILTER_CTL allows to send a filter-specific command to the filter on block
+device and get the result of its execution. The module provides the
+``include/uapi/blksnap.h`` header file with a description of the commands and
+their data structures.
+
+1. ``blkfilter_ctl_blksnap_cbtinfo`` allows to get information from the
+   change tracker.
+2. ``blkfilter_ctl_blksnap_cbtmap`` reads the change tracker table. If a write
+   operation was performed for the snapshot, then the change tracker takes this
+   into account. Therefore, it is necessary to receive tracker data after write
+   operations have been completed.
+3. ``blkfilter_ctl_blksnap_cbtdirty`` mark blocks as changed in the change
+   tracker table. This is necessary if post-processing is performed after the
+   backup is created, which changes the backup blocks.
+4. ``blkfilter_ctl_blksnap_snapshotadd`` adds a block device to the snapshot.
+5. ``blkfilter_ctl_blksnap_snapshotinfo`` allows to get the name of the snapshot
+   image block device and the presence of an error.
+
+Using ioctl
+-----------
+
+Using a BLKFILTER_CTL ioctl does not allow to fully implement the management of
+the blksnap module. A control file ``blksnap-control`` is created to manage
+snapshots. The control commands are also described in the file
+``include/uapi/blksnap.h``.
+
+1. ``blksnap_ioctl_version`` get the version number.
+2. ``blk_snap_ioctl_snapshot_create`` initiates the snapshot creation process.
+3. ``blk_snap_ioctl_snapshot_append_storage`` add the range of blocks to
+   difference storage.
+4. ``blk_snap_ioctl_snapshot_take`` creates block devices of block device
+   snapshot images.
+5. ``blk_snap_ioctl_snapshot_collect`` collect all created snapshots.
+6. ``blk_snap_ioctl_snapshot_wait_event`` allows to track the status of
+   snapshots and receive events about the requirement to expand the difference
+   storage or about snapshot overflow.
+7. ``blk_snap_ioctl_snapshot_destroy`` releases the snapshot.
+
+Static C++ library
+------------------
+
+The [#userspace_libs]_ library was created primarily to simplify creation of
+tests in C++, and it is also a good example of using the module interface.
+When creating applications, direct use of control calls is preferable.
+However, the library can be used in an application with a GPL-2+ license,
+or a library with an LGPL-2+ license can be created, with which even a
+proprietary application can be dynamically linked.
+
+blksnap console tool
+--------------------
+
+The blksnap [#userspace_tools]_ console tool allows to control the module from
+the command line. The tool contains detailed built-in help. To get list of
+commands with usage description, see ``blksnap --help`` command. The ``blksnap
+<command name> --help`` command allows to get detailed information about the
+parameters of each command call. This option may be convenient when creating
+proprietary software, as it allows not to compile with the open source code.
+At the same time, the blksnap tool can be used for creating backup scripts.
+For example, rsync can be called to synchronize files on the filesystem of
+the mounted snapshot image and files in the archive on a filesystem that
+supports compression.
+
+Tests
+-----
+
+A set of tests was created for regression testing [#userspace_tests]_.
+Tests with simple algorithms that use the ``blksnap`` console tool to
+control the module are written in Bash. More complex testing algorithms
+are implemented in C++.
+
+References
+==========
+
+.. [#userspace_libs] https://github.com/veeam/blksnap/tree/stable-v2.0/lib
+
+.. [#userspace_tools] https://github.com/veeam/blksnap/tree/stable-v2.0/tools
+
+.. [#userspace_tests] https://github.com/veeam/blksnap/tree/stable-v2.0/tests
+
+Module interface description
+============================
+
+.. kernel-doc:: include/uapi/linux/blksnap.h
Documentation/block/index.rst +1 -0
index e9712f72cd6d..696ff150c6b7 100644
@@ -11,6 +11,7 @@ Block
    biovecs
    blk-mq
    blkfilter
+   blksnap
    cmdline-partition
    data-integrity
    deadline-iosched
MAINTAINERS +6 -0
index ef90cd0fec9c..9c81e4c83139 100644
@@ -3593,6 +3593,12 @@ F:	block/blk-filter.c
 F:	include/linux/blk-filter.h
 F:	include/uapi/linux/blk-filter.h
 
+BLOCK DEVICE SNAPSHOTS MODULE
+M:	Sergei Shtepa <[email protected]>
+L:	[email protected]
+S:	Supported
+F:	Documentation/block/blksnap.rst
+
 BLOCK LAYER
 M:	Jens Axboe <[email protected]>
 L:	[email protected]
Signature · 1 line
2.20.1
#6 lore raw

PATCH v6 4/11 blksnap: header file of the module interface

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The header file contains a set of declarations, structures and control requests (ioctl) that allows to manage the module from the user space.

---
 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 MAINTAINERS                                   |   1 +
 include/uapi/linux/blksnap.h                  | 388 ++++++++++++++++++
 3 files changed, 390 insertions(+)
 create mode 100644 include/uapi/linux/blksnap.h
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index 4ea5b837399a..81acae1b1859 100644
@@ -203,6 +203,7 @@ Code  Seq#    Include File                                           Comments
 'V'   C0     linux/ivtvfb.h                                          conflict!
 'V'   C0     linux/ivtv.h                                            conflict!
 'V'   C0     media/si4713.h                                          conflict!
+'V'   00-1F  uapi/linux/blksnap.h                                    conflict!
 'W'   00-1F  linux/watchdog.h                                        conflict!
 'W'   00-1F  linux/wanrouter.h                                       conflict! (pre 3.9)
 'W'   00-3F  sound/asound.h                                          conflict!
MAINTAINERS +1 -0
index 9c81e4c83139..9770c4d4b15d 100644
@@ -3598,6 +3598,7 @@ M:	Sergei Shtepa <[email protected]>
 L:	[email protected]
 S:	Supported
 F:	Documentation/block/blksnap.rst
+F:	include/uapi/linux/blksnap.h
 
 BLOCK LAYER
 M:	Jens Axboe <[email protected]>
include/uapi/linux/blksnap.h new file +388 -0

388 lines not on this page · raw message

Signature · 1 line
2.20.1
#7 lore raw

PATCH v6 5/11 blksnap: module management interface functions

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

Contains callback functions for loading and unloading the module and implementation of module management interface functions. The module parameters and other mandatory declarations for the kernel module are also defined.

---
 MAINTAINERS                    |   1 +
 drivers/block/blksnap/main.c   | 475 +++++++++++++++++++++++++++++++++
 drivers/block/blksnap/params.h |  16 ++
 3 files changed, 492 insertions(+)
 create mode 100644 drivers/block/blksnap/main.c
 create mode 100644 drivers/block/blksnap/params.h
MAINTAINERS +1 -0
index 9770c4d4b15d..6f666d772cf5 100644
@@ -3598,6 +3598,7 @@ M:	Sergei Shtepa <[email protected]>
 L:	[email protected]
 S:	Supported
 F:	Documentation/block/blksnap.rst
+F:	drivers/block/blksnap/*
 F:	include/uapi/linux/blksnap.h
 
 BLOCK LAYER
drivers/block/blksnap/main.c new file +475 -0

475 lines not on this page · raw message

drivers/block/blksnap/params.h new file +16 -0
new file mode 100644
index 000000000000..3ec4cce4de39
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#ifndef __BLKSNAP_PARAMS_H
+#define __BLKSNAP_PARAMS_H
+
+unsigned int get_tracking_block_minimum_shift(void);
+unsigned int get_tracking_block_maximum_shift(void);
+unsigned int get_tracking_block_maximum_count(void);
+unsigned int get_chunk_minimum_shift(void);
+unsigned int get_chunk_maximum_shift(void);
+unsigned long get_chunk_maximum_count(void);
+unsigned int get_chunk_maximum_in_queue(void);
+unsigned int get_free_diff_buffer_pool_size(void);
+sector_t get_diff_storage_minimum(void);
+
+#endif /* __BLKSNAP_PARAMS_H */
Signature · 1 line
2.20.1
#8 lore raw

PATCH v6 6/11 blksnap: handling and tracking I/O units

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The struct tracker contains callback functions for handling a I/O units of a block device. When a write request is handled, the change block tracking (CBT) map functions are called and initiates the process of copying data from the original block device to the change store. Registering and unregistering the tracker is provided by the functions blkfilter_register() and blkfilter_unregister().
The struct cbt_map allows to store the history of block device changes.

---
 drivers/block/blksnap/cbt_map.c | 228 +++++++++++++++++++++
 drivers/block/blksnap/cbt_map.h |  90 +++++++++
 drivers/block/blksnap/tracker.c | 344 ++++++++++++++++++++++++++++++++
 drivers/block/blksnap/tracker.h |  78 ++++++++
 4 files changed, 740 insertions(+)
 create mode 100644 drivers/block/blksnap/cbt_map.c
 create mode 100644 drivers/block/blksnap/cbt_map.h
 create mode 100644 drivers/block/blksnap/tracker.c
 create mode 100644 drivers/block/blksnap/tracker.h
drivers/block/blksnap/cbt_map.c new file +228 -0
new file mode 100644
index 000000000000..7b6ebe225c48
@@ -0,0 +1,228 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#define pr_fmt(fmt) KBUILD_MODNAME "-cbt_map: " fmt
+
+#include <linux/slab.h>
+#include <linux/vmalloc.h>
+#include <uapi/linux/blksnap.h>
+#include "cbt_map.h"
+#include "params.h"
+
+static inline unsigned long long count_by_shift(sector_t capacity,
+						unsigned long long shift)
+{
+	sector_t blk_size = 1ull << (shift - SECTOR_SHIFT);
+
+	return round_up(capacity, blk_size) / blk_size;
+}
+
+static void cbt_map_calculate_block_size(struct cbt_map *cbt_map)
+{
+	unsigned long long count;
+	unsigned long long shift = get_tracking_block_minimum_shift();
+
+	pr_debug("Device capacity %llu sectors\n", cbt_map->device_capacity);
+	/*
+	 * The size of the tracking block is calculated based on the size of
+	 * the disk so that the CBT table does not exceed a reasonable size.
+	 */
+	count = count_by_shift(cbt_map->device_capacity, shift);
+	pr_debug("Blocks count %llu\n", count);
+	while (count > get_tracking_block_maximum_count()) {
+		if (shift >= get_tracking_block_maximum_shift()) {
+			pr_info("The maximum allowable CBT block size has been reached.\n");
+			break;
+		}
+		shift = shift + 1ull;
+		count = count_by_shift(cbt_map->device_capacity, shift);
+		pr_debug("Blocks count %llu\n", count);
+	}
+
+	cbt_map->blk_size_shift = shift;
+	cbt_map->blk_count = count;
+	pr_debug("The optimal CBT block size was calculated as %llu bytes\n",
+		 (1ull << cbt_map->blk_size_shift));
+}
+
+static int cbt_map_allocate(struct cbt_map *cbt_map)
+{
+	unsigned char *read_map = NULL;
+	unsigned char *write_map = NULL;
+	size_t size = cbt_map->blk_count;
+
+	pr_debug("Allocate CBT map of %zu blocks\n", size);
+
+	if (cbt_map->read_map || cbt_map->write_map)
+		return -EINVAL;
+
+	read_map = __vmalloc(size, GFP_NOIO | __GFP_ZERO);
+	if (!read_map)
+		return -ENOMEM;
+
+	write_map = __vmalloc(size, GFP_NOIO | __GFP_ZERO);
+	if (!write_map) {
+		vfree(read_map);
+		return -ENOMEM;
+	}
+
+	cbt_map->read_map = read_map;
+	cbt_map->write_map = write_map;
+
+	cbt_map->snap_number_previous = 0;
+	cbt_map->snap_number_active = 1;
+	generate_random_uuid(cbt_map->generation_id.b);
+	cbt_map->is_corrupted = false;
+
+	return 0;
+}
+
+static void cbt_map_deallocate(struct cbt_map *cbt_map)
+{
+	cbt_map->is_corrupted = false;
+
+	if (cbt_map->read_map) {
+		vfree(cbt_map->read_map);
+		cbt_map->read_map = NULL;
+	}
+
+	if (cbt_map->write_map) {
+		vfree(cbt_map->write_map);
+		cbt_map->write_map = NULL;
+	}
+}
+
+int cbt_map_reset(struct cbt_map *cbt_map, sector_t device_capacity)
+{
+	cbt_map_deallocate(cbt_map);
+
+	cbt_map->device_capacity = device_capacity;
+	cbt_map_calculate_block_size(cbt_map);
+
+	return cbt_map_allocate(cbt_map);
+}
+
+void cbt_map_destroy(struct cbt_map *cbt_map)
+{
+	pr_debug("CBT map destroy\n");
+
+	cbt_map_deallocate(cbt_map);
+	kfree(cbt_map);
+}
+
+struct cbt_map *cbt_map_create(struct block_device *bdev)
+{
+	struct cbt_map *cbt_map = NULL;
+	int ret;
+
+	pr_debug("CBT map create\n");
+
+	cbt_map = kzalloc(sizeof(struct cbt_map), GFP_KERNEL);
+	if (cbt_map == NULL)
+		return NULL;
+
+	cbt_map->device_capacity = bdev_nr_sectors(bdev);
+	cbt_map_calculate_block_size(cbt_map);
+
+	ret = cbt_map_allocate(cbt_map);
+	if (ret) {
+		pr_err("Failed to create tracker. errno=%d\n", abs(ret));
+		cbt_map_destroy(cbt_map);
+		return NULL;
+	}
+
+	spin_lock_init(&cbt_map->locker);
+	cbt_map->is_corrupted = false;
+
+	return cbt_map;
+}
+
+void cbt_map_switch(struct cbt_map *cbt_map)
+{
+	pr_debug("CBT map switch\n");
+	spin_lock(&cbt_map->locker);
+
+	cbt_map->snap_number_previous = cbt_map->snap_number_active;
+	++cbt_map->snap_number_active;
+	if (cbt_map->snap_number_active == 256) {
+		cbt_map->snap_number_active = 1;
+
+		memset(cbt_map->write_map, 0, cbt_map->blk_count);
+
+		generate_random_uuid(cbt_map->generation_id.b);
+
+		pr_debug("CBT reset\n");
+	} else
+		memcpy(cbt_map->read_map, cbt_map->write_map,
+		       cbt_map->blk_count);
+	spin_unlock(&cbt_map->locker);
+}
+
+static inline int _cbt_map_set(struct cbt_map *cbt_map, sector_t sector_start,
+			       sector_t sector_cnt, u8 snap_number,
+			       unsigned char *map)
+{
+	int res = 0;
+	u8 num;
+	size_t inx;
+	size_t cbt_block_first = (size_t)(
+		sector_start >> (cbt_map->blk_size_shift - SECTOR_SHIFT));
+	size_t cbt_block_last = (size_t)(
+		(sector_start + sector_cnt - 1) >>
+		(cbt_map->blk_size_shift - SECTOR_SHIFT));
+
+	for (inx = cbt_block_first; inx <= cbt_block_last; ++inx) {
+		if (unlikely(inx >= cbt_map->blk_count)) {
+			pr_err("Block index is too large\n");
+			pr_err("Block #%zu was demanded, map size %zu blocks\n",
+			       inx, cbt_map->blk_count);
+			res = -EINVAL;
+			break;
+		}
+
+		num = map[inx];
+		if (num < snap_number)
+			map[inx] = snap_number;
+	}
+	return res;
+}
+
+int cbt_map_set(struct cbt_map *cbt_map, sector_t sector_start,
+		sector_t sector_cnt)
+{
+	int res;
+
+	spin_lock(&cbt_map->locker);
+	if (unlikely(cbt_map->is_corrupted)) {
+		spin_unlock(&cbt_map->locker);
+		return -EINVAL;
+	}
+	res = _cbt_map_set(cbt_map, sector_start, sector_cnt,
+			   (u8)cbt_map->snap_number_active, cbt_map->write_map);
+	if (unlikely(res))
+		cbt_map->is_corrupted = true;
+
+	spin_unlock(&cbt_map->locker);
+
+	return res;
+}
+
+int cbt_map_set_both(struct cbt_map *cbt_map, sector_t sector_start,
+		     sector_t sector_cnt)
+{
+	int res;
+
+	spin_lock(&cbt_map->locker);
+	if (unlikely(cbt_map->is_corrupted)) {
+		spin_unlock(&cbt_map->locker);
+		return -EINVAL;
+	}
+	res = _cbt_map_set(cbt_map, sector_start, sector_cnt,
+			   (u8)cbt_map->snap_number_active, cbt_map->write_map);
+	if (!res)
+		res = _cbt_map_set(cbt_map, sector_start, sector_cnt,
+				   (u8)cbt_map->snap_number_previous,
+				   cbt_map->read_map);
+	spin_unlock(&cbt_map->locker);
+
+	return res;
+}
drivers/block/blksnap/cbt_map.h new file +90 -0

90 lines not on this page · raw message

drivers/block/blksnap/tracker.c new file +344 -0

344 lines not on this page · raw message

drivers/block/blksnap/tracker.h new file +78 -0

78 lines not on this page · raw message

Signature · 1 line
2.20.1
#9 lore raw

Re: [PATCH v6 06/11] blksnap: handling and tracking I/O units

drivers/block/blksnap/tracker.c line 243

Quoted 9 lines
drivers/block/blksnap/tracker.c new file +9 -0
+
+static int (*const ctl_table[])(struct tracker *tracker,
+				__u8 __user *buf, __u32 *plen) = {
+	ctl_cbtinfo,
+	ctl_cbtmap,
+	ctl_cbtdirty,
+	ctl_snapshotadd,
+	ctl_snapshotinfo,
+};

Please use a switch statement like the rest of the kernel. Besides being simple to follow it also avoid having a speculation gadget on user controlled input.

#10 lore raw

PATCH v6 7/11 blksnap: difference storage and chunk

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The struct diff_area provides management of difference blocks of block devices. Storing difference blocks, and reading them to get a snapshot images.

The struct chunk describes the minimum data storage unit of the original block device. Functions for working with these minimal blocks implement algorithms for reading and writing blocks.

---
 drivers/block/blksnap/chunk.c        | 667 +++++++++++++++++++++++++++
 drivers/block/blksnap/chunk.h        | 142 ++++++
 drivers/block/blksnap/diff_area.c    | 601 ++++++++++++++++++++++++
 drivers/block/blksnap/diff_area.h    | 175 +++++++
 drivers/block/blksnap/diff_buffer.c  | 115 +++++
 drivers/block/blksnap/diff_buffer.h  |  37 ++
 drivers/block/blksnap/diff_storage.c | 291 ++++++++++++
 drivers/block/blksnap/diff_storage.h | 104 +++++
 8 files changed, 2132 insertions(+)
 create mode 100644 drivers/block/blksnap/chunk.c
 create mode 100644 drivers/block/blksnap/chunk.h
 create mode 100644 drivers/block/blksnap/diff_area.c
 create mode 100644 drivers/block/blksnap/diff_area.h
 create mode 100644 drivers/block/blksnap/diff_buffer.c
 create mode 100644 drivers/block/blksnap/diff_buffer.h
 create mode 100644 drivers/block/blksnap/diff_storage.c
 create mode 100644 drivers/block/blksnap/diff_storage.h
drivers/block/blksnap/chunk.c new file +667 -0
new file mode 100644
index 000000000000..cd82d0d9d6fd
@@ -0,0 +1,667 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#define pr_fmt(fmt) KBUILD_MODNAME "-chunk: " fmt
+
+#include <linux/blkdev.h>
+#include <linux/slab.h>
+#include "chunk.h"
+#include "diff_buffer.h"
+#include "diff_storage.h"
+#include "params.h"
+
+struct chunk_bio {
+	struct work_struct work;
+	struct list_head chunks;
+	struct bio *orig_bio;
+	struct bvec_iter orig_iter;
+	struct bio bio;
+};
+
+static struct bio_set chunk_io_bioset;
+static struct bio_set chunk_clone_bioset;
+
+static inline sector_t chunk_sector(struct chunk *chunk)
+{
+	return (sector_t)(chunk->number)
+	       << (chunk->diff_area->chunk_shift - SECTOR_SHIFT);
+}
+
+static inline sector_t chunk_sector_end(struct chunk *chunk)
+{
+	return chunk_sector(chunk) + chunk->sector_count;
+}
+
+void chunk_store_failed(struct chunk *chunk, int error)
+{
+	struct diff_area *diff_area = diff_area_get(chunk->diff_area);
+
+	WARN_ON_ONCE(chunk->state != CHUNK_ST_NEW &&
+		     chunk->state != CHUNK_ST_IN_MEMORY);
+	chunk->state = CHUNK_ST_FAILED;
+
+	if (likely(chunk->diff_buffer)) {
+		diff_buffer_release(diff_area, chunk->diff_buffer);
+		chunk->diff_buffer = NULL;
+	}
+
+	chunk_up(chunk);
+	if (error)
+		diff_area_set_corrupted(diff_area, error);
+	diff_area_put(diff_area);
+};
+
+static inline void chunk_io_failed(struct chunk *chunk)
+{
+	struct diff_area *diff_area = diff_area_get(chunk->diff_area);
+
+	if (likely(chunk->diff_buffer)) {
+		diff_buffer_release(diff_area, chunk->diff_buffer);
+		chunk->diff_buffer = NULL;
+	}
+
+	chunk_up(chunk);
+	diff_area_put(diff_area);
+}
+
+static void chunk_schedule_storing(struct chunk *chunk)
+{
+	struct diff_area *diff_area = diff_area_get(chunk->diff_area);
+	bool need_work = false;
+
+	WARN_ON_ONCE(chunk->state != CHUNK_ST_NEW &&
+		     chunk->state != CHUNK_ST_STORED);
+	chunk->state = CHUNK_ST_IN_MEMORY;
+
+	spin_lock(&diff_area->store_queue_lock);
+	list_add_tail(&chunk->link, &diff_area->store_queue);
+
+	need_work = (atomic_inc_return(&diff_area->store_queue_count) >
+		     get_chunk_maximum_in_queue()) &&
+		     !diff_area->store_queue_processing;
+	if (need_work)
+		diff_area->store_queue_processing = true;
+	spin_unlock(&diff_area->store_queue_lock);
+
+	chunk_up(chunk);
+
+	if (need_work) {
+		/* Initiate the queue clearing process */
+		queue_work(system_wq, &diff_area->store_queue_work);
+	}
+	diff_area_put(diff_area);
+}
+
+void chunk_copy_bio(struct chunk *chunk, struct bio *bio,
+		    struct bvec_iter *iter)
+{
+	unsigned int chunk_ofs, chunk_left;
+
+	chunk_ofs = (iter->bi_sector - chunk_sector(chunk)) << SECTOR_SHIFT;
+	chunk_left = chunk->diff_buffer->size - chunk_ofs;
+	while (chunk_left && iter->bi_size) {
+		struct bio_vec bvec = bio_iter_iovec(bio, *iter);
+		unsigned int page_ofs = offset_in_page(chunk_ofs);
+		unsigned int inx = chunk_ofs >> PAGE_SHIFT;
+		struct page *page = chunk->diff_buffer->bvec[inx].bv_page;
+		unsigned int len;
+
+		len = min3(bvec.bv_len,
+			   chunk_left,
+			   (unsigned int)PAGE_SIZE - page_ofs);
+
+		if (op_is_write(bio_op(bio))) {
+			/* from bio to buffer */
+			memcpy_page(page, page_ofs,
+				    bvec.bv_page, bvec.bv_offset, len);
+		} else {
+			/* from buffer to bio */
+			memcpy_page(bvec.bv_page, bvec.bv_offset,
+				    page, page_ofs, len);
+		}
+
+		chunk_ofs += len;
+		chunk_left -= len;
+		bio_advance_iter_single(bio, iter, len);
+	}
+}
+
+static void chunk_clone_endio(struct bio *bio)
+{
+	struct bio *orig_bio = bio->bi_private;
+
+	if (unlikely(bio->bi_status != BLK_STS_OK))
+		bio_io_error(orig_bio);
+	else
+		bio_endio(orig_bio);
+}
+
+static inline sector_t chunk_offset(struct chunk *chunk, struct bio *bio)
+{
+	return bio->bi_iter.bi_sector - chunk_sector(chunk);
+}
+
+static inline void chunk_limit_iter(struct chunk *chunk, struct bio *bio,
+				    sector_t sector, struct bvec_iter *iter)
+{
+	sector_t chunk_ofs = chunk_offset(chunk, bio);
+
+	iter->bi_sector = sector + chunk_ofs;
+	iter->bi_size = min_t(unsigned int,
+			bio->bi_iter.bi_size,
+			(chunk->sector_count - chunk_ofs) << SECTOR_SHIFT);
+}
+
+static inline unsigned int chunk_limit(struct chunk *chunk, struct bio *bio)
+{
+	unsigned int chunk_ofs, chunk_left;
+
+	chunk_ofs = (unsigned int)chunk_offset(chunk, bio) << SECTOR_SHIFT;
+	chunk_left = chunk->diff_buffer->size - chunk_ofs;
+
+	return min(bio->bi_iter.bi_size, chunk_left);
+}
+
+struct bio *chunk_alloc_clone(struct block_device *bdev, struct bio *bio)
+{
+	return bio_alloc_clone(bdev, bio, GFP_NOIO, &chunk_clone_bioset);
+}
+
+#if defined(CONFIG_BLKSNAP_DIFF_BLKDEV)
+void chunk_diff_bio_tobdev(struct chunk *chunk, struct bio *bio)
+{
+	struct bio *new_bio;
+
+	new_bio = chunk_alloc_clone(chunk->diff_bdev, bio);
+	chunk_limit_iter(chunk, bio, chunk->diff_ofs_sect, &new_bio->bi_iter);
+	new_bio->bi_end_io = chunk_clone_endio;
+	new_bio->bi_private = bio;
+
+	bio_advance(bio, new_bio->bi_iter.bi_size);
+	bio_inc_remaining(bio);
+
+	submit_bio_noacct(new_bio);
+}
+#endif
+
+static inline void chunk_io_ctx_free(struct chunk_io_ctx *io_ctx, long ret)
+{
+	struct chunk *chunk = io_ctx->chunk;
+	struct bio *bio = io_ctx->bio;
+
+	kfree(io_ctx);
+	if (ret < 0) {
+		bio_io_error(bio);
+		chunk_io_failed(chunk);
+		return;
+	}
+
+	bio_endio(bio);
+	chunk_up(chunk);
+}
+
+#ifdef CONFIG_BLKSNAP_CHUNK_DIFF_BIO_SYNC
+void chunk_diff_bio_execute(struct chunk_io_ctx *io_ctx)
+{
+	struct file *diff_file = io_ctx->chunk->diff_file;
+	ssize_t len;
+
+	if (io_ctx->iov_iter.data_source) {
+		file_start_write(diff_file);
+		len = vfs_iter_write(diff_file, &io_ctx->iov_iter,
+				     &io_ctx->pos, 0);
+		file_end_write(diff_file);
+	} else {
+		len = vfs_iter_read(diff_file, &io_ctx->iov_iter,
+				    &io_ctx->pos, 0);
+	}
+
+	chunk_io_ctx_free(io_ctx, len);
+}
+#else
+static void chunk_diff_bio_complete_read(struct kiocb *iocb, long ret)
+{
+	struct chunk_io_ctx *io_ctx;
+
+	io_ctx = container_of(iocb, struct chunk_io_ctx, iocb);
+	chunk_io_ctx_free(io_ctx, ret);
+}
+
+static void chunk_diff_bio_complete_write(struct kiocb *iocb, long ret)
+{
+	struct chunk_io_ctx *io_ctx;
+
+	io_ctx = container_of(iocb, struct chunk_io_ctx, iocb);
+	file_end_write(io_ctx->iocb.ki_filp);
+	chunk_io_ctx_free(io_ctx, ret);
+}
+
+static inline void chunk_diff_bio_execute_write(struct chunk_io_ctx *io_ctx)
+{
+	struct file *diff_file = io_ctx->chunk->diff_file;
+	ssize_t len;
+
+	file_start_write(diff_file);
+	len = vfs_iocb_iter_write(diff_file, &io_ctx->iocb,  &io_ctx->iov_iter);
+
+	if (len != -EIOCBQUEUED) {
+		if (unlikely(len < 0))
+			pr_err("Failed to write data to difference storage\n");
+		file_end_write(diff_file);
+		chunk_io_ctx_free(io_ctx, len);
+	}
+}
+
+static inline void chunk_diff_bio_execute_read(struct chunk_io_ctx *io_ctx)
+{
+	struct file *diff_file = io_ctx->chunk->diff_file;
+	ssize_t len;
+
+	len = vfs_iocb_iter_read(diff_file, &io_ctx->iocb, &io_ctx->iov_iter);
+	if (len != -EIOCBQUEUED) {
+		if (unlikely(len < 0))
+			pr_err("Failed to read data from difference storage\n");
+		chunk_io_ctx_free(io_ctx, len);
+	}
+}
+
+void chunk_diff_bio_execute(struct chunk_io_ctx *io_ctx)
+{
+	if (io_ctx->iov_iter.data_source)
+		chunk_diff_bio_execute_write(io_ctx);
+	else
+		chunk_diff_bio_execute_read(io_ctx);
+}
+#endif
+
+static inline void chunk_diff_bio_schedule(struct diff_area *diff_area,
+					   struct chunk_io_ctx *io_ctx)
+{
+	spin_lock(&diff_area->image_io_queue_lock);
+	list_add_tail(&io_ctx->link, &diff_area->image_io_queue);
+	spin_unlock(&diff_area->image_io_queue_lock);
+	queue_work(system_wq, &diff_area->image_io_work);
+}
+
+/*
+ * The data from bio is write to the diff file or read from it.
+ */
+int chunk_diff_bio(struct chunk *chunk, struct bio *bio)
+{
+	bool is_write = op_is_write(bio_op(bio));
+	loff_t chunk_ofs, chunk_left;
+	struct bio_vec iter_bvec, *bio_bvec;
+	struct bvec_iter iter;
+	unsigned long nr_segs = 0;
+	size_t nbytes = 0;
+	struct chunk_io_ctx *io_ctx;
+
+	io_ctx = kzalloc(sizeof(struct chunk_io_ctx), GFP_NOIO);
+	if (!io_ctx)
+		return -ENOMEM;
+
+	chunk_ofs = (bio->bi_iter.bi_sector - chunk_sector(chunk))
+			<< SECTOR_SHIFT;
+	chunk_left = (chunk->sector_count << SECTOR_SHIFT) - chunk_ofs;
+	bio_for_each_segment(iter_bvec, bio, iter) {
+		if (chunk_left == 0)
+			break;
+
+		if (chunk_left > iter_bvec.bv_len) {
+			chunk_left -= iter_bvec.bv_len;
+			nbytes += iter_bvec.bv_len;
+		} else {
+			nbytes += chunk_left;
+			chunk_left = 0;
+		}
+		nr_segs++;
+	}
+	bio_bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
+	iov_iter_bvec(&io_ctx->iov_iter, is_write ? WRITE : READ,
+		      bio_bvec, nr_segs, nbytes);
+	io_ctx->iov_iter.iov_offset = bio->bi_iter.bi_bvec_done;
+#ifdef CONFIG_BLKSNAP_CHUNK_DIFF_BIO_SYNC
+	io_ctx->pos = (chunk->diff_ofs_sect << SECTOR_SHIFT) + chunk_ofs;
+#else
+	io_ctx->iocb.ki_filp = chunk->diff_file;
+	io_ctx->iocb.ki_pos = (chunk->diff_ofs_sect << SECTOR_SHIFT) +
+								chunk_ofs;
+	io_ctx->iocb.ki_flags = IOCB_DIRECT;
+	if (is_write)
+		io_ctx->iocb.ki_flags |= IOCB_WRITE;
+	io_ctx->iocb.ki_ioprio = get_current_ioprio();
+	io_ctx->iocb.ki_complete = is_write ? chunk_diff_bio_complete_write
+					    : chunk_diff_bio_complete_read;
+#endif
+	io_ctx->chunk = chunk;
+	io_ctx->bio = bio;
+	bio_inc_remaining(bio);
+	bio_advance(bio, nbytes);
+
+	chunk_diff_bio_schedule(chunk->diff_area, io_ctx);
+
+	return 0;
+}
+
+static inline struct chunk *get_chunk_from_cbio(struct chunk_bio *cbio)
+{
+	struct chunk *chunk = list_first_entry_or_null(&cbio->chunks,
+						       struct chunk, link);
+
+	if (chunk)
+		list_del_init(&chunk->link);
+	return chunk;
+}
+
+static void notify_load_and_schedule_io(struct work_struct *work)
+{
+	struct chunk_bio *cbio = container_of(work, struct chunk_bio, work);
+	struct chunk *chunk;
+
+	while ((chunk = get_chunk_from_cbio(cbio))) {
+		if (unlikely(cbio->bio.bi_status != BLK_STS_OK)) {
+			chunk_store_failed(chunk, -EIO);
+			continue;
+		}
+		if (chunk->state == CHUNK_ST_FAILED) {
+			chunk_up(chunk);
+			continue;
+		}
+
+		chunk_copy_bio(chunk, cbio->orig_bio, &cbio->orig_iter);
+		bio_endio(cbio->orig_bio);
+
+		chunk_schedule_storing(chunk);
+	}
+
+	bio_put(&cbio->bio);
+}
+
+static void notify_load_and_postpone_io(struct work_struct *work)
+{
+	struct chunk_bio *cbio = container_of(work, struct chunk_bio, work);
+	struct chunk *chunk;
+
+	while ((chunk = get_chunk_from_cbio(cbio))) {
+		if (unlikely(cbio->bio.bi_status != BLK_STS_OK)) {
+			chunk_store_failed(chunk, -EIO);
+			continue;
+		}
+		if (chunk->state == CHUNK_ST_FAILED) {
+			chunk_up(chunk);
+			continue;
+		}
+
+		chunk_schedule_storing(chunk);
+	}
+
+	/* submit the original bio fed into the tracker */
+	submit_bio_noacct_nocheck(cbio->orig_bio);
+	bio_put(&cbio->bio);
+}
+
+static void chunk_notify_store(struct chunk *chunk, int err)
+{
+	if (err) {
+		chunk_store_failed(chunk, err);
+		return;
+	}
+
+	WARN_ON_ONCE(chunk->state != CHUNK_ST_IN_MEMORY);
+	chunk->state = CHUNK_ST_STORED;
+
+	if (chunk->diff_buffer) {
+		diff_buffer_release(chunk->diff_area,
+				    chunk->diff_buffer);
+		chunk->diff_buffer = NULL;
+	}
+	chunk_up(chunk);
+}
+
+#if defined(CONFIG_BLKSNAP_DIFF_BLKDEV)
+static void chunk_notify_store_tobdev(struct work_struct *work)
+{
+	struct chunk_bio *cbio = container_of(work, struct chunk_bio, work);
+	struct chunk *chunk;
+
+	while ((chunk = get_chunk_from_cbio(cbio))) {
+		if (unlikely(cbio->bio.bi_status != BLK_STS_OK)) {
+			chunk_store_failed(chunk, -EIO);
+			continue;
+		}
+
+		WARN_ON_ONCE(chunk->state != CHUNK_ST_IN_MEMORY);
+		chunk->state = CHUNK_ST_STORED;
+
+		if (chunk->diff_buffer) {
+			diff_buffer_release(chunk->diff_area,
+					    chunk->diff_buffer);
+			chunk->diff_buffer = NULL;
+		}
+		chunk_up(chunk);
+	}
+
+	bio_put(&cbio->bio);
+}
+#endif
+
+static void chunk_io_endio(struct bio *bio)
+{
+	struct chunk_bio *cbio = container_of(bio, struct chunk_bio, bio);
+
+	queue_work(system_wq, &cbio->work);
+}
+
+static void chunk_submit_bio(struct bio *bio)
+{
+	bio->bi_end_io = chunk_io_endio;
+	submit_bio_noacct(bio);
+}
+
+static inline unsigned short calc_max_vecs(sector_t left)
+{
+	return bio_max_segs(round_up(left, PAGE_SECTORS) / PAGE_SECTORS);
+}
+
+#if defined(CONFIG_BLKSNAP_DIFF_BLKDEV)
+void chunk_store_tobdev(struct chunk *chunk)
+{
+	struct block_device *bdev = chunk->diff_bdev;
+	sector_t sector = chunk->diff_ofs_sect;
+	sector_t count = chunk->sector_count;
+	unsigned int inx = 0;
+	struct bio *bio;
+	struct chunk_bio *cbio;
+
+	bio = bio_alloc_bioset(bdev, calc_max_vecs(count),
+			       REQ_OP_WRITE | REQ_SYNC | REQ_FUA, GFP_NOIO,
+			       &chunk_io_bioset);
+	bio->bi_iter.bi_sector = sector;
+
+	while (count) {
+		struct bio *next;
+		sector_t portion = min_t(sector_t, count, PAGE_SECTORS);
+		unsigned int bytes = portion << SECTOR_SHIFT;
+
+		if (bio_add_page(bio, chunk->diff_buffer->bvec[inx].bv_page,
+				 bytes, 0) == bytes) {
+			inx++;
+			count -= portion;
+			continue;
+		}
+
+		/* Create next bio */
+		next = bio_alloc_bioset(bdev, calc_max_vecs(count),
+					REQ_OP_WRITE | REQ_SYNC | REQ_FUA,
+					GFP_NOIO, &chunk_io_bioset);
+		next->bi_iter.bi_sector = bio_end_sector(bio);
+		bio_chain(bio, next);
+		submit_bio_noacct(bio);
+		bio = next;
+	}
+
+	cbio = container_of(bio, struct chunk_bio, bio);
+
+	INIT_WORK(&cbio->work, chunk_notify_store_tobdev);
+	INIT_LIST_HEAD(&cbio->chunks);
+	list_add_tail(&chunk->link, &cbio->chunks);
+	cbio->orig_bio = NULL;
+	chunk_submit_bio(bio);
+}
+#endif
+
+/*
+ * Synchronously store chunk to diff file.
+ */
+void chunk_diff_write(struct chunk *chunk)
+{
+	loff_t pos = chunk->diff_ofs_sect << SECTOR_SHIFT;
+	size_t length = chunk->sector_count << SECTOR_SHIFT;
+	struct iov_iter iov_iter;
+	ssize_t len;
+	int err = 0;
+
+	iov_iter_bvec(&iov_iter, ITER_SOURCE, chunk->diff_buffer->bvec,
+		      chunk->diff_buffer->nr_pages, length);
+	file_start_write(chunk->diff_file);
+	while (length) {
+		len = vfs_iter_write(chunk->diff_file, &iov_iter, &pos, 0);
+		if (len < 0) {
+			err = (int)len;
+			pr_debug("vfs_iter_write complete with error code %zd",
+				 len);
+			break;
+		}
+		length -= len;
+	}
+	file_end_write(chunk->diff_file);
+	chunk_notify_store(chunk, err);
+}
+
+static struct bio *chunk_origin_load_async(struct chunk *chunk)
+{
+	struct block_device *bdev;
+	struct bio *bio = NULL;
+	struct diff_buffer *diff_buffer;
+	unsigned int inx = 0;
+	sector_t sector, count = chunk->sector_count;
+
+	diff_buffer = diff_buffer_take(chunk->diff_area);
+	if (IS_ERR(diff_buffer))
+		return ERR_CAST(diff_buffer);
+	chunk->diff_buffer = diff_buffer;
+
+	bdev = chunk->diff_area->orig_bdev;
+	sector = chunk_sector(chunk);
+
+	bio = bio_alloc_bioset(bdev, calc_max_vecs(count),
+			       REQ_OP_READ, GFP_NOIO, &chunk_io_bioset);
+	bio->bi_iter.bi_sector = sector;
+
+	while (count) {
+		struct bio *next;
+		sector_t portion = min_t(sector_t, count, PAGE_SECTORS);
+		unsigned int bytes = portion << SECTOR_SHIFT;
+		struct page *pg = chunk->diff_buffer->bvec[inx].bv_page;
+
+		if (bio_add_page(bio, pg, bytes, 0) == bytes) {
+			inx++;
+			count -= portion;
+			continue;
+		}
+
+		/* Create next bio */
+		next = bio_alloc_bioset(bdev, calc_max_vecs(count),
+					REQ_OP_READ, GFP_NOIO,
+					&chunk_io_bioset);
+		next->bi_iter.bi_sector = bio_end_sector(bio);
+		bio_chain(bio, next);
+		submit_bio_noacct(bio);
+		bio = next;
+	}
+
+	return bio;
+}
+
+/*
+ * Load the chunk asynchronously.
+ */
+int chunk_load_and_postpone_io(struct chunk *chunk, struct bio **chunk_bio)
+{
+	struct bio *prev = *chunk_bio, *bio;
+
+	bio = chunk_origin_load_async(chunk);
+	if (IS_ERR(bio))
+		return PTR_ERR(bio);
+
+	if (prev) {
+		bio_chain(prev, bio);
+		submit_bio_noacct(prev);
+	}
+
+	*chunk_bio = bio;
+	return 0;
+}
+
+void chunk_load_and_postpone_io_finish(struct list_head *chunks,
+				struct bio *chunk_bio, struct bio *orig_bio)
+{
+	struct chunk_bio *cbio;
+
+	cbio = container_of(chunk_bio, struct chunk_bio, bio);
+	INIT_LIST_HEAD(&cbio->chunks);
+	while (!list_empty(chunks)) {
+		struct chunk *it;
+
+		it = list_first_entry(chunks, struct chunk, link);
+		list_del_init(&it->link);
+
+		list_add_tail(&it->link, &cbio->chunks);
+	}
+	INIT_WORK(&cbio->work, notify_load_and_postpone_io);
+	cbio->orig_bio = orig_bio;
+	chunk_submit_bio(chunk_bio);
+}
+
+bool chunk_load_and_schedule_io(struct chunk *chunk, struct bio *orig_bio)
+{
+	struct chunk_bio *cbio;
+	struct bio *bio;
+
+	bio = chunk_origin_load_async(chunk);
+	if (IS_ERR(bio)) {
+		chunk_up(chunk);
+		return false;
+	}
+
+	cbio = container_of(bio, struct chunk_bio, bio);
+	INIT_LIST_HEAD(&cbio->chunks);
+	list_add_tail(&chunk->link, &cbio->chunks);
+	INIT_WORK(&cbio->work, notify_load_and_schedule_io);
+	cbio->orig_bio = orig_bio;
+	cbio->orig_iter = orig_bio->bi_iter;
+	bio_advance_iter_single(orig_bio, &orig_bio->bi_iter,
+				chunk_limit(chunk, orig_bio));
+	bio_inc_remaining(orig_bio);
+
+	chunk_submit_bio(bio);
+	return true;
+}
+
+int __init chunk_init(void)
+{
+	int ret;
+
+	ret = bioset_init(&chunk_io_bioset, 64,
+			  offsetof(struct chunk_bio, bio),
+			  BIOSET_NEED_BVECS | BIOSET_NEED_RESCUER);
+	if (!ret)
+		ret = bioset_init(&chunk_clone_bioset, 64, 0,
+				  BIOSET_NEED_BVECS | BIOSET_NEED_RESCUER);
+	return ret;
+}
+
+void chunk_done(void)
+{
+	bioset_exit(&chunk_io_bioset);
+	bioset_exit(&chunk_clone_bioset);
+}
drivers/block/blksnap/chunk.h new file +142 -0

142 lines not on this page · raw message

drivers/block/blksnap/diff_area.c new file +601 -0

601 lines not on this page · raw message

drivers/block/blksnap/diff_area.h new file +175 -0

175 lines not on this page · raw message

drivers/block/blksnap/diff_buffer.c new file +115 -0

115 lines not on this page · raw message

drivers/block/blksnap/diff_buffer.h new file +37 -0
new file mode 100644
index 000000000000..077fcf4a2292
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#ifndef __BLKSNAP_DIFF_BUFFER_H
+#define __BLKSNAP_DIFF_BUFFER_H
+
+#include <linux/types.h>
+#include <linux/slab.h>
+#include <linux/list.h>
+#include <linux/blkdev.h>
+
+struct diff_area;
+
+/**
+ * struct diff_buffer - Difference buffer.
+ * @link:
+ *	The list header allows to create a pool of the diff_buffer structures.
+ * @size:
+ *	Count of bytes in the buffer.
+ * @nr_pages:
+ *	The number of pages reserved for the buffer.
+ * @bvec:
+ *	An array of pages in bio_vec form.
+ *
+ * Describes the memory buffer for a chunk in the memory.
+ */
+struct diff_buffer {
+	struct list_head link;
+	size_t size;
+	unsigned long nr_pages;
+	struct bio_vec bvec[];
+};
+
+struct diff_buffer *diff_buffer_take(struct diff_area *diff_area);
+void diff_buffer_release(struct diff_area *diff_area,
+			 struct diff_buffer *diff_buffer);
+void diff_buffer_cleanup(struct diff_area *diff_area);
+#endif /* __BLKSNAP_DIFF_BUFFER_H */
drivers/block/blksnap/diff_storage.c new file +291 -0

291 lines not on this page · raw message

drivers/block/blksnap/diff_storage.h new file +104 -0

104 lines not on this page · raw message

Signature · 1 line
2.20.1
#11 lore raw

Re: [PATCH v6 07/11] blksnap: difference storage and chunk

Quoted 5 lines
drivers/block/blksnap/diff_storage.c new file +5 -0
+static inline bool unsupported_mode(const umode_t m)
+{
+	return (S_ISCHR(m) || S_ISFIFO(m) || S_ISSOCK(m));
+}
+

drivers/block/blksnap/diff_storage.c line 145

Quoted 10 lines
drivers/block/blksnap/diff_storage.c new file +10 -0
+static inline bool unsupported_flags(const unsigned int flags)
+{
+	if (!(flags | O_RDWR)) {
+		pr_err("Read and write access is required\n");
+		return true;
+	}
+	if (!(flags | O_EXCL)) {
+		pr_err("Exclusive access is required\n");
+		return true;
+	}

You probably want to positively check the allowed flags and types to be more future proof. I'd also drop these very easy to trigger messages.

drivers/block/blksnap/diff_storage.c line 175

Quoted 1 line
drivers/block/blksnap/diff_storage.c new file +1 -0
+	if (S_ISBLK(file_inode(file)->i_mode)) {

Splitting the blk and regular file open path into separate helpers would improve readability a lot I think.

drivers/block/blksnap/diff_storage.c line 188

Quoted 8 lines
drivers/block/blksnap/diff_storage.c new file +8 -0
+		/*
+		 * The block device is opened non-exclusively.
+		 * It should be exclusive to open the file whose descriptor is
+		 * passed to the module.
+		 */
+		bdev = blkdev_get_by_dev(dev_id,
+					 BLK_OPEN_READ | BLK_OPEN_WRITE,
+					 NULL, NULL);

Note that this will have some interesting interaction with the patches from Jan to optionally disallow any other write for exclusively opened block devices. But given that right now we don't support using the original device as backing store, this probably should become an exclusive open anyway.

#12 lore raw

PATCH v6 8/11 blksnap: event queue from the difference storage

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

Events are used to immediately notify the user land of a change in the snapshot state. For example, if an error occurred while snapshot holding when reading data from the original block device or from the difference storage.

---
 drivers/block/blksnap/event_queue.c | 81 +++++++++++++++++++++++++++++
 drivers/block/blksnap/event_queue.h | 64 +++++++++++++++++++++++
 2 files changed, 145 insertions(+)
 create mode 100644 drivers/block/blksnap/event_queue.c
 create mode 100644 drivers/block/blksnap/event_queue.h
drivers/block/blksnap/event_queue.c new file +81 -0
new file mode 100644
index 000000000000..2256167b631b
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#define pr_fmt(fmt) KBUILD_MODNAME "-event_queue: " fmt
+
+#include <linux/slab.h>
+#include <linux/sched.h>
+#include "event_queue.h"
+
+void event_queue_init(struct event_queue *event_queue)
+{
+	INIT_LIST_HEAD(&event_queue->list);
+	spin_lock_init(&event_queue->lock);
+	init_waitqueue_head(&event_queue->wq_head);
+}
+
+void event_queue_done(struct event_queue *event_queue)
+{
+	struct event *event;
+
+	spin_lock(&event_queue->lock);
+	while (!list_empty(&event_queue->list)) {
+		event = list_first_entry(&event_queue->list, struct event,
+					 link);
+		list_del(&event->link);
+		event_free(event);
+	}
+	spin_unlock(&event_queue->lock);
+}
+
+int event_gen(struct event_queue *event_queue, gfp_t flags, int code,
+	      const void *data, int data_size)
+{
+	struct event *event;
+
+	event = kzalloc(sizeof(struct event) + data_size + 1, flags);
+	if (!event)
+		return -ENOMEM;
+
+	event->time = ktime_get();
+	event->code = code;
+	event->data_size = data_size;
+	memcpy(event->data, data, data_size);
+
+	pr_debug("Generate event: time=%lld code=%d data_size=%d\n",
+		 event->time, event->code, event->data_size);
+
+	spin_lock(&event_queue->lock);
+	list_add_tail(&event->link, &event_queue->list);
+	spin_unlock(&event_queue->lock);
+
+	wake_up(&event_queue->wq_head);
+	return 0;
+}
+
+struct event *event_wait(struct event_queue *event_queue,
+			 unsigned long timeout_ms)
+{
+	int ret;
+
+	ret = wait_event_interruptible_timeout(event_queue->wq_head,
+				!list_empty(&event_queue->list), timeout_ms);
+	if (ret >= 0) {
+		struct event *event = ERR_PTR(-ENOENT);
+
+		spin_lock(&event_queue->lock);
+		if (!list_empty(&event_queue->list)) {
+			event = list_first_entry(&event_queue->list,
+						 struct event, link);
+			list_del(&event->link);
+		}
+		spin_unlock(&event_queue->lock);
+		return event;
+	}
+	if (ret == -ERESTARTSYS) {
+		pr_debug("event waiting interrupted\n");
+		return ERR_PTR(-EINTR);
+	}
+
+	pr_err("Failed to wait event. errno=%d\n", abs(ret));
+	return ERR_PTR(ret);
+}
drivers/block/blksnap/event_queue.h new file +64 -0

64 lines not on this page · raw message

Signature · 1 line
2.20.1
#13 lore raw

PATCH v6 9/11 blksnap: snapshot and snapshot image block device

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

The struck snapshot combines block devices, for which a snapshot is created, block devices of their snapshot images, as well as a difference storage.
There may be several snapshots at the same time, but they should not contain common block devices. This can be used for cases when backup is scheduled once an hour for some block devices, and once a day for others, and once a week for others. In this case, it is possible that three snapshots are used at the same time.
Snapshot images of block devices provides the read and write operations. They redirect I/O units to the original block device or to differential storage devices.

---
 drivers/block/blksnap/snapimage.c | 134 +++++++++
 drivers/block/blksnap/snapimage.h |  10 +
 drivers/block/blksnap/snapshot.c  | 440 ++++++++++++++++++++++++++++++
 drivers/block/blksnap/snapshot.h  |  64 +++++
 4 files changed, 648 insertions(+)
 create mode 100644 drivers/block/blksnap/snapimage.c
 create mode 100644 drivers/block/blksnap/snapimage.h
 create mode 100644 drivers/block/blksnap/snapshot.c
 create mode 100644 drivers/block/blksnap/snapshot.h
drivers/block/blksnap/snapimage.c new file +134 -0
new file mode 100644
index 000000000000..6efd39d2ce79
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+/*
+ * Present the snapshot image as a block device.
+ */
+#define pr_fmt(fmt) KBUILD_MODNAME "-image: " fmt
+#include <linux/slab.h>
+#include <linux/cdrom.h>
+#include <linux/blk-mq.h>
+#include <linux/build_bug.h>
+#include <uapi/linux/blksnap.h>
+#include "snapimage.h"
+#include "tracker.h"
+#include "chunk.h"
+#include "cbt_map.h"
+
+/*
+ * The snapshot supports write operations.  This allows for example to delete
+ * some files from the file system before backing up the volume. The data can
+ * be stored only in the difference storage. Therefore, before partially
+ * overwriting this data, it should be read from the original block device.
+ */
+static void snapimage_submit_bio(struct bio *bio)
+{
+	struct tracker *tracker = bio->bi_bdev->bd_disk->private_data;
+	struct diff_area *diff_area = tracker->diff_area;
+	unsigned int old_nofs;
+	struct blkfilter *prev_filter;
+	bool is_success = true;
+
+	/*
+	 * We can use the diff_area here without fear that it will be released.
+	 * The diff_area is not blocked from releasing now, because
+	 * snapimage_free() is calling before diff_area_put() in
+	 * tracker_release_snapshot().
+	 */
+	if (diff_area_is_corrupted(diff_area)) {
+		bio_io_error(bio);
+		return;
+	}
+
+	/*
+	 * The change tracking table should indicate that the image block device
+	 * is different from the original device. At the next snapshot, such
+	 * blocks must be inevitably reread.
+	 */
+	if (op_is_write(bio_op(bio)))
+		cbt_map_set_both(tracker->cbt_map, bio->bi_iter.bi_sector,
+				 bio_sectors(bio));
+
+	prev_filter = current->blk_filter;
+	current->blk_filter = &tracker->filter;
+	old_nofs = memalloc_nofs_save();
+	while (bio->bi_iter.bi_size && is_success)
+		is_success = diff_area_submit_chunk(diff_area, bio);
+	memalloc_nofs_restore(old_nofs);
+	current->blk_filter = prev_filter;
+
+	if (is_success)
+		bio_endio(bio);
+	else
+		bio_io_error(bio);
+}
+
+static const struct block_device_operations bd_ops = {
+	.owner = THIS_MODULE,
+	.submit_bio = snapimage_submit_bio,
+};
+
+void snapimage_free(struct tracker *tracker)
+{
+	struct gendisk *disk = tracker->snap_disk;
+
+	if (!disk)
+		return;
+
+	pr_debug("Snapshot image disk %s delete\n", disk->disk_name);
+	del_gendisk(disk);
+	put_disk(disk);
+
+	tracker->snap_disk = NULL;
+}
+
+int snapimage_create(struct tracker *tracker)
+{
+	int ret = 0;
+	dev_t dev_id = tracker->dev_id;
+	struct gendisk *disk;
+
+	pr_info("Create snapshot image device for original device [%u:%u]\n",
+		MAJOR(dev_id), MINOR(dev_id));
+
+	disk = blk_alloc_disk(NUMA_NO_NODE);
+	if (!disk) {
+		pr_err("Failed to allocate disk\n");
+		return -ENOMEM;
+	}
+
+	disk->flags = GENHD_FL_NO_PART;
+	disk->fops = &bd_ops;
+	disk->private_data = tracker;
+	set_capacity(disk, tracker->cbt_map->device_capacity);
+	ret = snprintf(disk->disk_name, DISK_NAME_LEN, "%s_%d:%d",
+		       BLKSNAP_IMAGE_NAME, MAJOR(dev_id), MINOR(dev_id));
+	if (ret < 0) {
+		pr_err("Unable to set disk name for snapshot image device: invalid device id [%d:%d]\n",
+		       MAJOR(dev_id), MINOR(dev_id));
+		ret = -EINVAL;
+		goto fail_cleanup_disk;
+	}
+	pr_debug("Snapshot image disk name [%s]\n", disk->disk_name);
+
+	blk_queue_physical_block_size(disk->queue,
+					tracker->diff_area->physical_blksz);
+	blk_queue_logical_block_size(disk->queue,
+					tracker->diff_area->logical_blksz);
+
+	ret = add_disk(disk);
+	if (ret) {
+		pr_err("Failed to add disk [%s] for snapshot image device\n",
+		       disk->disk_name);
+		goto fail_cleanup_disk;
+	}
+	tracker->snap_disk = disk;
+
+	pr_debug("Image block device [%d:%d] has been created\n",
+		disk->major, disk->first_minor);
+
+	return 0;
+
+fail_cleanup_disk:
+	put_disk(disk);
+	return ret;
+}
drivers/block/blksnap/snapimage.h new file +10 -0
new file mode 100644
index 000000000000..cb2df7019eb8
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+/* Copyright (C) 2023 Veeam Software Group GmbH */
+#ifndef __BLKSNAP_SNAPIMAGE_H
+#define __BLKSNAP_SNAPIMAGE_H
+
+struct tracker;
+
+void snapimage_free(struct tracker *tracker);
+int snapimage_create(struct tracker *tracker);
+#endif /* __BLKSNAP_SNAPIMAGE_H */
drivers/block/blksnap/snapshot.c new file +440 -0

440 lines not on this page · raw message

drivers/block/blksnap/snapshot.h new file +64 -0

64 lines not on this page · raw message

Signature · 1 line
2.20.1
#14 lore raw

PATCH v6 10/11 blksnap: Kconfig and Makefile

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

Allows to build a module and add the blksnap to the kernel tree.

---
 drivers/block/Kconfig          |  2 ++
 drivers/block/Makefile         |  2 ++
 drivers/block/blksnap/Kconfig  | 31 +++++++++++++++++++++++++++++++
 drivers/block/blksnap/Makefile | 15 +++++++++++++++
 4 files changed, 50 insertions(+)
 create mode 100644 drivers/block/blksnap/Kconfig
 create mode 100644 drivers/block/blksnap/Makefile
drivers/block/Kconfig +2 -0
index 5b9d4aaebb81..74d2d55526a3 100644
@@ -404,4 +404,6 @@ config BLKDEV_UBLK_LEGACY_OPCODES
 
 source "drivers/block/rnbd/Kconfig"
 
+source "drivers/block/blksnap/Kconfig"
+
 endif # BLK_DEV
drivers/block/Makefile +2 -0
index 101612cba303..9a2a9a56a247 100644
@@ -40,3 +40,5 @@ obj-$(CONFIG_BLK_DEV_NULL_BLK)	+= null_blk/
 obj-$(CONFIG_BLK_DEV_UBLK)			+= ublk_drv.o
 
 swim_mod-y	:= swim.o swim_asm.o
+
+obj-$(CONFIG_BLKSNAP) += blksnap/
drivers/block/blksnap/Kconfig new file +31 -0
new file mode 100644
index 000000000000..f52272c12e1b
@@ -0,0 +1,31 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Block device snapshot module configuration
+#
+
+config BLKSNAP
+	tristate "Block Devices Snapshots Module (blksnap)"
+	help
+	  Allow to create snapshots and track block changes for block devices.
+	  Designed for creating backups for block devices. Snapshots are
+	  temporary and are released when backup is completed. Change block
+	  tracking allows to create incremental or differential backups.
+
+config BLKSNAP_DIFF_BLKDEV
+	bool "Use an optimized algorithm to store difference on a block device"
+	depends on BLKSNAP
+	default y
+	help
+	  The difference storage for a snapshot can be a regular file or a
+	  block device. We can work with a block device through the interface
+	  of a regular file. However, direct management of I/O units should
+	  allow for higher performance.
+
+config BLKSNAP_CHUNK_DIFF_BIO_SYNC
+	bool "Use a synchronous I/O unit processing algorithm for the snapshot image"
+	depends on BLKSNAP
+	default n
+	help
+	  Theoretical asynchronous algorithm for processing I/O units should
+	  have higher performance. However, an attempt to confirm this on test
+	  runs did not bring any results.
drivers/block/blksnap/Makefile new file +15 -0
new file mode 100644
index 000000000000..8d528b95579a
@@ -0,0 +1,15 @@
+# SPDX-License-Identifier: GPL-2.0
+
+blksnap-y := 		\
+	cbt_map.o	\
+	chunk.o		\
+	diff_area.o	\
+	diff_buffer.o	\
+	diff_storage.o	\
+	event_queue.o	\
+	main.o		\
+	snapimage.o	\
+	snapshot.o	\
+	tracker.o
+
+obj-$(CONFIG_BLKSNAP)	 += blksnap.o
Signature · 1 line
2.20.1
#15 lore raw

Re: [PATCH v6 10/11] blksnap: Kconfig and Makefile

drivers/block/blksnap/Kconfig line 22

Quoted 9 lines
drivers/block/blksnap/Kconfig new file +9 -0
+config BLKSNAP_DIFF_BLKDEV
+	bool "Use an optimized algorithm to store difference on a block device"
+	depends on BLKSNAP
+	default y
+	help
+	  The difference storage for a snapshot can be a regular file or a
+	  block device. We can work with a block device through the interface
+	  of a regular file. However, direct management of I/O units should
+	  allow for higher performance.

Is there much of a point in making this option?

Btw, Linus hates defaul y, so we should not have one in there.

drivers/block/blksnap/Kconfig line 27

Quoted 4 lines
drivers/block/blksnap/Kconfig new file +4 -0
+config BLKSNAP_CHUNK_DIFF_BIO_SYNC
+	bool "Use a synchronous I/O unit processing algorithm for the snapshot image"
+	depends on BLKSNAP
+	default n

n the default default, so no need to add it. But unless there is a really good reason to have two different bio submission mechanisms upstream I'd strongly suggest dropping one of them and this option.

#16 lore raw

PATCH v6 11/11 blksnap: prevents using devices with data integrity or inline encryption

In reply to Sergei Shtepa

From: Sergei Shtepa <[email protected]>

There is an opinion that the use of the blksnap module may violate the security of encrypted data. The difference storage file may be located on an unreliable disk or even network storage. To implement secure compatibility with hardware inline encrypted devices will require discussion of algorithms and restrictions. For example, a restriction on the location of the difference storage only in virtual memory might help. Currently, there is no need for compatibility of the blksnap module and hardware inline encryption.

I see no obstacles to ensuring the compatibility of the blksnap module and block devices with data integrity. However, this functionality was not planned or tested. Perhaps in the future this compatibility can be implemented.

Theoretically possible that the block device was added to the snapshot before crypto_profile and integrity.profile were initialized. Checking the values of bi_crypt_context and bi_integrity ensures that the blksnap will not perform any actions with I/O units with which it is not compatible.

---
 drivers/block/blksnap/snapshot.c | 17 +++++++++++++++++
 drivers/block/blksnap/tracker.c  | 14 ++++++++++++++
 2 files changed, 31 insertions(+)
drivers/block/blksnap/snapshot.c +17 -0
index 21d94f12b5fc..a7675fdcf359 100644
@@ -149,6 +149,23 @@ int snapshot_add_device(const uuid_t *id, struct tracker *tracker)
 	int ret = 0;
 	struct snapshot *snapshot = NULL;
 
+#ifdef CONFIG_BLK_DEV_INTEGRITY
+	if (tracker->orig_bdev->bd_disk->queue->integrity.profile) {
+		pr_err("Blksnap is not compatible with data integrity\n");
+		ret = -EPERM;
+		goto out_up;
+	} else
+		pr_debug("Data integrity not found\n");
+#endif
+
+#ifdef CONFIG_BLK_INLINE_ENCRYPTION
+	if (tracker->orig_bdev->bd_disk->queue->crypto_profile) {
+		pr_err("Blksnap is not compatible with hardware inline encryption\n");
+		ret = -EPERM;
+		goto out_up;
+	} else
+		pr_debug("Inline encryption not found\n");
+#endif
 	snapshot = snapshot_get_by_id(id);
 	if (!snapshot)
 		return -ESRCH;
drivers/block/blksnap/tracker.c +14 -0
index 2b8978a2f42e..b38ead9afa69 100644
@@ -57,6 +57,20 @@ static bool tracker_submit_bio(struct bio *bio)
 	if (diff_area_is_corrupted(tracker->diff_area))
 		return false;
 
+#ifdef CONFIG_BLK_INLINE_ENCRYPTION
+	if (bio->bi_crypt_context) {
+		pr_err_once("Hardware inline encryption is not supported\n");
+		diff_area_set_corrupted(tracker->diff_area, -EPERM);
+		return false;
+	}
+#endif
+#ifdef CONFIG_BLK_DEV_INTEGRITY
+	if (bio->bi_integrity) {
+		pr_err_once("Data integrity is not supported\n");
+		diff_area_set_corrupted(tracker->diff_area, -EPERM);
+		return false;
+	}
+#endif
 	return diff_area_cow(bio, tracker->diff_area, &copy_iter);
 }
 
Signature · 1 line
2.20.1
#17 lore raw

Re: [PATCH v6 11/11] blksnap: prevents using devices with data integrity or inline encryption

Quoted 3 lines · Sergei Shtepa

There is an opinion that the use of the blksnap module may violate the security of encrypted data. The difference storage file may be located on an unreliable disk or even network storage.

I think this misses the point slightly. The main problem is that blksnap writes data in plaintext that is supposed to be encrypted, as indicated by the bio having an encryption context. That's just what it does, at least based on the last patchset; it's not just "an opinion". See
https://lore.kernel.org/linux-block/[email protected]/

drivers/block/blksnap/tracker.c static bool tracker_submit_bio(struct bio *bio) · line 66

Quoted 7 lines
drivers/block/blksnap/tracker.c +7 -0
+#ifdef CONFIG_BLK_INLINE_ENCRYPTION
+	if (bio->bi_crypt_context) {
+		pr_err_once("Hardware inline encryption is not supported\n");
+		diff_area_set_corrupted(tracker->diff_area, -EPERM);
+		return false;
+	}
+#endif

The error message for ->bi_crypt_context being set should say "Inline encryption", not "Hardware inline encryption". The submitter of the bio may have intended to use blk-crypto-fallback.

Anyway, this patch is better than ignoring the problem. It's worth noting, though, that this patch does not prevent blksnap from being set up on a block device on which blk-crypto-fallback is already being used (or will be used). When that happens, I/O will suddenly start failing. For usability reasons, ideally that would be prevented somehow.

- Eric

#18 lore raw

Re: [PATCH v6 11/11] blksnap: prevents using devices with data integrity or inline encryption

Quoted 9 lines · Eric Biggers
Quoted 3 lines · Sergei Shtepa

There is an opinion that the use of the blksnap module may violate the security of encrypted data. The difference storage file may be located on an unreliable disk or even network storage.

I think this misses the point slightly. The main problem is that blksnap writes data in plaintext that is supposed to be encrypted, as indicated by the bio having an encryption context. That's just what it does, at least based on the last patchset; it's not just "an opinion". See
https://lore.kernel.org/linux-block/[email protected]/

Thanks Eric. Perhaps I formulated the thought inaccurately. The point is that blksnap should not be compatible with blk-crypto. Changes in version 6 do not allow to take a snapshot with a device on which the encryption context is detected. Additionally, protection is implemented in the bio handling code. For bio with bi_crypt_context, the COW algorithm is not executed.

Quoted 11 lines

drivers/block/blksnap/tracker.c static bool tracker_submit_bio(struct bio *bio) · line 66

Quoted 8 lines
drivers/block/blksnap/tracker.c +7 -0
+#ifdef CONFIG_BLK_INLINE_ENCRYPTION
+	if (bio->bi_crypt_context) {
+		pr_err_once("Hardware inline encryption is not supported\n");
+		diff_area_set_corrupted(tracker->diff_area, -EPERM);
+		return false;
+	}
+#endif

The error message for ->bi_crypt_context being set should say "Inline encryption", not "Hardware inline encryption". The submitter of the bio may have intended to use blk-crypto-fallback.

I was looking at the blk-crypto-fallback code. I tested the work in this case. Encryption is performed before the bio gets to the block layer. So, the filter receives cloned bios with already encrypted data. Therefore, the text of the message is correct.

But I haven't tested the code on a device where hardware inline encryption is available. I would be glad if anyone could help with this.

Quoted 6 lines

Anyway, this patch is better than ignoring the problem. It's worth noting, though, that this patch does not prevent blksnap from being set up on a block device on which blk-crypto-fallback is already being used (or will be used). When that happens, I/O will suddenly start failing. For usability reasons, ideally that would be prevented somehow.

I didn't observe any failures during testing. It's just that the snapshot image shows files with encrypted names and data. Backup in this case is useless. Unfortunately, there is no way to detect a blk-crypto-fallback on the block device filter level.

Maybe my tests aren't enough. The next step I think would be great to add new tests to xfstests.

#19 lore raw

Re: [PATCH v6 11/11] blksnap: prevents using devices with data integrity or inline encryption

Quoted 9 lines · Sergei Shtepa

But I haven't tested the code on a device where hardware inline encryption is available. I would be glad if anyone could help with this.

Quoted 6 lines

Anyway, this patch is better than ignoring the problem. It's worth noting, though, that this patch does not prevent blksnap from being set up on a block device on which blk-crypto-fallback is already being used (or will be used). When that happens, I/O will suddenly start failing. For usability reasons, ideally that would be prevented somehow.

Quoted 4 lines

I didn't observe any failures during testing. It's just that the snapshot image shows files with encrypted names and data. Backup in this case is useless. Unfortunately, there is no way to detect a blk-crypto-fallback on the block device filter level.

Huh, I thought that this patch is supposed to exclude blk-crypto-fallback too. __submit_bio() calls bio->bi_bdev->bd_filter->ops->submit_bio(bio) before blk_crypto_bio_prep(), so doesn't your check of ->bi_crypt_context exclude blk-crypto-fallback?

I think you're right that it might actually be fine to use blksnap with blk-crypto-fallback, provided that the encryption is done first. I would like to see a proper explanation of that, though. And we still have this patch which claims that it doesn't work, which is confusing.

- Eric

#20 lore raw

Re: [PATCH v6 11/11] blksnap: prevents using devices with data integrity or inline encryption

Quoted 8 lines · Eric Biggers
Quoted 7 lines · Sergei Shtepa

But I haven't tested the code on a device where hardware inline encryption is available. I would be glad if anyone could help with this.

Quoted 5 lines

Anyway, this patch is better than ignoring the problem. It's worth noting, though, that this patch does not prevent blksnap from being set up on a block device on which blk-crypto-fallback is already being used (or will be used). When that happens, I/O will suddenly start failing. For usability reasons, ideally that would be prevented somehow.

Quoted 8 lines
Quoted 4 lines

I didn't observe any failures during testing. It's just that the snapshot image shows files with encrypted names and data. Backup in this case is useless. Unfortunately, there is no way to detect a blk-crypto-fallback on the block device filter level.

Huh, I thought that this patch is supposed to exclude blk-crypto-fallback too. __submit_bio() calls bio->bi_bdev->bd_filter->ops->submit_bio(bio) before blk_crypto_bio_prep(), so doesn't your check of ->bi_crypt_context exclude blk-crypto-fallback?

Thank you, Eric. You're right.
The filter handle unencrypted data when using blk-crypto-fallback. Indeed, the I/O unit has an encryption context.

And yes, the word "Hardware" is not necessary.
- pr_err_once("Hardware inline encryption is not supported\n");
+ pr_err_once("Inline encryption is not supported\n");

Quoted 5 lines

I think you're right that it might actually be fine to use blksnap with blk-crypto-fallback, provided that the encryption is done first. I would like to see a proper explanation of that, though. And we still have this patch which claims that it doesn't work, which is confusing.

I found a bug in my test. I was let down by the cache. I redid the test and posted it.

When the bi_crypt_context is detected in the write I/O unit, the snapshot image is marked as corrupted. The COW algorithm is not executed. The blksnap code does not allow data leakage.

For a disk with hardware encryption, a block device cannot be added to the snapshot since the encryption context for the disk will be detected for it. Unfortunately, it is impossible to detect the presence of a blk-crypto-fallback when adding a block device to the snapshot.

So, I think that the patch fully ensures the confidentiality of data when using inline encryption. However, it does not allow to perform a backup for this case.

If we make a filter handling point in the __submit_bio() function after calling blk_crypto_bio_prep(), then this will not change the situation for the case of hardware encryption. But the filter will never know what the blk-crypto-fallback is being used. I have no opinion whether it will be better.

maintainer
#21 lore raw
In reply to Sergei Shtepa
Quoted 8 lines · Sergei Shtepa

From: Sergei Shtepa <[email protected]>

Hi all.

I am happy to offer an improved version of the Block Devices Snapshots Module. It allows creating non-persistent snapshots of any block devices. The main purpose of such snapshots is to provide backups of block devices. See more in Documentation/block/blksnap.rst.

Please stop posting the same version, this is the third one of the morning. What's going on?

Signature · 1 line
Jens Axboe
#22 lore raw

I'm very sorry.

Script get_maintainer.pl returns a very large list. I get "Error: too many recipients from 86.49.140.21" when trying to send an email from the smtp.migadu.com.

But it seems that for the third time it was possible to send a whole set of patches.

I'm sorry for the inconvenience.
Sending patches by mail gives me pain...
It seems that I have already gone through all the rakes, but there are new ones.