1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
3 #include <linux/blkpg.h>
10 #include "sd-device.h"
12 #include "alloc-util.h"
13 #include "blockdev-util.h"
14 #include "btrfs-util.h"
15 #include "device-private.h"
16 #include "device-util.h"
17 #include "devnum-util.h"
18 #include "dirent-util.h"
19 #include "errno-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "string-util.h"
27 static int fd_get_devnum(int fd
, BlockDeviceLookupFlag flags
, dev_t
*ret
) {
35 if (fstat(fd
, &st
) < 0)
38 if (S_ISBLK(st
.st_mode
))
40 else if (!FLAGS_SET(flags
, BLOCK_DEVICE_LOOKUP_BACKING
))
42 else if (!S_ISREG(st
.st_mode
) && !S_ISDIR(st
.st_mode
))
44 else if (major(st
.st_dev
) != 0)
47 /* If major(st.st_dev) is zero, this might mean we are backed by btrfs, which needs special
48 * handing, to get the backing device node. */
50 r
= btrfs_get_block_device_fd(fd
, &devnum
);
51 if (r
== -ENOTTY
) /* not btrfs */
61 int block_device_is_whole_disk(sd_device
*dev
) {
66 r
= device_in_subsystem(dev
, "block");
72 return device_is_devtype(dev
, "disk");
75 int block_device_get_whole_disk(sd_device
*dev
, sd_device
**ret
) {
81 /* Do not unref returned sd_device object. */
83 r
= block_device_is_whole_disk(dev
);
87 r
= sd_device_get_parent(dev
, &dev
);
88 if (r
== -ENOENT
) /* Already removed? Let's return a recognizable error. */
93 r
= block_device_is_whole_disk(dev
);
104 int block_device_get_originating(sd_device
*dev
, sd_device
**ret
) {
105 _cleanup_(sd_device_unrefp
) sd_device
*first_found
= NULL
;
107 dev_t devnum
= 0; /* avoid false maybe-uninitialized warning */
109 /* For the specified block device tries to chase it through the layers, in case LUKS-style DM
110 * stacking is used, trying to find the next underlying layer. */
115 FOREACH_DEVICE_CHILD_WITH_SUFFIX(dev
, child
, suffix
) {
116 sd_device
*child_whole_disk
;
119 if (!path_startswith(suffix
, "slaves"))
122 if (block_device_get_whole_disk(child
, &child_whole_disk
) < 0)
125 if (sd_device_get_devnum(child_whole_disk
, &n
) < 0)
129 first_found
= sd_device_ref(child
);
134 /* We found a device backed by multiple other devices. We don't really support automatic
135 * discovery on such setups, with the exception of dm-verity partitions. In this case there
136 * are two backing devices: the data partition and the hash partition. We are fine with such
137 * setups, however, only if both partitions are on the same physical device. Hence, let's
138 * verify this by iterating over every node in the 'slaves/' directory and comparing them with
139 * the first that gets returned by readdir(), to ensure they all point to the same device. */
147 *ret
= TAKE_PTR(first_found
);
151 int block_device_new_from_fd(int fd
, BlockDeviceLookupFlag flags
, sd_device
**ret
) {
152 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
159 r
= fd_get_devnum(fd
, flags
, &devnum
);
163 r
= sd_device_new_from_devnum(&dev
, 'b', devnum
);
167 if (FLAGS_SET(flags
, BLOCK_DEVICE_LOOKUP_ORIGINATING
)) {
168 _cleanup_(sd_device_unrefp
) sd_device
*dev_origin
= NULL
;
169 sd_device
*dev_whole_disk
;
171 r
= block_device_get_whole_disk(dev
, &dev_whole_disk
);
175 r
= block_device_get_originating(dev_whole_disk
, &dev_origin
);
177 device_unref_and_replace(dev
, dev_origin
);
178 else if (r
!= -ENOENT
)
182 if (FLAGS_SET(flags
, BLOCK_DEVICE_LOOKUP_WHOLE_DISK
)) {
183 sd_device
*dev_whole_disk
;
185 r
= block_device_get_whole_disk(dev
, &dev_whole_disk
);
189 *ret
= sd_device_ref(dev_whole_disk
);
193 *ret
= sd_device_ref(dev
);
197 int block_device_new_from_path(const char *path
, BlockDeviceLookupFlag flags
, sd_device
**ret
) {
198 _cleanup_close_
int fd
= -EBADF
;
203 fd
= open(path
, O_CLOEXEC
|O_PATH
);
207 return block_device_new_from_fd(fd
, flags
, ret
);
210 int block_get_whole_disk(dev_t d
, dev_t
*ret
) {
211 char p
[SYS_BLOCK_PATH_MAX("/partition")];
212 _cleanup_free_
char *s
= NULL
;
221 /* If it has a queue this is good enough for us */
222 xsprintf_sys_block_path(p
, "/queue", d
);
223 if (access(p
, F_OK
) >= 0) {
230 /* If it is a partition find the originating device */
231 xsprintf_sys_block_path(p
, "/partition", d
);
232 if (access(p
, F_OK
) < 0)
235 /* Get parent dev_t */
236 xsprintf_sys_block_path(p
, "/../dev", d
);
237 r
= read_one_line_file(p
, &s
);
241 r
= parse_devnum(s
, &devt
);
245 /* Only return this if it is really good enough for us. */
246 xsprintf_sys_block_path(p
, "/queue", devt
);
247 if (access(p
, F_OK
) < 0)
254 int get_block_device_fd(int fd
, dev_t
*ret
) {
261 /* Gets the block device directly backing a file system. If the block device is encrypted, returns
262 * the device mapper block device. */
267 if (major(st
.st_dev
) != 0) {
272 r
= btrfs_get_block_device_fd(fd
, ret
);
273 if (r
!= -ENOTTY
) /* ENOTTY: not btrfs */
280 int get_block_device(const char *path
, dev_t
*ret
) {
281 _cleanup_close_
int fd
= -EBADF
;
286 fd
= open(path
, O_RDONLY
|O_NOFOLLOW
|O_CLOEXEC
);
290 return get_block_device_fd(fd
, ret
);
293 int block_get_originating(dev_t dt
, dev_t
*ret
) {
294 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
, *origin
= NULL
;
299 r
= sd_device_new_from_devnum(&dev
, 'b', dt
);
303 r
= block_device_get_originating(dev
, &origin
);
307 return sd_device_get_devnum(origin
, ret
);
310 int get_block_device_harder_fd(int fd
, dev_t
*ret
) {
316 /* Gets the backing block device for a file system, and handles LUKS encrypted file systems, looking for its
317 * immediate parent, if there is one. */
319 r
= get_block_device_fd(fd
, ret
);
323 r
= block_get_originating(*ret
, ret
);
325 log_debug_errno(r
, "Failed to chase block device, ignoring: %m");
330 int get_block_device_harder(const char *path
, dev_t
*ret
) {
331 _cleanup_close_
int fd
= -EBADF
;
336 fd
= open(path
, O_RDONLY
|O_NOFOLLOW
|O_CLOEXEC
);
340 return get_block_device_harder_fd(fd
, ret
);
343 int lock_whole_block_device(dev_t devt
, int operation
) {
344 _cleanup_close_
int lock_fd
= -EBADF
;
348 /* Let's get a BSD file lock on the whole block device, as per: https://systemd.io/BLOCK_DEVICE_LOCKING */
350 r
= block_get_whole_disk(devt
, &whole_devt
);
354 lock_fd
= r
= device_open_from_devnum(S_IFBLK
, whole_devt
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
, NULL
);
358 if (flock(lock_fd
, operation
) < 0)
361 return TAKE_FD(lock_fd
);
364 int blockdev_partscan_enabled(sd_device
*dev
) {
368 /* Checks if partition scanning is correctly enabled on the block device.
370 * The 'GENHD_FL_NO_PART_SCAN' flag was introduced by
371 * https://github.com/torvalds/linux/commit/d27769ec3df1a8de9ca450d2dcd72d1ab259ba32 (v3.2).
372 * But at that time, the flag is also effectively implied when 'minors' element of 'struct gendisk'
373 * is 1, which can be check with 'ext_range' sysfs attribute. Explicit flag ('GENHD_FL_NO_PART_SCAN')
374 * can be obtained from 'capability' sysattr.
376 * With https://github.com/torvalds/linux/commit/46e7eac647b34ed4106a8262f8bedbb90801fadd (v5.17),
377 * the flag is renamed to GENHD_FL_NO_PART.
379 * With https://github.com/torvalds/linux/commit/1ebe2e5f9d68e94c524aba876f27b945669a7879 (v5.17),
380 * we can check the flag from 'ext_range' sysfs attribute directly.
382 * With https://github.com/torvalds/linux/commit/430cc5d3ab4d0ba0bd011cfbb0035e46ba92920c (v5.17),
383 * the value of GENHD_FL_NO_PART is changed from 0x0200 to 0x0004. 💣💣💣
384 * Note, the new value was used by the GENHD_FL_MEDIA_CHANGE_NOTIFY flag, which was introduced by
385 * 86ce18d7b7925bfd6b64c061828ca2a857ee83b8 (v2.6.22), and removed by
386 * 9243c6f3e012a92dd900d97ef45efaf8a8edc448 (v5.7). If we believe the commit message of
387 * e81cd5a983bb35dabd38ee472cf3fea1c63e0f23, the flag was never used. So, fortunately, we can use
388 * both the new and old values safely.
390 * With https://github.com/torvalds/linux/commit/b9684a71fca793213378dd410cd11675d973eaa1 (v5.19),
391 * another flag GD_SUPPRESS_PART_SCAN is introduced for loopback block device, and partition scanning
392 * is done only when both GENHD_FL_NO_PART and GD_SUPPRESS_PART_SCAN are not set. Before the commit,
393 * LO_FLAGS_PARTSCAN flag was directly tied with GENHD_FL_NO_PART. But with this change now it is
394 * tied with GD_SUPPRESS_PART_SCAN. So, LO_FLAGS_PARTSCAN cannot be obtained from 'ext_range'
395 * sysattr, which corresponds to GENHD_FL_NO_PART, and we need to read 'loop/partscan'. 💣💣💣
397 * With https://github.com/torvalds/linux/commit/73a166d9749230d598320fdae3b687cdc0e2e205 (v6.3),
398 * the GD_SUPPRESS_PART_SCAN flag is also introduced for userspace block device (ublk). Though, not
399 * sure if we should support the device...
401 * With https://github.com/torvalds/linux/commit/e81cd5a983bb35dabd38ee472cf3fea1c63e0f23 (v6.3),
402 * the 'capability' sysfs attribute is deprecated, hence we cannot check flags from it. 💣💣💣
404 * With https://github.com/torvalds/linux/commit/a4217c6740dc64a3eb6815868a9260825e8c68c6 (v6.10,
405 * backported to v6.6+), the partscan status is directly exposed as 'partscan' sysattr.
407 * To support both old and new kernels, we need to do the following:
408 * 1) check 'partscan' sysfs attribute where the information is made directly available,
409 * 2) check if the blockdev refers to a partition, where partscan is not supported,
410 * 3) check 'loop/partscan' sysfs attribute for loopback block devices, and if '0' we can conclude
411 * partition scanning is disabled,
412 * 4) check 'ext_range' sysfs attribute, and if '1' we can conclude partition scanning is disabled,
413 * 5) otherwise check 'capability' sysfs attribute for ancient version. */
417 /* For v6.10 or newer. */
418 r
= device_get_sysattr_bool(dev
, "partscan");
422 /* Partition block devices never have partition scanning on, there's no concept of sub-partitions for
424 r
= device_is_devtype(dev
, "partition");
430 /* For loopback block device, especially for v5.19 or newer. Even if this is enabled, we also need to
431 * check GENHD_FL_NO_PART flag through 'ext_range' and 'capability' sysfs attributes below. */
432 if (device_get_sysattr_bool(dev
, "loop/partscan") == 0)
435 r
= device_get_sysattr_int(dev
, "ext_range", &ext_range
);
436 if (r
== -ENOENT
) /* If the ext_range file doesn't exist then we are most likely looking at a
437 * partition block device, not the whole block device. And that means we have no
438 * partition scanning on for it (we do for its parent, but not for the partition
444 if (ext_range
<= 1) /* The value should be always positive, but the kernel uses '%d' for the
445 * attribute. Let's gracefully handle zero or negative. */
448 r
= device_get_sysattr_unsigned_full(dev
, "capability", 16, &capability
);
454 #define GENHD_FL_NO_PART_OLD 0x0200
455 #define GENHD_FL_NO_PART_NEW 0x0004
456 /* If one of the NO_PART flags is set, part scanning is definitely off. */
457 if ((capability
& (GENHD_FL_NO_PART_OLD
| GENHD_FL_NO_PART_NEW
)) != 0)
460 /* Otherwise, assume part scanning is on, we have no further checks available. Assume the best. */
464 int blockdev_partscan_enabled_fd(int fd
) {
465 _cleanup_(sd_device_unrefp
) sd_device
*dev
= NULL
;
470 r
= block_device_new_from_fd(fd
, 0, &dev
);
474 return blockdev_partscan_enabled(dev
);
477 static int blockdev_is_encrypted(const char *sysfs_path
, unsigned depth_left
) {
478 _cleanup_free_
char *p
= NULL
, *uuids
= NULL
;
479 _cleanup_closedir_
DIR *d
= NULL
;
480 int r
, found_encrypted
= false;
487 p
= path_join(sysfs_path
, "dm/uuid");
491 r
= read_one_line_file(p
, &uuids
);
496 /* The DM device's uuid attribute is prefixed with "CRYPT-" if this is a dm-crypt device. */
497 if (startswith(uuids
, "CRYPT-"))
501 /* Not a dm-crypt device itself. But maybe it is on top of one? Follow the links in the "slaves/"
505 p
= path_join(sysfs_path
, "slaves");
511 if (errno
== ENOENT
) /* Doesn't have underlying devices */
518 _cleanup_free_
char *q
= NULL
;
522 de
= readdir_no_dot(d
);
527 break; /* No more underlying devices */
530 q
= path_join(p
, de
->d_name
);
534 r
= blockdev_is_encrypted(q
, depth_left
- 1);
537 if (r
== 0) /* we found one that is not encrypted? then propagate that immediately */
540 found_encrypted
= true;
543 return found_encrypted
;
546 int fd_is_encrypted(int fd
) {
547 char p
[SYS_BLOCK_PATH_MAX("")];
551 r
= get_block_device_fd(fd
, &devt
);
554 if (r
== 0) /* doesn't have a block device */
557 xsprintf_sys_block_path(p
, NULL
, devt
);
559 return blockdev_is_encrypted(p
, 10 /* safety net: maximum recursion depth */);
562 int path_is_encrypted(const char *path
) {
563 char p
[SYS_BLOCK_PATH_MAX("")];
567 r
= get_block_device(path
, &devt
);
570 if (r
== 0) /* doesn't have a block device */
573 xsprintf_sys_block_path(p
, NULL
, devt
);
575 return blockdev_is_encrypted(p
, 10 /* safety net: maximum recursion depth */);
578 int fd_get_whole_disk(int fd
, bool backing
, dev_t
*ret
) {
585 r
= fd_get_devnum(fd
, backing
? BLOCK_DEVICE_LOOKUP_BACKING
: 0, &devt
);
589 return block_get_whole_disk(devt
, ret
);
592 int path_get_whole_disk(const char *path
, bool backing
, dev_t
*ret
) {
593 _cleanup_close_
int fd
= -EBADF
;
595 fd
= open(path
, O_CLOEXEC
|O_PATH
);
599 return fd_get_whole_disk(fd
, backing
, ret
);
602 int block_device_add_partition(
613 struct blkpg_partition bp
= {
619 struct blkpg_ioctl_arg ba
= {
620 .op
= BLKPG_ADD_PARTITION
,
622 .datalen
= sizeof(bp
),
625 if (strlen(name
) >= sizeof(bp
.devname
))
628 strcpy(bp
.devname
, name
);
630 return RET_NERRNO(ioctl(fd
, BLKPG
, &ba
));
633 int block_device_remove_partition(
642 struct blkpg_partition bp
= {
646 struct blkpg_ioctl_arg ba
= {
647 .op
= BLKPG_DEL_PARTITION
,
649 .datalen
= sizeof(bp
),
652 if (strlen(name
) >= sizeof(bp
.devname
))
655 strcpy(bp
.devname
, name
);
657 return RET_NERRNO(ioctl(fd
, BLKPG
, &ba
));
660 int block_device_resize_partition(
669 struct blkpg_partition bp
= {
675 struct blkpg_ioctl_arg ba
= {
676 .op
= BLKPG_RESIZE_PARTITION
,
678 .datalen
= sizeof(bp
),
681 return RET_NERRNO(ioctl(fd
, BLKPG
, &ba
));
684 int partition_enumerator_new(sd_device
*dev
, sd_device_enumerator
**ret
) {
685 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
692 /* Refuse invocation on partition block device, insist on "whole" device */
693 r
= block_device_is_whole_disk(dev
);
697 return -ENXIO
; /* return a recognizable error */
699 r
= sd_device_enumerator_new(&e
);
703 r
= sd_device_enumerator_allow_uninitialized(e
);
707 r
= sd_device_enumerator_add_match_parent(e
, dev
);
711 r
= sd_device_get_sysname(dev
, &s
);
715 /* Also add sysname check for safety. Hopefully, this also improves performance. */
716 s
= strjoina(s
, "*");
717 r
= sd_device_enumerator_add_match_sysname(e
, s
);
721 r
= sd_device_enumerator_add_match_subsystem(e
, "block", /* match = */ true);
725 r
= sd_device_enumerator_add_match_property(e
, "DEVTYPE", "partition");
733 int block_device_remove_all_partitions(sd_device
*dev
, int fd
) {
734 _cleanup_(sd_device_enumerator_unrefp
) sd_device_enumerator
*e
= NULL
;
735 _cleanup_(sd_device_unrefp
) sd_device
*dev_unref
= NULL
;
736 _cleanup_close_
int fd_close
= -EBADF
;
737 bool has_partitions
= false;
740 assert(dev
|| fd
>= 0);
743 r
= block_device_new_from_fd(fd
, 0, &dev_unref
);
750 r
= partition_enumerator_new(dev
, &e
);
755 fd_close
= sd_device_open(dev
, O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
|O_RDONLY
);
762 FOREACH_DEVICE(e
, part
) {
763 const char *v
, *devname
;
766 has_partitions
= true;
768 r
= sd_device_get_devname(part
, &devname
);
772 r
= sd_device_get_property_value(part
, "PARTN", &v
);
776 r
= safe_atoi(v
, &nr
);
780 r
= btrfs_forget_device(devname
);
781 if (r
< 0 && r
!= -ENOENT
)
782 log_debug_errno(r
, "Failed to forget btrfs device %s, ignoring: %m", devname
);
784 r
= block_device_remove_partition(fd
, devname
, nr
);
786 log_debug("Kernel removed partition %s before us, ignoring", devname
);
790 log_debug_errno(r
, "Failed to remove partition %s: %m", devname
);
795 log_debug("Removed partition %s", devname
);
798 return k
< 0 ? k
: has_partitions
;
802 int blockdev_reread_partition_table(sd_device
*dev
) {
803 _cleanup_close_
int fd
= -EBADF
;
807 /* Try to re-read the partition table. This only succeeds if none of the devices is busy. */
809 fd
= sd_device_open(dev
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_NOCTTY
);
813 if (flock(fd
, LOCK_EX
|LOCK_NB
) < 0)
816 if (ioctl(fd
, BLKRRPART
, 0) < 0)
822 int blockdev_get_sector_size(int fd
, uint32_t *ret
) {
828 if (ioctl(fd
, BLKSSZGET
, &ssz
) < 0)
830 if (ssz
<= 0) /* make sure the field is initialized */
831 return log_debug_errno(SYNTHETIC_ERRNO(EIO
), "Block device reported invalid sector size %i.", ssz
);
837 int blockdev_get_device_size(int fd
, uint64_t *ret
) {
843 /* This is just a type-safe wrapper around BLKGETSIZE64 that gets us around having to include messy linux/fs.h in various clients */
845 if (ioctl(fd
, BLKGETSIZE64
, &sz
) < 0)
852 int blockdev_get_root(int level
, dev_t
*ret
) {
853 _cleanup_free_
char *p
= NULL
;
857 /* Returns the device node backing the root file system. Traces through
858 * dm-crypt/dm-verity/... Returns > 0 and the devno of the device on success. If there's no block
859 * device (or multiple) returns 0 and a devno of 0. Failure otherwise.
861 * If the root mount has been replaced by some form of volatile file system (overlayfs), the original
862 * root block device node is symlinked in /run/systemd/volatile-root. Let's read that here. */
863 r
= readlink_malloc("/run/systemd/volatile-root", &p
);
864 if (r
== -ENOENT
) { /* volatile-root not found */
865 r
= get_block_device_harder("/", &devno
);
867 return btrfs_log_dev_root(level
, r
, "root file system");
869 return log_full_errno(level
, r
, "Failed to determine block device of root file system: %m");
870 if (r
== 0) { /* Not backed by a single block device. (Could be NFS or so, or could be multi-device RAID or so) */
871 r
= get_block_device_harder("/usr", &devno
);
873 return btrfs_log_dev_root(level
, r
, "/usr");
875 return log_full_errno(level
, r
, "Failed to determine block device of /usr/ file system: %m");
876 if (r
== 0) { /* /usr/ not backed by single block device, either. */
877 log_debug("Neither root nor /usr/ file system are on a (single) block device.");
886 return log_full_errno(level
, r
, "Failed to read symlink /run/systemd/volatile-root: %m");
889 r
= device_path_parse_major_minor(p
, &m
, &devno
);
891 return log_full_errno(level
, r
, "Failed to parse major/minor device node: %m");
893 return log_full_errno(level
, SYNTHETIC_ERRNO(ENOTBLK
), "Volatile root device is of wrong type.");