← Documents Documentation/block/ublk.rst GitHub 원문 ↗

Linux 6.18.37 · Block

Userspace block device driver (ublk driver)

io_uring 기반 userspace block device framework인 ublk의 control/data plane, recovery, zero-copy와 auto buffer registration을 설명합니다.

Source pathDocumentation/block/ublk.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

ublk.rst:1-441

ublk는 `/dev/ublkb*`의 request를 userspace server로 전달하고 결과를 io_uring passthrough command로 돌려받는 고성능 block device framework입니다. block logic을 userspace library·language·debugging tool로 구현하면서 kernel crash와 보안 영향 범위를 줄일 수 있습니다.

`/dev/ublk-control`의 `UBLK_CMD_*` command가 device lifecycle과 parameter를 관리하고, `/dev/ublkc*`의 mmap descriptor와 `UBLK_IO_*` command가 queue별 data plane을 구성합니다. tag는 block request와 userspace IO를 1:1로 연결합니다.

user recovery는 server 교체 중 request를 abort·reissue·fail하는 정책을 선택합니다. zero copy는 fixed kernel buffer와 strict alignment·trust 요건을 가지며, `UBLK_F_AUTO_BUF_REG`는 같은 `io_ring_ctx` 안에서 buffer lifecycle을 자동화해 command dependency와 overhead를 줄입니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 ===========================================
4 Userspace block device driver (ublk driver)
5 ===========================================
6
7 Overview
8 ========
9
10 ublk is a generic framework for implementing block device logic from userspace.
11 The motivation behind it is that moving virtual block drivers into userspace,
12 such as loop, nbd and similar can be very helpful. It can help to implement
13 new virtual block device such as ublk-qcow2 (there are several attempts of
14 implementing qcow2 driver in kernel).
15
16 Userspace block devices are attractive because:
17
18 - They can be written many programming languages.
19 - They can use libraries that are not available in the kernel.
20 - They can be debugged with tools familiar to application developers.
21 - Crashes do not kernel panic the machine.
22 - Bugs are likely to have a lower security impact than bugs in kernel
23 code.
24 - They can be installed and updated independently of the kernel.
25 - They can be used to simulate block device easily with user specified
26 parameters/setting for test/debug purpose
27
28 ublk block device (``/dev/ublkb*``) is added by ublk driver. Any IO request
29 on the device will be forwarded to ublk userspace program. For convenience,
30 in this document, ``ublk server`` refers to generic ublk userspace
31 program. ``ublksrv`` [#userspace]_ is one of such implementation. It
32 provides ``libublksrv`` [#userspace_lib]_ library for developing specific
33 user block device conveniently, while also generic type block device is
34 included, such as loop and null. Richard W.M. Jones wrote userspace nbd device
35 ``nbdublk`` [#userspace_nbdublk]_ based on ``libublksrv`` [#userspace_lib]_.
36
37 After the IO is handled by userspace, the result is committed back to the
38 driver, thus completing the request cycle. This way, any specific IO handling
39 logic is totally done by userspace, such as loop's IO handling, NBD's IO
40 communication, or qcow2's IO mapping.
41
42 ``/dev/ublkb*`` is driven by blk-mq request-based driver. Each request is
43 assigned by one queue wide unique tag. ublk server assigns unique tag to each
44 IO too, which is 1:1 mapped with IO of ``/dev/ublkb*``.
45
46 Both the IO request forward and IO handling result committing are done via
47 ``io_uring`` passthrough command; that is why ublk is also one io_uring based
48 block driver. It has been observed that using io_uring passthrough command can
49 give better IOPS than block IO; which is why ublk is one of high performance
50 implementation of userspace block device: not only IO request communication is
51 done by io_uring, but also the preferred IO handling in ublk server is io_uring
52 based approach too.
53
54 ublk provides control interface to set/get ublk block device parameters.
55 The interface is extendable and kabi compatible: basically any ublk request
56 queue's parameter or ublk generic feature parameters can be set/get via the
57 interface. Thus, ublk is generic userspace block device framework.
58 For example, it is easy to setup a ublk device with specified block
59 parameters from userspace.
60
61 Using ublk
62 ==========
63
64 ublk requires userspace ublk server to handle real block device logic.
65
66 Below is example of using ``ublksrv`` to provide ublk-based loop device.
67
68 - add a device::
69
70 ublk add -t loop -f ublk-loop.img
71
72 - format with xfs, then use it::
73
74 mkfs.xfs /dev/ublkb0
75 mount /dev/ublkb0 /mnt
76 # do anything. all IOs are handled by io_uring
77 ...
78 umount /mnt
79
80 - list the devices with their info::
81
82 ublk list
83
84 - delete the device::
85
86 ublk del -a
87 ublk del -n $ublk_dev_id
88
89 See usage details in README of ``ublksrv`` [#userspace_readme]_.
90
91 Design
92 ======
93
94 Control plane
95 -------------
96
97 ublk driver provides global misc device node (``/dev/ublk-control``) for
98 managing and controlling ublk devices with help of several control commands:
99
100 - ``UBLK_CMD_ADD_DEV``
101
102 Add a ublk char device (``/dev/ublkc*``) which is talked with ublk server
103 WRT IO command communication. Basic device info is sent together with this
104 command. It sets UAPI structure of ``ublksrv_ctrl_dev_info``,
105 such as ``nr_hw_queues``, ``queue_depth``, and max IO request buffer size,
106 for which the info is negotiated with the driver and sent back to the server.
107 When this command is completed, the basic device info is immutable.
108
109 - ``UBLK_CMD_SET_PARAMS`` / ``UBLK_CMD_GET_PARAMS``
110
111 Set or get parameters of the device, which can be either generic feature
112 related, or request queue limit related, but can't be IO logic specific,
113 because the driver does not handle any IO logic. This command has to be
114 sent before sending ``UBLK_CMD_START_DEV``.
115
116 - ``UBLK_CMD_START_DEV``
117
118 After the server prepares userspace resources (such as creating I/O handler
119 threads & io_uring for handling ublk IO), this command is sent to the
120 driver for allocating & exposing ``/dev/ublkb*``. Parameters set via
121 ``UBLK_CMD_SET_PARAMS`` are applied for creating the device.
122
123 - ``UBLK_CMD_STOP_DEV``
124
125 Halt IO on ``/dev/ublkb*`` and remove the device. When this command returns,
126 ublk server will release resources (such as destroying I/O handler threads &
127 io_uring).
128
129 - ``UBLK_CMD_DEL_DEV``
130
131 Remove ``/dev/ublkc*``. When this command returns, the allocated ublk device
132 number can be reused.
133
134 - ``UBLK_CMD_GET_QUEUE_AFFINITY``
135
136 When ``/dev/ublkc`` is added, the driver creates block layer tagset, so
137 that each queue's affinity info is available. The server sends
138 ``UBLK_CMD_GET_QUEUE_AFFINITY`` to retrieve queue affinity info. It can
139 set up the per-queue context efficiently, such as bind affine CPUs with IO
140 pthread and try to allocate buffers in IO thread context.
141
142 - ``UBLK_CMD_GET_DEV_INFO``
143
144 For retrieving device info via ``ublksrv_ctrl_dev_info``. It is the server's
145 responsibility to save IO target specific info in userspace.
146
147 - ``UBLK_CMD_GET_DEV_INFO2``
148 Same purpose with ``UBLK_CMD_GET_DEV_INFO``, but ublk server has to
149 provide path of the char device of ``/dev/ublkc*`` for kernel to run
150 permission check, and this command is added for supporting unprivileged
151 ublk device, and introduced with ``UBLK_F_UNPRIVILEGED_DEV`` together.
152 Only the user owning the requested device can retrieve the device info.
153
154 How to deal with userspace/kernel compatibility:
155
156 1) if kernel is capable of handling ``UBLK_F_UNPRIVILEGED_DEV``
157
158 If ublk server supports ``UBLK_F_UNPRIVILEGED_DEV``:
159
160 ublk server should send ``UBLK_CMD_GET_DEV_INFO2``, given anytime
161 unprivileged application needs to query devices the current user owns,
162 when the application has no idea if ``UBLK_F_UNPRIVILEGED_DEV`` is set
163 given the capability info is stateless, and application should always
164 retrieve it via ``UBLK_CMD_GET_DEV_INFO2``
165
166 If ublk server doesn't support ``UBLK_F_UNPRIVILEGED_DEV``:
167
168 ``UBLK_CMD_GET_DEV_INFO`` is always sent to kernel, and the feature of
169 UBLK_F_UNPRIVILEGED_DEV isn't available for user
170
171 2) if kernel isn't capable of handling ``UBLK_F_UNPRIVILEGED_DEV``
172
173 If ublk server supports ``UBLK_F_UNPRIVILEGED_DEV``:
174
175 ``UBLK_CMD_GET_DEV_INFO2`` is tried first, and will be failed, then
176 ``UBLK_CMD_GET_DEV_INFO`` needs to be retried given
177 ``UBLK_F_UNPRIVILEGED_DEV`` can't be set
178
179 If ublk server doesn't support ``UBLK_F_UNPRIVILEGED_DEV``:
180
181 ``UBLK_CMD_GET_DEV_INFO`` is always sent to kernel, and the feature of
182 ``UBLK_F_UNPRIVILEGED_DEV`` isn't available for user
183
184 - ``UBLK_CMD_START_USER_RECOVERY``
185
186 This command is valid if ``UBLK_F_USER_RECOVERY`` feature is enabled. This
187 command is accepted after the old process has exited, ublk device is quiesced
188 and ``/dev/ublkc*`` is released. User should send this command before he starts
189 a new process which re-opens ``/dev/ublkc*``. When this command returns, the
190 ublk device is ready for the new process.
191
192 - ``UBLK_CMD_END_USER_RECOVERY``
193
194 This command is valid if ``UBLK_F_USER_RECOVERY`` feature is enabled. This
195 command is accepted after ublk device is quiesced and a new process has
196 opened ``/dev/ublkc*`` and get all ublk queues be ready. When this command
197 returns, ublk device is unquiesced and new I/O requests are passed to the
198 new process.
199
200 - user recovery feature description
201
202 Three new features are added for user recovery: ``UBLK_F_USER_RECOVERY``,
203 ``UBLK_F_USER_RECOVERY_REISSUE``, and ``UBLK_F_USER_RECOVERY_FAIL_IO``. To
204 enable recovery of ublk devices after the ublk server exits, the ublk server
205 should specify the ``UBLK_F_USER_RECOVERY`` flag when creating the device. The
206 ublk server may additionally specify at most one of
207 ``UBLK_F_USER_RECOVERY_REISSUE`` and ``UBLK_F_USER_RECOVERY_FAIL_IO`` to
208 modify how I/O is handled while the ublk server is dying/dead (this is called
209 the ``nosrv`` case in the driver code).
210
211 With just ``UBLK_F_USER_RECOVERY`` set, after the ublk server exits,
212 ublk does not delete ``/dev/ublkb*`` during the whole
213 recovery stage and ublk device ID is kept. It is ublk server's
214 responsibility to recover the device context by its own knowledge.
215 Requests which have not been issued to userspace are requeued. Requests
216 which have been issued to userspace are aborted.
217
218 With ``UBLK_F_USER_RECOVERY_REISSUE`` additionally set, after the ublk server
219 exits, contrary to ``UBLK_F_USER_RECOVERY``,
220 requests which have been issued to userspace are requeued and will be
221 re-issued to the new process after handling ``UBLK_CMD_END_USER_RECOVERY``.
222 ``UBLK_F_USER_RECOVERY_REISSUE`` is designed for backends who tolerate
223 double-write since the driver may issue the same I/O request twice. It
224 might be useful to a read-only FS or a VM backend.
225
226 With ``UBLK_F_USER_RECOVERY_FAIL_IO`` additionally set, after the ublk server
227 exits, requests which have issued to userspace are failed, as are any
228 subsequently issued requests. Applications continuously issuing I/O against
229 devices with this flag set will see a stream of I/O errors until a new ublk
230 server recovers the device.
231
232 Unprivileged ublk device is supported by passing ``UBLK_F_UNPRIVILEGED_DEV``.
233 Once the flag is set, all control commands can be sent by unprivileged
234 user. Except for command of ``UBLK_CMD_ADD_DEV``, permission check on
235 the specified char device(``/dev/ublkc*``) is done for all other control
236 commands by ublk driver, for doing that, path of the char device has to
237 be provided in these commands' payload from ublk server. With this way,
238 ublk device becomes container-ware, and device created in one container
239 can be controlled/accessed just inside this container.
240
241 Data plane
242 ----------
243
244 The ublk server should create dedicated threads for handling I/O. Each
245 thread should have its own io_uring through which it is notified of new
246 I/O, and through which it can complete I/O. These dedicated threads
247 should focus on IO handling and shouldn't handle any control &
248 management tasks.
249
250 The's IO is assigned by a unique tag, which is 1:1 mapping with IO
251 request of ``/dev/ublkb*``.
252
253 UAPI structure of ``ublksrv_io_desc`` is defined for describing each IO from
254 the driver. A fixed mmapped area (array) on ``/dev/ublkc*`` is provided for
255 exporting IO info to the server; such as IO offset, length, OP/flags and
256 buffer address. Each ``ublksrv_io_desc`` instance can be indexed via queue id
257 and IO tag directly.
258
259 The following IO commands are communicated via io_uring passthrough command,
260 and each command is only for forwarding the IO and committing the result
261 with specified IO tag in the command data:
262
263 - ``UBLK_IO_FETCH_REQ``
264
265 Sent from the server IO pthread for fetching future incoming IO requests
266 destined to ``/dev/ublkb*``. This command is sent only once from the server
267 IO pthread for ublk driver to setup IO forward environment.
268
269 Once a thread issues this command against a given (qid,tag) pair, the thread
270 registers itself as that I/O's daemon. In the future, only that I/O's daemon
271 is allowed to issue commands against the I/O. If any other thread attempts
272 to issue a command against a (qid,tag) pair for which the thread is not the
273 daemon, the command will fail. Daemons can be reset only be going through
274 recovery.
275
276 The ability for every (qid,tag) pair to have its own independent daemon task
277 is indicated by the ``UBLK_F_PER_IO_DAEMON`` feature. If this feature is not
278 supported by the driver, daemons must be per-queue instead - i.e. all I/Os
279 associated to a single qid must be handled by the same task.
280
281 - ``UBLK_IO_COMMIT_AND_FETCH_REQ``
282
283 When an IO request is destined to ``/dev/ublkb*``, the driver stores
284 the IO's ``ublksrv_io_desc`` to the specified mapped area; then the
285 previous received IO command of this IO tag (either ``UBLK_IO_FETCH_REQ``
286 or ``UBLK_IO_COMMIT_AND_FETCH_REQ)`` is completed, so the server gets
287 the IO notification via io_uring.
288
289 After the server handles the IO, its result is committed back to the
290 driver by sending ``UBLK_IO_COMMIT_AND_FETCH_REQ`` back. Once ublkdrv
291 received this command, it parses the result and complete the request to
292 ``/dev/ublkb*``. In the meantime setup environment for fetching future
293 requests with the same IO tag. That is, ``UBLK_IO_COMMIT_AND_FETCH_REQ``
294 is reused for both fetching request and committing back IO result.
295
296 - ``UBLK_IO_NEED_GET_DATA``
297
298 With ``UBLK_F_NEED_GET_DATA`` enabled, the WRITE request will be firstly
299 issued to ublk server without data copy. Then, IO backend of ublk server
300 receives the request and it can allocate data buffer and embed its addr
301 inside this new io command. After the kernel driver gets the command,
302 data copy is done from request pages to this backend's buffer. Finally,
303 backend receives the request again with data to be written and it can
304 truly handle the request.
305
306 ``UBLK_IO_NEED_GET_DATA`` adds one additional round-trip and one
307 io_uring_enter() syscall. Any user thinks that it may lower performance
308 should not enable UBLK_F_NEED_GET_DATA. ublk server pre-allocates IO
309 buffer for each IO by default. Any new project should try to use this
310 buffer to communicate with ublk driver. However, existing project may
311 break or not able to consume the new buffer interface; that's why this
312 command is added for backwards compatibility so that existing projects
313 can still consume existing buffers.
314
315 - data copy between ublk server IO buffer and ublk block IO request
316
317 The driver needs to copy the block IO request pages into the server buffer
318 (pages) first for WRITE before notifying the server of the coming IO, so
319 that the server can handle WRITE request.
320
321 When the server handles READ request and sends
322 ``UBLK_IO_COMMIT_AND_FETCH_REQ`` to the server, ublkdrv needs to copy
323 the server buffer (pages) read to the IO request pages.
324
325 Zero copy
326 ---------
327
328 ublk zero copy relies on io_uring's fixed kernel buffer, which provides
329 two APIs: `io_buffer_register_bvec()` and `io_buffer_unregister_bvec`.
330
331 ublk adds IO command of `UBLK_IO_REGISTER_IO_BUF` to call
332 `io_buffer_register_bvec()` for ublk server to register client request
333 buffer into io_uring buffer table, then ublk server can submit io_uring
334 IOs with the registered buffer index. IO command of `UBLK_IO_UNREGISTER_IO_BUF`
335 calls `io_buffer_unregister_bvec()` to unregister the buffer, which is
336 guaranteed to be live between calling `io_buffer_register_bvec()` and
337 `io_buffer_unregister_bvec()`. Any io_uring operation which supports this
338 kind of kernel buffer will grab one reference of the buffer until the
339 operation is completed.
340
341 ublk server implementing zero copy or user copy has to be CAP_SYS_ADMIN and
342 be trusted, because it is ublk server's responsibility to make sure IO buffer
343 filled with data for handling read command, and ublk server has to return
344 correct result to ublk driver when handling READ command, and the result
345 has to match with how many bytes filled to the IO buffer. Otherwise,
346 uninitialized kernel IO buffer will be exposed to client application.
347
348 ublk server needs to align the parameter of `struct ublk_param_dma_align`
349 with backend for zero copy to work correctly.
350
351 For reaching best IO performance, ublk server should align its segment
352 parameter of `struct ublk_param_segment` with backend for avoiding
353 unnecessary IO split, which usually hurts io_uring performance.
354
355 Auto Buffer Registration
356 ------------------------
357
358 The ``UBLK_F_AUTO_BUF_REG`` feature automatically handles buffer registration
359 and unregistration for I/O requests, which simplifies the buffer management
360 process and reduces overhead in the ublk server implementation.
361
362 This is another feature flag for using zero copy, and it is compatible with
363 ``UBLK_F_SUPPORT_ZERO_COPY``.
364
365 Feature Overview
366 ~~~~~~~~~~~~~~~~
367
368 This feature automatically registers request buffers to the io_uring context
369 before delivering I/O commands to the ublk server and unregisters them when
370 completing I/O commands. This eliminates the need for manual buffer
371 registration/unregistration via ``UBLK_IO_REGISTER_IO_BUF`` and
372 ``UBLK_IO_UNREGISTER_IO_BUF`` commands, then IO handling in ublk server
373 can avoid dependency on the two uring_cmd operations.
374
375 IOs can't be issued concurrently to io_uring if there is any dependency
376 among these IOs. So this way not only simplifies ublk server implementation,
377 but also makes concurrent IO handling becomes possible by removing the
378 dependency on buffer registration & unregistration commands.
379
380 Usage Requirements
381 ~~~~~~~~~~~~~~~~~~
382
383 1. The ublk server must create a sparse buffer table on the same ``io_ring_ctx``
384 used for ``UBLK_IO_FETCH_REQ`` and ``UBLK_IO_COMMIT_AND_FETCH_REQ``. If
385 uring_cmd is issued on a different ``io_ring_ctx``, manual buffer
386 unregistration is required.
387
388 2. Buffer registration data must be passed via uring_cmd's ``sqe->addr`` with the
389 following structure::
390
391 struct ublk_auto_buf_reg {
392 __u16 index; /* Buffer index for registration */
393 __u8 flags; /* Registration flags */
394 __u8 reserved0; /* Reserved for future use */
395 __u32 reserved1; /* Reserved for future use */
396 };
397
398 ublk_auto_buf_reg_to_sqe_addr() is for converting the above structure into
399 ``sqe->addr``.
400
401 3. All reserved fields in ``ublk_auto_buf_reg`` must be zeroed.
402
403 4. Optional flags can be passed via ``ublk_auto_buf_reg.flags``.
404
405 Fallback Behavior
406 ~~~~~~~~~~~~~~~~~
407
408 If auto buffer registration fails:
409
410 1. When ``UBLK_AUTO_BUF_REG_FALLBACK`` is enabled:
411
412 - The uring_cmd is completed
413 - ``UBLK_IO_F_NEED_REG_BUF`` is set in ``ublksrv_io_desc.op_flags``
414 - The ublk server must manually deal with the failure, such as, register
415 the buffer manually, or using user copy feature for retrieving the data
416 for handling ublk IO
417
418 2. If fallback is not enabled:
419
420 - The ublk I/O request fails silently
421 - The uring_cmd won't be completed
422
423 Limitations
424 ~~~~~~~~~~~
425
426 - Requires same ``io_ring_ctx`` for all operations
427 - May require manual buffer management in fallback cases
428 - io_ring_ctx buffer table has a max size of 16K, which may not be enough
429 in case that too many ublk devices are handled by this single io_ring_ctx
430 and each one has very large queue depth
431
432 References
433 ==========
434
435 .. [#userspace] https://github.com/ming1/ubdsrv
436
437 .. [#userspace_lib] https://github.com/ming1/ubdsrv/tree/master/lib
438
439 .. [#userspace_nbdublk] https://gitlab.com/rwmjones/libnbd/-/tree/nbdublk
440
441 .. [#userspace_readme] https://github.com/ming1/ubdsrv/blob/master/README
442

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

ublk 개요와 동기

1-27

이 문서는 `SPDX-License-Identifier: GPL-2.0`으로 배포되는 userspace block device driver인 ublk를 설명합니다.

ublk는 userspace에서 block device logic을 구현하기 위한 generic framework입니다. loop, nbd 같은 virtual block driver를 userspace로 옮기거나, kernel에서 여러 차례 구현을 시도한 qcow2를 `ublk-qcow2` 같은 새 virtual block device로 구현하는 데 유용합니다.

Userspace block device가 매력적인 이유는 다음과 같습니다.

  • 여러 programming language로 작성할 수 있습니다.
  • kernel에서 사용할 수 없는 library를 사용할 수 있습니다.
  • application developer에게 익숙한 tool로 debug할 수 있습니다.
  • crash가 machine의 kernel panic을 일으키지 않습니다.
  • bug의 security impact가 kernel code의 bug보다 작을 가능성이 큽니다.
  • kernel과 독립적으로 설치하고 update할 수 있습니다.
  • 시험·debug를 위해 사용자가 지정한 parameter와 setting으로 block device를 쉽게 simulate할 수 있습니다.

Device·server·io_uring 구조

28-59

ublk driver는 ublk block device `/dev/ublkb*`를 추가합니다. 이 device의 모든 IO request는 ublk userspace program으로 전달됩니다. 이 문서에서는 generic ublk userspace program을 `ublk server`라고 부릅니다.

`ublksrv`는 그러한 구현 중 하나이며, 특정 user block device를 편리하게 개발하는 `libublksrv` library를 제공합니다. loop와 null 같은 generic type block device도 포함합니다. Richard W.M. Jones는 `libublksrv`를 기반으로 userspace nbd device인 `nbdublk`를 작성했습니다.

userspace가 IO를 처리한 뒤 결과를 driver에 commit하면 request cycle이 완료됩니다. loop의 IO 처리, NBD의 IO communication, qcow2의 IO mapping 같은 구체적인 IO 처리 logic은 모두 userspace에서 수행합니다.

`/dev/ublkb*`는 blk-mq request-based driver로 구동됩니다. 각 request에는 queue 전체에서 unique한 tag 하나가 할당됩니다. ublk server도 각 IO에 unique tag를 부여하며 `/dev/ublkb*`의 IO와 1:1로 mapping합니다.

IO request 전달과 IO 처리 결과 commit은 모두 `io_uring` passthrough command로 수행하므로 ublk는 io_uring 기반 block driver입니다. io_uring passthrough command는 block IO보다 높은 IOPS를 낼 수 있는 것으로 관찰됐습니다. request communication뿐 아니라 ublk server에서 선호하는 IO 처리도 io_uring 기반이므로 ublk는 고성능 userspace block device 구현입니다.

ublk는 block device parameter를 set/get하는 control interface를 제공합니다. 이 interface는 확장 가능하고 KABI compatible하며, ublk request queue parameter나 generic feature parameter를 set/get할 수 있습니다. userspace에서 지정한 block parameter로 ublk device를 쉽게 구성할 수 있습니다.

ublksrv 사용 예

60-89

ublk는 실제 block device logic을 처리할 userspace ublk server가 필요합니다. 다음은 `ublksrv`로 ublk 기반 loop device를 제공하는 예입니다.

device를 추가합니다.

ublk add -t loop -f ublk-loop.img

XFS로 format한 뒤 사용합니다.

mkfs.xfs /dev/ublkb0
mount /dev/ublkb0 /mnt
# do anything. all IOs are handled by io_uring
...
umount /mnt

device와 정보를 나열합니다.

ublk list

모든 device 또는 지정한 device를 삭제합니다.

ublk del -a
ublk del -n $ublk_dev_id

자세한 사용법은 `ublksrv` README인 `https://github.com/ming1/ubdsrv/blob/master/README`를 참조하십시오.

Control plane: 생성과 시작

90-121

ublk driver는 여러 control command로 ublk device를 관리하는 global misc device node `/dev/ublk-control`을 제공합니다.

`UBLK_CMD_ADD_DEV`는 ublk server와 IO command를 통신할 ublk char device `/dev/ublkc*`를 추가합니다. 기본 device info를 함께 보내며 `nr_hw_queues`, `queue_depth`, 최대 IO request buffer size 같은 `ublksrv_ctrl_dev_info` UAPI structure 값을 driver와 negotiate해 server로 돌려줍니다. command가 완료되면 기본 device info는 immutable입니다.

`UBLK_CMD_SET_PARAMS`와 `UBLK_CMD_GET_PARAMS`는 generic feature 또는 request queue limit 관련 device parameter를 설정하거나 가져옵니다. driver는 IO logic을 처리하지 않으므로 IO logic 고유 parameter는 대상이 아닙니다. `UBLK_CMD_SET_PARAMS`는 `UBLK_CMD_START_DEV`보다 먼저 보내야 합니다.

`UBLK_CMD_START_DEV`는 server가 ublk IO 처리용 I/O handler thread와 io_uring 같은 userspace resource를 준비한 뒤 보냅니다. driver는 `/dev/ublkb*`를 할당하고 노출하며, `UBLK_CMD_SET_PARAMS`로 설정한 parameter를 device 생성에 적용합니다.

Control plane: 중지·삭제·정보

122-151

`UBLK_CMD_STOP_DEV`는 `/dev/ublkb*`의 IO를 중단하고 device를 제거합니다. command가 반환되면 ublk server는 I/O handler thread와 io_uring을 파괴하는 등 resource를 해제합니다.

`UBLK_CMD_DEL_DEV`는 `/dev/ublkc*`를 제거합니다. command가 반환되면 할당했던 ublk device number를 재사용할 수 있습니다.

`UBLK_CMD_GET_QUEUE_AFFINITY`는 `/dev/ublkc`를 추가할 때 driver가 생성한 block layer tagset에서 queue affinity 정보를 가져옵니다. server는 affine CPU를 IO pthread에 bind하고 IO thread context에서 buffer를 할당하는 등 per-queue context를 효율적으로 구성할 수 있습니다.

`UBLK_CMD_GET_DEV_INFO`는 `ublksrv_ctrl_dev_info`를 통해 device info를 가져옵니다. IO target 고유 정보는 server가 userspace에 저장할 책임이 있습니다.

`UBLK_CMD_GET_DEV_INFO2`는 같은 목적이지만 kernel의 permission check를 위해 ublk server가 `/dev/ublkc*` char device path를 제공해야 합니다. unprivileged ublk device 지원을 위해 `UBLK_F_UNPRIVILEGED_DEV`와 함께 도입됐으며, 요청한 device를 소유한 user만 정보를 가져올 수 있습니다.

GET_DEV_INFO userspace/kernel 호환성

152-183

kernel과 ublk server가 모두 `UBLK_F_UNPRIVILEGED_DEV`를 지원하면, unprivileged application이 현재 user 소유 device를 조회할 때 ublk server는 항상 `UBLK_CMD_GET_DEV_INFO2`를 보내야 합니다. capability info는 stateless라 application은 해당 flag 설정 여부를 미리 알 수 없기 때문입니다.

kernel은 `UBLK_F_UNPRIVILEGED_DEV`를 지원하지만 ublk server가 지원하지 않으면 항상 `UBLK_CMD_GET_DEV_INFO`를 보내며 이 feature는 user에게 제공되지 않습니다.

kernel은 `UBLK_F_UNPRIVILEGED_DEV`를 지원하지 않지만 ublk server가 지원하면 먼저 `UBLK_CMD_GET_DEV_INFO2`를 시도합니다. 실패한 뒤 flag를 설정할 수 없으므로 `UBLK_CMD_GET_DEV_INFO`로 retry해야 합니다.

kernel과 ublk server 모두 `UBLK_F_UNPRIVILEGED_DEV`를 지원하지 않으면 항상 `UBLK_CMD_GET_DEV_INFO`를 보내며 feature는 user에게 제공되지 않습니다.

User recovery command와 정책

184-230

`UBLK_CMD_START_USER_RECOVERY`는 `UBLK_F_USER_RECOVERY` feature가 활성화됐을 때 유효합니다. 이전 process가 종료되고 ublk device가 quiesce되며 `/dev/ublkc*`가 해제된 뒤 받아들입니다. 새 process가 `/dev/ublkc*`를 다시 열기 전에 보내야 하며, 반환되면 device가 새 process를 받을 준비를 마칩니다.

`UBLK_CMD_END_USER_RECOVERY`도 `UBLK_F_USER_RECOVERY`가 필요합니다. device가 quiesce된 상태에서 새 process가 `/dev/ublkc*`를 열고 모든 ublk queue를 준비한 뒤 받아들입니다. 반환되면 device의 quiesce가 풀리고 새 IO request가 새 process로 전달됩니다.

user recovery에는 `UBLK_F_USER_RECOVERY`, `UBLK_F_USER_RECOVERY_REISSUE`, `UBLK_F_USER_RECOVERY_FAIL_IO` 세 feature가 추가됐습니다. server 종료 뒤 device를 복구하려면 생성할 때 `UBLK_F_USER_RECOVERY`를 지정합니다. server가 dying/dead인 driver의 `nosrv` case에서 IO 처리 방식을 바꾸려면 나머지 두 flag 중 최대 하나만 추가할 수 있습니다.

`UBLK_F_USER_RECOVERY`만 설정하면 recovery 전체 동안 `/dev/ublkb*`를 삭제하지 않고 ublk device ID도 유지합니다. server는 자체 지식으로 device context를 복구해야 합니다. userspace에 아직 발행하지 않은 request는 requeue하고, 이미 발행한 request는 abort합니다.

`UBLK_F_USER_RECOVERY_REISSUE`도 설정하면 userspace에 이미 발행한 request까지 requeue하고 `UBLK_CMD_END_USER_RECOVERY` 처리 뒤 새 process에 다시 발행합니다. driver가 같은 IO request를 두 번 발행할 수 있으므로 double-write를 허용하는 backend용이며 read-only FS나 VM backend에 유용할 수 있습니다.

`UBLK_F_USER_RECOVERY_FAIL_IO`도 설정하면 server 종료 뒤 userspace에 발행한 request와 이후 발행되는 request를 실패 처리합니다. 새 ublk server가 device를 복구할 때까지 계속 IO를 발행하는 application에는 연속된 IO error가 보입니다.

Unprivileged·container-aware device

231-239

`UBLK_F_UNPRIVILEGED_DEV`를 전달하면 unprivileged ublk device를 지원합니다. flag를 설정한 뒤에는 unprivileged user가 모든 control command를 보낼 수 있습니다.

`UBLK_CMD_ADD_DEV`를 제외한 모든 control command에 대해 ublk driver는 지정한 `/dev/ublkc*` char device의 permission을 검사하므로 server는 command payload에 char device path를 제공해야 합니다. 이 방식으로 ublk device는 container-aware가 되어 한 container에서 생성한 device를 그 container 안에서만 control하고 access할 수 있습니다.

Data plane과 UBLK_IO_FETCH_REQ

240-279

ublk server는 IO 처리 전용 thread를 만들어야 합니다. 각 thread는 새 IO notification과 IO completion에 사용할 자체 io_uring을 가져야 하며, control·management task를 처리하지 않고 IO handling에 집중해야 합니다.

각 IO에는 `/dev/ublkb*`의 IO request와 1:1 mapping되는 unique tag를 할당합니다.

driver의 각 IO를 설명하는 `ublksrv_io_desc` UAPI structure가 정의돼 있습니다. `/dev/ublkc*`의 고정 mmap area인 array를 통해 IO offset, length, OP/flags, buffer address를 server에 export합니다. 각 `ublksrv_io_desc` instance는 queue ID와 IO tag로 직접 index할 수 있습니다.

`UBLK_IO_FETCH_REQ`는 server IO pthread가 `/dev/ublkb*`로 향하는 미래의 incoming IO request를 가져오기 위해 보냅니다. ublk driver가 IO forward 환경을 구성하도록 server IO pthread에서 한 번만 보냅니다.

thread가 특정 `(qid,tag)` pair에 이 command를 발행하면 자신을 해당 IO의 daemon으로 등록합니다. 이후에는 그 daemon만 해당 IO에 command를 발행할 수 있으며 다른 thread의 command는 실패합니다. daemon은 recovery를 거쳐야만 reset할 수 있습니다.

각 `(qid,tag)` pair가 독립 daemon task를 가질 수 있는지는 `UBLK_F_PER_IO_DAEMON` feature로 표시합니다. driver가 지원하지 않으면 daemon은 per-queue여야 하므로 한 qid에 속한 모든 IO를 같은 task가 처리해야 합니다.

COMMIT_AND_FETCH·NEED_GET_DATA·data copy

280-324

IO request가 `/dev/ublkb*`로 향하면 driver는 해당 IO의 `ublksrv_io_desc`를 지정된 mmap area에 저장합니다. 그런 다음 이 IO tag가 이전에 받은 `UBLK_IO_FETCH_REQ` 또는 `UBLK_IO_COMMIT_AND_FETCH_REQ`를 완료하므로 server는 io_uring으로 IO notification을 받습니다.

server가 IO를 처리한 뒤 `UBLK_IO_COMMIT_AND_FETCH_REQ`를 보내 결과를 driver에 commit합니다. ublk driver는 결과를 parse해 `/dev/ublkb*` request를 완료하는 동시에 같은 IO tag로 미래 request를 가져올 환경을 구성합니다. 따라서 이 command는 request fetch와 IO result commit에 함께 재사용됩니다.

`UBLK_F_NEED_GET_DATA`를 활성화하면 WRITE request를 data copy 없이 먼저 ublk server에 발행합니다. backend는 request를 받은 뒤 data buffer를 할당하고 address를 `UBLK_IO_NEED_GET_DATA` command에 넣습니다. kernel driver가 command를 받으면 request page에서 backend buffer로 data를 copy하고, backend는 write data가 담긴 request를 다시 받아 실제로 처리합니다.

`UBLK_IO_NEED_GET_DATA`는 round-trip 하나와 `io_uring_enter()` syscall 하나를 추가합니다. 성능 저하가 우려되면 `UBLK_F_NEED_GET_DATA`를 활성화하지 않아야 합니다. 기본적으로 ublk server는 IO마다 buffer를 미리 할당하며 새 project는 이 buffer interface 사용을 시도해야 합니다. 기존 project가 새 interface를 사용할 수 없거나 깨질 수 있어 기존 buffer와의 backwards compatibility를 위해 이 command를 추가했습니다.

WRITE에서는 server에 IO를 알리기 전에 driver가 block IO request page를 server buffer page로 먼저 copy해야 합니다. READ에서는 server가 request를 처리하고 `UBLK_IO_COMMIT_AND_FETCH_REQ`를 보낸 뒤 ublk driver가 server buffer에서 읽은 page를 IO request page로 copy해야 합니다.

Zero copy

325-354

ublk zero copy는 io_uring fixed kernel buffer와 그 API인 `io_buffer_register_bvec()`, `io_buffer_unregister_bvec()`에 의존합니다.

`UBLK_IO_REGISTER_IO_BUF` command는 `io_buffer_register_bvec()`를 호출해 client request buffer를 io_uring buffer table에 등록하며, server는 등록된 buffer index로 io_uring IO를 제출할 수 있습니다. `UBLK_IO_UNREGISTER_IO_BUF`는 `io_buffer_unregister_bvec()`를 호출해 buffer 등록을 해제합니다.

buffer는 register와 unregister 호출 사이에서 살아 있음이 보장됩니다. 이 kernel buffer를 지원하는 io_uring operation은 완료될 때까지 buffer reference 하나를 잡습니다.

zero copy나 user copy를 구현하는 ublk server는 `CAP_SYS_ADMIN` 권한을 가진 trusted server여야 합니다. READ 처리 시 IO buffer를 data로 채우고 채운 byte 수와 일치하는 올바른 결과를 driver에 반환할 책임이 server에 있습니다. 그렇지 않으면 초기화되지 않은 kernel IO buffer가 client application에 노출됩니다.

zero copy가 올바르게 동작하도록 server는 `struct ublk_param_dma_align` parameter를 backend와 맞춰야 합니다. 최상의 IO 성능을 위해 `struct ublk_param_segment`의 segment parameter도 backend와 맞춰 불필요한 IO split을 피해야 합니다. IO split은 보통 io_uring 성능을 해칩니다.

Auto Buffer Registration 개요

355-378

`UBLK_F_AUTO_BUF_REG` feature는 I/O request의 buffer register와 unregister를 자동 처리해 buffer management를 단순화하고 ublk server 구현 overhead를 줄입니다. zero copy를 위한 또 다른 feature flag이며 `UBLK_F_SUPPORT_ZERO_COPY`와 compatible합니다.

IO command를 ublk server에 전달하기 전에 request buffer를 io_uring context에 자동 등록하고, IO command를 완료할 때 등록을 해제합니다. `UBLK_IO_REGISTER_IO_BUF`와 `UBLK_IO_UNREGISTER_IO_BUF`를 수동으로 사용할 필요가 없어 server의 IO 처리는 두 `uring_cmd` operation에 의존하지 않습니다.

IO 사이에 dependency가 있으면 io_uring에 동시에 발행할 수 없습니다. 자동 등록 방식은 server 구현을 단순화할 뿐 아니라 buffer register/unregister command dependency를 제거해 concurrent IO handling도 가능하게 합니다.

Auto registration 사용 요건

379-403

1. ublk server는 `UBLK_IO_FETCH_REQ`와 `UBLK_IO_COMMIT_AND_FETCH_REQ`에 쓰는 동일한 `io_ring_ctx`에 sparse buffer table을 만들어야 합니다. 다른 `io_ring_ctx`에서 `uring_cmd`를 발행하면 buffer를 수동으로 unregister해야 합니다.

2. buffer registration data는 다음 structure로 `uring_cmd`의 `sqe->addr`를 통해 전달해야 합니다.

struct ublk_auto_buf_reg {
    __u16 index;      /* Buffer index for registration */
    __u8 flags;       /* Registration flags */
    __u8 reserved0;   /* Reserved for future use */
    __u32 reserved1;  /* Reserved for future use */
};

`ublk_auto_buf_reg_to_sqe_addr()`는 이 structure를 `sqe->addr`로 변환합니다.

3. `ublk_auto_buf_reg`의 모든 reserved field는 `0`으로 만들어야 합니다.

4. optional flag는 `ublk_auto_buf_reg.flags`를 통해 전달할 수 있습니다.

Fallback 동작과 제한

404-430

auto buffer registration이 실패하고 `UBLK_AUTO_BUF_REG_FALLBACK`이 활성화돼 있으면 다음과 같이 동작합니다.

  • `uring_cmd`를 완료합니다.
  • `ublksrv_io_desc.op_flags`에 `UBLK_IO_F_NEED_REG_BUF`를 설정합니다.
  • ublk server는 buffer를 수동 등록하거나 user copy feature로 data를 가져오는 등 실패를 직접 처리해야 합니다.

fallback이 활성화되지 않았으면 다음과 같이 동작합니다.

  • ublk I/O request가 알림 없이 실패합니다.
  • `uring_cmd`가 완료되지 않습니다.

제한 사항은 다음과 같습니다.

  • 모든 operation에 동일한 `io_ring_ctx`가 필요합니다.
  • fallback case에서는 수동 buffer management가 필요할 수 있습니다.
  • `io_ring_ctx` buffer table의 최대 크기는 `16K`입니다. 하나의 context가 queue depth가 매우 큰 ublk device를 너무 많이 처리하면 부족할 수 있습니다.

References

431-441

관련 userspace 구현과 library의 reference는 다음과 같습니다.

  • `ublksrv`: https://github.com/ming1/ubdsrv
  • `libublksrv`: https://github.com/ming1/ubdsrv/tree/master/lib
  • `nbdublk`: https://gitlab.com/rwmjones/libnbd/-/tree/nbdublk
  • `ublksrv README`: https://github.com/ming1/ubdsrv/blob/master/README