当前位置:   article > 正文

linux内核AIO使用方法_linux 5.4内核 使用aio读写数据

linux 5.4内核 使用aio读写数据
  1. Linux Asynchronous I/O Explained (Last updated: 13 Apr 2012)
  2. *******************************************************************************
  3. by Vasily Tarasov <tarasov AT vasily dot name>
  4. Asynchronoes I/O (AIO) is a method for performing I/O operations so that the
  5. process that issued an I/O request is not blocked till the data is available.
  6. Instead, after an I/O request is submitted, the process continues to execute
  7. its code and can later check the status of the submitted request.
  8. Linux kernel provides only *5* system calls for performing asynchronoes I/O.
  9. Other AIO functions commonly descibed in the literature are implemented in the
  10. user space libraries and use the system calls internally. Some libraries can
  11. also emulate AIO functionality entirely in the user space without any kernel
  12. support.
  13. There are two main libraries in Linux that facilitate AIO, we will refer to
  14. them as *libaio* and *librt* (the latter one is a part of libc).
  15. In this text, I first discuss system calls, then libaio, and finaly librt.
  16. AIO System Calls
  17. *******************************************************************************
  18. based on Linux 3.2.1 kernel
  19. AIO system call entry points are located in "fs/aio.c" file in the kernel's
  20. source code. Types and constants exported to the user space reside in
  21. "/usr/include/linux/aio_abi.h" header file.
  22. There are only 5 AIO system calls:
  23. * int io_setup(unsigned nr_events, aio_context_t *ctxp);
  24. * int io_destroy(aio_context_t ctx);
  25. * int io_submit(aio_context_t ctx, long nr, struct iocb *cbp[]);
  26. * int io_cancel(aio_context_t ctx, struct iocb *, struct io_event *result);
  27. * int io_getevents(aio_context_t ctx, long min_nr, long nr,
  28. struct io_event *events, struct timespec *timeout);
  29. I will demonstrate the usage of these system calls using a sequence of programs
  30. in the increasing order of their complexity.
  31. Program 1:
  32. >> snip start: 1.c >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  33. 00 #define _GNU_SOURCE /* syscall() is not POSIX */
  34. 01
  35. 02 #include <stdio.h> /* for perror() */
  36. 03 #include <unistd.h> /* for syscall() */
  37. 04 #include <sys/syscall.h> /* for __NR_* definitions */
  38. 05 #include <linux/aio_abi.h> /* for AIO types and constants */
  39. 06
  40. 07 inline int io_setup(unsigned nr, aio_context_t *ctxp)
  41. 08 {
  42. 09 return syscall(__NR_io_setup, nr, ctxp);
  43. 10 }
  44. 11
  45. 12 inline int io_destroy(aio_context_t ctx)
  46. 13 {
  47. 14 return syscall(__NR_io_destroy, ctx);
  48. 15 }
  49. 16
  50. 17 int main()
  51. 18 {
  52. 19 aio_context_t ctx;
  53. 20 int ret;
  54. 21
  55. 22 ctx = 0;
  56. 23
  57. 24 ret = io_setup(128, &ctx);
  58. 25 if (ret < 0) {
  59. 26 perror("io_setup error");
  60. 27 return -1;
  61. 28 }
  62. 29
  63. 30 ret = io_destroy(ctx);
  64. 31 if (ret < 0) {
  65. 32 perror("io_destroy error");
  66. 33 return -1;
  67. 34 }
  68. 35
  69. 36 return 0;
  70. 37 }
  71. << snip end: 1.c <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  72. For now, ignore first 17 lines of the code and look at main() function. In line
  73. 24 we call io_setup() system call to create so called "AIO context" in the
  74. kernel. AIO context is a set of data structures that the kernel supports to
  75. perform AIO. Every process can have multiple AIO contextes and as such one
  76. needs an identificator for every AIO context in a process (XXX: come up with a
  77. handy example how it can be used). Ctx variable of type aio_context_t defined in
  78. line 19 stores such an identificator in our example. A pointer to ctx variable
  79. is passed to io_setup() as a second argument and kernel fills this variable
  80. with a context identifier. Interestingly, aio_context_t is actually just an
  81. unsigned long defined in the kernel ("linux/aio_abi.h") like that:
  82. typedef unsigned long aio_context_t;
  83. In line 22 we set ctx to 0 which is required by kernel or io_setup() fails with
  84. -EINVAL error.
  85. The first argument of io_setup() function - 128 in our case - is the maximum
  86. number of requests that can simultaneously reside in the context. This will be
  87. explained in more details in the next examples.
  88. In line 30 we destroy just created AIO context by calling io_destroy() system
  89. call with ctx as an argument.
  90. The lines above 17 are just helpers that allow to call system calls directly. We
  91. use glibc's syscall() function that invokes any system call by its number. It
  92. is only required if one wants to call system calls directly without using AIO
  93. libraries' wrapper functions (provided by libaio and librt). Notice, that
  94. syscall() functions's return value follows the usual conventions for indicating
  95. an error: -1, with errno set to a positive value that indicates the error.
  96. So, we check if the values returned by io_setup() and io_destroy() are less than
  97. zero to detect the error, and then use perror() function that will print the
  98. errno.
  99. In the last example we did a minimal thing: created an AIO context and then
  100. destroyed it immediatelly. In the next example we submit one request to the
  101. context and then query its status later.
  102. Program 2:
  103. >> snip start: 2.c >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  104. 00 #define _GNU_SOURCE /* syscall() is not POSIX */
  105. 01
  106. 02 #include <stdio.h> /* for perror() */
  107. 03 #include <unistd.h> /* for syscall() */
  108. 04 #include <sys/syscall.h> /* for __NR_* definitions */
  109. 05 #include <linux/aio_abi.h> /* for AIO types and constants */
  110. 06 #include <fcntl.h> /* O_RDWR */
  111. 07 #include <string.h> /* memset() */
  112. 08 #include <inttypes.h> /* uint64_t */
  113. 09
  114. 10 inline int io_setup(unsigned nr, aio_context_t *ctxp)
  115. 11 {
  116. 12 return syscall(__NR_io_setup, nr, ctxp);
  117. 13 }
  118. 14
  119. 15 inline int io_destroy(aio_context_t ctx)
  120. 16 {
  121. 17 return syscall(__NR_io_destroy, ctx);
  122. 18 }
  123. 19
  124. 20 inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp)
  125. 21 {
  126. 22 return syscall(__NR_io_submit, ctx, nr, iocbpp);
  127. 23 }
  128. 24
  129. 25 inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr,
  130. 26 struct io_event *events, struct timespec *timeout)
  131. 27 {
  132. 28 return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout);
  133. 29 }
  134. 30
  135. 31 int main()
  136. 32 {
  137. 33 aio_context_t ctx;
  138. 34 struct iocb cb;
  139. 35 struct iocb *cbs[1];
  140. 36 char data[4096];
  141. 37 struct io_event events[1];
  142. 38 int ret;
  143. 39 int fd;
  144. 40
  145. 41 fd = open("/tmp/testfile", O_RDWR | O_CREAT);
  146. 42 if (fd < 0) {
  147. 43 perror("open error");
  148. 44 return -1;
  149. 45 }
  150. 46
  151. 47 ctx = 0;
  152. 48
  153. 49 ret = io_setup(128, &ctx);
  154. 50 if (ret < 0) {
  155. 51 perror("io_setup error");
  156. 52 return -1;
  157. 53 }
  158. 54
  159. 55 /* setup I/O control block */
  160. 56 memset(&cb, 0, sizeof(cb));
  161. 57 cb.aio_fildes = fd;
  162. 58 cb.aio_lio_opcode = IOCB_CMD_PWRITE;
  163. 59
  164. 60 /* command-specific options */
  165. 61 cb.aio_buf = (uint64_t)data;
  166. 62 cb.aio_offset = 0;
  167. 63 cb.aio_nbytes = 4096;
  168. 64
  169. 65 cbs[0] = &cb;
  170. 66
  171. 67 ret = io_submit(ctx, 1, cbs);
  172. 68 if (ret != 1) {
  173. 69 if (ret < 0)
  174. 70 perror("io_submit error");
  175. 71 else
  176. 72 fprintf(stderr, "could not sumbit IOs");
  177. 73 return -1;
  178. 74 }
  179. 75
  180. 76 /* get the reply */
  181. 77 ret = io_getevents(ctx, 1, 1, events, NULL);
  182. 78 printf("%d\n", ret);
  183. 79
  184. 80 ret = io_destroy(ctx);
  185. 81 if (ret < 0) {
  186. 82 perror("io_destroy error");
  187. 83 return -1;
  188. 84 }
  189. 85
  190. 86 return 0;
  191. 87 }
  192. << snip end: 2.c <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  193. Every I/O request that is submitted to an AIO context is represented by an I/O
  194. control block structure - struct iocb - declared in line 34. We initialize this
  195. structure in lines 55-63. First, the whole structure is zeroed, then file
  196. descriptor (aio_fildes) and command (aio_lio_opcode) fields are set.
  197. File descriptor corresponds to a previously opened file, in our example we
  198. open "/tmp/testfile" file in line 41.
  199. AIO commands currently supported by Linux kernel are:
  200. IOCB_CMD_PREAD
  201. positioned read; corresponds to pread() system call.
  202. IOCB_CMD_PWRITE
  203. positioned write; corresponds to pwrite() system call.
  204. IOCB_CMD_FSYNC
  205. sync file's data and metadata with disk; corresponds to fsync() system call.
  206. IOCB_CMD_FDSYNC
  207. sync file's data and metadata with disk, but only metadata needed to access
  208. modified file data is written; corresponds to fdatasync() system call.
  209. IOCB_CMD_PREADV
  210. vectored positioned read, sometimes called "scattered input";
  211. corresponds to pread() system call.
  212. IOCB_CMD_PWRITEV
  213. vectored positioned write, sometimes called "gathered output";
  214. corresponds to pwrite() system call.
  215. IOCB_CMD_NOOP
  216. defined in the header file, but is not used anywhere else in the kernel.
  217. The semantics of other fields in the iocb structure depends on the command
  218. specified. For now, we will limit our discussion to IOCB_CMD_PREAD and
  219. IOCB_CMD_PWRITE commands. After understanding AIO interface for these two
  220. commands, we will look into the remaining ones.
  221. In lines 60-63 of our running example we set command-specific fields of iocb
  222. structure: aio_buf and aio_nbytes corresond to a region in memory to which
  223. data should be read or written to; aio_offset is an absolute offset in a file.
  224. Now, when one I/O control block is ready, we put a pointer to it in an array
  225. (line 65) and then pass this array to the io_submit() system call (line 67).
  226. io_submit() takes AIO context ID, size of the array and the array itself as the
  227. arguments. Notice, that array should contain *pointers* to the iocb structures,
  228. not the structures themself.
  229. io_submit()'s return code can be one of the following values:
  230. A) ret = (number of iocbs sumbmitted)
  231. Ideal case, all iocbs were accepted for processing.
  232. B) 0 < ret < (number of iocbs sumbmitted)
  233. io_submit() system call processes iocbs one by one starting from
  234. the first entry in the passed array. If submission of some iocb fails,
  235. it stops at this point and returns the index of iocb that failed.
  236. There is no way to know what is the exact reason of a failure.
  237. However, if the very first iocb submission fails, see point C.
  238. C) ret < 0
  239. There are two reasons why this could happen:
  240. 1) Some error happened even before io_submit() started to iterate
  241. over iocbs in the array (e.g., AIO context was invalid).
  242. 2) The submission of the very first iocb (cbx[0]) failed).
  243. So, in our example, we handle io_submit()'s return code in an unusual way. If
  244. return code is not equal to the number of iocbs, then that is a clear error but
  245. we don't know its reason (errno is not set). Consequently, we use
  246. fprintf(stderr, ...) function to print error notification on the screen.
  247. Otherwise, if return code is less than zero, then we know the error (errno is
  248. set) and use perror() function instead. Notice, that in case of a single iocb
  249. in the array (as in our example) such a complex error handling makes less sense:
  250. if the first (and only) iocb fails, we are guaranteed to get an error
  251. information (see point C above). We handle error in a more complex way in this
  252. example only to reuse the same code later, when we submit multiple iocbs in a
  253. single io_submit() call.
  254. After iocb is submitted we can perform any other actions without waiting for I/O
  255. to complete. For every completed I/O request (successfully or unsuccessfully)
  256. kernel creates an io_event structure. To obtain the list of io_events (and
  257. consequently all completed iocbs) io_getevent() system call should be used (line
  258. 77). When calling io_getevents(), one needs to specify:
  259. a) which AIO context to get events from (ctx variable)
  260. b) a buffer where the kernel should load events to (events varaiable)
  261. c) minimal number of events one wants to get (first 1 in our program).
  262. If less then this number of iocbs are currently completed,
  263. io_getevents() will block till enough events appear. See point e)
  264. for more details on how to control blocking time.
  265. d) maximum number of events one wants to get. This usually is
  266. the size of the events buffer (second 1 in our program)
  267. e) If not enough events are available, we don't want to wait forever.
  268. One can specify a relative deadline as the last argument.
  269. NULL in this case means to wait infinitely.
  270. If one wants io_getevents() not to block at all then
  271. timespec timeout structure need to be initialzed to zero
  272. seconds and zero nanoseconds.
  273. The return code of io_getevents can be:
  274. A) ret = (max number of events)
  275. All events that fit in the user provided buffer were obtained
  276. from the kernel. There might be more pending events in the kernel.
  277. B) (min number of events) <= ret <= (max number of events)
  278. All currently available events were read from the kernel and no
  279. blocking happened.
  280. C) 0 < ret < (min number of events)
  281. All currently available events were read from the kernel and
  282. we blocked to wait for the time user has specified.
  283. E) ret = 0
  284. no events are available XXX:? does blocking happen in this case?..
  285. F) ret < 0
  286. an error happened
  287. TO BE CONTINUED...
  288. /proc/sys/fs/aio-max-nr
  289. /proc/sys/fs/aio-nr
  290. Note that timeout is relative and will be updated if not NULL and the operation
  291. blocks
  292. Check how vectors a provide to vectored PREADV and PWRITEV commands.
  293. Other fields to fill/explain:
  294. /* these are internal to the kernel/libc. */
  295. __u64 aio_data; /* data to be returned in event's data */
  296. __u32 PADDED(aio_key, aio_reserved1);
  297. /* the kernel sets aio_key to the req # */
  298. /* common fields */
  299. +++ __u16 aio_lio_opcode; /* see IOCB_CMD_ above */
  300. __s16 aio_reqprio;
  301. __u32 aio_fildes;
  302. __u64 aio_buf;
  303. __u64 aio_nbytes;
  304. __s64 aio_offset;
  305. /* extra parameters */
  306. __u64 aio_reserved2; /* TODO: use this for a (struct sigevent *) */
  307. /* flags for the "struct iocb" */
  308. __u32 aio_flags;
  309. /*
  310. * if the IOCB_FLAG_RESFD flag of "aio_flags" is set, this is an
  311. * eventfd to signal AIO readiness to
  312. */
  313. __u32 aio_resfd;
  314. *** SYNC RELATED COMMANDS ***
  315. IOCB_CMD_FSYNC
  316. sync file's data and metadata with disk; corresponds to fsync() system call.
  317. IOCB_CMD_FDSYNC
  318. sync file's data and metadata with disk, but only metadata needed to access
  319. modified file data is written; corresponds to fdatasync() system call.
  320. *** VECTORED INPUT and OUTPUT ***
  321. IOCB_CMD_PREADV
  322. vectored positioned read, sometimes called "scattered input";
  323. corresponds to pread() system call.
  324. IOCB_CMD_PWRITEV
  325. vectored positioned write, sometimes called "gathered output";
  326. corresponds to pwrite() system call.
  327. *** OTHER COMMANDS ***
  328. IOCB_CMD_NOOP
  329. defined in the header file, but is not used anywhere else in the kernel.
  330. XXX: May be discass Poll and other semi-existing commands here?...
  331. *********************************************************
  332. ********************* LIBAIO LIBRARY ********************
  333. *********************************************************
  334. libaio:
  335. /lib64/libaio.so.1 (shared library)
  336. libaio-devel:
  337. /usr/include/libaio.h (header library)
  338. /usr/lib64/libaio.a (static library)
  339. Functions:
  340. a) Actual system call wrappers:
  341. int io_setup(int maxevents, io_context_t *ctxp);
  342. int io_destroy(io_context_t ctx);
  343. int io_submit(io_context_t ctx, long nr, struct iocb *ios[]);
  344. int io_cancel(io_context_t ctx, struct iocb *iocb, struct io_event *evt);
  345. io_getevents(io_context_t ctx_id, long min_nr, long nr, struct io_event *events, struct timespec *timeout);
  346. io_context_t is a pointer to an non-existing stucture:
  347. typedef struct io_context *io_context_t;
  348. Not a single line of code in any user tool or in the libaio library looks at the
  349. members of 'struct io_context'. So, gcc happily compiles the code even though
  350. struct io_context is not defined. This structure is probably defined just for
  351. type checking. The rule of thumb when using libaio is just to declare all
  352. variables as io_context_t and forget that it actually is a pointer!
  353. b) Convenient macroses:
  354. static inline void io_prep_pread(struct iocb *iocb, int fd, void *buf, size_t count, long long offset)
  355. static inline void io_prep_pwrite(struct iocb *iocb, int fd, void *buf, size_t count, long long offset)
  356. static inline void io_prep_preadv(struct iocb *iocb, int fd, const struct iovec *iov, int iovcnt, long long offset)
  357. static inline void io_prep_pwritev(struct iocb *iocb, int fd, const struct iovec *iov, int iovcnt, long long offset)
  358. static inline void io_prep_poll(struct iocb *iocb, int fd, int events)
  359. static inline void io_prep_fsync(struct iocb *iocb, int fd)
  360. static inline void io_prep_fdsync(struct iocb *iocb, int fd)
  361. static inline int io_poll(io_context_t ctx, struct iocb *iocb, io_callback_t cb, int fd, int events)
  362. static inline int io_fsync(io_context_t ctx, struct iocb *iocb, io_callback_t cb, int fd)
  363. static inline int io_fdsync(io_context_t ctx, struct iocb *iocb, io_callback_t cb, int fd)
  364. static inline void io_set_eventfd(struct iocb *iocb, int eventfd);
  365. *********************************************************
  366. ******** MATCHING LIBAIO AND KERNEL INTERFACE ***********
  367. *********************************************************
  368. libaio.h redefines some of the kernel definitions (god know why),
  369. but they match at the binary level. E.g., this is kernel
  370. exported definition of iocb:
  371. struct iocb {
  372. /* these are internal to the kernel/libc. */
  373. __u64 aio_data; /* data to be returned in event's data */
  374. __u32 PADDED(aio_key, aio_reserved1);
  375. /* the kernel sets aio_key to the req # */
  376. /* common fields */
  377. __u16 aio_lio_opcode; /* see IOCB_CMD_ above */
  378. __s16 aio_reqprio;
  379. __u32 aio_fildes;
  380. __u64 aio_buf;
  381. __u64 aio_nbytes;
  382. __s64 aio_offset;
  383. /* extra parameters */
  384. __u64 aio_reserved2; /* TODO: use this for a (struct sigevent *) */
  385. /* flags for the "struct iocb" */
  386. __u32 aio_flags;
  387. /*
  388. * if the IOCB_FLAG_RESFD flag of "aio_flags" is set, this is an
  389. * eventfd to signal AIO readiness to
  390. */
  391. __u32 aio_resfd;
  392. }; /* 64 bytes */
  393. And this is definition of iocb by libaio.h:
  394. struct io_iocb_common {
  395. PADDEDptr(void *buf, __pad1);
  396. PADDEDul(nbytes, __pad2);
  397. long long offset;
  398. long long __pad3;
  399. unsigned flags;
  400. unsigned resfd;
  401. }; /* result code is the amount read or -'ve errno */
  402. struct iocb {
  403. PADDEDptr(void *data, __pad1); /* Return in the io completion event */
  404. PADDED(unsigned key, __pad2); /* For use in identifying io requests */
  405. short aio_lio_opcode;
  406. short aio_reqprio;
  407. int aio_fildes;
  408. union {
  409. struct io_iocb_common c;
  410. struct io_iocb_vector v;
  411. struct io_iocb_poll poll;
  412. struct io_iocb_sockaddr saddr;
  413. } u;
  414. };
  415. ****** AIO LIBRARY *****
  416. glibc:
  417. /lib64/librt.so.1
  418. glibc-headers:
  419. /usr/include/aio.h
  420. Provide POSIX-defined interface for async I/O.
  421. aio_read()
  422. aio_write()
  423. aio_cancel()
  424. aio_error()
  425. aio_fsync()
  426. aio_suspend()
  427. aio_return()
  428. lio_listio
  429. ****** To discover ****
  430. XXX: see if these are implemented in some other kernels:
  431. /* These two are experimental.
  432. * IOCB_CMD_PREADX = 4,
  433. * IOCB_CMD_POLL = 5,
  434. */
  435. XXX: potential resubmittion of the wrong iocb, knowing its index.
  436. XXX: two AIO contextes per process?

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/216270
推荐阅读
相关标签
  

闽ICP备14008679号