From: Lennart Poettering Date: Mon, 18 May 2020 16:31:04 +0000 (+0200) Subject: blockdev: add helper for locking whole block device X-Git-Tag: v246-rc1~336^2~3 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=ac83e5aeca7ca4eff3de6ef6d9a55b71b6eb10b1;p=thirdparty%2Fsystemd.git blockdev: add helper for locking whole block device --- diff --git a/src/basic/blockdev-util.c b/src/basic/blockdev-util.c index 54431f5d0fb..5f8212685b7 100644 --- a/src/basic/blockdev-util.c +++ b/src/basic/blockdev-util.c @@ -1,5 +1,6 @@ /* SPDX-License-Identifier: LGPL-2.1+ */ +#include #include #include "alloc-util.h" @@ -187,3 +188,29 @@ int get_block_device_harder(const char *path, dev_t *ret) { return 1; } + +int lock_whole_block_device(dev_t devt, int operation) { + _cleanup_free_ char *whole_node = NULL; + _cleanup_close_ int lock_fd = -1; + dev_t whole_devt; + int r; + + /* Let's get a BSD file lock on the whole block device, as per: https://systemd.io/BLOCK_DEVICE_LOCKING */ + + r = block_get_whole_disk(devt, &whole_devt); + if (r < 0) + return r; + + r = device_path_make_major_minor(S_IFBLK, whole_devt, &whole_node); + if (r < 0) + return r; + + lock_fd = open(whole_node, O_RDONLY|O_CLOEXEC|O_NONBLOCK); + if (lock_fd < 0) + return -errno; + + if (flock(lock_fd, operation) < 0) + return -errno; + + return TAKE_FD(lock_fd); +} diff --git a/src/basic/blockdev-util.h b/src/basic/blockdev-util.h index 6d8a796568e..1e7588f71ca 100644 --- a/src/basic/blockdev-util.h +++ b/src/basic/blockdev-util.h @@ -18,3 +18,5 @@ int block_get_originating(dev_t d, dev_t *ret); int get_block_device(const char *path, dev_t *dev); int get_block_device_harder(const char *path, dev_t *dev); + +int lock_whole_block_device(dev_t devt, int operation);