| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
""" |
| 19 |
This module contains the implementation of the calling side of several kernel |
| 20 |
ioctl functions, as well as Python object representations of related C structs. |
| 21 |
|
| 22 |
For convenience reasons, many of the functions can be called implicitly by |
| 23 |
calling utility functions on a :class:`btrfs.ctree.FileSystem` object. |
| 24 |
""" |
| 25 |
|
| 26 |
from collections import namedtuple |
| 27 |
import array |
| 28 |
import btrfs |
| 29 |
import errno |
| 30 |
import fcntl |
| 31 |
import os |
| 32 |
import platform |
| 33 |
import struct |
| 34 |
import uuid |
| 35 |
|
| 36 |
ULLONG_MAX = (1 << 64) - 1 |
| 37 |
ULONG_MAX = (1 << 32) - 1 |
| 38 |
|
| 39 |
BTRFS_IOCTL_MAGIC = 0x94 |
| 40 |
|
| 41 |
_IOC_NRBITS = 8 |
| 42 |
_IOC_TYPEBITS = 8 |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
arch = platform.machine() |
| 48 |
if arch in ('x86_64', 'i686', 'i386', 'i586', 'amd64', 'ia64', 'm68k', 'i486') \ |
| 49 |
or arch.startswith(('aarch64', 'arm', 's390')): |
| 50 |
_IOC_SIZEBITS = 14 |
| 51 |
_IOC_DIRBITS = 2 |
| 52 |
_IOC_NONE = 0 |
| 53 |
_IOC_WRITE = 1 |
| 54 |
_IOC_READ = 2 |
| 55 |
elif arch in ('powerpc', 'alpha') or arch.startswith(('sparc', 'ppc', 'mips')): |
| 56 |
_IOC_SIZEBITS = 13 |
| 57 |
_IOC_DIRBITS = 3 |
| 58 |
_IOC_NONE = 1 |
| 59 |
_IOC_READ = 2 |
| 60 |
_IOC_WRITE = 4 |
| 61 |
elif arch == 'hppa' or arch.startswith('parisc'): |
| 62 |
_IOC_SIZEBITS = 14 |
| 63 |
_IOC_DIRBITS = 2 |
| 64 |
_IOC_NONE = 0 |
| 65 |
_IOC_WRITE = 2 |
| 66 |
_IOC_READ = 1 |
| 67 |
else: |
| 68 |
raise Exception("Unsupported machine type {}, please report as bug.".format(arch)) |
| 69 |
|
| 70 |
_IOC_NRSHIFT = 0 |
| 71 |
_IOC_TYPESHIFT = _IOC_NRSHIFT + _IOC_NRBITS |
| 72 |
_IOC_SIZESHIFT = _IOC_TYPESHIFT + _IOC_TYPEBITS |
| 73 |
_IOC_DIRSHIFT = _IOC_SIZESHIFT + _IOC_SIZEBITS |
| 74 |
|
| 75 |
|
| 76 |
def _IOC(_dir, _type, nr, size): |
| 77 |
return (_dir << _IOC_DIRSHIFT) | (_type << _IOC_TYPESHIFT) | \ |
| 78 |
(nr << _IOC_NRSHIFT) | (size << _IOC_SIZESHIFT) |
| 79 |
|
| 80 |
|
| 81 |
def _IO(_type, nr): |
| 82 |
return _IOC(_IOC_NONE, _type, nr, 0) |
| 83 |
|
| 84 |
|
| 85 |
def _IOR(_type, nr, _struct): |
| 86 |
return _IOC(_IOC_READ, _type, nr, _struct.size) |
| 87 |
|
| 88 |
|
| 89 |
def _IOW(_type, nr, _struct): |
| 90 |
return _IOC(_IOC_WRITE, _type, nr, _struct.size) |
| 91 |
|
| 92 |
|
| 93 |
def _IOWR(_type, nr, _struct): |
| 94 |
return _IOC(_IOC_READ | _IOC_WRITE, _type, nr, _struct.size) |
| 95 |
|
| 96 |
|
| 97 |
DEVICE_PATH_NAME_MAX = 1024 |
| 98 |
|
| 99 |
ioctl_fs_info_args = struct.Struct('=QQ16sLLL980x') |
| 100 |
IOC_FS_INFO = _IOR(BTRFS_IOCTL_MAGIC, 31, ioctl_fs_info_args) |
| 101 |
|
| 102 |
|
| 103 |
class FsInfo(object): |
| 104 |
"""Object representation of struct `btrfs_ioctl_fs_info_args`. |
| 105 |
|
| 106 |
:ivar int max_id: Highest device id of currently attached devices. |
| 107 |
:ivar int num_devices: Amount of devices attached to the filesystem. |
| 108 |
:ivar uuid.UUID fsid: Filesystem ID. |
| 109 |
:ivar int nodesize: B-tree node size (same as leaf size). |
| 110 |
:ivar int sectorsize: Smallest allocatable block size in bytes for storing |
| 111 |
data. |
| 112 |
:ivar int clone_alignment: Expected alignment of arguments for clone and |
| 113 |
deduplication ioctls. |
| 114 |
|
| 115 |
.. note:: |
| 116 |
An object of this type should be retrieved by calling the |
| 117 |
:func:`~btrfs.ctree.FileSystem.fs_info` function on a |
| 118 |
:class:`btrfs.ctree.FileSystem` object. |
| 119 |
""" |
| 120 |
def __init__(self, buf): |
| 121 |
self.max_id, self.num_devices, fsid_bytes, self.nodesize, self.sectorsize, \ |
| 122 |
self.clone_alignment = ioctl_fs_info_args.unpack(buf) |
| 123 |
self.fsid = uuid.UUID(bytes=fsid_bytes) |
| 124 |
|
| 125 |
def __str__(self): |
| 126 |
return "max_id {0} num_devices {1} fsid {2} nodesize {3} sectorsize {4} " \ |
| 127 |
"clone_alignment {5}".format(self.max_id, self.num_devices, self.fsid, self.nodesize, |
| 128 |
self.sectorsize, self.clone_alignment) |
| 129 |
|
| 130 |
@staticmethod |
| 131 |
def _pretty_properties(): |
| 132 |
return [ |
| 133 |
(btrfs.utils.pretty_size, 'nodesize'), |
| 134 |
(btrfs.utils.pretty_size, 'sectorsize'), |
| 135 |
(btrfs.utils.pretty_size, 'clone_alignment'), |
| 136 |
] |
| 137 |
|
| 138 |
|
| 139 |
def fs_info(fd): |
| 140 |
"""Call the `BTRFS_IOC_FS_INFO` ioctl. |
| 141 |
|
| 142 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 143 |
:returns: A :class:`FsInfo` object. |
| 144 |
|
| 145 |
.. note:: |
| 146 |
This function should usually be used implicitly by calling the |
| 147 |
:func:`~btrfs.ctree.FileSystem.fs_info` function on a |
| 148 |
:class:`btrfs.ctree.FileSystem` object. |
| 149 |
""" |
| 150 |
buf = bytearray(ioctl_fs_info_args.size) |
| 151 |
fcntl.ioctl(fd, IOC_FS_INFO, buf) |
| 152 |
return FsInfo(buf) |
| 153 |
|
| 154 |
|
| 155 |
ioctl_dev_info_args = struct.Struct('=Q16sQQ3032x{0}s'.format(DEVICE_PATH_NAME_MAX)) |
| 156 |
IOC_DEV_INFO = _IOWR(BTRFS_IOCTL_MAGIC, 30, ioctl_dev_info_args) |
| 157 |
|
| 158 |
|
| 159 |
class DevInfo(object): |
| 160 |
"""Object representation of struct btrfs_ioctl_dev_info_args. |
| 161 |
|
| 162 |
:ivar int devid: Device ID. |
| 163 |
:ivar uuid.UUID uuid: Device UUID. |
| 164 |
:ivar int bytes_used: Amount of allocated bytes on the device. |
| 165 |
:ivar int total_bytes: Device size in bytes. |
| 166 |
:ivar str path: Path to the device node to access this device directly. |
| 167 |
|
| 168 |
.. note:: |
| 169 |
An object of this type should be retrieved by calling the |
| 170 |
:func:`~btrfs.ctree.FileSystem.dev_info` function on a |
| 171 |
:class:`btrfs.ctree.FileSystem` object. |
| 172 |
""" |
| 173 |
def __init__(self, buf): |
| 174 |
self.devid, uuid_bytes, self.bytes_used, self.total_bytes, path_bytes = \ |
| 175 |
ioctl_dev_info_args.unpack(buf) |
| 176 |
self.path = path_bytes.split(b'\0', 1)[0].decode() |
| 177 |
self.uuid = uuid.UUID(bytes=uuid_bytes) |
| 178 |
|
| 179 |
def __str__(self): |
| 180 |
return "devid {0} uuid {1} bytes_used {2} total_bytes {3} path {4}".format( |
| 181 |
self.devid, self.uuid, self.bytes_used, self.total_bytes, self.path) |
| 182 |
|
| 183 |
@staticmethod |
| 184 |
def _pretty_properties(): |
| 185 |
return [ |
| 186 |
(btrfs.utils.pretty_size, 'bytes_used'), |
| 187 |
(btrfs.utils.pretty_size, 'total_bytes'), |
| 188 |
] |
| 189 |
|
| 190 |
|
| 191 |
def dev_info(fd, devid): |
| 192 |
"""Call the `BTRFS_IOC_DEV_INFO` ioctl. |
| 193 |
|
| 194 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 195 |
:param int devid: Device ID of the device to retrieve information about. |
| 196 |
:returns: A :class:`DevInfo` object. |
| 197 |
|
| 198 |
.. note:: |
| 199 |
This function should usually be used implicitly by calling the |
| 200 |
:func:`~btrfs.ctree.FileSystem.dev_info` function on a |
| 201 |
:class:`btrfs.ctree.FileSystem` object. |
| 202 |
""" |
| 203 |
buf = bytearray(ioctl_dev_info_args.size) |
| 204 |
ioctl_dev_info_args.pack_into(buf, 0, devid, b'', 0, 0, b'') |
| 205 |
fcntl.ioctl(fd, IOC_DEV_INFO, buf) |
| 206 |
return DevInfo(buf) |
| 207 |
|
| 208 |
|
| 209 |
ioctl_get_dev_stats = struct.Struct('=QQQ5Q968x') |
| 210 |
IOC_GET_DEV_STATS = _IOWR(BTRFS_IOCTL_MAGIC, 52, ioctl_get_dev_stats) |
| 211 |
|
| 212 |
|
| 213 |
class DevStats(object): |
| 214 |
"""Object representation of struct btrfs_ioctl_get_dev_stats. |
| 215 |
|
| 216 |
:ivar int devid: Device ID. |
| 217 |
:ivar int write_errs: Amount of write errors. |
| 218 |
:ivar int read_errs: Amount of read errors. |
| 219 |
:ivar int flush_errs: Amount of flush errors. |
| 220 |
:ivar int generation_errs: Amount of metadata tree generation mismatch |
| 221 |
errors. |
| 222 |
:ivar int corruption_errs: Amount of checksum failures. |
| 223 |
|
| 224 |
.. note:: |
| 225 |
An object of this type should be retrieved by calling the |
| 226 |
:func:`~btrfs.ctree.FileSystem.dev_stats` function on a |
| 227 |
:class:`btrfs.ctree.FileSystem` object. |
| 228 |
""" |
| 229 |
def __init__(self, buf): |
| 230 |
self.devid, self.nr_items, self.flags, self.write_errs, self.read_errs, \ |
| 231 |
self.flush_errs, self.corruption_errs, self.generation_errs = \ |
| 232 |
ioctl_get_dev_stats.unpack_from(buf) |
| 233 |
|
| 234 |
@property |
| 235 |
def counters(self): |
| 236 |
return { |
| 237 |
'write_errs': self.write_errs, |
| 238 |
'read_errs': self.read_errs, |
| 239 |
'flush_errs': self.flush_errs, |
| 240 |
'corruption_errs': self.corruption_errs, |
| 241 |
'generation_errs': self.generation_errs, |
| 242 |
} |
| 243 |
|
| 244 |
def __str__(self): |
| 245 |
return "devid {0} write_errs {1} read_errs {2} flush_errs {3} corruption_errs {4} " \ |
| 246 |
"generation_errs {5}".format(self.devid, self.write_errs, self.read_errs, |
| 247 |
self.flush_errs, self.corruption_errs, |
| 248 |
self.generation_errs) |
| 249 |
|
| 250 |
|
| 251 |
def dev_stats(fd, devid, reset=False): |
| 252 |
"""Call the `BTRFS_IOC_DEV_STATS` ioctl. |
| 253 |
|
| 254 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 255 |
:param int devid: Device ID of the device to retrieve information about. |
| 256 |
:param bool reset: If true, counters are reset to zero. |
| 257 |
:returns: A :class:`DevStats` object. |
| 258 |
|
| 259 |
.. note:: |
| 260 |
This function should usually be used implicitly by calling the |
| 261 |
:func:`~btrfs.ctree.FileSystem.dev_stats` function on a |
| 262 |
:class:`btrfs.ctree.FileSystem` object. |
| 263 |
""" |
| 264 |
buf = bytearray(ioctl_get_dev_stats.size) |
| 265 |
ioctl_get_dev_stats.pack_into(buf, 0, devid, 5, int(reset), 0, 0, 0, 0, 0) |
| 266 |
fcntl.ioctl(fd, IOC_GET_DEV_STATS, buf) |
| 267 |
return DevStats(buf) |
| 268 |
|
| 269 |
|
| 270 |
ioctl_space_args = struct.Struct('=2Q') |
| 271 |
ioctl_space_info = struct.Struct('=3Q') |
| 272 |
IOC_SPACE_INFO = _IOWR(BTRFS_IOCTL_MAGIC, 20, ioctl_space_args) |
| 273 |
|
| 274 |
SpaceArgs = namedtuple('SpaceArgs', ['space_slots', 'total_spaces']) |
| 275 |
|
| 276 |
|
| 277 |
class SpaceInfo(object): |
| 278 |
"""Object representation of struct btrfs_ioctl_space_info. |
| 279 |
|
| 280 |
In btrfs terminology, a 'space' is the collection of all block groups that |
| 281 |
have identical type and profile flags. For example, Metadata, DUP is a |
| 282 |
'space'. |
| 283 |
|
| 284 |
:ivar int flags: Block group type and profile, e.g. `Data, RAID1`. |
| 285 |
:ivar int total_bytes: Total amount of allocated bytes for this space. |
| 286 |
:ivar int used_bytes: Total amount of bytes used. |
| 287 |
|
| 288 |
.. note:: |
| 289 |
A list of objects of this type should be retrieved by calling the |
| 290 |
:func:`~btrfs.ctree.FileSystem.space_info` function on a |
| 291 |
:class:`btrfs.ctree.FileSystem` object. |
| 292 |
""" |
| 293 |
def __init__(self, buf, pos): |
| 294 |
self.flags, self.total_bytes, self.used_bytes = ioctl_space_info.unpack_from(buf, pos) |
| 295 |
self._type = self.flags & \ |
| 296 |
(btrfs.ctree.BLOCK_GROUP_TYPE_MASK | btrfs.ctree.SPACE_INFO_GLOBAL_RSV) |
| 297 |
self._profile = self.flags & btrfs.ctree.BLOCK_GROUP_PROFILE_MASK |
| 298 |
|
| 299 |
@property |
| 300 |
def type(self): |
| 301 |
"""Only block group type, e.g. `Data`, from flags.""" |
| 302 |
return self._type |
| 303 |
|
| 304 |
@property |
| 305 |
def profile(self): |
| 306 |
"""Only block group profile, e.g. `RAID1`, from flags.""" |
| 307 |
return self._profile |
| 308 |
|
| 309 |
def __str__(self): |
| 310 |
return "{}: total={}, used={}".format( |
| 311 |
self.flags_str, self.total_bytes_str, self.used_bytes_str) |
| 312 |
|
| 313 |
@staticmethod |
| 314 |
def _pretty_properties(): |
| 315 |
return [ |
| 316 |
(btrfs.utils.space_flags_description, 'flags'), |
| 317 |
(btrfs.utils.space_type_description, 'type'), |
| 318 |
(btrfs.utils.space_profile_description, 'profile'), |
| 319 |
(btrfs.utils.pretty_size, 'total_bytes'), |
| 320 |
(btrfs.utils.pretty_size, 'used_bytes'), |
| 321 |
] |
| 322 |
|
| 323 |
|
| 324 |
def _space_args(fd): |
| 325 |
buf = bytearray(ioctl_space_args.size) |
| 326 |
fcntl.ioctl(fd, IOC_SPACE_INFO, buf) |
| 327 |
return SpaceArgs(*ioctl_space_args.unpack(buf)) |
| 328 |
|
| 329 |
|
| 330 |
def space_info(fd): |
| 331 |
"""Call the `BTRFS_IOC_SPACE_INFO` ioctl. |
| 332 |
|
| 333 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 334 |
:returns: A list of :class:`SpaceInfo` objects. |
| 335 |
|
| 336 |
.. note:: |
| 337 |
This function should usually be used implicitly by calling the |
| 338 |
:func:`~btrfs.ctree.FileSystem.space_info` function on a |
| 339 |
:class:`btrfs.ctree.FileSystem` object. |
| 340 |
""" |
| 341 |
args = _space_args(fd) |
| 342 |
buf_size = ioctl_space_args.size + ioctl_space_info.size * args.total_spaces |
| 343 |
buf = bytearray(buf_size) |
| 344 |
ioctl_space_args.pack_into(buf, 0, args.total_spaces, 0) |
| 345 |
fcntl.ioctl(fd, IOC_SPACE_INFO, buf) |
| 346 |
return [SpaceInfo(buf, pos) |
| 347 |
for pos in range(ioctl_space_args.size, buf_size, ioctl_space_info.size)] |
| 348 |
|
| 349 |
|
| 350 |
ioctl_search_key = struct.Struct('=Q6QLLL4x32x') |
| 351 |
ioctl_search_args = struct.Struct('{0}{1}x'.format( |
| 352 |
btrfs.ctree._struct_format(ioctl_search_key), 4096 - ioctl_search_key.size)) |
| 353 |
ioctl_search_header = struct.Struct('=3Q2L') |
| 354 |
IOC_TREE_SEARCH = _IOWR(BTRFS_IOCTL_MAGIC, 17, ioctl_search_args) |
| 355 |
|
| 356 |
SearchHeader = namedtuple('SearchHeader', ['transid', 'objectid', 'offset', 'type', 'len']) |
| 357 |
|
| 358 |
|
| 359 |
def search(fd, tree, min_key=None, max_key=None, |
| 360 |
min_transid=0, max_transid=ULLONG_MAX, |
| 361 |
nr_items=None): |
| 362 |
"""Call the `BTRFS_IOC_TREE_SEARCH` ioctl. |
| 363 |
|
| 364 |
The `TREE_SEARCH` ioctl allow us to directly read btrfs metadata. |
| 365 |
|
| 366 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 367 |
:param int tree: The tree we're searching in. 1 is the tree of tree roots, |
| 368 |
2 is the extent tree, etc... A special tree_id value of 0 will cause a |
| 369 |
search in the subvolume tree that the inode which is passed to the |
| 370 |
ioctl is part of. |
| 371 |
:param btrfs.ctree.Key min_key: Minimum key value for items to return. |
| 372 |
:param btrfs.ctree.Key max_key: Maximum key value for items to return. |
| 373 |
:param int min_transid: Minimum transaction id for the metadata leaf to |
| 374 |
have items included. Defaults to 0. |
| 375 |
:param int max_transid: Maximum transaction id for the metadata leaf to |
| 376 |
have items included. Defaults to 2**64-1. |
| 377 |
:param int nr_items: Maximum amount of items to fetch. Defaults to no |
| 378 |
limit. |
| 379 |
|
| 380 |
:returns: An iterator over search results, containing a search header and |
| 381 |
the item data per item. |
| 382 |
:rtype: Iterator[Tuple[:class:`SearchHeader`, :class:`memoryview`]] |
| 383 |
""" |
| 384 |
return _search(fd, tree, min_key, max_key, min_transid, max_transid, |
| 385 |
nr_items, _v2=False) |
| 386 |
|
| 387 |
|
| 388 |
_ioctl_search_args_v2 = [ |
| 389 |
ioctl_search_key, |
| 390 |
struct.Struct('=Q') |
| 391 |
] |
| 392 |
ioctl_search_args_v2 = struct.Struct('=' + ''.join([btrfs.ctree._struct_format(s)[1:] |
| 393 |
for s in _ioctl_search_args_v2])) |
| 394 |
IOC_TREE_SEARCH_V2 = _IOWR(BTRFS_IOCTL_MAGIC, 17, ioctl_search_args_v2) |
| 395 |
|
| 396 |
|
| 397 |
def search_v2(fd, tree, min_key=None, max_key=None, |
| 398 |
min_transid=0, max_transid=ULLONG_MAX, |
| 399 |
nr_items=None, buf_size=16384): |
| 400 |
"""Call the `BTRFS_IOC_TREE_SEARCH_V2` ioctl. |
| 401 |
|
| 402 |
The `TREE_SEARCH_V2` ioctl allow us to directly read btrfs metadata. |
| 403 |
|
| 404 |
Unlike `TREE_SEARCH`, it allows to use a bigger buffer than 4096 bytes for |
| 405 |
results. This makes it possible to retrieve individual metadata items that |
| 406 |
are bigger than 4kiB, or get more results from a single lookup for |
| 407 |
efficiency reasons. |
| 408 |
|
| 409 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 410 |
:param int tree: The tree we're searching in. 1 is the tree of tree roots, |
| 411 |
2 is the extent tree, etc... A special tree_id value of 0 will cause a |
| 412 |
search in the subvolume tree that the inode which is passed to the |
| 413 |
ioctl is part of. |
| 414 |
:param btrfs.ctree.Key min_key: Minimum key value for items to return. |
| 415 |
:param btrfs.ctree.Key max_key: Maximum key value for items to return. |
| 416 |
:param int min_transid: Minimum transaction id for the metadata leaf to |
| 417 |
have items included. Defaults to 0. |
| 418 |
:param int max_transid: Maximum transaction id for the metadata leaf to |
| 419 |
have items included. Defaults to 2**64-1. |
| 420 |
:param int nr_items: Maximum amount of items to fetch. Defaults to no |
| 421 |
limit. |
| 422 |
:param int buf_size: Buffer size in bytes that will be used for search |
| 423 |
results. |
| 424 |
|
| 425 |
:returns: An iterator over search results, containing a search header and |
| 426 |
the item data per item. |
| 427 |
:rtype: Iterator[Tuple[:class:`SearchHeader`, :class:`memoryview`]] |
| 428 |
""" |
| 429 |
return _search(fd, tree, min_key, max_key, min_transid, max_transid, |
| 430 |
nr_items, buf_size, _v2=True) |
| 431 |
|
| 432 |
|
| 433 |
def _search(fd, tree, min_key=None, max_key=None, |
| 434 |
min_transid=0, max_transid=ULLONG_MAX, |
| 435 |
nr_items=None, buf_size=None, _v2=True): |
| 436 |
if min_key is None: |
| 437 |
min_key = btrfs.ctree.Key(0, 0, 0) |
| 438 |
if max_key is None: |
| 439 |
max_key = btrfs.ctree.Key(ULLONG_MAX, 255, ULLONG_MAX) |
| 440 |
if nr_items is not None: |
| 441 |
wanted_nr_items = nr_items |
| 442 |
result_nr_items = -1 |
| 443 |
else: |
| 444 |
wanted_nr_items = ULONG_MAX |
| 445 |
while True: |
| 446 |
if _v2: |
| 447 |
buf = bytearray(ioctl_search_args_v2.size + buf_size) |
| 448 |
else: |
| 449 |
buf = bytearray(4096) |
| 450 |
buf_view = memoryview(buf) |
| 451 |
pos = 0 |
| 452 |
ioctl_search_key.pack_into(buf, pos, tree, |
| 453 |
min_key.objectid, max_key.objectid, |
| 454 |
min_key.offset, max_key.offset, |
| 455 |
min_transid, max_transid, |
| 456 |
min_key.type, max_key.type, |
| 457 |
wanted_nr_items) |
| 458 |
pos += ioctl_search_key.size |
| 459 |
if _v2: |
| 460 |
_ioctl_search_args_v2[1].pack_into(buf, pos, buf_size) |
| 461 |
pos += _ioctl_search_args_v2[1].size |
| 462 |
fcntl.ioctl(fd, IOC_TREE_SEARCH_V2, buf) |
| 463 |
else: |
| 464 |
fcntl.ioctl(fd, IOC_TREE_SEARCH, buf) |
| 465 |
result_nr_items = ioctl_search_key.unpack_from(buf, 0)[9] |
| 466 |
if result_nr_items > 0: |
| 467 |
for i in range(result_nr_items): |
| 468 |
header = SearchHeader(*ioctl_search_header.unpack_from(buf, pos)) |
| 469 |
pos += ioctl_search_header.size |
| 470 |
yield header, buf_view[pos:pos+header.len] |
| 471 |
if nr_items is not None: |
| 472 |
wanted_nr_items -= 1 |
| 473 |
if wanted_nr_items == 0: |
| 474 |
return |
| 475 |
pos += header.len |
| 476 |
min_key = btrfs.ctree.Key(header.objectid, header.type, header.offset) |
| 477 |
min_key += 1 |
| 478 |
else: |
| 479 |
return |
| 480 |
if min_key > max_key: |
| 481 |
return |
| 482 |
|
| 483 |
|
| 484 |
data_container = struct.Struct('=LLLL') |
| 485 |
ioctl_logical_ino_args = struct.Struct('=QQ32xQ') |
| 486 |
IOC_LOGICAL_INO = _IOWR(BTRFS_IOCTL_MAGIC, 36, ioctl_logical_ino_args) |
| 487 |
inum_offset_root = struct.Struct('=QQQ') |
| 488 |
|
| 489 |
Inode = namedtuple('Inode', ['inum', 'offset', 'root']) |
| 490 |
|
| 491 |
|
| 492 |
def logical_ino(fd, vaddr, bufsize=4096): |
| 493 |
"""Call the `BTRFS_IOC_LOGICAL_INO` ioctl. |
| 494 |
|
| 495 |
The `LOGICAL_INO` ioctl helps us converting a virtual address into a list |
| 496 |
of inode numbers of files that use the data extent at that specific |
| 497 |
address. |
| 498 |
|
| 499 |
Example:: |
| 500 |
|
| 501 |
>>> import btrfs |
| 502 |
>>> with btrfs.FileSystem('/') as fs: |
| 503 |
... btrfs.ioctl.logical_ino(fs.fd, 607096483840) |
| 504 |
([Inode(inum=4686948, offset=0, root=259), |
| 505 |
Inode(inum=4686948, offset=0, root=2104)], 0) |
| 506 |
|
| 507 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 508 |
:param int vaddr: Virtual address to search for. |
| 509 |
:param int bufsize: Size in bytes. Default value is 4kiB (4096 bytes). |
| 510 |
Maximum allowed value is 64kiB (65536 bytes). |
| 511 |
:returns: A list of :class:`Inode` objects and the amount of extra bytes |
| 512 |
for the provided buffer that would be needed to be able to return all |
| 513 |
results found. |
| 514 |
:rtype: Tuple[List[:class:`Inode`], int] |
| 515 |
|
| 516 |
The default buffer size, 4kiB, can store 170 results. The maximum buffer |
| 517 |
size, 64kiB, can store 2730 results. If a large buffer size is needed, then |
| 518 |
use the logical ino v2 ioctl, which was introduced in Linux kernel 4.15. |
| 519 |
|
| 520 |
Also, if the requested virtual address points to a disk block that is part |
| 521 |
of a larger extent, but there's no inode that references exactly this block |
| 522 |
in the extent, there will be no results. To get a list of inodes that |
| 523 |
reference any block in the extent, use the logical ino v2 ioctl instead, |
| 524 |
while setting the ignore_offset flag. |
| 525 |
""" |
| 526 |
return _logical_ino(fd, vaddr, bufsize, _v2=False) |
| 527 |
|
| 528 |
|
| 529 |
def logical_to_ino(*args, **kwargs): |
| 530 |
""" |
| 531 |
.. deprecated:: 15 |
| 532 |
Backwards compatibility function. Use :func:`~btrfs.ioctl.logical_ino` |
| 533 |
instead. |
| 534 |
""" |
| 535 |
return logical_ino(*args, **kwargs) |
| 536 |
|
| 537 |
|
| 538 |
ioctl_logical_ino_args_v2 = struct.Struct('=QQ24xQQ') |
| 539 |
IOC_LOGICAL_INO_V2 = _IOWR(BTRFS_IOCTL_MAGIC, 59, ioctl_logical_ino_args) |
| 540 |
LOGICAL_INO_ARGS_IGNORE_OFFSET = 1 << 0 |
| 541 |
|
| 542 |
|
| 543 |
def logical_ino_v2(fd, vaddr, bufsize=4096, ignore_offset=False): |
| 544 |
"""Call the `BTRFS_IOC_LOGICAL_INO_V2` ioctl. |
| 545 |
|
| 546 |
The `LOGICAL_INO_V2` ioctl helps us converting a virtual address into a |
| 547 |
list of inode numbers of files that use the data extent at that specific |
| 548 |
address. |
| 549 |
|
| 550 |
Example:: |
| 551 |
|
| 552 |
>>> import btrfs |
| 553 |
>>> with btrfs.FileSystem('/') as fs: |
| 554 |
... btrfs.ioctl.logical_ino_v2(fs.fd, 607096483840) |
| 555 |
([Inode(inum=4686948, offset=0, root=259), |
| 556 |
Inode(inum=4686948, offset=0, root=2104)], 0) |
| 557 |
|
| 558 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 559 |
:param int vaddr: Virtual address to search for. |
| 560 |
:param int bufsize: Size in bytes. Default value is 4kiB (4096 bytes). |
| 561 |
Maximum allowed value is 16MiB (16777216 bytes). |
| 562 |
:param bool ignore_offset: If ignore_offset is set to True, the results |
| 563 |
returned will list all inodes that reference any disk block from the |
| 564 |
extent the virtual address is part of. |
| 565 |
:returns: A list of :class:`Inode` objects and the amount of extra bytes |
| 566 |
for the provided buffer that would be needed to be able to return all |
| 567 |
results found. |
| 568 |
:rtype: Tuple[List[:class:`Inode`], int] |
| 569 |
|
| 570 |
The default buffer size, 4kiB can store 170 results. To get additional |
| 571 |
results, retry the call with a larger buffer, adding the amount of bytes |
| 572 |
that was reported to be additionally needed. |
| 573 |
""" |
| 574 |
return _logical_ino(fd, vaddr, bufsize, ignore_offset, _v2=True) |
| 575 |
|
| 576 |
|
| 577 |
def logical_to_ino_v2(*args, **kwargs): |
| 578 |
""" |
| 579 |
.. deprecated:: 15 |
| 580 |
Backwards compatibility function. Use |
| 581 |
:func:`~btrfs.ioctl.logical_ino_v2` instead. |
| 582 |
""" |
| 583 |
return logical_ino_v2(*args, **kwargs) |
| 584 |
|
| 585 |
|
| 586 |
def _logical_ino(fd, vaddr, bufsize=4096, ignore_offset=False, _v2=True): |
| 587 |
if _v2: |
| 588 |
bufsize = min(bufsize, 16777216) |
| 589 |
else: |
| 590 |
bufsize = min(bufsize, 65536) |
| 591 |
inodes_buf = array.array(u'B', bytearray(bufsize)) |
| 592 |
inodes_ptr = inodes_buf.buffer_info()[0] |
| 593 |
args = bytearray(ioctl_logical_ino_args.size) |
| 594 |
if _v2: |
| 595 |
flags = 0 |
| 596 |
if ignore_offset: |
| 597 |
flags |= LOGICAL_INO_ARGS_IGNORE_OFFSET |
| 598 |
ioctl_logical_ino_args_v2.pack_into(args, 0, vaddr, bufsize, flags, inodes_ptr) |
| 599 |
fcntl.ioctl(fd, IOC_LOGICAL_INO_V2, args) |
| 600 |
else: |
| 601 |
ioctl_logical_ino_args.pack_into(args, 0, vaddr, bufsize, inodes_ptr) |
| 602 |
fcntl.ioctl(fd, IOC_LOGICAL_INO, args) |
| 603 |
bytes_left, bytes_missing, elem_cnt, elem_missed = data_container.unpack_from(inodes_buf, 0) |
| 604 |
inodes = [] |
| 605 |
pos = data_container.size |
| 606 |
for elem in range(int(elem_cnt//3)): |
| 607 |
inodes.append(Inode(*inum_offset_root.unpack_from(inodes_buf, pos))) |
| 608 |
pos += inum_offset_root.size |
| 609 |
return inodes, bytes_missing |
| 610 |
|
| 611 |
|
| 612 |
INO_LOOKUP_PATH_MAX = 4080 |
| 613 |
ioctl_ino_lookup_args = struct.Struct('=QQ{}s'.format(INO_LOOKUP_PATH_MAX)) |
| 614 |
IOC_INO_LOOKUP = _IOWR(BTRFS_IOCTL_MAGIC, 18, ioctl_ino_lookup_args) |
| 615 |
|
| 616 |
InoLookupResult = namedtuple('InoLookupResult', ['treeid', 'name_bytes']) |
| 617 |
|
| 618 |
|
| 619 |
def ino_lookup(fd, treeid=0, objectid=btrfs.ctree.FIRST_FREE_OBJECTID): |
| 620 |
"""Call the `BTRFS_IOC_INO_LOOKUP` ioctl. |
| 621 |
|
| 622 |
The `INO_LOOKUP` ioctl returns the containing subvolume tree id and the |
| 623 |
relative path inside that subvolume of the first listed path for an inode |
| 624 |
number. |
| 625 |
|
| 626 |
Example:: |
| 627 |
|
| 628 |
>>> import btrfs |
| 629 |
>>> import os |
| 630 |
>>> fd = os.open('/', os.O_RDONLY) |
| 631 |
>>> btrfs.ioctl.ino_lookup(fd, objectid=4686948) |
| 632 |
InoLookupResult(treeid=259, name_bytes=b'bin/bash/') |
| 633 |
|
| 634 |
:param int fd: File descriptor pointing to an inode. |
| 635 |
:param int treeid: Subvolume tree to search in, or 0 to use the subvolume |
| 636 |
that contains the inode that fd points to. |
| 637 |
:param int objectid: Inode number to get the path for. |
| 638 |
|
| 639 |
:returns: An :class:`InoLookupResult` tuple with subvolume tree id and |
| 640 |
filesystem path as bytes. |
| 641 |
:rtype: :class:`InoLookupResult` |
| 642 |
""" |
| 643 |
args = bytearray(ioctl_ino_lookup_args.size) |
| 644 |
ioctl_ino_lookup_args.pack_into(args, 0, treeid, objectid, b'') |
| 645 |
fcntl.ioctl(fd, IOC_INO_LOOKUP, args) |
| 646 |
treeid, _, name_bytes = ioctl_ino_lookup_args.unpack_from(args, 0) |
| 647 |
return InoLookupResult(treeid, name_bytes.split(b'\0', 1)[0]) |
| 648 |
|
| 649 |
|
| 650 |
BALANCE_ARGS_PROFILES = 1 << 0 |
| 651 |
BALANCE_ARGS_USAGE = 1 << 1 |
| 652 |
BALANCE_ARGS_DEVID = 1 << 2 |
| 653 |
BALANCE_ARGS_DRANGE = 1 << 3 |
| 654 |
BALANCE_ARGS_VRANGE = 1 << 4 |
| 655 |
BALANCE_ARGS_LIMIT = 1 << 5 |
| 656 |
BALANCE_ARGS_LIMIT_RANGE = 1 << 6 |
| 657 |
BALANCE_ARGS_STRIPES_RANGE = 1 << 7 |
| 658 |
BALANCE_ARGS_CONVERT = 1 << 8 |
| 659 |
BALANCE_ARGS_SOFT = 1 << 9 |
| 660 |
BALANCE_ARGS_USAGE_RANGE = 1 << 10 |
| 661 |
|
| 662 |
_balance_args_flags_str_map = { |
| 663 |
BALANCE_ARGS_PROFILES: 'PROFILES', |
| 664 |
BALANCE_ARGS_USAGE: 'USAGE', |
| 665 |
BALANCE_ARGS_DEVID: 'DEVID', |
| 666 |
BALANCE_ARGS_DRANGE: 'DRANGE', |
| 667 |
BALANCE_ARGS_VRANGE: 'VRANGE', |
| 668 |
BALANCE_ARGS_LIMIT: 'LIMIT', |
| 669 |
BALANCE_ARGS_LIMIT_RANGE: 'LIMIT_RANGE', |
| 670 |
BALANCE_ARGS_STRIPES_RANGE: 'STRIPES_RANGE', |
| 671 |
BALANCE_ARGS_CONVERT: 'CONVERT', |
| 672 |
BALANCE_ARGS_SOFT: 'SOFT', |
| 673 |
BALANCE_ARGS_USAGE_RANGE: 'USAGE_RANGE', |
| 674 |
} |
| 675 |
|
| 676 |
|
| 677 |
def _balance_args_flags_str(flags): |
| 678 |
return btrfs.utils.flags_str(flags, _balance_args_flags_str_map) |
| 679 |
|
| 680 |
|
| 681 |
def _balance_args_profiles_str(profiles): |
| 682 |
return btrfs.utils.flags_str(profiles, btrfs.ctree._balance_args_profiles_str_map) |
| 683 |
|
| 684 |
|
| 685 |
class BalanceArgs(object): |
| 686 |
"""Object representation of struct `btrfs_balance_args`. |
| 687 |
|
| 688 |
When calling the balance ioctl, we have to pass filters that define which |
| 689 |
subset of block groups in the filesystem we want to rewrite. |
| 690 |
|
| 691 |
Example:: |
| 692 |
|
| 693 |
>>> args = btrfs.ioctl.BalanceArgs(vstart=115993477120, |
| 694 |
vend=191155404800, limit_min=2, limit_max=2) |
| 695 |
>>> print(args) |
| 696 |
flags(VRANGE|LIMIT_RANGE) vrange=115993477120..191155404800, limit=2..2 |
| 697 |
>>> args |
| 698 |
BalanceArgs(vstart=115993477120, vend=191155404800, limit_min=2, |
| 699 |
limit_max=2) |
| 700 |
|
| 701 |
When defining multiple filter criteria, they all have to match for a block |
| 702 |
group to be processed by the balance run. |
| 703 |
|
| 704 |
The balance ioctl accepts three of these BalanceArgs at the same time, |
| 705 |
one for data, one for metadata and one for the system type. |
| 706 |
|
| 707 |
:param int profiles: Match block groups having either of the given |
| 708 |
profiles. A single value of or-ed together block group profile |
| 709 |
constants. E.g. `BLOCK_GROUP_RAID1 | BLOCK_GROUP_DUP`. Note that |
| 710 |
there is no `BLOCK_GROUP_SINGLE`, since the single profile uses the |
| 711 |
value zero. For choosing the single profile here, use the |
| 712 |
`AVAIL_ALLOC_BIT_SINGLE` constant that is available in the |
| 713 |
`btrfs.ctree` module. |
| 714 |
:param int usage_min: Match block groups with usage equal to or above |
| 715 |
the given percentage. |
| 716 |
:param int usage_max: Match block groups with usage under the given |
| 717 |
percentage. |
| 718 |
:param int devid: Match block groups whose related Chunk object has a |
| 719 |
Stripe object using physical space on this device. |
| 720 |
:param int pstart: Match block groups using physical bytes on a device on |
| 721 |
or after the given start address. Use this in combination with the |
| 722 |
`devid` option. |
| 723 |
:param int pend: Match block groups using physical bytes on a device before |
| 724 |
the given end address. Use this in combination with the `devid` option. |
| 725 |
:param int vstart: Match block groups that overlap with the given virtual |
| 726 |
address, or a higher address. |
| 727 |
:param int vend: Match block groups that overlap with a virtual address |
| 728 |
before the given address. |
| 729 |
:param int target: Target block group profile to convert to. |
| 730 |
:param int limit_min: Try to process at least this amount of block groups. |
| 731 |
:param int limit_max: Process at most this amount of block groups. |
| 732 |
:param int stripes_min: Match block groups which have an associated Chunk |
| 733 |
object that has at least this amount of related Stripe objects. |
| 734 |
:param int stripes_max: Match block groups which have an associated Chunk |
| 735 |
object that has at most this amount of related Stripe objects. |
| 736 |
:param bool soft: When set, skip matching block groups that already have |
| 737 |
the target profile when doing a conversion. |
| 738 |
|
| 739 |
The arguments given when creating a BalanceArgs object are available as |
| 740 |
attributes on the resulting object, together with a flags field: |
| 741 |
|
| 742 |
:ivar int flags: Flags denoting which filter options are set. |
| 743 |
|
| 744 |
The flags are an or-ed combination of one or more of the following values |
| 745 |
(available as attribute of this module): |
| 746 |
|
| 747 |
- BALANCE_ARGS_PROFILES |
| 748 |
- BALANCE_ARGS_USAGE |
| 749 |
- BALANCE_ARGS_DEVID |
| 750 |
- BALANCE_ARGS_DRANGE |
| 751 |
- BALANCE_ARGS_VRANGE |
| 752 |
- BALANCE_ARGS_LIMIT |
| 753 |
- BALANCE_ARGS_LIMIT_RANGE |
| 754 |
- BALANCE_ARGS_STRIPES_RANGE |
| 755 |
- BALANCE_ARGS_CONVERT |
| 756 |
- BALANCE_ARGS_SOFT |
| 757 |
- BALANCE_ARGS_USAGE_RANGE |
| 758 |
|
| 759 |
.. note:: |
| 760 |
This class does not implement single usage and limit values, and is |
| 761 |
thus incompatible with a Linux kernel older than v4.4. |
| 762 |
""" |
| 763 |
def __init__(self, profiles=None, usage_min=None, usage_max=None, |
| 764 |
devid=None, pstart=None, pend=None, vstart=None, vend=None, |
| 765 |
target=None, limit_min=None, limit_max=None, |
| 766 |
stripes_min=None, stripes_max=None, soft=False): |
| 767 |
self.flags = 0 |
| 768 |
|
| 769 |
if profiles is not None: |
| 770 |
self.flags |= BALANCE_ARGS_PROFILES |
| 771 |
self.profiles = profiles |
| 772 |
else: |
| 773 |
self.profiles = 0 |
| 774 |
|
| 775 |
if usage_min is not None: |
| 776 |
self.flags |= BALANCE_ARGS_USAGE_RANGE |
| 777 |
self.usage_min = usage_min |
| 778 |
else: |
| 779 |
self.usage_min = 0 |
| 780 |
|
| 781 |
if usage_max is not None: |
| 782 |
self.flags |= BALANCE_ARGS_USAGE_RANGE |
| 783 |
self.usage_max = usage_max |
| 784 |
else: |
| 785 |
self.usage_max = 100 |
| 786 |
|
| 787 |
if devid is not None: |
| 788 |
self.flags |= BALANCE_ARGS_DEVID |
| 789 |
self.devid = devid |
| 790 |
if pstart is not None: |
| 791 |
self.flags |= BALANCE_ARGS_DRANGE |
| 792 |
self.pstart = pstart |
| 793 |
else: |
| 794 |
self.pstart = 0 |
| 795 |
if pend is not None: |
| 796 |
self.flags |= BALANCE_ARGS_DRANGE |
| 797 |
self.pend = pend |
| 798 |
else: |
| 799 |
self.pend = ULLONG_MAX |
| 800 |
else: |
| 801 |
self.devid = 0 |
| 802 |
self.pstart = 0 |
| 803 |
self.pend = ULLONG_MAX |
| 804 |
|
| 805 |
if vstart is not None: |
| 806 |
self.flags |= BALANCE_ARGS_VRANGE |
| 807 |
self.vstart = vstart |
| 808 |
else: |
| 809 |
self.vstart = 0 |
| 810 |
if vend is not None: |
| 811 |
self.flags |= BALANCE_ARGS_VRANGE |
| 812 |
self.vend = vend |
| 813 |
else: |
| 814 |
self.vend = ULLONG_MAX |
| 815 |
|
| 816 |
if target is not None: |
| 817 |
self.flags |= BALANCE_ARGS_CONVERT |
| 818 |
self.target = target |
| 819 |
if soft: |
| 820 |
self.flags |= BALANCE_ARGS_SOFT |
| 821 |
self.soft = soft |
| 822 |
else: |
| 823 |
self.target = 0 |
| 824 |
|
| 825 |
if limit_min is not None: |
| 826 |
self.flags |= BALANCE_ARGS_LIMIT_RANGE |
| 827 |
self.limit_min = limit_min |
| 828 |
else: |
| 829 |
self.limit_min = 0 |
| 830 |
|
| 831 |
if limit_max is not None: |
| 832 |
self.flags |= BALANCE_ARGS_LIMIT_RANGE |
| 833 |
self.limit_max = limit_max |
| 834 |
else: |
| 835 |
self.limit_max = ULONG_MAX |
| 836 |
|
| 837 |
if stripes_min is not None: |
| 838 |
self.flags |= BALANCE_ARGS_STRIPES_RANGE |
| 839 |
self.stripes_min = stripes_min |
| 840 |
else: |
| 841 |
self.stripes_min = 0 |
| 842 |
|
| 843 |
if stripes_max is not None: |
| 844 |
self.flags |= BALANCE_ARGS_STRIPES_RANGE |
| 845 |
self.stripes_max = stripes_max |
| 846 |
else: |
| 847 |
self.stripes_max = ULONG_MAX |
| 848 |
|
| 849 |
def _for_struct(self): |
| 850 |
return self.profiles, self.usage_min, self.usage_max, self.devid, self.pstart, self.pend, \ |
| 851 |
self.vstart, self.vend, self.target, self.flags, self.limit_min, self.limit_max, \ |
| 852 |
self.stripes_min, self.stripes_max |
| 853 |
|
| 854 |
def __repr__(self): |
| 855 |
opts = [] |
| 856 |
if self.flags & BALANCE_ARGS_PROFILES: |
| 857 |
opts.append("profiles={:#x}".format(self.profiles)) |
| 858 |
if self.flags & BALANCE_ARGS_USAGE_RANGE: |
| 859 |
opts.append("usage_min={}, usage_max={}".format(self.usage_min, self.usage_max)) |
| 860 |
if self.flags & BALANCE_ARGS_DEVID: |
| 861 |
opts.append("devid={}".format(self.devid)) |
| 862 |
if self.flags & BALANCE_ARGS_DRANGE: |
| 863 |
opts.append("pstart={}, pend={}".format(self.pstart, self.pend)) |
| 864 |
if self.flags & BALANCE_ARGS_VRANGE: |
| 865 |
opts.append("vstart={}, vend={}".format(self.vstart, self.vend)) |
| 866 |
if self.flags & BALANCE_ARGS_CONVERT: |
| 867 |
opts.append("target={:#x}".format(self.target)) |
| 868 |
if self.flags & BALANCE_ARGS_LIMIT_RANGE: |
| 869 |
opts.append("limit_min={}, limit_max={}".format(self.limit_min, self.limit_max)) |
| 870 |
if self.flags & BALANCE_ARGS_STRIPES_RANGE: |
| 871 |
opts.append("stripes_min={}, stripes_max={}".format( |
| 872 |
self.stripes_min, self.stripes_max)) |
| 873 |
if self.flags & BALANCE_ARGS_SOFT: |
| 874 |
opts.append("soft=True") |
| 875 |
return "BalanceArgs({})".format(', '.join(opts)) |
| 876 |
|
| 877 |
def __str__(self): |
| 878 |
opts = [] |
| 879 |
if self.flags & BALANCE_ARGS_PROFILES: |
| 880 |
opts.append("profiles={}".format(self.profiles_str)) |
| 881 |
if self.flags & BALANCE_ARGS_USAGE_RANGE: |
| 882 |
opts.append("usage={}..{}".format(self.usage_min, self.usage_max)) |
| 883 |
if self.flags & BALANCE_ARGS_DEVID: |
| 884 |
opts.append("devid={}".format(self.devid)) |
| 885 |
if self.flags & BALANCE_ARGS_DRANGE: |
| 886 |
opts.append("drange={}..{}".format(self.pstart, self.pend)) |
| 887 |
if self.flags & BALANCE_ARGS_VRANGE: |
| 888 |
opts.append("vrange={}..{}".format(self.vstart, self.vend)) |
| 889 |
if self.flags & BALANCE_ARGS_CONVERT: |
| 890 |
opts.append("target={}".format(self.target_str)) |
| 891 |
if self.flags & BALANCE_ARGS_LIMIT_RANGE: |
| 892 |
opts.append("limit={}..{}".format(self.limit_min, self.limit_max)) |
| 893 |
if self.flags & BALANCE_ARGS_STRIPES_RANGE: |
| 894 |
opts.append("stripes={}..{}".format(self.stripes_min, self.stripes_max)) |
| 895 |
if self.flags & BALANCE_ARGS_SOFT: |
| 896 |
opts.append("soft") |
| 897 |
return "flags({}) {}".format(self.flags_str, ', '.join(opts)) |
| 898 |
|
| 899 |
@staticmethod |
| 900 |
def _pretty_properties(): |
| 901 |
return [ |
| 902 |
(_balance_args_flags_str, 'flags'), |
| 903 |
(_balance_args_profiles_str, 'profiles'), |
| 904 |
(_balance_args_profiles_str, 'target'), |
| 905 |
] |
| 906 |
|
| 907 |
|
| 908 |
BALANCE_DATA = 1 << 0 |
| 909 |
BALANCE_SYSTEM = 1 << 1 |
| 910 |
BALANCE_METADATA = 1 << 2 |
| 911 |
BALANCE_TYPE_MASK = BALANCE_DATA | BALANCE_SYSTEM | BALANCE_METADATA |
| 912 |
BALANCE_FORCE = 1 << 3 |
| 913 |
BALANCE_RESUME = 1 << 4 |
| 914 |
|
| 915 |
BALANCE_STATE_RUNNING = 1 << 0 |
| 916 |
BALANCE_STATE_PAUSE_REQ = 1 << 1 |
| 917 |
BALANCE_STATE_CANCEL_REQ = 1 << 2 |
| 918 |
|
| 919 |
_balance_state_str_map = { |
| 920 |
BALANCE_STATE_RUNNING: 'RUNNING', |
| 921 |
BALANCE_STATE_PAUSE_REQ: 'PAUSE_REQ', |
| 922 |
BALANCE_STATE_CANCEL_REQ: 'CANCEL_REQ', |
| 923 |
} |
| 924 |
|
| 925 |
|
| 926 |
def _balance_state_str(state): |
| 927 |
return btrfs.utils.flags_str(state, _balance_state_str_map) |
| 928 |
|
| 929 |
|
| 930 |
|
| 931 |
|
| 932 |
_balance_args = struct.Struct('=QLL7Q4L48x') |
| 933 |
_balance_progress = struct.Struct('=3Q') |
| 934 |
|
| 935 |
|
| 936 |
class BalanceProgress(object): |
| 937 |
"""Object representation of struct `btrfs_balance_progress`. |
| 938 |
|
| 939 |
:ivar int state: current state of a running balance operation. |
| 940 |
|
| 941 |
When a progress object is returned by :func:`~btrfs.ioctl.balance_v2` after |
| 942 |
a successful uninterrupted run, the value of state is 0. |
| 943 |
|
| 944 |
When obtaining a progress object by calling |
| 945 |
:func:`~btrfs.ioctl.balance_progress`, the possible state values (available |
| 946 |
as attribute of this module) are: |
| 947 |
|
| 948 |
- `BALANCE_STATE_RUNNING`: Balance is running. |
| 949 |
- `BALANCE_STATE_PAUSE_REQ`: Balance is running, but a pause is requested. |
| 950 |
- `BALANCE_STATE_CANCEL_REQ`: Balance is running, but cancel is requested. |
| 951 |
|
| 952 |
:ivar int expected: Estimated number of block groups that will be relocated |
| 953 |
to fulfill the request. |
| 954 |
:ivar int considered: Number of block groups that were inspected to see if |
| 955 |
they match the requested filters. |
| 956 |
:ivar int completed: Number of block groups relocated so far. |
| 957 |
""" |
| 958 |
def __init__(self, state, expected, considered, completed): |
| 959 |
self.state = state |
| 960 |
self.expected = expected |
| 961 |
self.considered = considered |
| 962 |
self.completed = completed |
| 963 |
|
| 964 |
def __repr__(self): |
| 965 |
return "BalanceProgress(state={self.state:#x}, expected={self.expected}, " \ |
| 966 |
"considered={self.considered}, completed={self.completed})".format(self=self) |
| 967 |
|
| 968 |
def __str__(self): |
| 969 |
return "state {self.state_str} expected {self.expected} considered {self.considered} " \ |
| 970 |
"completed {self.completed}".format(self=self) |
| 971 |
|
| 972 |
@staticmethod |
| 973 |
def _pretty_properties(): |
| 974 |
return [ |
| 975 |
(_balance_state_str, 'state'), |
| 976 |
] |
| 977 |
|
| 978 |
|
| 979 |
_ioctl_balance_args = [ |
| 980 |
struct.Struct('=Q'), |
| 981 |
struct.Struct('=Q'), |
| 982 |
_balance_args, |
| 983 |
_balance_args, |
| 984 |
_balance_args, |
| 985 |
_balance_progress, |
| 986 |
struct.Struct('=576x') |
| 987 |
] |
| 988 |
ioctl_balance_args = struct.Struct('=' + ''.join([btrfs.ctree._struct_format(s)[1:] |
| 989 |
for s in _ioctl_balance_args])) |
| 990 |
IOC_BALANCE_V2 = _IOWR(BTRFS_IOCTL_MAGIC, 32, ioctl_balance_args) |
| 991 |
|
| 992 |
|
| 993 |
class BalanceError(Exception): |
| 994 |
"""Exception class for balance functionality. |
| 995 |
|
| 996 |
A :class:`BalanceError` can be thrown by any of the balance related |
| 997 |
functions in this module. |
| 998 |
|
| 999 |
:ivar int state: One of the balance state values, see below. This field is |
| 1000 |
only set to a non-zero value when the error is raised by the |
| 1001 |
:func:`balance_v2` function. |
| 1002 |
:ivar int errno: An errno errorcode that was returned when executing the |
| 1003 |
ioctl call in one of the balance related functions. |
| 1004 |
:ivar str msg: A message describing the error condition. |
| 1005 |
|
| 1006 |
Refer to the docucumentation of the different functions who can raise this |
| 1007 |
error for more information about combinations of the state and errno |
| 1008 |
numbers that can be expected, and about what they mean. |
| 1009 |
""" |
| 1010 |
def __init__(self, state, msg): |
| 1011 |
self.state = state |
| 1012 |
self.msg = msg |
| 1013 |
|
| 1014 |
@property |
| 1015 |
def errno(self): |
| 1016 |
return self.__context__.errno |
| 1017 |
|
| 1018 |
def __str__(self): |
| 1019 |
return self.msg |
| 1020 |
|
| 1021 |
|
| 1022 |
def balance_v2(fd, data_args=None, meta_args=None, sys_args=None, force=False, resume=False): |
| 1023 |
"""Call the `BTRFS_IOC_BALANCE_V2` ioctl. |
| 1024 |
|
| 1025 |
Ask the kernel to relocate block groups. |
| 1026 |
|
| 1027 |
Example:: |
| 1028 |
|
| 1029 |
>>> import btrfs |
| 1030 |
>>> args = btrfs.ioctl.BalanceArgs(vstart=115993477120, |
| 1031 |
vend=191155404800, limit_min=2, limit_max=2) |
| 1032 |
>>> with btrfs.FileSystem('/') as fs: |
| 1033 |
... btrfs.ioctl.balance_v2(fs.fd, data_args=args) |
| 1034 |
... |
| 1035 |
BalanceProgress(state=0x0, expected=2, considered=466, completed=2) |
| 1036 |
|
| 1037 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 1038 |
:param BalanceArgs data_args: Filters for Data type block groups. |
| 1039 |
:param BalanceArgs meta_args: Filters for Metadata type block groups. |
| 1040 |
:param BalanceArgs sys_args: Filters for System type block groups. |
| 1041 |
:param bool force: When True, this allows converting to a profile with less |
| 1042 |
redundancy. |
| 1043 |
:param bool resume: When True, all args are ignored and we ask the kernel |
| 1044 |
to resume a previous balance operation. |
| 1045 |
|
| 1046 |
:returns: A :class:`BalanceProgress` object, describing the end result. |
| 1047 |
:rtype: :class:`BalanceProgress` |
| 1048 |
|
| 1049 |
:raises: :class:`BalanceError`, in case the balance operation does not exit |
| 1050 |
in a clean way. Possible reasons include pausing or canceling the |
| 1051 |
balance operation by a separate call to |
| 1052 |
:func:`~btrfs.ioctl.balance_ctl`, or having another balance operation |
| 1053 |
already running. |
| 1054 |
|
| 1055 |
When a :class:`BalanceError` is raised, the following combinations of state |
| 1056 |
and errno attributes can be expected: |
| 1057 |
|
| 1058 |
- errno `ECANCELED`, state `BALANCE_STATE_PAUSE_REQ`: The balance operation |
| 1059 |
was paused because of a user request. |
| 1060 |
- errno `ECANCELED`, state `BALANCE_STATE_CANCEL_REQ`: The balance |
| 1061 |
operation was aborted because of a user request. |
| 1062 |
- errno `ENOTCONN`: A resume was requested, but there was no previously |
| 1063 |
paused balance operation. |
| 1064 |
- errno `EINPROGRESS`: A resume or start was requested, but there is |
| 1065 |
already a balance operation in progress. |
| 1066 |
""" |
| 1067 |
args = bytearray(ioctl_balance_args.size) |
| 1068 |
if resume: |
| 1069 |
_ioctl_balance_args[0].pack_into(args, 0, BALANCE_RESUME) |
| 1070 |
else: |
| 1071 |
flags = 0 |
| 1072 |
pos = _ioctl_balance_args[0].size |
| 1073 |
pos += _ioctl_balance_args[1].size |
| 1074 |
if data_args is not None: |
| 1075 |
flags |= BALANCE_DATA |
| 1076 |
_balance_args.pack_into(args, pos, *data_args._for_struct()) |
| 1077 |
pos += _balance_args.size |
| 1078 |
if meta_args is not None: |
| 1079 |
flags |= BALANCE_METADATA |
| 1080 |
_balance_args.pack_into(args, pos, *meta_args._for_struct()) |
| 1081 |
pos += _balance_args.size |
| 1082 |
if sys_args is not None: |
| 1083 |
flags |= BALANCE_SYSTEM |
| 1084 |
_balance_args.pack_into(args, pos, *sys_args._for_struct()) |
| 1085 |
if force: |
| 1086 |
flags |= BALANCE_FORCE |
| 1087 |
_ioctl_balance_args[0].pack_into(args, 0, flags) |
| 1088 |
try: |
| 1089 |
fcntl.ioctl(fd, IOC_BALANCE_V2, args) |
| 1090 |
except OSError as oserror: |
| 1091 |
pos = _ioctl_balance_args[0].size |
| 1092 |
state, = _ioctl_balance_args[1].unpack_from(args, pos) |
| 1093 |
errorcode = errno.errorcode[oserror.errno] |
| 1094 |
if oserror.errno == errno.ECANCELED: |
| 1095 |
if state & BALANCE_STATE_PAUSE_REQ: |
| 1096 |
msg = "Balance paused by user" |
| 1097 |
if state & BALANCE_STATE_CANCEL_REQ: |
| 1098 |
msg = "Balance canceled by user" |
| 1099 |
elif oserror.errno == errno.ENOTCONN and resume: |
| 1100 |
msg = "Balance resume failed: Not in progress ({})".format(errorcode) |
| 1101 |
elif oserror.errno == errno.EINPROGRESS: |
| 1102 |
if resume: |
| 1103 |
msg = "Balance resume failed: Already running ({})".format(errorcode) |
| 1104 |
else: |
| 1105 |
msg = "Balance start failed: Already in progress ({})".format(errorcode) |
| 1106 |
else: |
| 1107 |
msg = "Error during balancing, there may be more info in dmesg: {}, " \ |
| 1108 |
"state {}".format(errorcode, _balance_state_str(state)) |
| 1109 |
raise BalanceError(state, msg) from None |
| 1110 |
pos = _ioctl_balance_args[0].size |
| 1111 |
state, = _ioctl_balance_args[1].unpack_from(args, pos) |
| 1112 |
pos = sum(x.size for x in _ioctl_balance_args[:5]) |
| 1113 |
return BalanceProgress(state, *_balance_progress.unpack_from(args, pos)) |
| 1114 |
|
| 1115 |
|
| 1116 |
BALANCE_CTL_PAUSE = 1 |
| 1117 |
BALANCE_CTL_CANCEL = 2 |
| 1118 |
ioctl_balance_ctl_int = struct.Struct('=i') |
| 1119 |
IOC_BALANCE_CTL = _IOW(BTRFS_IOCTL_MAGIC, 33, ioctl_balance_ctl_int) |
| 1120 |
|
| 1121 |
|
| 1122 |
def balance_ctl(fd, cmd): |
| 1123 |
"""Call the `BTRFS_IOC_BALANCE_CTL` ioctl. |
| 1124 |
|
| 1125 |
Ask the kernel to pause or cancel a running balance operation. |
| 1126 |
|
| 1127 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 1128 |
:param int cmd: Balance control command. |
| 1129 |
|
| 1130 |
Available commands (available as attribute of this module) are: |
| 1131 |
|
| 1132 |
- `BALANCE_CTL_PAUSE` |
| 1133 |
- `BALANCE_CTL_CANCEL` |
| 1134 |
|
| 1135 |
:raises: :class:`BalanceError` if there is no balance in progress, or if |
| 1136 |
pausing or cancelling it failed. |
| 1137 |
|
| 1138 |
When a :class:`BalanceError` is raised, the following values for the errno |
| 1139 |
attribute can be expected: |
| 1140 |
|
| 1141 |
- errno `ENOTCONN`: There is no balance operation in progress, so it cannot |
| 1142 |
be paused or cancelled. |
| 1143 |
""" |
| 1144 |
try: |
| 1145 |
fcntl.ioctl(fd, IOC_BALANCE_CTL, cmd) |
| 1146 |
except OSError as oserror: |
| 1147 |
errorcode = errno.errorcode[oserror.errno] |
| 1148 |
if cmd == BALANCE_CTL_PAUSE: |
| 1149 |
if oserror.errno == errno.ENOTCONN: |
| 1150 |
msg = "Balance pause failed: Not in progress ({})".format(errorcode) |
| 1151 |
else: |
| 1152 |
msg = "Balance pause failed ({})".format(errorcode) |
| 1153 |
elif cmd == BALANCE_CTL_CANCEL: |
| 1154 |
if oserror.errno == errno.ENOTCONN: |
| 1155 |
msg = "Balance cancel failed: Not in progress ({})".format(errorcode) |
| 1156 |
else: |
| 1157 |
msg = "Balance cancel failed ({})".format(errorcode) |
| 1158 |
raise BalanceError(0, msg) from None |
| 1159 |
|
| 1160 |
|
| 1161 |
IOC_BALANCE_PROGRESS = _IOR(BTRFS_IOCTL_MAGIC, 34, ioctl_balance_args) |
| 1162 |
|
| 1163 |
|
| 1164 |
def balance_progress(fd): |
| 1165 |
"""Call the `BTRFS_IOC_BALANCE_PROGRESS` ioctl. |
| 1166 |
|
| 1167 |
Ask the kernel about progress of a running balance operation. |
| 1168 |
|
| 1169 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 1170 |
:returns: A :class:`BalanceProgress` object, describing the current state |
| 1171 |
of the balance operation. |
| 1172 |
:rtype: :class:`BalanceProgress` |
| 1173 |
|
| 1174 |
:raises: :class:`BalanceError` if there is no balance in progress, or if |
| 1175 |
inquiring about the progress failed. |
| 1176 |
|
| 1177 |
When a :class:`BalanceError` is raised, the following values for the errno |
| 1178 |
attribute can be expected: |
| 1179 |
|
| 1180 |
- errno `ENOTCONN`: There is no balance operation in progress. |
| 1181 |
""" |
| 1182 |
args = bytearray(ioctl_balance_args.size) |
| 1183 |
try: |
| 1184 |
fcntl.ioctl(fd, IOC_BALANCE_PROGRESS, args) |
| 1185 |
except OSError as oserror: |
| 1186 |
pos = _ioctl_balance_args[0].size |
| 1187 |
state, = _ioctl_balance_args[1].unpack_from(args, pos) |
| 1188 |
errorcode = errno.errorcode[oserror.errno] |
| 1189 |
if oserror.errno == errno.ENOTCONN: |
| 1190 |
msg = "No balance found ({})".format(errorcode) |
| 1191 |
else: |
| 1192 |
msg = "Balance progress failed ({})".format(errorcode) |
| 1193 |
raise BalanceError(0, msg) from None |
| 1194 |
pos = _ioctl_balance_args[0].size |
| 1195 |
state, = _ioctl_balance_args[1].unpack_from(args, pos) |
| 1196 |
pos = sum(x.size for x in _ioctl_balance_args[:5]) |
| 1197 |
return BalanceProgress(state, *_balance_progress.unpack_from(args, pos)) |
| 1198 |
|
| 1199 |
|
| 1200 |
ioctl_received_subvol_args = struct.Struct('=16sQQQLQLQ128x') |
| 1201 |
_ioctl_received_subvol_args_in = struct.Struct('=16sQ8xQL148x') |
| 1202 |
_ioctl_received_subvol_args_out_up_to_rtime = struct.Struct('=24xQ12x') |
| 1203 |
IOC_SET_RECEIVED_SUBVOL = _IOWR(BTRFS_IOCTL_MAGIC, 37, ioctl_received_subvol_args) |
| 1204 |
|
| 1205 |
|
| 1206 |
def set_received_subvol(fd, received_uuid, stransid, stime): |
| 1207 |
"""Call the `BTRFS_IOC_SET_RECEIVED_SUBVOL` ioctl. |
| 1208 |
|
| 1209 |
This function allows setting information about a sent subvolume after a |
| 1210 |
receive operation. |
| 1211 |
|
| 1212 |
Using this functionality it is possible to manually change relationships |
| 1213 |
between sent and received subvolumes, removing safeguards and tricking |
| 1214 |
btrfs into accepting certain incremental send and receive operations. |
| 1215 |
|
| 1216 |
Use with caution, as it is also possible to cause subsequent `btrfs |
| 1217 |
receive` to try doing wildly invalid things as result. |
| 1218 |
|
| 1219 |
:param int fd: An open file descriptor to the subvolume root directory |
| 1220 |
(inode 256). |
| 1221 |
:param uuid.UUID uuid: The uuid (a python uuid object) we want to have set |
| 1222 |
as received_uuid. |
| 1223 |
:param int stransid: Generation of the subvolume that was sent. |
| 1224 |
:param btrfs.ctree.TimeSpec stime: Time when the subvolume was sent. |
| 1225 |
|
| 1226 |
Note that the stime field is not set at all by `btrfs receive`. |
| 1227 |
""" |
| 1228 |
args = bytearray(_ioctl_received_subvol_args_in.size) |
| 1229 |
_ioctl_received_subvol_args_in.pack_into(args, 0, received_uuid.bytes, stransid, |
| 1230 |
stime.sec, stime.nsec) |
| 1231 |
fcntl.ioctl(fd, IOC_SET_RECEIVED_SUBVOL, args) |
| 1232 |
rtransid, = _ioctl_received_subvol_args_out_up_to_rtime.unpack_from(args, 0) |
| 1233 |
pos = _ioctl_received_subvol_args_out_up_to_rtime.size |
| 1234 |
rtime = btrfs.ctree.TimeSpec(args[pos:pos+btrfs.ctree.TimeSpec._timespec.size]) |
| 1235 |
return rtransid, rtime |
| 1236 |
|
| 1237 |
|
| 1238 |
IOC_SYNC = _IO(BTRFS_IOCTL_MAGIC, 8) |
| 1239 |
|
| 1240 |
|
| 1241 |
def sync(fd): |
| 1242 |
"""Call the `BTRFS_IOC_SYNC` ioctl. |
| 1243 |
|
| 1244 |
The sync ioctl triggers delayed allocations, a btrfs transaction commit and |
| 1245 |
the cleaner kthread. |
| 1246 |
|
| 1247 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 1248 |
|
| 1249 |
.. note:: |
| 1250 |
This function should usually be used implicitly by calling the |
| 1251 |
:func:`~btrfs.ctree.FileSystem.sync` function on a |
| 1252 |
:class:`btrfs.ctree.FileSystem` object. |
| 1253 |
""" |
| 1254 |
fcntl.ioctl(fd, IOC_SYNC) |
| 1255 |
|
| 1256 |
|
| 1257 |
file_dedupe_range_info = struct.Struct('=qQQl4x') |
| 1258 |
file_dedupe_range = struct.Struct('=QQH6x') |
| 1259 |
|
| 1260 |
FIDEDUPERANGE = _IOWR(BTRFS_IOCTL_MAGIC, 54, file_dedupe_range) |
| 1261 |
|
| 1262 |
FILE_DEDUPE_RANGE_SAME = 0 |
| 1263 |
FILE_DEDUPE_RANGE_DIFFERS = 1 |
| 1264 |
|
| 1265 |
|
| 1266 |
class FileDedupeRangeInfo(object): |
| 1267 |
"""Object representation of struct `file_dedupe_range_info`. |
| 1268 |
|
| 1269 |
:param int dest_fd: An open file descriptor to a destination file which |
| 1270 |
should get content deduped. |
| 1271 |
:param int dest_offset: Byte offset in the destination file from where the |
| 1272 |
dedupe operation should happen. |
| 1273 |
|
| 1274 |
After calling :func:`fideduperange`, the object will contain return values |
| 1275 |
of the dedupe operation for this destination file: |
| 1276 |
|
| 1277 |
:ivar int bytes_deduped: Amount of actual bytes at the given offset that |
| 1278 |
could be deduped. |
| 1279 |
:ivar int status: One of the two status codes mentioned below (available as |
| 1280 |
attribute of this module) or a negative number, which means it's a |
| 1281 |
standard errno integer value from the kernel. |
| 1282 |
|
| 1283 |
- `FILE_DEDUPE_RANGE_SAME`: The source range provided was identical to the |
| 1284 |
data at the destination offset and could be deduped. |
| 1285 |
- `FILE_DEDUPE_RANGE_DIFFERS`: Data in the destination was not matching, |
| 1286 |
and the range could not be deduped. |
| 1287 |
""" |
| 1288 |
def __init__(self, dest_fd, dest_offset): |
| 1289 |
self.dest_fd = dest_fd |
| 1290 |
self.dest_offset = dest_offset |
| 1291 |
self.bytes_deduped = None |
| 1292 |
self.status = None |
| 1293 |
|
| 1294 |
@property |
| 1295 |
def status_str(self): |
| 1296 |
"""Pretty string representation for the status attribute.""" |
| 1297 |
if self.status == btrfs.ioctl.FILE_DEDUPE_RANGE_SAME: |
| 1298 |
return "RANGE_SAME" |
| 1299 |
if self.status == FILE_DEDUPE_RANGE_DIFFERS: |
| 1300 |
return "RANGE_DIFFERS" |
| 1301 |
return "ERROR {}: {}".format(self.status, os.strerror(-self.status)) |
| 1302 |
|
| 1303 |
def __str__(self): |
| 1304 |
return "dest_fd {self.dest_fd} dest_offset {self.dest_offset} " \ |
| 1305 |
"bytes_deduped {self.bytes_deduped} status {self.status_str}".format(self=self) |
| 1306 |
|
| 1307 |
|
| 1308 |
def fideduperange(fd, src_offset, src_length, range_infos): |
| 1309 |
"""Call the `FIDEDUPERANGE` ioctl. |
| 1310 |
|
| 1311 |
:param int fd: Open file descriptor to a source file. |
| 1312 |
:param int src_offset: Offset in the source file where the source range |
| 1313 |
starts. |
| 1314 |
:param int src_length: Length of the source range. |
| 1315 |
:param range_infos: Information about offsets in destination files. |
| 1316 |
:type range_infos: list of :class:`FileDedupeRangeInfo` |
| 1317 |
""" |
| 1318 |
buf = bytearray(file_dedupe_range.size + file_dedupe_range_info.size * len(range_infos)) |
| 1319 |
file_dedupe_range.pack_into(buf, 0, src_offset, src_length, len(range_infos)) |
| 1320 |
pos = file_dedupe_range.size |
| 1321 |
for info in range_infos: |
| 1322 |
file_dedupe_range_info.pack_into(buf, pos, info.dest_fd, info.dest_offset, 0, 0) |
| 1323 |
pos += file_dedupe_range_info.size |
| 1324 |
fcntl.ioctl(fd, FIDEDUPERANGE, buf) |
| 1325 |
pos = file_dedupe_range.size |
| 1326 |
for info in range_infos: |
| 1327 |
_, _, bytes_deduped, status = file_dedupe_range_info.unpack_from(buf, pos) |
| 1328 |
info.bytes_deduped = bytes_deduped |
| 1329 |
info.status = status |
| 1330 |
pos += file_dedupe_range_info.size |
| 1331 |
|
| 1332 |
|
| 1333 |
ioctl_feature_flags = struct.Struct('=QQQ') |
| 1334 |
IOC_GET_FEATURES = _IOR(BTRFS_IOCTL_MAGIC, 57, ioctl_feature_flags) |
| 1335 |
|
| 1336 |
_feature_compat_str_map = { |
| 1337 |
} |
| 1338 |
|
| 1339 |
|
| 1340 |
def _compat_flags_str(flags): |
| 1341 |
return btrfs.utils.flags_str(flags, _feature_compat_str_map) |
| 1342 |
|
| 1343 |
|
| 1344 |
FEATURE_COMPAT_RO_FREE_SPACE_TREE = 1 << 0 |
| 1345 |
FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID = 1 << 1 |
| 1346 |
FEATURE_COMPAT_RO_BLOCK_GROUP_TREE = 1 << 3 |
| 1347 |
|
| 1348 |
_feature_compat_ro_str_map = { |
| 1349 |
FEATURE_COMPAT_RO_FREE_SPACE_TREE: 'free_space_tree', |
| 1350 |
FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID: 'free_space_tree_valid', |
| 1351 |
FEATURE_COMPAT_RO_BLOCK_GROUP_TREE: 'block_group_tree', |
| 1352 |
} |
| 1353 |
|
| 1354 |
|
| 1355 |
def _compat_ro_flags_str(flags): |
| 1356 |
return btrfs.utils.flags_str(flags, _feature_compat_ro_str_map) |
| 1357 |
|
| 1358 |
|
| 1359 |
FEATURE_INCOMPAT_MIXED_BACKREF = 1 << 0 |
| 1360 |
FEATURE_INCOMPAT_DEFAULT_SUBVOL = 1 << 1 |
| 1361 |
FEATURE_INCOMPAT_MIXED_GROUPS = 1 << 2 |
| 1362 |
FEATURE_INCOMPAT_COMPRESS_LZO = 1 << 3 |
| 1363 |
FEATURE_INCOMPAT_COMPRESS_ZSTD = 1 << 4 |
| 1364 |
FEATURE_INCOMPAT_BIG_METADATA = 1 << 5 |
| 1365 |
FEATURE_INCOMPAT_EXTENDED_IREF = 1 << 6 |
| 1366 |
FEATURE_INCOMPAT_RAID56 = 1 << 7 |
| 1367 |
FEATURE_INCOMPAT_SKINNY_METADATA = 1 << 8 |
| 1368 |
FEATURE_INCOMPAT_NO_HOLES = 1 << 9 |
| 1369 |
|
| 1370 |
_feature_incompat_str_map = { |
| 1371 |
FEATURE_INCOMPAT_MIXED_BACKREF: 'mixed_backref', |
| 1372 |
FEATURE_INCOMPAT_DEFAULT_SUBVOL: 'default_subvol', |
| 1373 |
FEATURE_INCOMPAT_MIXED_GROUPS: 'mixed_groups', |
| 1374 |
FEATURE_INCOMPAT_COMPRESS_LZO: 'compress_lzo', |
| 1375 |
FEATURE_INCOMPAT_COMPRESS_ZSTD: 'compress_zstd', |
| 1376 |
FEATURE_INCOMPAT_BIG_METADATA: 'big_metadata', |
| 1377 |
FEATURE_INCOMPAT_EXTENDED_IREF: 'extended_iref', |
| 1378 |
FEATURE_INCOMPAT_RAID56: 'raid56', |
| 1379 |
FEATURE_INCOMPAT_SKINNY_METADATA: 'skinny_metadata', |
| 1380 |
FEATURE_INCOMPAT_NO_HOLES: 'no_holes', |
| 1381 |
} |
| 1382 |
|
| 1383 |
|
| 1384 |
def _incompat_flags_str(flags): |
| 1385 |
return btrfs.utils.flags_str(flags, _feature_incompat_str_map) |
| 1386 |
|
| 1387 |
|
| 1388 |
class FeatureFlags(object): |
| 1389 |
"""Object representation of struct `btrfs_ioctl_feature_flags`. |
| 1390 |
|
| 1391 |
Quoting from linux kernel commit `f2b636e80d`: |
| 1392 |
|
| 1393 |
:ivar int compat_flags: These hold the features that are compatible with |
| 1394 |
older versions of btrfs. |
| 1395 |
:ivar int compat_ro_flags: These flags have features that are compatible |
| 1396 |
with older versions of btrfs if the fs is mounted read only. |
| 1397 |
:ivar int incompat_flags: This has features that are incompatible with |
| 1398 |
older versions of btrfs. |
| 1399 |
|
| 1400 |
Compat flags are currently not used. |
| 1401 |
|
| 1402 |
Known compat_ro flags (available as attribute of this module) are: |
| 1403 |
|
| 1404 |
- FEATURE_COMPAT_RO_FREE_SPACE_TREE |
| 1405 |
- FEATURE_COMPAT_RO_FREE_SPACE_TREE_VALID |
| 1406 |
- FEATURE_COMPAT_RO_BLOCK_GROUP_TREE |
| 1407 |
|
| 1408 |
Known incompat_flags (available as attribute of this module) are: |
| 1409 |
|
| 1410 |
- FEATURE_INCOMPAT_MIXED_BACKREF |
| 1411 |
- FEATURE_INCOMPAT_DEFAULT_SUBVOL |
| 1412 |
- FEATURE_INCOMPAT_MIXED_GROUPS |
| 1413 |
- FEATURE_INCOMPAT_COMPRESS_LZO |
| 1414 |
- FEATURE_INCOMPAT_COMPRESS_ZSTD |
| 1415 |
- FEATURE_INCOMPAT_BIG_METADATA |
| 1416 |
- FEATURE_INCOMPAT_EXTENDED_IREF |
| 1417 |
- FEATURE_INCOMPAT_RAID56 |
| 1418 |
- FEATURE_INCOMPAT_SKINNY_METADATA |
| 1419 |
- FEATURE_INCOMPAT_NO_HOLES |
| 1420 |
|
| 1421 |
Example:: |
| 1422 |
|
| 1423 |
>>> import btrfs |
| 1424 |
>>> with btrfs.FileSystem('/') as fs: |
| 1425 |
... features = fs.features() |
| 1426 |
... |
| 1427 |
>>> btrfs.utils.pretty_print(features) |
| 1428 |
<btrfs.ioctl.FeatureFlags> |
| 1429 |
compat_flags: none |
| 1430 |
compat_ro_flags: free_space_tree|free_space_tree_valid |
| 1431 |
incompat_flags: mixed_backref|default_subvol|compress_lzo|big_metadata|extended_iref |
| 1432 |
>>> features.incompat_flags & btrfs.ioctl.FEATURE_INCOMPAT_MIXED_GROUPS |
| 1433 |
0 |
| 1434 |
>>> features.compat_ro_flags & btrfs.ioctl.FEATURE_COMPAT_RO_FREE_SPACE_TREE |
| 1435 |
1 |
| 1436 |
|
| 1437 |
.. note:: |
| 1438 |
An object of this type should be retrieved by calling the |
| 1439 |
:func:`~btrfs.ctree.FileSystem.features` function on a |
| 1440 |
:class:`btrfs.ctree.FileSystem` object. |
| 1441 |
""" |
| 1442 |
def __init__(self, compat_flags, compat_ro_flags, incompat_flags): |
| 1443 |
self.compat_flags = compat_flags |
| 1444 |
self.compat_ro_flags = compat_ro_flags |
| 1445 |
self.incompat_flags = incompat_flags |
| 1446 |
|
| 1447 |
@staticmethod |
| 1448 |
def _pretty_properties(): |
| 1449 |
return [ |
| 1450 |
(_compat_flags_str, 'compat_flags'), |
| 1451 |
(_compat_ro_flags_str, 'compat_ro_flags'), |
| 1452 |
(_incompat_flags_str, 'incompat_flags'), |
| 1453 |
] |
| 1454 |
|
| 1455 |
|
| 1456 |
def get_features(fd): |
| 1457 |
"""Call the `BTRFS_IOC_GET_FEATURES` ioctl. |
| 1458 |
|
| 1459 |
:param int fd: Open file descriptor to any inode in the filesystem. |
| 1460 |
:returns: A :class:`FeatureFlags` object. |
| 1461 |
|
| 1462 |
.. note:: |
| 1463 |
This function should usually be used implicitly by calling the |
| 1464 |
:func:`~btrfs.ctree.FileSystem.features` function on a |
| 1465 |
:class:`btrfs.ctree.FileSystem` object. |
| 1466 |
""" |
| 1467 |
buf = bytearray(ioctl_feature_flags.size) |
| 1468 |
fcntl.ioctl(fd, IOC_GET_FEATURES, buf) |
| 1469 |
compat_flags, compat_ro_flags, incompat_flags = ioctl_feature_flags.unpack(buf) |
| 1470 |
return FeatureFlags(compat_flags, compat_ro_flags, incompat_flags) |
| 1471 |
|
| 1472 |
|
| 1473 |
DEFRAG_RANGE_COMPRESS = 1 << 0 |
| 1474 |
DEFRAG_RANGE_START_IO = 1 << 1 |
| 1475 |
|
| 1476 |
ioctl_defrag_range_args = struct.Struct('=QQQLL16x') |
| 1477 |
IOC_DEFRAG_RANGE = _IOW(BTRFS_IOCTL_MAGIC, 16, ioctl_defrag_range_args) |
| 1478 |
|
| 1479 |
|
| 1480 |
def defrag_range(fd, start=0, length=ULLONG_MAX, flags=0, extent_thresh=0, compress_type=0): |
| 1481 |
"""Call the `BTRFS_IOC_DEFRAG_RANGE` ioctl. |
| 1482 |
|
| 1483 |
Using the defrag_range function, we can: |
| 1484 |
|
| 1485 |
- Defragment (parts of) files (when fd points to a regular file). |
| 1486 |
- Defragment subvolume metadata (when fd points to a directory). |
| 1487 |
- (Re)compress (parts of) files to a certain compression type. |
| 1488 |
|
| 1489 |
:param int fd: Open file descriptor to a regular file or a directory. |
| 1490 |
:param int start: Offset to start the defragmentation at. Defaults |
| 1491 |
to 0. |
| 1492 |
:param int length: Amount of bytes to defrag, from the start position. |
| 1493 |
Defaults to 2**64-1. |
| 1494 |
:param int flags: Flags, mainly to activate the (re)compression |
| 1495 |
functionality. See below for more information. By default, no flags are |
| 1496 |
set. |
| 1497 |
:param int extent_thresh: Skip extents larger than this value in bytes. |
| 1498 |
Warning: this value might be ignored by kernel code, especially for |
| 1499 |
small-ish values. Defaults to 0, which in turn means it will be set to |
| 1500 |
the kernel code default value of 256kiB. |
| 1501 |
:param int compress_type: Compression type to use when (re)compressing file |
| 1502 |
content. Use one of the `COMPRESS_*` values from the |
| 1503 |
:class:`btrfs.ctree` module, e.g. `btrfs.ctree.COMPRESS_ZSTD`. |
| 1504 |
|
| 1505 |
Example:: |
| 1506 |
|
| 1507 |
>>> # In the first 40MiB of the file, try to combine together all |
| 1508 |
>>> # extents that have a length of less than a MiB. |
| 1509 |
>>> MiB = 2**20 |
| 1510 |
>>> fd = os.open('defrag_me', os.O_RDONLY) |
| 1511 |
>>> btrfs.ioctl.defrag_range(fd, start=0, length=40*MiB, extent_thresh=MiB) |
| 1512 |
|
| 1513 |
About using defrag to (re)compress file content: |
| 1514 |
|
| 1515 |
- To turn on the (re)compression functionality, provide |
| 1516 |
`DEFRAG_RANGE_COMPRESS` as flags. (Internally, this also sets the |
| 1517 |
`DEFRAG_RANGE_START_IO` flag and forces extent_thresh to 2**64-1.) |
| 1518 |
- Additionally, specify the target type as compression_type. |
| 1519 |
- It is not possible to decompress existing compressed data using this |
| 1520 |
function. This is because only a compress_type value greater than 0 is |
| 1521 |
considered, while the kernel default value is to use ZLIB. IOW, providing |
| 1522 |
value 0 selects ZLIB instead. |
| 1523 |
|
| 1524 |
Example:: |
| 1525 |
|
| 1526 |
>>> MiB = 2**20 |
| 1527 |
>>> fd = os.open('compress_me', os.O_RDONLY) |
| 1528 |
>>> btrfs.ioctl.defrag_range(fd, start=50*MiB, length=25*MiB, |
| 1529 |
... flags=btrfs.ioctl.DEFRAG_RANGE_COMPRESS, |
| 1530 |
... compress_type=btrfs.ctree.COMPRESS_ZSTD) |
| 1531 |
|
| 1532 |
Note: the parameter 'length' is called 'len' in kernel code, but 'len' is a |
| 1533 |
reserved keyword in Python. |
| 1534 |
""" |
| 1535 |
args = bytearray(ioctl_defrag_range_args.size) |
| 1536 |
ioctl_defrag_range_args.pack_into(args, 0, start, length, flags, extent_thresh, compress_type) |
| 1537 |
fcntl.ioctl(fd, IOC_DEFRAG_RANGE, args) |