├── .github
└── workflows
│ ├── ci.yaml
│ └── future_proof.yaml
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── LICENSE-GPL-3.0
├── README.md
├── build.rs
├── clippy.toml
├── contrib
├── 19-ublk-unprivileged.example.rules
├── config-memory.example.toml
├── config-onedrive.example.toml
├── cryptsetup-format-zoned.sh
├── orb.nix
└── orb@.example.service
├── default.nix
├── flake.lock
├── flake.nix
├── orb-ublk
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── build.rs
├── examples
│ ├── loop.rs
│ ├── management.rs
│ └── zoned.rs
├── src
│ ├── lib.rs
│ ├── runtime.rs
│ ├── sys.rs
│ └── ublk.rs
└── tests
│ ├── basic.rs
│ └── interrupt.rs
├── src
├── cli.rs
├── lib.rs
├── main.rs
├── memory_backend.rs
├── onedrive_backend.rs
├── onedrive_backend
│ └── login.rs
├── service.rs
└── tests.rs
└── ublk-chown-unprivileged
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
└── src
└── main.rs
/.github/workflows/ci.yaml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | pull_request:
4 | push:
5 |
6 | permissions:
7 | contents: read
8 |
9 | env:
10 | RUST_BACKTRACE: full
11 | RUSTDOCFLAGS: -Dwarnings
12 | RUSTFLAGS: -Dwarnings
13 |
14 | jobs:
15 | style:
16 | name: Code style
17 | runs-on: ubuntu-latest
18 | timeout-minutes: 15
19 | steps:
20 | - name: Checkout
21 | uses: actions/checkout@v4
22 |
23 | - name: Install Rust stable
24 | run: |
25 | rustup update --no-self-update stable
26 | rustup default stable
27 |
28 | - name: Cache Dependencies
29 | uses: Swatinem/rust-cache@v2
30 |
31 | - name: Rustfmt
32 | run: cargo fmt -- --check
33 |
34 | - name: Clippy
35 | run: cargo clippy --workspace --all-targets -- -D clippy::dbg_macro -D clippy::todo
36 |
37 | - name: Rustdoc
38 | run: cargo doc --workspace
39 |
40 | test:
41 | strategy:
42 | matrix:
43 | rust: [stable, '1.76'] # NB. Sync with Cargo.toml.
44 | name: Test ${{ matrix.rust }}
45 | runs-on: ubuntu-latest
46 | timeout-minutes: 15
47 | steps:
48 | - name: Load kernel module ublk_drv
49 | run: |
50 | sudo apt-get update
51 | sudo apt-get install --no-install-recommends --yes "linux-modules-extra-$(uname -r)"
52 | sudo modprobe ublk_drv
53 |
54 | - name: Checkout
55 | uses: actions/checkout@v4
56 |
57 | - name: Install Rust ${{ matrix.rust }}
58 | run: |
59 | rustup update --no-self-update ${{ matrix.rust }}
60 | rustup default ${{ matrix.rust }}
61 |
62 | - name: Cache Dependencies
63 | uses: Swatinem/rust-cache@v2
64 |
65 | - name: Build
66 | run: cargo build --workspace --all-targets
67 |
68 | - name: Test
69 | run: cargo test --workspace --all-targets -- --include-ignored
70 | env:
71 | CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER: sudo
72 |
73 | nix-flake:
74 | name: Flake package
75 | runs-on: ubuntu-latest
76 | timeout-minutes: 15
77 | steps:
78 | - name: Checkout
79 | uses: actions/checkout@v4
80 |
81 | - name: Install Nix
82 | uses: cachix/install-nix-action@v26
83 | with:
84 | github_access_token: ${{ secrets.GITHUB_TOKEN }}
85 |
86 | - name: Flake check
87 | run: nix flake check --no-update-lock-file --show-trace
88 |
89 | - name: Flake build
90 | run: nix build --no-update-lock-file --show-trace --print-build-logs
91 |
--------------------------------------------------------------------------------
/.github/workflows/future_proof.yaml:
--------------------------------------------------------------------------------
1 | name: Future proof tests
2 | on:
3 | schedule:
4 | - cron: '6 1 * * 0' # Sun *-*-* 01:06:00 UTC
5 |
6 | workflow_dispatch:
7 |
8 | permissions:
9 | contents: read
10 |
11 | env:
12 | RUST_BACKTRACE: full
13 | RUSTFLAGS: -Dwarnings
14 |
15 | jobs:
16 | outdated:
17 | name: Outdated
18 | runs-on: ubuntu-latest
19 | timeout-minutes: 15
20 | steps:
21 | - name: Checkout
22 | uses: actions/checkout@v4
23 |
24 | - name: Install cargo-outdated
25 | uses: dtolnay/install@cargo-outdated
26 |
27 | - name: cargo-outdated
28 | run: |
29 | rm Cargo.lock # Ignore trivially updatable compatible versions.
30 | cargo outdated --workspace --exit-code 1
31 |
32 | test:
33 | strategy:
34 | matrix:
35 | rust: [beta, nightly]
36 | name: Test ${{ matrix.rust }}
37 | runs-on: ubuntu-latest
38 | timeout-minutes: 15
39 | steps:
40 | - name: Load kernel module ublk_drv
41 | run: |
42 | sudo apt-get update
43 | sudo apt-get install --no-install-recommends --yes "linux-modules-extra-$(uname -r)"
44 | sudo modprobe ublk_drv
45 |
46 | - name: Checkout
47 | uses: actions/checkout@v4
48 |
49 | - name: Install Rust ${{ matrix.rust }}
50 | run: |
51 | rustup update --no-self-update ${{ matrix.rust }}
52 | rustup default ${{ matrix.rust }}
53 |
54 | - name: Cache Dependencies
55 | uses: Swatinem/rust-cache@v2
56 |
57 | - name: Build
58 | run: cargo build --workspace --all-targets
59 |
60 | - name: Test
61 | run: cargo test --workspace --all-targets -- --include-ignored
62 | env:
63 | CARGO_TARGET_X86_64_UNKNOWN_LINUX_GNU_RUNNER: sudo
64 |
65 |
66 | nix-flake-latest:
67 | name: Flake package following latest
68 | runs-on: ubuntu-latest
69 | timeout-minutes: 15
70 | steps:
71 | - name: Checkout
72 | uses: actions/checkout@v4
73 |
74 | - name: Install Nix
75 | uses: cachix/install-nix-action@v26
76 | with:
77 | github_access_token: ${{ secrets.GITHUB_TOKEN }}
78 |
79 | - name: Flake update
80 | # https://github.com/actions/checkout/tree/v3.3.0#push-a-commit-using-the-built-in-token
81 | run: |
82 | git config user.name github-actions
83 | git config user.email github-actions@github.com
84 | nix flake update --commit-lock-file
85 |
86 | - name: Flake check
87 | run: nix flake check --no-update-lock-file --show-trace
88 |
89 | - name: Flake build
90 | run: nix build --no-update-lock-file --show-trace --print-build-logs
91 |
92 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | /completions
3 |
4 | result
5 | result-*
6 | config*.toml
7 | !config*.example.toml
8 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "orb"
3 | version = "0.1.0"
4 | edition = "2021"
5 | description = "OneDrive as a block device"
6 | license = "GPL-3.0-or-later"
7 | # NB. Sync with CI and README.
8 | rust-version = "1.76" # orb-ublk
9 |
10 | [features]
11 | default = []
12 | completion = ["dep:clap", "dep:clap_complete"]
13 |
14 | [dependencies]
15 | anyhow = "1"
16 | bytes = "1"
17 | bytesize = { version = "2", features = ["serde"] }
18 | clap = { version = "4", features = ["derive"] }
19 | dirs = "6"
20 | futures-util = { version = "0.3", features = ["io"] }
21 | hostname = "0.4"
22 | humantime = "2"
23 | hyper = { version = "1", features = ["http1", "server"] }
24 | hyper-util = "0.1"
25 | itertools = "0.14"
26 | lru = "0.14"
27 | onedrive-api = "0.10"
28 | open = "5.1"
29 | orb-ublk = { path = "./orb-ublk", features = ["tokio"] }
30 | parking_lot = "0.12"
31 | rand = "0.9"
32 | reqwest = { version = "0.12", features = ["stream"] }
33 | rustix = { version = "1", features = ["fs", "time", "stdio"] }
34 | scoped-tls = "1"
35 | scopeguard = "1"
36 | sd-notify = "0.4"
37 | serde = { version = "1", features = ["derive"] }
38 | serde-inline-default = "0.2"
39 | serde_json = "1"
40 | tokio = { version = "1", features = ["macros", "net", "rt", "signal", "sync", "time"] }
41 | toml = "0.8"
42 | tracing = { version = "0.1", features = ["log"] }
43 | tracing-futures = { version = "0.2", features = ["futures-03"] }
44 | tracing-subscriber = { version = "0.3", features = ["env-filter", "tracing-log"] }
45 |
46 | [dev-dependencies]
47 | rustix = { version = "1", features = ["fs"] }
48 |
49 | [build-dependencies]
50 | clap = { version = "4", optional = true, features = ["derive"] }
51 | clap_complete = { version = "4", optional = true }
52 |
53 | [workspace]
54 | resolver = "2"
55 | members = ["orb-ublk", "ublk-chown-unprivileged"]
56 |
57 | [profile.bench]
58 | debug = "full"
59 |
60 | [lints.clippy]
61 | pedantic = { level = "warn", priority = -1 }
62 |
63 | # Of course everything involving networks may fail.
64 | missing-errors-doc = "allow"
65 | # False positive: `rest` vs. `ret`, `off` vs. `coff`, etc.
66 | similar-names = "allow"
67 | # False positive on `unwrap` and `expect` for fail-means-bug semantics.
68 | missing-panics-doc = "allow"
69 | # Long sequential tasks (`login::interactive`, `onedrive_backend::init`) where
70 | # splitting fns can only increase the complexity.
71 | too-many-lines = "allow"
72 | # Workaround: https://github.com/rust-lang/rust-clippy/issues/13184
73 | explicit-iter-loop = "allow"
74 |
75 | # TODO: Caused by zid and coff are used as u32 and usize interchangably.
76 | cast-lossless = "allow"
77 | cast-possible-truncation = "allow"
78 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OneDrive as a block device
2 |
3 | :warning: This project is in beta stage.
4 |
5 | ## Audience
6 |
7 | If you are not sure whether this project fits your need, then it does not. You
8 | are probably looking for
9 | [OneDrive Online](https://onedrive.live.com/) or sync and FUSE implementations
10 | like [rclone](https://github.com/rclone/rclone).
11 |
12 | This project may be helpful for :penguin: *real nerds* :penguin: who enjoy
13 | wacky block device stacking, intend to leverage block level encryption or their
14 | existing BTRFS backup infrastructure, or explore fresh new bugs in BTRFS zoned
15 | mode, with the cost of *everything*.
16 |
17 | ## Installation
18 |
19 | System requirements:
20 |
21 | - Linux >= 5.19 is required for io-uring with `IORING_SETUP_SQE128` support.
22 |
23 | - Kernel driver `ublk_drv` and zoned block device support should be enabled.
24 | Most distributions like Arch Linux and NixOS unstable meet these requirements
25 | by default. You can check your system by:
26 |
27 | ```console
28 | $ zgrep -E 'CONFIG_BLK_DEV_UBLK|CONFIG_BLK_DEV_ZONED' /proc/config.gz
29 | CONFIG_BLK_DEV_ZONED=y
30 | CONFIG_BLK_DEV_UBLK=m
31 | ```
32 | If you see the same result, your kernel is probably supported.
33 |
34 | - You may need to run `sudo modprobe ublk_drv` manually to load the driver
35 | first. This is not required for running orb in the shipped systemd service or
36 | via NixOS module, which does this automatically.
37 |
38 | ### Nix/NixOS (flake)
39 |
40 | This project is packaged in Nix flake. Here's the simplified output graph:
41 | ```
42 | ├───nixosModules
43 | │ ├───default: Alias to `orb`.
44 | │ └───orb: The NixOS module.
45 | └───packages
46 | ├───x86_64-linux
47 | │ ├───default: Alias to `orb`.
48 | │ ├───orb: The main program with systemd units.
49 | │ ├───cryptsetup-format-zoned: workaround script for cryptsetup-luksFormat on zoned devices.
50 | │ └───ublk-chown-unprivileged: The optional utility for unprivileged ublk.
51 | [..more Linux platforms are supported..]
52 | ```
53 |
54 |
55 |
56 | Example configurations
57 |
58 | To use the orb service, add the flake input `github:oxalica/orb`, and import
59 | its NixOS modules.
60 | ```nix
61 | # Example flake.nix for demostration. Please edit your own one to add changes.
62 | {
63 | inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
64 | inputs.orb.url = "github:oxalica/orb";
65 |
66 | outputs = { nixpkgs, orb, ... }: {
67 | nixosConfigurations.your-system = nixpkgs.lib.nixosSystem {
68 | system = "x86_64-linux";
69 | modules = with nixosModules; [
70 | orb.nixosModules.orb
71 | ./path/to/your/configuration.nix
72 | ];
73 | };
74 | };
75 | }
76 | ```
77 |
78 | Now you can use the module in your `configuration.nix`:
79 | ```nix
80 | { ... }:
81 | {
82 | services.orb.instances = {
83 | # The instance name. It coresponds to the systemd service
84 | # `orb@my-device.service`. By default it will not be automatically started.
85 | "my-device".settings = {
86 | # Required device id. It's recommended to start at 80.
87 | # This creates block device `/dev/ublkb80`.
88 | ublk.id = 80;
89 | # Other settings and their defaults can be seen in
90 | # ./contrib/config-onedrive.example.toml
91 | device = {
92 | dev_size = "1TiB";
93 | zone_size = "256MiB";
94 | min_chunk_size = "1MiB";
95 | max_chunk_size = "256MiB";
96 | };
97 | backend.onedrive.remote_dir = "/orb";
98 | };
99 | };
100 |
101 | # If you want to mount the block device, you can create systemd mounts.
102 | # This is an example.
103 | systemd.mounts = [
104 | {
105 | type = "btrfs";
106 | # Fill in your filesystem UUID after mkfs.
107 | what = "/dev/disk/by-uuid/11111111-2222-3333-4444-555555555555";
108 | where = "/mnt/my-mount-point";
109 | # Do not forget dependencies.
110 | requires = [ "orb@my-device.service" ];
111 | after = [ "orb@my-device.service" ];
112 | # It's recommended to set `noatime` and `compress` to reduce write
113 | # frequency and amplification.
114 | options = "noatime,compress=zstd:7";
115 | }
116 | ];
117 | }
118 | ```
119 |
120 | Note that the service can only work after login and setup first. See the
121 | following sections for details.
122 |
123 |
124 |
125 | ### Other Linux distributions
126 |
127 | You need following dependencies to be installed with your package manager:
128 | - Rust >= 1.76
129 | - pkg-config
130 | - openssl
131 |
132 | Build command: `cargo build --release`
133 |
134 | [`contrib/orb@.example.service`](./contrib/orb@.example.service)
135 | is the example template systemd service to install.
136 | The instance configurations locate at `/etc/orb/.toml`, whose format is
137 | documented in
138 | [`./contrib/config-onedrive.example.toml`](./contrib/config-onedrive.example.toml).
139 | Once configured and logined (see the next section), run
140 | `systemctl start orb@.service` to start the service.
141 |
142 | ## First time login
143 |
144 | The service configuration does not contain the login credential. It must be
145 | interactively setup for the first time, and then the service will rotate the
146 | credentials automatically unless the user revokes the permission, or after a
147 | long offline time (seems to be >1month, but is determined by Microsoft).
148 |
149 | 1. First, you need to know this project (orb) is an third party program which
150 | access your files on Microsoft OneDrive on behalf of you, to provide block
151 | device interface as a service. Your files and/or data on your Microsoft
152 | OneDrive may be lost due to program bugs or other reasons. We provide no
153 | warranties. By following the login steps below, you understood and want to
154 | use orb at your own risk.
155 |
156 | 2. We cannot provide an "official App/Client ID" without risking impersonated
157 | because this project is open sourced and free to distribute. So you need to
158 | [register your own App on Microsoft
159 | Azure](https://portal.azure.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).
160 |
161 | In the registration page,
162 | - In "Supported account types" section, select "Personal Microsoft accounts
163 | only". Other accounts are currently unsupported.
164 | - In "Redirect URI (optional)" section, select "Public client/native
165 | (mobile & desktop)", and enter the following URI:
166 | ```text
167 | http://localhost
168 | ```
169 | It must be this exactly (it's `http` not `https`), or you may fail the
170 | next step.
171 |
172 | Then click "Register", it will jump to the registered App information page
173 | if success. In "Essential" section, copy the UUID in the "Application
174 | (client) ID" field. This is the Client ID to be used in the next step.
175 | Note that one App can be used in multiple accounts, for multiple times. You
176 | do not need to register more than one App in almost any cases.
177 |
178 | 3. Login with this command with root permission with arguments filled:
179 | ```console
180 | # orb login --systemd --client-id
181 | ```
182 | `` is the instance name of your systemd service (for example, you
183 | setup `/etc/orb/foo.toml`, then `foo` is the instance name) or in NixOS
184 | module setting `services.orb.instances.`.
185 |
186 | It will prompt a URL, and you need to open it in your browser and following
187 | the interactive login steps to login into your Microsoft account with
188 | OneDrive.
189 |
190 | The credential will be saved under `/var/lib/orb/`, owned by
191 | root, and cannot be accessed by non-root users. It will be rotated by the
192 | service, and please never copy or save it outside the local machine. If you
193 | need to login to the same account on two machines, login twice.
194 |
195 | :warning:
196 | You must not serve the same remote directory simultaneously in multiple
197 | instances (or machines), or it will cause data race and your data will be
198 | corrupted. orb will try its best to detect and prevent such racing serving.
199 |
200 | 4. On success, the web page will redirect to a mostly empty page with only one line:
201 | ```text
202 | Successfully logined. This page can be closed.
203 | ```
204 |
205 | The command should exit normally with credential saved. Now you are ready
206 | to start the orb service.
207 |
208 | ## Use the emulated block device
209 |
210 | Once your logined and started the service successfully, you are ready to use it.
211 | Usually you need to create an filesystem on the emulated block device, and this
212 | is almost the same as the setup for your fresh hard disks, with a few
213 | exceptions:
214 |
215 | - The emulated device is under `/dev/ublkb` where `ID` is specified in
216 | your configuration `ublk.id`.
217 |
218 | - The device is a
219 | [zoned device](https://zonedstorage.io/docs/introduction/zoned-storage)
220 | (aka. ZBC/ZBD/ZNS, host managed SMR disks) due to API restrictions and
221 | performance reasons. Only a few filesystems and/or device mappers support it,
222 | eg. dm-crypt, F2FS and BTRFS.
223 |
224 | - It has a high latency and low throughput depend on your network. Doing
225 | active works on it should be avoided. It can be used, for example, for
226 | backup purpose.
227 |
228 | - :warning: Since the block device is emulated, you must ensure to `umount` the
229 | filesystem on it before shutting down the backing device service
230 | (`orb@.service`), or you will lose your last written data. This
231 | could be enforced by systemd mounts with a `BindsTo=` dependency.
232 |
233 | ### Caveats on deletion and space usage
234 |
235 | Due to the limitation of OneDrive API, permanently deletion cannot be done via
236 | API. You may need to regularily "Empty recycle bin" on [OneDrive
237 | online](https://onedrive.live.com) to free the capacity occupied.
238 |
239 | :warning: You MUST not "Restore" any files under the directory managed by the
240 | orb service (`backend.onedrive.remote_dir`). Otherwise, it may break filesystem
241 | consistency and your data may be lost.
242 |
243 | ### Example: setup encryption via LUKS/dm-crypt
244 |
245 |
246 |
247 | Details
248 |
249 |
250 | :warning: cryptsetup does not and probably will not support zoned devices
251 | natively, because of non-trivial handling logic, see
252 | [this issue](https://gitlab.com/cryptsetup/cryptsetup/-/issues/877) and
253 | [this merge request](https://gitlab.com/cryptsetup/cryptsetup/-/merge_requests/638).
254 | Generally you should avoid this unsupported usage, unless there is no other way
255 | around.
256 |
257 | :warning: Of course, this will destroy all of your data on the emulated device,
258 | aka. the remote directory in OneDrive holding the data.
259 |
260 | cryptsetup does not support formatting zoned devices, but dm-crypt supports it.
261 | We need to format and place the LUKS2 header manually, and then it can be
262 | opened and/or closed in the normal way. For convenience, there is a script
263 | under
264 | [`./contrib/cryptsetup-format-zoned.sh`](./contrib/cryptsetup-format-zoned.sh)
265 | to mimic `cryptsetup luksFormat` as a workaround. Run:
266 |
267 | ```console
268 | # ./contrib/cryptsetup-format-zoned.sh /dev/ublkb # Use a a password.
269 | OR
270 | # ./contrib/cryptsetup-format-zoned.sh /dev/ublkb /path/to/key/file # Use a key file.
271 | ```
272 |
273 | Alternatively, you can run the script via flake package:
274 | ```console
275 | $ nix shell github:oxalica/orb#cryptsetup-format-zoned -c sudo cryptsetup-format-zoned /dev/ublkb
276 | ```
277 |
278 | Note that editing header, ie. adding or removing keys, also requires careful
279 | manual operations. You need do it yourself when needed.
280 |
281 | After formatting the block device, you can open and/or close it in the normal
282 | way:
283 | ```console
284 | # cryptsetup luksOpen /dev/ublkb my-device-unencrypted
285 | # cryptsetup close my-device-unencrypted
286 | ```
287 |
288 | If you are using key files, you can also use systemd-cryptsetup services to
289 | manage dm-crypt. This is useful when you want to specify dependencies to
290 | `orb@.service` and downstream services, eg. backup services.
291 | ```nix
292 | { ... }:
293 | {
294 | environment.etc."crypttab".text = ''
295 | mydecrypteddev /dev/ublkb /path/to/key/file noauto
296 | '';
297 | systemd.services."systemd-cryptsetup@mydecrypteddev" = {
298 | # Inform Nix that this is an overriding units for auto-generated ones.
299 | overrideStrategy = "asDropin";
300 | # Specify dependencies to the orb service.
301 | bindsTo = [ "orb@my-instance.service" ];
302 | after = [ "orb@my-instance.service" ];
303 | };
304 | }
305 | ```
306 |
307 |
308 |
309 | ### Example: format it as BTRFS
310 |
311 |
312 |
313 | Details
314 |
315 |
316 | :warning: Of course, this will destroy all of your data on the emulated device,
317 | aka. the remote directory in OneDrive holding the data.
318 |
319 | It is recommended to format BTRFS with `block-group-tree` feature enabled, to
320 | dramastically reduce mounting time (~50s to ~2s). You need btrfs-progs >= 6.8.1
321 | with [a relevant bug](https://github.com/kdave/btrfs-progs/issues/765) getting fixed.
322 |
323 | ```console
324 | # mkfs.btrfs /dev/ublkb -O block-group-tree
325 | ```
326 |
327 | `zoned` feature will be automatically detected and enabled without manual
328 | specification.
329 |
330 | Now you can mount it and do read/write operations. These are recommended mount
331 | options (disable atime, high level zstd compression enabled):
332 | ```console
333 | sudo mount -t btrfs -o noatime,compress=zstd:7 /dev/ublkb /mnt/my-mount-point
334 | ```
335 |
336 |
337 |
338 | ## License
339 |
340 | The sub-package `orb-ublk` and `ublk-chown-unprivileged` (directory
341 | `/orb-ublk`, `/ublk-chown-unprivileged` and the whole sub-tree of them)
342 | are licensed under either of [Apache License, Version
343 | 2.0](./orb-ublk/LICENSE-APACHE) or [MIT license](./orb-ublk/LICENSE-MIT) at
344 | your option.
345 |
346 | The main package (all other files in the repository except content of
347 | `/orb-ublk` and/or `/ublk-chown-unprivileged` directory) is licensed under
348 | [GNU General Public License v3.0](./LICENSE-GPL-3.0) or (at your option) later
349 | versions.
350 |
--------------------------------------------------------------------------------
/build.rs:
--------------------------------------------------------------------------------
1 | #[cfg(feature = "completion")]
2 | #[allow(dead_code)]
3 | #[path = "src/cli.rs"]
4 | mod cli;
5 |
6 | fn main() {
7 | // Do NOT rerun on src changes.
8 | println!("cargo:rerun-if-changed=build.rs");
9 |
10 | println!("cargo:rerun-if-env-changed=CFG_RELEASE");
11 | if std::env::var("CFG_RELEASE").is_err() {
12 | let version = std::env::var("CARGO_PKG_VERSION").unwrap();
13 | println!("cargo:rustc-env=CFG_RELEASE={version}");
14 | }
15 |
16 | #[cfg(feature = "completion")]
17 | {
18 | use clap::ValueEnum;
19 | use clap_complete::{generate_to, shells::Shell};
20 |
21 | let out_dir = std::path::Path::new("completions");
22 | let pkg_name = std::env::var("CARGO_PKG_NAME").expect("have CARGO_PKG_NAME");
23 | let mut cmd = ::command();
24 | for &shell in Shell::value_variants() {
25 | let out_dir = out_dir.join(shell.to_string());
26 | std::fs::create_dir_all(&out_dir).expect("create_dir_all");
27 | if let Err(err) = generate_to(shell, &mut cmd, &pkg_name, &out_dir) {
28 | panic!("failed to generate completion for {shell}: {err}");
29 | }
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/clippy.toml:
--------------------------------------------------------------------------------
1 | doc-valid-idents = [
2 | "OneDrive",
3 | "READ", "WRITE", "ZONE_RESET", "ZONE_RESET_ALL", "ZONE_APPEND",
4 | "..",
5 | ]
6 |
--------------------------------------------------------------------------------
/contrib/19-ublk-unprivileged.example.rules:
--------------------------------------------------------------------------------
1 | KERNEL=="ublk-control", MODE="0666", OPTIONS+="static_node=ublk-control"
2 | ACTION=="add",KERNEL=="ublk[bc]*",RUN+="/usr/libexec/ublk-chown-unprivileged /dev/%k"
3 |
--------------------------------------------------------------------------------
/contrib/config-memory.example.toml:
--------------------------------------------------------------------------------
1 | # This is an example configuration for a virtual block device in memory,
2 | # which is mainly for testing and benchmarking the chunking implementation
3 | # (frontend).
4 |
5 | # `[device]` and `[ublk]` section is the same for all backends.
6 | # See `config-onedrive.example.toml` for details.
7 | [device]
8 | dev_size = "1GiB"
9 | zone_size = "8MiB"
10 | min_chunk_size = "1MiB"
11 | max_chunk_size = "8MiB"
12 |
13 | [ublk]
14 | unprivileged = true
15 |
16 | # Use 'memory' backend.
17 | # Exact one backend must be chosen.
18 | [backend.memory]
19 | # This backend has no sub-configurations currently, but the section header must
20 | # not be omitted.
21 |
--------------------------------------------------------------------------------
/contrib/config-onedrive.example.toml:
--------------------------------------------------------------------------------
1 | # This is an example configuration serving OneDrive storage as a block device.
2 | # Note that login credentials are not passed here, see README.md for details.
3 | #
4 | # Commented options are not required and have default values as in the comment.
5 | # Uncommented options are required and values are given as examples.
6 |
7 | # Device parameters and geometry.
8 | # Sizes below can be written as integers for byte unit, or a string with usual
9 | # SI-units. They must be multiples of logical sectors (512B).
10 | [device]
11 | # Total device size, must be a multiple of `zone_size`.
12 | dev_size = "4GiB"
13 | # The size of a zone, the minimal reset (delete) unit. It cannot be changed
14 | # without losing all the data. Some filesystems have requirement on it, eg.
15 | # BTRFS requires it to be `4MiB..=4GiB`.
16 | zone_size = "256MiB"
17 | # The minimal size for a standalone chunk to minimize fragmentation, must be
18 | # less than `max_chunk_size`. Chunks smaller than it will be fully rewritten on
19 | # committing until they grow larger than this limit.
20 | min_chunk_size = "1MiB"
21 | # The maximum size a chunk can be, also the maximum buffer size for each zone,
22 | # must be less than `zone_size`. When a trailing chunk in a zone is grown
23 | # exceeding this size, following write requests will wait the chunk to be
24 | # committed to backend before continue.
25 | max_chunk_size = "128MiB"
26 |
27 | # The maximum number of concurrenct download streams.
28 | #max_concurrent_streams = 16
29 |
30 | # The maximum number of concurrent upload streams. The maximum buffer memory
31 | # consumption can be calculated by `max_concurrent_commits * max_chunk_size`.
32 | # Further WRITE/APPEND/FINISH will block until some buffers being committed.
33 | #max_concurrent_commits = 8
34 |
35 | # ublk device and queue configurations.
36 | [ublk]
37 | # The device id, ie. the integer part in `/dev/ublk{b,c}X`, to use.
38 | # A negative id indicates auto-allocation.
39 | #id = -1
40 |
41 | # Create an unprivileged block device, this requires a custom udev rules to
42 | # change permission automatically. An unprivileged device also have a hard
43 | # limit 10 seconds to complete any requests, or the service process will be
44 | # killed by the ublk_drv driver. Using unprivileged block device also disables
45 | # IO_FLUSHER state setting (see prctl(2)), which can potentially cause kernel
46 | # deadlock under memory pressure.
47 | #
48 | # See:
49 | # https://github.com/ublk-org/ublksrv?tab=readme-ov-file#use-unprivileged-ublk-in-docker
50 | # https://man7.org/linux/man-pages/man2/prctl.2.html
51 | #unprivileged = false
52 |
53 | # The max concurrency of the request queue.
54 | #queue_depth = 64
55 |
56 | # Use 'onedrive' backend.
57 | # Exact one backend must be chosen.
58 | [backend.onedrive]
59 |
60 | # The remote directory path for storing data. It must have no trailing slashes.
61 | # It must not be root, to keep this application scoped.
62 | remote_dir = "/orb"
63 |
64 | # The directory to store states, including credentials. It is taken verbatimly
65 | # if it is non-empty. Otherwise, following values are checked with environment
66 | # substitution:
67 | # 1. `$STATE_DIRECTORY`, if it is set.
68 | # 2. `$XDG_STATE_HOME/orb`, if `$XDG_STATE_HOME` is set.
69 | # 3. `$HOME/.local/state/orb`, if `$HOME` is set or can be inferred.
70 | # 4. Fail.
71 | #
72 | # The directory will be created recursively if not exists, and it should be
73 | # writable.
74 | #state_dir = ""
75 |
76 | # Connection timeout in seconds.
77 | #connect_timeout_sec = 15
78 |
79 | # The size of each part request for large uploads.
80 | # It will be clamped to [4MB, 60MiB] and aligned to 320KiB.
81 | #upload_part_max_size = "60MiB"
82 |
--------------------------------------------------------------------------------
/contrib/cryptsetup-format-zoned.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # This script is the workaround for cryptsetup-luksFormat on zoned device
3 | # See: https://gitlab.com/cryptsetup/cryptsetup/-/issues/877
4 | set -euo pipefail
5 |
6 | if [[ $# < 1 || ! -b "$1" ]]; then
7 | echo "Usage: $0 [CRYPTSETUP_OPTS...]" >&2
8 | exit 1
9 | fi
10 |
11 | if [[ $UID -ne 0 ]]; then
12 | echo "WARNING: The script is not running as root. Operations may fail." >&2
13 | fi
14 |
15 | bdev="$1"
16 | shift
17 | zone_size="$(lsblk --noheadings --nodeps --bytes -o ZONE-SZ "$bdev")"
18 | if [[ ! "$zone_size" =~ [0-9]+ ]]; then
19 | echo "Invalid zone size for $bdev: $zone_size" >&2
20 | exit 1
21 | fi
22 |
23 | header_size=$(( 16 << 20 ))
24 | format_args=(--luks2-keyslots-size 15M)
25 | if (( zone_size < header_size )); then
26 | header_size=$zone_size
27 | format_args=()
28 | fi
29 |
30 | echo -n "Reset the first zone of $bdev and format it as LUKS? This will kill all data on the device [y/N]: " >&2
31 | read -r line
32 | if [[ "$line" != [yY] ]]; then
33 | echo "Cancelled" >&2
34 | exit 1
35 | fi
36 |
37 | header="$(mktemp /dev/shm/header.XXX)"
38 | trap 'rm -vf "$header"' EXIT
39 | truncate -s "$header_size" "$header"
40 |
41 | set -x
42 | blkzone reset --offset 0 --count 1 "$bdev"
43 | cryptsetup luksFormat --header "$header" --offset "$(( zone_size >> 9 ))" "${format_args[@]}" "$bdev" "$@"
44 | dd if="$header" of="$bdev" bs=4k count=$(( header_size >> 12 )) oseek=0 conv=notrunc,sync oflag=direct
45 |
--------------------------------------------------------------------------------
/contrib/orb.nix:
--------------------------------------------------------------------------------
1 | { self }:
2 | { lib, config, pkgs, ... }:
3 | let
4 | inherit (lib)
5 | literalExpression
6 | literalMD
7 | mdDoc
8 | mkIf
9 | mkOption
10 | types
11 | ;
12 |
13 | cfg = config.services.orb;
14 |
15 | sizeType = types.either types.ints.unsigned types.str;
16 |
17 | lowIdThreshould = 50;
18 |
19 | toml = pkgs.formats.toml {};
20 | mkConfigFile = name: config: (toml.generate name config).overrideAttrs (old: {
21 | buildCommand = old.buildCommand + ''
22 | ${lib.getExe cfg.package} verify -c $out
23 | '';
24 | });
25 |
26 | settingsType = types.submodule {
27 | freeformType = toml.type;
28 |
29 | options = {
30 | ublk = {
31 | id = mkOption {
32 | type = types.ints.unsigned;
33 | example = "80";
34 | description = mdDoc ''
35 | The device id, ie. the integer part in `/dev/ublk{b,c}X`, to use.
36 |
37 | Low ids (<${toString lowIdThreshould}) are not recommended and will generate
38 | warnings, to avoid colliding with auto-generated ids.
39 | '';
40 | };
41 | unprivileged = mkOption {
42 | type = types.enum [ false ];
43 | default = false;
44 | description = mdDoc ''
45 | Whether to create an unprivileged block device. This must be
46 | `false` since this module generates privileged systemd services.
47 | '';
48 | };
49 | };
50 | device = {
51 | dev_size = mkOption {
52 | type = sizeType;
53 | description = mdDoc ''
54 | Total device size, must be a multiple of `zone_size`.
55 | '';
56 | };
57 | zone_size = mkOption {
58 | type = sizeType;
59 | description = mdDoc ''
60 | The size of a zone, the minimal reset (delete) unit. It cannot be changed
61 | without losing all the data. Some filesystems have requirement on it, eg.
62 | BTRFS requires it to be `4MiB..=4GiB`.
63 | '';
64 | };
65 | min_chunk_size = mkOption {
66 | type = sizeType;
67 | description = mdDoc ''
68 | The minimal size for a standalone chunk to minimize fragmentation, must be
69 | less than `max_chunk_size`. Chunks smaller than it will be fully rewritten on
70 | committing until they grow larger than this limit.
71 | '';
72 | };
73 | max_chunk_size = mkOption {
74 | type = sizeType;
75 | description = mdDoc ''
76 | The maximum size a chunk can be, also the maximum buffer size for each zone,
77 | must be less than `zone_size`. When a trailing chunk in a zone is grown
78 | exceeding this size, following write requests will wait the chunk to be
79 | committed to backend before continue.
80 | '';
81 | };
82 | };
83 | # `onedrive.state_dir` must be `null` but toml generators will fail
84 | # instead of skipping.
85 | };
86 | };
87 |
88 | in {
89 | options.services.orb = {
90 | enable = mkOption {
91 | type = lib.types.bool;
92 | description = "Whether to enable orb network block device service.";
93 | default = cfg.instances != {};
94 | defaultText = literalExpression "config.services.orb.instances != {}";
95 | example = true;
96 | };
97 |
98 | package = mkOption {
99 | description = mdDoc "The orb package to install and for systemd services";
100 | type = types.package;
101 | default = self.packages.${pkgs.system}.orb;
102 | defaultText = literalMD "orb package from its flake output";
103 | };
104 |
105 | instances = mkOption {
106 | description = mdDoc "Set of orb instances.";
107 | default = {};
108 | type = with types;
109 | attrsOf (
110 | submodule {
111 | options = {
112 | settings = mkOption {
113 | description = "orb configurations.";
114 | type = settingsType;
115 | example = {
116 | ublk.id = 50;
117 | device = {
118 | dev_size = "1TiB";
119 | zone_size = "256MiB";
120 | min_chunk_size = "1MiB";
121 | max_chunk_size = "256MiB";
122 | max_concurrent_streams = 16;
123 | max_concurrent_commits = 4;
124 | };
125 | backend.onedrive.remote_dir = "/orb";
126 | };
127 | };
128 | };
129 | }
130 | );
131 | };
132 | };
133 |
134 | config = mkIf cfg.enable {
135 | assertions = let
136 | groups = lib.groupBy
137 | (name: toString (cfg.instances.${name}.settings.ublk.id or null))
138 | (lib.attrNames cfg.instances);
139 | in lib.mapAttrsToList (id: names: {
140 | assertion = lib.length names == 1;
141 | message = "orb instances ublk.id collision on ${id}: ${lib.concatStringsSep ", " names}";
142 | }) groups;
143 |
144 | warnings =
145 | lib.filter (msg: msg != null)
146 | (lib.mapAttrsToList (name: instance:
147 | let id = instance.settings.ublk.id; in
148 | if id < lowIdThreshould then
149 | "orb instance '${name}' uses a low id ${toString id} < ${toString lowIdThreshould} risking collision"
150 | else
151 | null
152 | ) cfg.instances);
153 |
154 | systemd.packages = [ cfg.package ];
155 | environment.systemPackages = [ cfg.package ];
156 |
157 | # Do not accidentally stop active filesystems.
158 | systemd.services."orb@" = {
159 | overrideStrategy = "asDropin";
160 | restartIfChanged = false;
161 | stopIfChanged = false;
162 | };
163 |
164 | environment.etc = lib.mapAttrs' (name: instance: {
165 | name = "orb/${name}.toml";
166 | value.source = mkConfigFile "${name}.toml" instance.settings;
167 | }) cfg.instances;
168 | };
169 | }
170 |
--------------------------------------------------------------------------------
/contrib/orb@.example.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=OneDrive Block Device Daemon (%i)
3 | Requires=modprobe@ublk_drv.service
4 | After=network-online.service modprobe@ublk_drv.service
5 |
6 | [Service]
7 | Type=notify-reload
8 | ExecStart=/usr/bin/orb serve --config-file "${CONFIGURATION_DIRECTORY}/%i.toml"
9 | StateDirectory="orb/%i"
10 | StateDirectoryMode=0700
11 | ConfigurationDirectory=orb
12 | # Save debug dumps in the cache directory, unified, because they have timestamp
13 | # suffixes. TMPDIR is otherwise readonly because of PrivateTmp.
14 | CacheDirectory=orb
15 | CacheDirectoryMode=0700
16 | Environment="RUST_BACKTRACE=1" "TMPDIR=%C/orb"
17 |
18 | CapabilityBoundingSet=CAP_SYS_ADMIN CAP_SYS_RESOURCE
19 | DeviceAllow=/dev/ublk-control rw
20 | DeviceAllow=char-ublk-char rw
21 | LockPersonality=yes
22 | MemoryDenyWriteExecute=yes
23 | NoNewPrivileges=yes
24 | PrivateTmp=yes
25 | ProtectClock=yes
26 | ProtectControlGroups=yes
27 | ProtectHome=yes
28 | ProtectHostname=yes
29 | ProtectKernelLogs=yes
30 | ProtectKernelModules=yes
31 | ProtectKernelTunables=yes
32 | ProtectProc=invisible
33 | ProtectSystem=strict
34 | RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
35 | RestrictNamespaces=yes
36 | RestrictRealtime=yes
37 | RestrictSUIDSGID=yes
38 | SystemCallArchitectures=native
39 | SystemCallErrorNumber=EPERM
40 | SystemCallFilter=@system-service
41 | SystemCallFilter=~@privileged
42 |
--------------------------------------------------------------------------------
/default.nix:
--------------------------------------------------------------------------------
1 | (import (fetchTarball "https://github.com/edolstra/flake-compat/archive/master.tar.gz") {
2 | src = builtins.fetchGit ./.;
3 | }).defaultNix
4 |
--------------------------------------------------------------------------------
/flake.lock:
--------------------------------------------------------------------------------
1 | {
2 | "nodes": {
3 | "nixpkgs": {
4 | "locked": {
5 | "lastModified": 1732014248,
6 | "narHash": "sha256-y/MEyuJ5oBWrWAic/14LaIr/u5E0wRVzyYsouYY3W6w=",
7 | "owner": "NixOS",
8 | "repo": "nixpkgs",
9 | "rev": "23e89b7da85c3640bbc2173fe04f4bd114342367",
10 | "type": "github"
11 | },
12 | "original": {
13 | "owner": "NixOS",
14 | "ref": "nixos-unstable",
15 | "repo": "nixpkgs",
16 | "type": "github"
17 | }
18 | },
19 | "root": {
20 | "inputs": {
21 | "nixpkgs": "nixpkgs"
22 | }
23 | }
24 | },
25 | "root": "root",
26 | "version": 7
27 | }
28 |
--------------------------------------------------------------------------------
/flake.nix:
--------------------------------------------------------------------------------
1 | rec {
2 | description = "OneDrive as a block device";
3 |
4 | inputs = {
5 | nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
6 | };
7 |
8 | outputs = { self, nixpkgs }: let
9 | inherit (nixpkgs) lib;
10 | eachSystem =
11 | lib.genAttrs (
12 | lib.filter
13 | (lib.hasSuffix "-linux")
14 | lib.systems.flakeExposed);
15 | in {
16 | packages = eachSystem (system: let
17 | pkgs = nixpkgs.legacyPackages.${system};
18 | rev = self.rev or (lib.warn "Git changes are not committed" (self.dirtyRev or "dirty"));
19 | in rec {
20 | default = orb;
21 | orb = with pkgs; rustPlatform.buildRustPackage rec {
22 | pname = "orb";
23 | version = "git-${rev}";
24 | src = self;
25 |
26 | cargoLock.lockFile = ./Cargo.lock;
27 |
28 | nativeBuildInputs = [ pkg-config installShellFiles ];
29 | buildInputs = [ openssl ];
30 |
31 | buildFeatures = [ "completion" ];
32 |
33 | env.CFG_RELEASE = version;
34 |
35 | postInstall = ''
36 | mkdir -p $out/etc/systemd/system
37 | substitute ./contrib/orb@.example.service $out/etc/systemd/system/orb@.service \
38 | --replace-fail '/usr/bin/orb' "$out/bin/orb"
39 |
40 | installShellCompletion \
41 | --bash completions/bash/${pname}.bash \
42 | --fish completions/fish/${pname}.fish \
43 | --zsh completions/zsh/_${pname}
44 | '';
45 |
46 | meta = {
47 | inherit description;
48 | homepage = "https://github.com/oxalica/orb";
49 | mainProgram = "orb";
50 | license = [ lib.licenses.gpl3Plus ];
51 | platforms = lib.platforms.linux;
52 | };
53 | };
54 |
55 | ublk-chown-unprivileged = with pkgs; rustPlatform.buildRustPackage {
56 | pname = "ublk-chown-unprivileged";
57 | version = "git-${rev}";
58 | src = self;
59 |
60 | cargoLock.lockFile = ./Cargo.lock;
61 |
62 | buildAndTestSubdir = "ublk-chown-unprivileged";
63 |
64 | postInstall = ''
65 | mv $out/bin $out/libexec
66 | mkdir -p $out/etc/udev/rules.d
67 | substitute ./contrib/19-ublk-unprivileged.example.rules $out/etc/udev/rules.d/19-ublk-unprivileged.rules \
68 | --replace-fail '/usr/libexec/' "$out/libexec/"
69 | '';
70 |
71 | meta = {
72 | description = "udev rules to enable unprivileged ublk usage";
73 | homepage = "https://github.com/oxalica/orb";
74 | license = with lib.licenses; [ mit asl20 ];
75 | platforms = lib.platforms.linux;
76 | };
77 | };
78 |
79 | cryptsetup-format-zoned = with pkgs; writeShellApplication rec {
80 | name = "cryptsetup-format-zoned";
81 | runtimeInputs = [ coreutils util-linux cryptsetup ];
82 | text = builtins.readFile ./contrib/cryptsetup-format-zoned.sh;
83 | meta = {
84 | description = "Workaround script for cryptsetup-luksFormat on zoned devices";
85 | mainProgram = name;
86 | license = with lib.licenses; [ gpl3Plus ];
87 | };
88 | };
89 | });
90 |
91 | devShells = eachSystem (system: {
92 | without-rust =
93 | with nixpkgs.legacyPackages.${system};
94 | mkShell {
95 | nativeBuildInputs = [ pkg-config rustPlatform.bindgenHook ];
96 | buildInputs = [ linuxHeaders openssl ];
97 | env = {
98 | RUST_BACKTRACE = "1";
99 | ORB_LOG = "orb=debug";
100 | RUST_LOG = "orb_ublk=trace";
101 | };
102 | };
103 | });
104 |
105 | nixosModules = rec {
106 | default = orb;
107 | orb = import ./contrib/orb.nix {
108 | inherit self;
109 | };
110 | };
111 | };
112 | }
113 |
--------------------------------------------------------------------------------
/orb-ublk/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "orb-ublk"
3 | version = "0.1.0"
4 | edition = "2021"
5 | license = "MIT or Apache-2.0"
6 | rust-version = "1.76" # result_option_inspect
7 |
8 | [features]
9 | default = []
10 | generate-sys = ["dep:bindgen"]
11 | tokio = ["dep:tokio"]
12 |
13 | [[test]]
14 | name = "basic"
15 | required-features = ["tokio"]
16 |
17 | [[test]]
18 | name = "interrupt"
19 | harness = false
20 |
21 | [[example]]
22 | name = "loop"
23 | required-features = ["tokio"]
24 |
25 | [[example]]
26 | name = "zoned"
27 | required-features = ["tokio"]
28 |
29 | [dependencies]
30 | bitflags = "2"
31 | io-uring = { version = "0.7", features = ["io_safety"] }
32 | rustix = { version = "1", features = ["event", "mm", "process"] }
33 | scopeguard = "1"
34 | tokio = { version = "1", features = ["net", "rt"], optional = true }
35 | tracing = "0.1"
36 |
37 | [build-dependencies]
38 | bindgen = { version = "0.71", optional = true }
39 |
40 | [dev-dependencies]
41 | anyhow = "1"
42 | bytesize = "2"
43 | clap = { version = "4", features = ["derive"] }
44 | ctrlc = "3"
45 | libtest-mimic = "0.8"
46 | rand = "0.9"
47 | rstest = "0.25"
48 | rustix = { version = "1", features = ["fs"] }
49 | serde = { version = "1", features = ["derive"] }
50 | serde_json = "1"
51 | tokio = { version = "1", features = ["time"] }
52 | tracing = "0.1"
53 | tracing-subscriber = { version = "0.3", features = ["env-filter", "tracing-log"] }
54 | xshell = "0.2"
55 |
56 | [lints.rust]
57 | missing_debug_implementations = "warn"
58 |
59 | [lints.clippy]
60 | pedantic = { level = "warn", priority = -1 }
61 | # Of course system calls can fail.
62 | missing-errors-doc = "allow"
63 | # Interop with generated constants
64 | cast-possible-truncation = "allow"
65 | cast-sign-loss = "allow"
66 | # Convenient for C structs.
67 | default-trait-access = "allow"
68 | # For semantics.
69 | items-after-statements = "allow"
70 | # It makes things more unreadable.
71 | transmute-ptr-to-ptr = "allow"
72 |
73 | # TODO
74 | missing-panics-doc = "allow"
75 | cast-lossless = "allow"
76 | wildcard-imports = "allow"
77 |
--------------------------------------------------------------------------------
/orb-ublk/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/orb-ublk/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
2 |
3 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
4 |
5 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
6 |
--------------------------------------------------------------------------------
/orb-ublk/README.md:
--------------------------------------------------------------------------------
1 | # Ergonomic interface library for block device in user space (ublk)
2 |
3 | ### License
4 |
5 | This package (the whole sub-tree of the directory containing this file) is
6 | licensed under either of [Apache License, Version
7 | 2.0](./orb-ublk/LICENSE-APACHE) or [MIT license](./orb-ublk/LICENSE-MIT) at
8 | your option.
9 |
--------------------------------------------------------------------------------
/orb-ublk/build.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | println!("cargo:rerun-if-changed=build.rs");
3 |
4 | #[cfg(feature = "generate-sys")]
5 | generate("src/sys.rs");
6 | }
7 |
8 | #[cfg(feature = "generate-sys")]
9 | fn generate(out_path: &str) {
10 | const HEADER_CONTENT: &str = "
11 | #include
12 | #include
13 |
14 | /* Workaround: https://github.com/rust-lang/rust-bindgen/issues/753#issuecomment-459851952 */
15 | #define MARK_FIX_753(req_name) const __u32 Fix753_##req_name = req_name;
16 | MARK_FIX_753(UBLK_U_CMD_GET_QUEUE_AFFINITY)
17 | MARK_FIX_753(UBLK_U_CMD_GET_DEV_INFO)
18 | MARK_FIX_753(UBLK_U_CMD_ADD_DEV)
19 | MARK_FIX_753(UBLK_U_CMD_DEL_DEV)
20 | MARK_FIX_753(UBLK_U_CMD_START_DEV)
21 | MARK_FIX_753(UBLK_U_CMD_STOP_DEV)
22 | MARK_FIX_753(UBLK_U_CMD_SET_PARAMS)
23 | MARK_FIX_753(UBLK_U_CMD_GET_PARAMS)
24 | MARK_FIX_753(UBLK_U_CMD_START_USER_RECOVERY)
25 | MARK_FIX_753(UBLK_U_CMD_END_USER_RECOVERY)
26 | MARK_FIX_753(UBLK_U_CMD_GET_DEV_INFO2)
27 | MARK_FIX_753(UBLK_U_CMD_GET_FEATURES)
28 |
29 | MARK_FIX_753(UBLK_U_IO_FETCH_REQ)
30 | MARK_FIX_753(UBLK_U_IO_COMMIT_AND_FETCH_REQ)
31 | MARK_FIX_753(UBLK_U_IO_NEED_GET_DATA)
32 | ";
33 |
34 | #[derive(Debug)]
35 | struct CustomCallback;
36 |
37 | impl bindgen::callbacks::ParseCallbacks for CustomCallback {
38 | fn item_name(&self, original_item_name: &str) -> Option {
39 | Some(original_item_name.trim_start_matches("Fix753_").to_owned())
40 | }
41 |
42 | fn add_derives(&self, info: &bindgen::callbacks::DeriveInfo<'_>) -> Vec {
43 | if info.name == "blk_zone" {
44 | return vec!["PartialEq".into(), "Eq".into()];
45 | }
46 | Vec::new()
47 | }
48 | }
49 |
50 | bindgen::Builder::default()
51 | .header_contents("wrapper.h", HEADER_CONTENT)
52 | .parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
53 | .parse_callbacks(Box::new(CustomCallback))
54 | .use_core()
55 | .allowlist_var("UBLK(?:SRV)?_.*|Fix753_.*")
56 | .allowlist_type("ublk(?:srv)?_.*|blk_zone(?:_type|_cond|)")
57 | // `blk_zone_{type,cond}` need no extra prefixes.
58 | .prepend_enum_name(false)
59 | .derive_default(true)
60 | .layout_tests(false)
61 | .generate()
62 | .expect("failed to bindgen")
63 | .write_to_file(out_path)
64 | .expect("failed to write bindgen output");
65 | }
66 |
--------------------------------------------------------------------------------
/orb-ublk/examples/loop.rs:
--------------------------------------------------------------------------------
1 | use std::fs::File;
2 | use std::io;
3 | use std::os::unix::fs::FileExt;
4 | use std::path::PathBuf;
5 |
6 | use anyhow::Context;
7 | use clap::Parser;
8 | use orb_ublk::runtime::TokioRuntimeBuilder;
9 | use orb_ublk::{
10 | BlockDevice, ControlDevice, DeviceAttrs, DeviceBuilder, DeviceInfo, DeviceParams,
11 | DiscardParams, IoFlags, ReadBuf, Sector, Stopper, WriteBuf,
12 | };
13 | use rustix::fs::{fallocate, FallocateFlags};
14 | use rustix::io::Errno;
15 |
16 | /// Example loop device.
17 | #[derive(Debug, Parser)]
18 | struct Cli {
19 | backing_file: PathBuf,
20 |
21 | #[clap(long)]
22 | dev_id: Option,
23 | #[clap(long, default_value = "512")]
24 | logical_block_size: u64,
25 | #[clap(long, default_value = "4096")]
26 | physical_block_size: u64,
27 |
28 | #[clap(long)]
29 | discard: bool,
30 | #[clap(long)]
31 | user_copy: bool,
32 | #[clap(long)]
33 | privileged: bool,
34 | }
35 |
36 | fn main() -> anyhow::Result<()> {
37 | tracing_subscriber::fmt::init();
38 | let cli = Cli::parse();
39 |
40 | let file = File::options()
41 | .read(true)
42 | .write(true)
43 | .open(cli.backing_file)
44 | .context("failed to open backing file")?;
45 | let size = file
46 | .metadata()
47 | .context("failed to query backing file")?
48 | .len();
49 | let size_sectors =
50 | Sector::try_from_bytes(size).context("backing file size must be multiples of sectors")?;
51 |
52 | let ctl = ControlDevice::open()
53 | .context("failed to open control device, kernel module 'ublk_drv' not loaded?")?;
54 | let mut builder = DeviceBuilder::new();
55 | builder.name("ublk-loop");
56 | if !cli.privileged {
57 | builder.unprivileged();
58 | }
59 | if cli.user_copy {
60 | builder.user_copy();
61 | }
62 | let mut srv = builder
63 | .name("ublk-loop")
64 | .dev_id(cli.dev_id)
65 | .create_service(&ctl)
66 | .context("failed to create ublk device")?;
67 | let mut params = *DeviceParams::new()
68 | .dev_sectors(size_sectors)
69 | .logical_block_size(cli.logical_block_size)
70 | .physical_block_size(cli.physical_block_size)
71 | .io_min_size(cli.physical_block_size)
72 | .io_opt_size(cli.physical_block_size)
73 | .attrs(DeviceAttrs::VolatileCache)
74 | .set_io_flusher(cli.privileged);
75 | if cli.discard {
76 | params.discard(DiscardParams {
77 | alignment: Sector::SIZE as _,
78 | granularity: Sector::SIZE as _,
79 | max_size: Sector(1 << 30),
80 | max_write_zeroes_size: Sector(1 << 30),
81 | max_segments: 1,
82 | });
83 | }
84 | let handler = LoopDev { file };
85 | let ret = srv
86 | .serve(&TokioRuntimeBuilder, ¶ms, &handler)
87 | .context("service error");
88 | handler.file.sync_all().context("failed to sync file")?;
89 | ret
90 | }
91 |
92 | struct LoopDev {
93 | file: File,
94 | }
95 |
96 | impl BlockDevice for LoopDev {
97 | fn ready(&self, dev_info: &DeviceInfo, stop: Stopper) -> io::Result<()> {
98 | tracing::info!(dev_id = dev_info.dev_id(), "device ready");
99 | ctrlc::set_handler(move || stop.stop()).expect("failed to set Ctrl-C hook");
100 | Ok(())
101 | }
102 |
103 | async fn read(&self, off: Sector, buf: &mut ReadBuf<'_>, _flags: IoFlags) -> Result<(), Errno> {
104 | let mut buf2 = vec![0u8; buf.remaining()];
105 | self.file
106 | .read_exact_at(&mut buf2, off.bytes())
107 | .map_err(convert_err)?;
108 | buf.put_slice(&buf2)?;
109 | Ok(())
110 | }
111 |
112 | async fn write(&self, off: Sector, buf: WriteBuf<'_>, _flags: IoFlags) -> Result {
113 | self.file
114 | .write_all_at(buf.as_slice().unwrap(), off.bytes())
115 | .map_err(convert_err)?;
116 | Ok(buf.len())
117 | }
118 |
119 | async fn flush(&self, _flags: IoFlags) -> Result<(), Errno> {
120 | self.file.sync_data().map_err(convert_err)
121 | }
122 |
123 | async fn discard(&self, off: Sector, len: usize, _flags: IoFlags) -> Result<(), Errno> {
124 | fallocate(
125 | &self.file,
126 | FallocateFlags::PUNCH_HOLE,
127 | off.bytes(),
128 | len as _,
129 | )
130 | }
131 |
132 | async fn write_zeroes(&self, off: Sector, len: usize, _flags: IoFlags) -> Result<(), Errno> {
133 | fallocate(
134 | &self.file,
135 | FallocateFlags::PUNCH_HOLE,
136 | off.bytes(),
137 | len as _,
138 | )
139 | }
140 | }
141 |
142 | #[allow(clippy::needless_pass_by_value)]
143 | fn convert_err(err: io::Error) -> Errno {
144 | Errno::from_io_error(&err).unwrap_or(Errno::IO)
145 | }
146 |
--------------------------------------------------------------------------------
/orb-ublk/examples/management.rs:
--------------------------------------------------------------------------------
1 | use anyhow::{ensure, Context};
2 | use clap::Parser;
3 | use orb_ublk::ControlDevice;
4 |
5 | /// Ublk device management.
6 | #[derive(Debug, Parser)]
7 | enum Cli {
8 | /// Print all features supported by the current kernel driver.
9 | GetFeatures,
10 | /// Print the ublk device informantion at `dev_id`.
11 | GetInfo { dev_id: u32 },
12 | /// Delete the ublk device at `dev_id`.
13 | Delete { dev_id: u32 },
14 | /// Delete all ublk devices.
15 | DeleteAll,
16 | }
17 |
18 | fn main() -> anyhow::Result<()> {
19 | let cli = Cli::parse();
20 | let ctl = ControlDevice::open()
21 | .context("failed to open control device, kernel module 'ublk_drv' not loaded?")?;
22 | match cli {
23 | Cli::GetFeatures => {
24 | let feat = ctl.get_features().context("failed to get features")?;
25 | println!("{feat:?}");
26 | }
27 | Cli::GetInfo { dev_id } => {
28 | let info = ctl
29 | .get_device_info(dev_id)
30 | .context("failed to get device info")?;
31 | println!("{info:?}");
32 | }
33 | Cli::Delete { dev_id } => {
34 | ctl.delete_device(dev_id)
35 | .context("failed to delete device")?;
36 | }
37 | Cli::DeleteAll => {
38 | let mut success = true;
39 | for ent in std::fs::read_dir("/dev").context("failed to read /dev")? {
40 | if let Some(dev_id) = (|| {
41 | ent.ok()?
42 | .file_name()
43 | .to_str()?
44 | .strip_prefix("ublkc")?
45 | .parse::()
46 | .ok()
47 | })() {
48 | eprintln!("deleting device {dev_id}");
49 | if let Err(err) = ctl.delete_device(dev_id) {
50 | eprintln!("{err}");
51 | success = false;
52 | }
53 | }
54 | }
55 | ensure!(success, "some operations failed");
56 | }
57 | }
58 | Ok(())
59 | }
60 |
--------------------------------------------------------------------------------
/orb-ublk/examples/zoned.rs:
--------------------------------------------------------------------------------
1 | use std::fs::{self, File};
2 | use std::io;
3 | use std::os::unix::fs::FileExt;
4 | use std::path::PathBuf;
5 | use std::sync::Mutex;
6 |
7 | use anyhow::{ensure, Context};
8 | use bytesize::ByteSize;
9 | use clap::Parser;
10 | use orb_ublk::runtime::TokioRuntimeBuilder;
11 | use orb_ublk::{
12 | BlockDevice, ControlDevice, DeviceAttrs, DeviceBuilder, DeviceInfo, DeviceParams, IoFlags,
13 | ReadBuf, Sector, Stopper, WriteBuf, Zone, ZoneBuf, ZoneCond, ZoneType, ZonedParams,
14 | };
15 | use rustix::fs::{fallocate, FallocateFlags};
16 | use rustix::io::Errno;
17 | use serde::{Deserialize, Serialize};
18 |
19 | /// Example loop device.
20 | #[derive(Debug, Parser)]
21 | struct Cli {
22 | backing_file: PathBuf,
23 | metadata_file: PathBuf,
24 |
25 | #[clap(long)]
26 | dev_id: Option,
27 | #[clap(long, default_value = "512")]
28 | logical_block_size: ByteSize,
29 | #[clap(long, default_value = "4KiB")]
30 | physical_block_size: ByteSize,
31 | #[clap(long, default_value = "512KiB")]
32 | io_buf_size: ByteSize,
33 |
34 | #[clap(long)]
35 | zone_size: ByteSize,
36 | #[clap(long)]
37 | max_open_zones: u32,
38 | #[clap(long)]
39 | max_active_zones: u32,
40 | #[clap(long, default_value = "1GiB")]
41 | max_zone_append_size: ByteSize,
42 |
43 | #[clap(long)]
44 | privileged: bool,
45 | }
46 |
47 | #[derive(Debug, Serialize, Deserialize)]
48 | struct ZonesMetadata {
49 | zone_size: u64,
50 | zones: Vec,
51 | }
52 |
53 | #[derive(Debug, Clone, Copy)]
54 | struct ZoneState {
55 | rel_wptr: u64,
56 | cond: ZoneCond,
57 | }
58 |
59 | impl Default for ZoneState {
60 | fn default() -> Self {
61 | Self {
62 | rel_wptr: 0,
63 | cond: ZoneCond::Empty,
64 | }
65 | }
66 | }
67 |
68 | impl Serialize for ZoneState {
69 | fn serialize(&self, serializer: S) -> Result
70 | where
71 | S: serde::Serializer,
72 | {
73 | self.rel_wptr.serialize(serializer)
74 | }
75 | }
76 |
77 | impl<'de> Deserialize<'de> for ZoneState {
78 | fn deserialize(deserializer: D) -> Result
79 | where
80 | D: serde::Deserializer<'de>,
81 | {
82 | let wptr = u64::deserialize(deserializer)?;
83 | Ok(Self {
84 | rel_wptr: wptr,
85 | // Full is processed in main.
86 | cond: if wptr == 0 {
87 | ZoneCond::Empty
88 | } else {
89 | ZoneCond::Closed
90 | },
91 | })
92 | }
93 | }
94 |
95 | fn main() -> anyhow::Result<()> {
96 | tracing_subscriber::fmt::init();
97 | let cli = Cli::parse();
98 |
99 | let backing_file = File::options()
100 | .read(true)
101 | .write(true)
102 | .open(cli.backing_file)
103 | .context("failed to open backing file")?;
104 | let size = backing_file
105 | .metadata()
106 | .context("failed to query backing file")?
107 | .len();
108 | let zone_size = cli.zone_size.0;
109 | let zone_sectors =
110 | Sector::try_from_bytes(zone_size).context("zone size mut be multiple of sectors")?;
111 | ensure!(
112 | size % zone_sectors.bytes() == 0,
113 | "device size must be multiples of zone size"
114 | );
115 | let size_sectors = Sector::try_from_bytes(size).unwrap();
116 | let zones_cnt = size / zone_sectors.bytes();
117 |
118 | let zones = cli
119 | .metadata_file
120 | .exists()
121 | .then(|| {
122 | let src = fs::read_to_string(&cli.metadata_file)?;
123 | let mut meta = serde_json::from_str::(&src)?;
124 | ensure!(meta.zone_size == zone_size, "zone size mismatch");
125 | ensure!(meta.zones.len() as u64 == zones_cnt, "zone number mismatch");
126 | for (idx, z) in meta.zones.iter_mut().enumerate() {
127 | ensure!(z.rel_wptr <= zone_size, "invalid wptr for zone {idx}");
128 | z.cond = if z.rel_wptr == 0 {
129 | ZoneCond::Empty
130 | } else if z.rel_wptr == zone_size {
131 | ZoneCond::Full
132 | } else {
133 | ZoneCond::Closed
134 | };
135 | }
136 | Ok(meta)
137 | })
138 | .transpose()
139 | .context("failed to read metadata")?
140 | .unwrap_or_else(|| ZonesMetadata {
141 | zone_size: cli.zone_size.0,
142 | zones: vec![ZoneState::default(); zones_cnt.try_into().unwrap()],
143 | });
144 |
145 | let ctl = ControlDevice::open()
146 | .context("failed to open control device, kernel module 'ublk_drv' not loaded?")?;
147 | let mut builder = DeviceBuilder::new();
148 | if !cli.privileged {
149 | builder.unprivileged();
150 | }
151 | let mut srv = builder
152 | .name("ublk-zoned")
153 | .zoned()
154 | .io_buf_size(u32::try_from(cli.io_buf_size.0).context("buffer size too large")?)
155 | .dev_id(cli.dev_id)
156 | .create_service(&ctl)
157 | .context("failed to create ublk device")?;
158 | let zones_cnt_u32 = u32::try_from(zones_cnt).unwrap_or(u32::MAX);
159 | let params = *DeviceParams::new()
160 | .dev_sectors(size_sectors)
161 | .chunk_sectors(zone_sectors)
162 | .attrs(DeviceAttrs::VolatileCache)
163 | .logical_block_size(cli.logical_block_size.0)
164 | .physical_block_size(cli.physical_block_size.0)
165 | .io_min_size(cli.physical_block_size.0)
166 | .io_opt_size(cli.physical_block_size.0)
167 | .io_max_sectors(Sector::from_bytes(cli.io_buf_size.0))
168 | .set_io_flusher(cli.privileged)
169 | .zoned(ZonedParams {
170 | max_open_zones: cli.max_open_zones.min(zones_cnt_u32),
171 | max_active_zones: cli.max_active_zones.min(zones_cnt_u32),
172 | max_zone_append_size: Sector::try_from_bytes(cli.max_zone_append_size.0)
173 | .unwrap()
174 | .min(size_sectors),
175 | });
176 | let handler = ZonedDev {
177 | file: backing_file,
178 | size,
179 | zone_size,
180 | zones: Mutex::new(zones),
181 | metadata_path: cli.metadata_file,
182 | };
183 | let ret = srv
184 | .serve(&TokioRuntimeBuilder, ¶ms, &handler)
185 | .context("service error");
186 | handler.flush_sync().context("failed to sync")?;
187 | ret
188 | }
189 |
190 | struct ZonedDev {
191 | file: File,
192 | size: u64,
193 | zone_size: u64,
194 | zones: Mutex,
195 | metadata_path: PathBuf,
196 | }
197 |
198 | impl ZonedDev {
199 | fn flush_sync(&self) -> Result<(), Errno> {
200 | self.file.sync_data().map_err(convert_err)?;
201 | let content = serde_json::to_vec(&*self.zones.lock().unwrap()).unwrap();
202 | let tmp_path = self.metadata_path.with_extension("tmp");
203 | fs::write(&tmp_path, content).map_err(convert_err)?;
204 | fs::rename(&tmp_path, &self.metadata_path).map_err(convert_err)?;
205 | Ok(())
206 | }
207 | }
208 |
209 | impl BlockDevice for ZonedDev {
210 | fn ready(&self, dev_info: &DeviceInfo, stop: Stopper) -> io::Result<()> {
211 | tracing::info!(dev_id = dev_info.dev_id(), ?dev_info, "device ready");
212 | ctrlc::set_handler(move || stop.stop()).expect("failed to set Ctrl-C hook");
213 | Ok(())
214 | }
215 |
216 | async fn read(&self, off: Sector, buf: &mut ReadBuf<'_>, _flags: IoFlags) -> Result<(), Errno> {
217 | let mut buf2 = vec![0u8; buf.remaining()];
218 | self.file
219 | .read_exact_at(&mut buf2, off.bytes())
220 | .map_err(convert_err)?;
221 | buf.put_slice(&buf2)?;
222 | Ok(())
223 | }
224 |
225 | async fn write(&self, off: Sector, buf: WriteBuf<'_>, _flags: IoFlags) -> Result {
226 | let off = off.bytes();
227 | let zid = off / self.zone_size;
228 | let mut zones = self.zones.lock().unwrap();
229 | let z = &mut zones.zones[zid as usize];
230 | if (zid * self.zone_size + z.rel_wptr) != off {
231 | return Err(Errno::IO);
232 | }
233 | let new_rel_wptr = z
234 | .rel_wptr
235 | .checked_add(buf.len() as u64)
236 | .filter(|&p| p <= self.zone_size)
237 | .ok_or(Errno::IO)?;
238 | let mut buf2 = vec![0u8; buf.len()];
239 | buf.copy_to_slice(&mut buf2)?;
240 | self.file.write_all_at(&buf2, off).map_err(convert_err)?;
241 | z.rel_wptr = new_rel_wptr;
242 | if new_rel_wptr == self.zone_size {
243 | z.cond = ZoneCond::Full;
244 | } else if matches!(z.cond, ZoneCond::Closed | ZoneCond::Empty) {
245 | z.cond = ZoneCond::ImpOpen;
246 | }
247 | Ok(buf.len())
248 | }
249 |
250 | async fn flush(&self, _flags: IoFlags) -> Result<(), Errno> {
251 | self.flush_sync()
252 | }
253 |
254 | async fn zone_open(&self, off: Sector, _flags: IoFlags) -> Result<(), Errno> {
255 | let zid = off.bytes() / self.zone_size;
256 | let mut zones = self.zones.lock().unwrap();
257 | let z = &mut zones.zones[zid as usize];
258 | z.cond = match z.cond {
259 | ZoneCond::Empty | ZoneCond::ImpOpen | ZoneCond::ExpOpen | ZoneCond::Closed => {
260 | ZoneCond::ExpOpen
261 | }
262 | ZoneCond::Full => return Err(Errno::IO),
263 | _ => unreachable!(),
264 | };
265 | Ok(())
266 | }
267 |
268 | async fn zone_close(&self, off: Sector, _flags: IoFlags) -> Result<(), Errno> {
269 | let zid = off.bytes() / self.zone_size;
270 | let mut zones = self.zones.lock().unwrap();
271 | let z = &mut zones.zones[zid as usize];
272 | z.cond = match z.cond {
273 | ZoneCond::ExpOpen | ZoneCond::ImpOpen => {
274 | if z.rel_wptr == 0 {
275 | ZoneCond::Empty
276 | } else {
277 | ZoneCond::Closed
278 | }
279 | }
280 | ZoneCond::Empty | ZoneCond::Closed => z.cond,
281 | ZoneCond::Full => return Err(Errno::IO),
282 | _ => unreachable!(),
283 | };
284 | Ok(())
285 | }
286 |
287 | async fn zone_finish(&self, off: Sector, _flags: IoFlags) -> Result<(), Errno> {
288 | let zid = off.bytes() / self.zone_size;
289 | let mut zones = self.zones.lock().unwrap();
290 | let z = &mut zones.zones[zid as usize];
291 | z.rel_wptr = self.zone_size;
292 | z.cond = ZoneCond::Full;
293 | Ok(())
294 | }
295 |
296 | async fn zone_reset(&self, off: Sector, _flags: IoFlags) -> Result<(), Errno> {
297 | let zid = off.bytes() / self.zone_size;
298 | let mut zones = self.zones.lock().unwrap();
299 | let z = &mut zones.zones[zid as usize];
300 | fallocate(
301 | &self.file,
302 | FallocateFlags::PUNCH_HOLE | FallocateFlags::KEEP_SIZE,
303 | off.bytes(),
304 | self.zone_size,
305 | )?;
306 | z.rel_wptr = 0;
307 | z.cond = ZoneCond::Empty;
308 | Ok(())
309 | }
310 |
311 | async fn zone_reset_all(&self, _flags: IoFlags) -> Result<(), Errno> {
312 | let mut zones = self.zones.lock().unwrap();
313 | fallocate(
314 | &self.file,
315 | FallocateFlags::PUNCH_HOLE | FallocateFlags::KEEP_SIZE,
316 | 0,
317 | self.size,
318 | )?;
319 | zones.zones.fill_with(ZoneState::default);
320 | Ok(())
321 | }
322 |
323 | async fn report_zones(
324 | &self,
325 | off: Sector,
326 | buf: &mut ZoneBuf<'_>,
327 | _flags: IoFlags,
328 | ) -> Result<(), Errno> {
329 | let zid = off.bytes() / self.zone_size;
330 | let zones = self.zones.lock().unwrap();
331 | let info = zones.zones[zid as usize..][..buf.remaining()]
332 | .iter()
333 | .zip(zid..)
334 | .map(|(z, zid)| {
335 | Zone::new(
336 | Sector::from_bytes(zid * self.zone_size),
337 | Sector::from_bytes(self.zone_size),
338 | Sector::from_bytes(z.rel_wptr),
339 | ZoneType::SeqWriteReq,
340 | z.cond,
341 | )
342 | })
343 | .collect::>();
344 | buf.report(&info)?;
345 | Ok(())
346 | }
347 |
348 | async fn zone_append(
349 | &self,
350 | off: Sector,
351 | buf: WriteBuf<'_>,
352 | _flags: IoFlags,
353 | ) -> Result {
354 | let zid = off.bytes() / self.zone_size;
355 | let mut zones = self.zones.lock().unwrap();
356 | let z = &mut zones.zones[zid as usize];
357 | let new_rel_wptr = z
358 | .rel_wptr
359 | .checked_add(buf.len() as u64)
360 | .filter(|&p| p <= self.zone_size)
361 | .ok_or(Errno::IO)?;
362 | let mut buf2 = vec![0u8; buf.len()];
363 | buf.copy_to_slice(&mut buf2)?;
364 | let old_wptr = zid * self.zone_size + z.rel_wptr;
365 | self.file
366 | .write_all_at(&buf2, old_wptr)
367 | .map_err(convert_err)?;
368 | z.rel_wptr = new_rel_wptr;
369 | if new_rel_wptr == self.zone_size {
370 | z.cond = ZoneCond::Full;
371 | } else if matches!(z.cond, ZoneCond::Closed | ZoneCond::Empty) {
372 | z.cond = ZoneCond::ImpOpen;
373 | }
374 | Ok(Sector::from_bytes(old_wptr))
375 | }
376 | }
377 |
378 | #[allow(clippy::needless_pass_by_value)]
379 | fn convert_err(err: io::Error) -> Errno {
380 | tracing::error!(%err);
381 | Errno::from_io_error(&err).unwrap_or(Errno::IO)
382 | }
383 |
--------------------------------------------------------------------------------
/orb-ublk/src/lib.rs:
--------------------------------------------------------------------------------
1 | pub mod runtime;
2 | mod ublk;
3 |
4 | #[allow(warnings)]
5 | #[rustfmt::skip]
6 | mod sys;
7 |
8 | use std::{fmt, ops};
9 |
10 | pub use ublk::*;
11 |
12 | /// Size or offset in unit of sectors (512bytes).
13 | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
14 | pub struct Sector(pub u64);
15 |
16 | impl fmt::Display for Sector {
17 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18 | self.0.fmt(f)?;
19 | "s".fmt(f)
20 | }
21 | }
22 |
23 | impl Sector {
24 | pub const SHIFT: u32 = 9;
25 | pub const SIZE: u32 = 1 << Self::SHIFT;
26 |
27 | #[must_use]
28 | pub const fn from_bytes(bytes: u64) -> Self {
29 | match Self::try_from_bytes(bytes) {
30 | Some(sec) => sec,
31 | None => panic!("bytes is not multiples of sectors"),
32 | }
33 | }
34 |
35 | #[must_use]
36 | pub const fn try_from_bytes(bytes: u64) -> Option {
37 | if bytes % Self::SIZE as u64 == 0 {
38 | Some(Self(bytes >> Self::SHIFT))
39 | } else {
40 | None
41 | }
42 | }
43 |
44 | #[must_use]
45 | pub const fn bytes(self) -> u64 {
46 | match self.0.checked_mul(Self::SIZE as u64) {
47 | Some(bytes) => bytes,
48 | None => panic!("overflow"),
49 | }
50 | }
51 |
52 | #[must_use]
53 | pub const fn wrapping_bytes(self) -> u64 {
54 | self.0.wrapping_mul(Self::SIZE as u64)
55 | }
56 | }
57 |
58 | impl ops::Add for Sector {
59 | type Output = Sector;
60 |
61 | fn add(self, rhs: Sector) -> Self::Output {
62 | Self(self.0 + rhs.0)
63 | }
64 | }
65 |
66 | impl ops::AddAssign for Sector {
67 | fn add_assign(&mut self, rhs: Self) {
68 | self.0 += rhs.0;
69 | }
70 | }
71 |
72 | impl ops::Sub for Sector {
73 | type Output = Sector;
74 |
75 | fn sub(self, rhs: Sector) -> Self::Output {
76 | Self(self.0 - rhs.0)
77 | }
78 | }
79 |
80 | impl ops::SubAssign for Sector {
81 | fn sub_assign(&mut self, rhs: Self) {
82 | self.0 -= rhs.0;
83 | }
84 | }
85 |
86 | impl ops::Mul for Sector {
87 | type Output = Self;
88 |
89 | fn mul(self, rhs: u64) -> Self::Output {
90 | Self(self.0 * rhs)
91 | }
92 | }
93 |
94 | impl ops::Div for Sector {
95 | type Output = u64;
96 |
97 | fn div(self, rhs: Self) -> Self::Output {
98 | self.0 / rhs.0
99 | }
100 | }
101 |
102 | impl ops::Rem for Sector {
103 | type Output = Sector;
104 |
105 | fn rem(self, rhs: Sector) -> Self::Output {
106 | Sector(self.0 % rhs.0)
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/orb-ublk/src/runtime.rs:
--------------------------------------------------------------------------------
1 | #![allow(clippy::module_name_repetitions)]
2 | use std::future::Future;
3 | use std::io;
4 | use std::ops::ControlFlow;
5 | use std::pin::Pin;
6 |
7 | use io_uring::IoUring;
8 |
9 | pub trait AsyncRuntimeBuilder {
10 | type Runtime: AsyncRuntime;
11 |
12 | fn build(&self) -> io::Result;
13 | }
14 |
15 | pub trait AsyncRuntime {
16 | type Spawner<'env>: AsyncScopeSpawner<'env>;
17 |
18 | fn drive_uring<'env, T, F>(&mut self, uring: &IoUring, on_cqe: F) -> io::Result
19 | where
20 | F: for<'scope> FnMut(&'scope Self::Spawner<'env>) -> io::Result>;
21 | }
22 |
23 | pub trait AsyncScopeSpawner<'env> {
24 | fn spawn(&self, fut: Fut)
25 | where
26 | Fut: Future