Skip to content

btrfs: Add bd_btrfs_device_stats() to expose per-device error stats#1192

Merged
vojtechtrefny merged 1 commit intostoraged-project:masterfrom
vojtechtrefny:master_btrfs-device-stats
Apr 24, 2026
Merged

btrfs: Add bd_btrfs_device_stats() to expose per-device error stats#1192
vojtechtrefny merged 1 commit intostoraged-project:masterfrom
vojtechtrefny:master_btrfs-device-stats

Conversation

@vojtechtrefny
Copy link
Copy Markdown
Member

@vojtechtrefny vojtechtrefny commented Apr 21, 2026

Add a new function that retrieves btrfs device statistics (write/read/flush I/O errors, corruption errors, generation errors) using the BTRFS_IOC_GET_DEV_STATS ioctl. This avoids depending on the btrfs CLI tool and works without elevated privileges.

Fixes: #1167

Summary by CodeRabbit

  • New Features
    • Added ability to query Btrfs device statistics, retrieving per-device I/O and error metrics including write, read, and flush errors.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 21, 2026

Warning

Rate limit exceeded

@vojtechtrefny has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 49 minutes and 29 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 49 minutes and 29 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e2c934fd-0efb-423e-a8a4-10c79c218734

📥 Commits

Reviewing files that changed from the base of the PR and between cb1386e and b821d8a.

📒 Files selected for processing (5)
  • docs/libblockdev-sections.txt
  • src/lib/plugin_apis/btrfs.api
  • src/plugins/btrfs.c
  • src/plugins/btrfs.h
  • tests/btrfs_test.py
📝 Walkthrough

Walkthrough

This PR adds support for exposing Btrfs device statistics through libblockdev. It introduces a BDBtrfsDeviceStats type to represent per-device error counters and implements a bd_btrfs_device_stats() function that queries device statistics for all devices in a mounted Btrfs filesystem using ioctl calls. Memory management helpers and comprehensive test coverage are included.

Changes

Cohort / File(s) Summary
API Declarations
docs/libblockdev-sections.txt, src/lib/plugin_apis/btrfs.api, src/plugins/btrfs.h
Added new BDBtrfsDeviceStats type with fields for per-device error counters (write/read/flush I/O errors, corruption, generation errors). Added function declarations for bd_btrfs_device_stats() query function and bd_btrfs_device_stats_copy()/bd_btrfs_device_stats_free() memory management helpers. Includes type macro BD_BTRFS_TYPE_DEVICE_STATS and GObject type registration.
Implementation
src/plugins/btrfs.c
Implemented bd_btrfs_device_stats() using ioctl calls (BTRFS_IOC_FS_INFO, BTRFS_IOC_DEV_INFO, BTRFS_IOC_GET_DEV_STATS) to enumerate and collect device statistics. Implements copy and free helpers for the stats type. Includes error handling for missing devices (ENODEV) and array construction. Added system headers (fcntl.h, errno.h, sys/ioctl.h, linux/btrfs.h).
Tests
tests/btrfs_test.py
Added BtrfsTestDeviceStats test class with test_device_stats() method. Creates multi-device Btrfs volume, mounts filesystem, calls BlockDev.btrfs_device_stats(), and validates returned stats contain correct device count, IDs, paths, and zero error counters.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title clearly summarizes the main change: adding bd_btrfs_device_stats() function to expose per-device Btrfs error statistics.
Linked Issues check ✅ Passed The implementation fully addresses issue #1167 requirements by providing bd_btrfs_device_stats() that exposes per-device statistics (devid, path, write/read/flush I/O errors, corruption and generation errors) via ioctl without requiring elevated privileges.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the bd_btrfs_device_stats() function and its supporting infrastructure (type definitions, copy/free helpers, and comprehensive test coverage).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/plugins/btrfs.c (1)

997-1034: Bound enumeration by the reported device count.

Iterating until fs_info.max_id can issue a large number of BTRFS_IOC_DEV_INFO calls on filesystems with sparse/high device IDs. Stop once fs_info.num_devices entries have been collected to avoid avoidable latency.

♻️ Proposed loop bound
-    for (guint64 devid = 1; devid <= fs_info.max_id; devid++) {
+    for (guint64 devid = 1; devid <= fs_info.max_id && stats_array->len < fs_info.num_devices; devid++) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/plugins/btrfs.c` around lines 997 - 1034, The loop currently iterates
from 1 to fs_info.max_id calling BTRFS_IOC_DEV_INFO and BTRFS_IOC_GET_DEV_STATS
for every id which can be very large; change the logic in the loop that uses
devid to stop once you've successfully collected fs_info.num_devices entries
into stats_array (e.g., maintain a counter incremented when you g_ptr_array_add
a BDBtrfsDeviceStats) so you break out early when count == fs_info.num_devices,
keeping the existing ioctl/error handling for BTRFS_IOC_DEV_INFO and
BTRFS_IOC_GET_DEV_STATS and using the same variables (devid, dev_info,
dev_stats, stats_array, fs_info.num_devices).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib/plugin_apis/btrfs.api`:
- Around line 536-546: The documentation/availability mismatch:
bd_btrfs_device_stats is an ioctl-only API but the tech category in its header
(%BD_BTRFS_TECH_MULTI_DEV-%BD_BTRFS_TECH_MODE_QUERY) is treated by
bd_btrfs_is_tech_avail() as requiring the btrfs CLI; either add a new tech
category (e.g. %BD_BTRFS_TECH_DEVICE_STATS) and document bd_btrfs_device_stats
under that category, or update bd_btrfs_is_tech_avail() to treat this specific
category as ioctl-only (not requiring btrfs-progs); update the header comment
for bd_btrfs_device_stats and the tech enum/lookup so consumers can observe
availability without the CLI present and ensure bd_btrfs_is_tech_avail(), the
tech enum, and any docstrings are kept consistent.

In `@src/plugins/btrfs.c`:
- Around line 977-978: The availability check currently routes through
bd_btrfs_is_tech_avail() which requires the btrfs CLI, but
bd_btrfs_device_stats() only needs the kernel module; update the
module-dependency check to reflect the no-CLI implementation by removing or
replacing MODULE_DEPS_BTRFS_MASK with the kernel-only dependency mask (or a new
MODULE_DEPS_BTRFS_KERNEL constant) in the check_module_deps call used by
bd_btrfs_is_tech_avail() and the checks around bd_btrfs_device_stats(); ensure
the change touches the check_module_deps(invocation using avail_module_deps,
module_deps, MODULE_DEPS_LAST, deps_check_lock, error) sites so availability no
longer requires the btrfs CLI.

---

Nitpick comments:
In `@src/plugins/btrfs.c`:
- Around line 997-1034: The loop currently iterates from 1 to fs_info.max_id
calling BTRFS_IOC_DEV_INFO and BTRFS_IOC_GET_DEV_STATS for every id which can be
very large; change the logic in the loop that uses devid to stop once you've
successfully collected fs_info.num_devices entries into stats_array (e.g.,
maintain a counter incremented when you g_ptr_array_add a BDBtrfsDeviceStats) so
you break out early when count == fs_info.num_devices, keeping the existing
ioctl/error handling for BTRFS_IOC_DEV_INFO and BTRFS_IOC_GET_DEV_STATS and
using the same variables (devid, dev_info, dev_stats, stats_array,
fs_info.num_devices).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a1ecfe5a-b256-45c0-815f-a04037295b74

📥 Commits

Reviewing files that changed from the base of the PR and between 81c7a4b and cb1386e.

📒 Files selected for processing (5)
  • docs/libblockdev-sections.txt
  • src/lib/plugin_apis/btrfs.api
  • src/plugins/btrfs.c
  • src/plugins/btrfs.h
  • tests/btrfs_test.py

Comment thread src/lib/plugin_apis/btrfs.api
Comment thread src/plugins/btrfs.c
Add a new function that retrieves btrfs device statistics (write/read/flush
I/O errors, corruption errors, generation errors) using the
BTRFS_IOC_GET_DEV_STATS ioctl. This avoids depending on the btrfs CLI tool
and works without elevated privileges.

Fixes: storaged-project#1167

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@vojtechtrefny vojtechtrefny force-pushed the master_btrfs-device-stats branch from cb1386e to b821d8a Compare April 21, 2026 08:43
@vojtechtrefny
Copy link
Copy Markdown
Member Author

@jelly please take a look

Copy link
Copy Markdown
Contributor

@jelly jelly left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me

@vojtechtrefny vojtechtrefny merged commit 770148e into storaged-project:master Apr 24, 2026
49 of 50 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RFE] expose btrfs device stats

4 participants