操作系统与存储:解析Linux内核全新异步IO引擎io_uring设计与实现
作者:draculaqian,騰訊后臺開發(fā)工程師
引言
存儲場景中,我們對性能的要求非常高。在存儲引擎底層的IO技術選型時,可能會有如下討論關于IO的討論。
http://davmac.org/davpage/linux/async-io.html
So from the above documentation, it seems that Linux doesn't have a true async file I/O that is not blocking (AIO, Epoll or POSIX AIO are all broken in some ways). I wonder if tlinux has any remedy. We should reach out to tlinux experts to get their opinions.
看完這段話,讀者可能會有如下的問題。
這是在討論什么,為何會有此番討論?
有沒有更好的解決方案?
更好的解決方案是通過怎樣的設計和實現(xiàn)解決問題?
...
2019年,Linux Kernel正式進入5.x時代,眾多新特性中,與存儲領域相關度最高的便是最新的IO引擎——io_uring。從一些性能測試的結論來看,io_uring性能遠高于native AIO方式,帶來了巨大的性能提升,這對當前異步IO領域也是一個big news。
對于問題1,本文簡述了Linux過往的的IO發(fā)展歷程,同步IO接口、原生異步IO接口AIO的缺陷,為何原有方式存在缺陷。
對于問題2,本文從設計的角度出發(fā),介紹了最新的IO引擎io_uring的相關內(nèi)容。
對于問題3,本文深入最新版內(nèi)核linux-5.10中解析了io_uring的大體實現(xiàn)(關鍵數(shù)據(jù)結構、流程、特性實現(xiàn)等)。
...
一切過往,皆為序章
以史為鏡,可以知興替。我們先看看現(xiàn)存過往IO接口的缺陷。
過往同步IO接口
當今Linux對文件的操作有很多種方式,過往同步IO接口從功能上劃分,大體分為如下幾種。
原始版本
offset版本
向量版本
offset+向量版本
read,write
最原始的文件IO系統(tǒng)調用就是read,write
read系統(tǒng)調用從文件描述符所指代的打開文件中讀取數(shù)據(jù)。
read簡單介紹:
NAMEread - read from a file descriptor SYNOPSIS#include <unistd.h>ssize_t read(int fd, void *buf, size_t count); DESCRIPTIONread() attempts to read up to count bytes from file descriptor fdinto the buffer starting at buf.On files that support seeking, the read operation commences at thefile offset, and the file offset is incremented by the number ofbytes read. If the file offset is at or past the end of file, nobytes are read, and read() returns zero.If count is zero, read() may detect the errors described below. Inthe absence of any errors, or if read() does not check for errors, aread() with a count of 0 returns zero and has no other effects.According to POSIX.1, if count is greater than SSIZE_MAX, the resultis implementation-defined; see NOTES for the upper limit on Linux.write系統(tǒng)調用將數(shù)據(jù)寫入一個已打開的文件中。
write簡單介紹:
NAMEwrite - write to a file descriptor SYNOPSIS#include <unistd.h>ssize_t write(int fd, const void *buf, size_t count); DESCRIPTIONwrite() writes up to count bytes from the buffer starting at buf tothe file referred to by the file descriptor fd.The number of bytes written may be less than count if, for example,there is insufficient space on the underlying physical medium, or theRLIMIT_FSIZE resource limit is encountered (see setrlimit(2)), or thecall was interrupted by a signal handler after having written lessthan count bytes. (See also pipe(7).)For a seekable file (i.e., one to which lseek(2) may be applied, forexample, a regular file) writing takes place at the file offset, andthe file offset is incremented by the number of bytes actuallywritten. If the file was open(2)ed with O_APPEND, the file offset isfirst set to the end of the file before writing. The adjustment ofthe file offset and the write operation are performed as an atomicstep.POSIX requires that a read(2) that can be proved to occur after awrite() has returned will return the new data. Note that not allfilesystems are POSIX conforming.According to POSIX.1, if count is greater than SSIZE_MAX, the resultis implementation-defined; see NOTES for the upper limit on Linux.在文件特定偏移處的IO:pread,pwrite
在多線程環(huán)境下,為了保證線程安全,需要保證下列操作的原子性。
????off_t?orig;orig?=?lseek(fd,?0,?SEEK_CUR);?//?Save?current?offsetlseek(fd,?offset,?SEEK_SET);s?=?read(fd,?buf,?len);lseek(fd,?orig,?SEEK_SET);?//?Restore?original?file?offset讓使用者來保證原子性較繁,從接口上就有保證是一個好的選擇,后來出現(xiàn)的pread便實現(xiàn)了這一點。
與read, write類似,pread, pwrite調用時可以指定位置進行文件IO操作,而非始于文件的當前偏移處,且他們不會改變文件的當前偏移量。這種方式,減少了編碼,并提高了代碼的健壯性。
pread、pwrite簡單介紹:
NAMEpread, pwrite - read from or write to a file descriptor at a givenoffset SYNOPSIS#include <unistd.h>ssize_t pread(int fd, void *buf, size_t count, off_t offset);ssize_t pwrite(int fd, const void *buf, size_t count, off_t offset);DESCRIPTIONpread() reads up to count bytes from file descriptor fd at offsetoffset (from the start of the file) into the buffer starting at buf.The file offset is not changed.pwrite() writes up to count bytes from the buffer starting at buf tothe file descriptor fd at offset offset. The file offset is notchanged.The file referenced by fd must be capable of seeking.當然,往read,write接口參數(shù)的標志位集合中加入新標志,用以表征新邏輯,可能達到相同的效果,但是這可能不夠優(yōu)雅——如果某個參數(shù)有多種可能的值,而函數(shù)內(nèi)又以條件表達式檢查這些參數(shù)值,并根據(jù)不同參數(shù)值做出不同的行為,那么以明確函數(shù)取代參數(shù)(Replace Parameter with Explicit Methods)也是一種合適的重構手法。
如果需要反復執(zhí)行l(wèi)seek,并伴之以文件IO,那么pread和pwrite系統(tǒng)調用在某些情況下是具有性能優(yōu)勢的。這是因為執(zhí)行單個pread或pwrite系統(tǒng)調用的成本要低于執(zhí)行l(wèi)seek和read/write兩個系統(tǒng)調用(當然,相對地,執(zhí)行實際IO的開銷通常要遠大于執(zhí)行系統(tǒng)調用,系統(tǒng)調用的性能優(yōu)勢作用有限)。歷史上,一些數(shù)據(jù)庫,通過使用kernel的這一新接口,獲得了不菲的收益。如PostgreSQL:[PATCH] Using pread instead of lseek (with analysis)
分散輸入和集中輸出(Scatter-Gather IO):readv, writev
“物質的組成與結構決定物質的性質,性質決定用途,用途體現(xiàn)性質。”是自然科學的重要思想,在計算機科學中也是如此。現(xiàn)有計算機體系結構下,數(shù)據(jù)存儲由一個或多個基本單元組成,物理、邏輯上的結構,決定了數(shù)據(jù)存儲的性質——可能是連續(xù)的,也可能是不連續(xù)的。
對于不連續(xù)的數(shù)據(jù)的處理相對較繁,例如,使用read將數(shù)據(jù)讀到不連續(xù)的內(nèi)存,使用write將不連續(xù)的內(nèi)存發(fā)送出去。更具體地看,如果要從文件中讀一片連續(xù)的數(shù)據(jù)至進程的不同區(qū)域,有兩種方案:
使用read一次將它們讀至一個較大的緩沖區(qū)中,然后將它們分成若干部分復制到不同的區(qū)域。
調用read若干次分批將它們讀至不同區(qū)域。
同樣地,如果想將程序中不同區(qū)域的數(shù)據(jù)塊連續(xù)地寫至文件,也必須進行類似的處理。而且這種方案需要多次調用read、write系統(tǒng)調用,有損性能。
那么如何簡化編程,如何解決這種開銷呢?一種有效的解法就是使用特定的數(shù)據(jù)結構對非連續(xù)的數(shù)據(jù)進行管理,批量傳輸數(shù)據(jù)。從接口上就有此保證是一個好的選擇,后來出現(xiàn)的readv,writev便實現(xiàn)了這一點。
這種基于向量的,分散輸入和集中輸出的系統(tǒng)調用并非只對單個緩沖區(qū)進行讀寫操作,而是一次即可傳輸多個緩沖區(qū)的數(shù)據(jù),免除了多次系統(tǒng)調用的開銷。該機制使用一個數(shù)組iov定義了一組用來傳輸數(shù)據(jù)的緩沖區(qū),一個整形數(shù)iovcnt指定iov的成員個數(shù),其中,iov中的每個成員都是如下形式的數(shù)據(jù)結構。
struct?iovec?{void??*iov_base;????/*?Starting?address?*/size_t?iov_len;?????/*?Number?of?bytes?to?transfer?*/ };功能交集:preadv,pwritev
上述兩種功能都是一種進步,不過似乎格格不入,那么是否能合二為一,進兩步呢?
數(shù)學上,集合是指具有某種特定性質的具體的或抽象的對象匯總而成的集體。其中,構成集合的這些對象則稱為該集合的元素。我這里將接口定義成一種集合,一種特定功能就是其中的一個元素。根據(jù)已知有限集構造一個子集,該子集對于每一個元素要么包含要么不包含,那么根據(jù)乘法原理,這個子集共有2^N 種構造方式,即有2^N個子集。這么多可能的集合,顯然較繁。基于場景對于功能子集的需求、元素之間的容斥、集合中元素是否需要有序(接口層面對功能的表現(xiàn))、簡約性等因素,我們會確立一些優(yōu)雅的接口,這也是函數(shù)接口設計的一個哲學話題。
后來出現(xiàn)的preadv,pwritev,便是偏移和向量的交集,也是一種在排列組合的巨大可能性下確立的少部分簡約的接口。
帶標志位集合的IO:preadv2,pwritev2
再后來,還出現(xiàn)了變種函數(shù)preadv2和pwritev2,相比較preadv,pwritev,v2版本還能設置本次IO的標志,比如RWF_DSYNC、RWF_HIPRI、RWF_SYNC、RWF_NOWAIT、RWF_APPEND。
readv、preadv、preadv2系列簡單介紹:
NAMEreadv, writev, preadv, pwritev, preadv2, pwritev2 - read or writedata into multiple buffersSYNOPSIS#include <sys/uio.h>ssize_t readv(int fd, const struct iovec *iov, int iovcnt);ssize_t writev(int fd, const struct iovec *iov, int iovcnt);ssize_t preadv(int fd, const struct iovec *iov, int iovcnt,off_t offset);ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt,off_t offset);ssize_t preadv2(int fd, const struct iovec *iov, int iovcnt,off_t offset, int flags);ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt,off_t offset, int flags);DESCRIPTIONThe readv() system call reads iovcnt buffers from the file associatedwith the file descriptor fd into the buffers described by iov("scatter input").The writev() system call writes iovcnt buffers of data described byiov to the file associated with the file descriptor fd ("gatheroutput").The pointer iov points to an array of iovec structures, defined in<sys/uio.h> as:struct iovec {void *iov_base; /* Starting address */size_t iov_len; /* Number of bytes to transfer */};The readv() system call works just like read(2) except that multiplebuffers are filled.The writev() system call works just like write(2) except that multi‐ple buffers are written out.Buffers are processed in array order. This means that readv() com‐pletely fills iov[0] before proceeding to iov[1], and so on. (Ifthere is insufficient data, then not all buffers pointed to by iovmay be filled.) Similarly, writev() writes out the entire contentsof iov[0] before proceeding to iov[1], and so on.The data transfers performed by readv() and writev() are atomic: thedata written by writev() is written as a single block that is not in‐termingled with output from writes in other processes (but seepipe(7) for an exception); analogously, readv() is guaranteed to reada contiguous block of data from the file, regardless of read opera‐tions performed in other threads or processes that have file descrip‐tors referring to the same open file description (see open(2)).preadv() and pwritev()The preadv() system call combines the functionality of readv() andpread(2). It performs the same task as readv(), but adds a fourthargument, offset, which specifies the file offset at which the inputoperation is to be performed.The pwritev() system call combines the functionality of writev() andpwrite(2). It performs the same task as writev(), but adds a fourthargument, offset, which specifies the file offset at which the outputoperation is to be performed.The file offset is not changed by these system calls. The file re‐ferred to by fd must be capable of seeking.preadv2() and pwritev2()These system calls are similar to preadv() and pwritev() calls, butadd a fifth argument, flags, which modifies the behavior on a per-call basis.Unlike preadv() and pwritev(), if the offset argument is -1, then thecurrent file offset is used and updated.The flags argument contains a bitwise OR of zero or more of the fol‐lowing flags:RWF_DSYNC (since Linux 4.7)Provide a per-write equivalent of the O_DSYNC open(2) flag.This flag is meaningful only for pwritev2(), and its effectapplies only to the data range written by the system call.RWF_HIPRI (since Linux 4.6)High priority read/write. Allows block-based filesystems touse polling of the device, which provides lower latency, butmay use additional resources. (Currently, this feature is us‐able only on a file descriptor opened using the O_DIRECTflag.)RWF_SYNC (since Linux 4.7)Provide a per-write equivalent of the O_SYNC open(2) flag.This flag is meaningful only for pwritev2(), and its effectapplies only to the data range written by the system call.RWF_NOWAIT (since Linux 4.14)Do not wait for data which is not immediately available. Ifthis flag is specified, the preadv2() system call will returninstantly if it would have to read data from the backing stor‐age or wait for a lock. If some data was successfully read,it will return the number of bytes read. If no bytes wereread, it will return -1 and set errno to EAGAIN. Currently,this flag is meaningful only for preadv2().RWF_APPEND (since Linux 4.16)Provide a per-write equivalent of the O_APPEND open(2) flag.This flag is meaningful only for pwritev2(), and its effectapplies only to the data range written by the system call.The offset argument does not affect the write operation; thedata is always appended to the end of the file. However, ifthe offset argument is -1, the current file offset is updated.同步IO接口的缺陷
上述接口,盡管形式多樣,但它們都有一個共同的特征,就是同步,即在讀寫IO時,系統(tǒng)調用會阻塞住等待,在數(shù)據(jù)讀取或寫入后才返回結果。
對于傳統(tǒng)、普通的編程模型,這類同步接口編程簡單,結果可預測,倒也無妨,但是在要求高效的場景下,同步導致的后果就是caller在阻塞的同時無法繼續(xù)執(zhí)行其他的操作,只能等待IO結果返回,其實caller本可以利用這段時間繼續(xù)往后執(zhí)行。例如,一個FTP server,接收到客戶機上傳的文件,然后將文件寫入到本機的過程中,若FTP服務程序忙于等待文件讀寫結果的返回,則會拒絕其他此刻正需要連接的客戶機請求。在這種場景下,更好的方式是采用異步編程模型,就上述例子而言,當服務器接收到某個客戶機上傳文件后,直接、無阻塞地將寫入IO的buffer提交給內(nèi)核,然后caller繼續(xù)接受下一個客戶請求,內(nèi)核處理完IO之后,主動調用某種通知機制,告訴caller該IO已完成,完成狀態(tài)保存在某位置。
存儲場景中,我們對性能的要求非常高,所以我們需要異步IO。
AIO
后來,應這類訴求,產(chǎn)生了異步IO接口,即Linux Native異步IO——AIO。
AIO接口簡單介紹(表格引用自Understanding Nginx Modules Development and Architecture Resolving(Second Edition)):
類似地,如同前文所提PostgreSQL——歷史上,也有一些項目通過使用kernel的新接口,獲得了不菲的收益。
例如,高性能服務器nginx就使用了這樣的機制,nginx把讀取文件的操作異步地提交給內(nèi)核后,內(nèi)核會通知IO設備獨立地執(zhí)行操作,這樣,nginx進程可以繼續(xù)充分地占用CPU,而且,當大量讀事件堆積到IO設備的隊列中時,將會發(fā)揮出內(nèi)核中“電梯算法”的優(yōu)勢,從而降低隨機讀取磁盤扇區(qū)的成本。
AIO的缺陷
但是,AIO仍然不夠完美,同樣存在很多缺陷,同樣以nginx為例,目前,nginx僅支持在讀取文件時使用AIO,因為正常寫入文件往往是寫入內(nèi)存就立刻返回,效率很高,而如果替換成AIO寫入速度會明顯下降。
這是因為AIO不支持緩存操作,即使需要操作的文件塊在linux文件緩存中存在,也不會通過操作緩存中的文件塊來代替實際對磁盤的操作,這可能降低實際處理的性能。需要看具體的使用場景,如果大部分用戶請求對文件操作都會落到文件緩存中,那么使用AIO可能不是一個好的選擇。
以上是AIO的不足之一,分析AIO緣何不足,需要較大的篇幅,這里按下不表直接總結一下其他不足之處。
僅支持direct IO。在采用AIO的時候,只能使用O_DIRECT,不能借助文件系統(tǒng)緩存來緩存當前的IO請求,還存在size對齊(直接操作磁盤,所有寫入內(nèi)存塊數(shù)量必須是文件系統(tǒng)塊大小的倍數(shù),而且要與內(nèi)存頁大小對齊。)等限制,這直接影響了aio在很多場景的使用。
仍然可能被阻塞。語義不完備。即使應用層主觀上,希望系統(tǒng)層采用異步IO,但是客觀上,有時候還是可能會被阻塞。io_getevents(2)調用read_events讀取AIO的完成events,read_events中的wait_event_interruptible_hrtimeout等待aio_read_events,如果條件不成立(events未完成)則調用__wait_event_hrtimeout進入睡眠(當然,支持用戶態(tài)設置最大等待時間)。
拷貝開銷大。每個IO提交需要拷貝64+8字節(jié),每個IO完成需要拷貝32字節(jié),總共104字節(jié)的拷貝。這個拷貝開銷是否可以承受,和單次IO大小有關:如果需要發(fā)送的IO本身就很大,相較之下,這點消耗可以忽略,而在大量小IO的場景下,這樣的拷貝影響比較大。
API不友好。每一個IO至少需要兩次系統(tǒng)調用才能完成(submit和wait-for-completion),需要非常小心地使用完成事件以避免丟事件。
系統(tǒng)調用開銷大。也正是因為上一條,io_submit/io_getevents造成了較大的系統(tǒng)調用開銷,在存在spectre/meltdown(CPU熔斷幽靈漏洞,CVE-2017-5754)的機器上,若要避免漏洞問題,則系統(tǒng)調用性能會大幅下降。所以在存儲場景下,高頻系統(tǒng)調用的性能影響較大。
在過去的數(shù)年間,針對上述限制的很多改進努力都未盡如人意。
終于,全新的異步IO引擎io_uring就在這樣的環(huán)境下誕生了。
設計——應該是什么樣子
既然是全新實現(xiàn),我們是否可以不囿于現(xiàn)狀,思考它應該是什么樣子?
關于“應該是什么樣子”,我曾聽智超兄說過這樣的一句話:“Linux應該是什么樣子,它現(xiàn)在就是什么樣子。”,這并不是類似于“存在即合理”這樣的謬傳,而是對Linux系統(tǒng)優(yōu)雅哲學的高度概括,同時也是對開源自由軟件精神的肯定——因為自始至終都是自由的,所以大家覺得應該是什么樣子(哪里有缺陷,哪里不夠優(yōu)雅),大家就會自由地去修改它,所以,經(jīng)過時代的發(fā)展,它的面貌與大家所期望的最相符,即眾人拾柴,眾望所歸。
以后世上可能會有無數(shù)文章講述io_uring是什么樣子,我們先看看它應該是什么樣子。
設計原則
如上所述,歷史實現(xiàn)在一定場景下,會有一定問題,新實現(xiàn)理應反思問題、解決問題。與此同時,需要遵循一定設計原則,如下是若干原則。
簡單:接口需要足夠簡單,這一點不言自明。
易用:同時需要足夠克制,保持易于理解,就不容易誤用,對于使用者來說,這是一種有效的助推(之所以如上沒有采用“簡單易用”這樣的慣用語,是因為簡單并不一定意味著易用。我們盡量避免這種不合邏輯的隱喻)。
可擴展:接口要有足夠的擴展性,盡管某個接口是為了某種場景(如存儲)而建立,但是我們需要面向未來,若有朝一日需要支持非阻塞設備(非塊存儲)以及網(wǎng)絡I/O時,這里不應是桎梏。
特性豐富:當然,接口需要支持足夠豐富的功能。
高效:在存儲場景下,高效率始終是關鍵目標。
可伸縮性:滿足峰值場景的性能需要(高效和低延遲很重要,但是峰值速率對于存儲設備來講也很重要)底層軟件是基于硬件建構的,為了適應新硬件的要求,接口還需要考慮到伸縮性。
另外,因為我們的部分目標之間,本質上往往是存在一定互斥性的(如可伸縮與足夠簡單互斥、特性豐富與高效互斥)很難同時滿足,所以,我們設計時也需要權衡。其中,io_uring始終需要圍繞高效進行設計。
實現(xiàn)思路
解決“系統(tǒng)調用開銷大”的問題
針對這個問題,考慮是否每次都需要系統(tǒng)調用。如果能將多次系統(tǒng)調用中的邏輯放到有限次數(shù)中來,就能將消耗降為常數(shù)時間復雜度。
解決“拷貝開銷大”的問題
之所以在提交和完成事件中存在大量的內(nèi)存拷貝,是因為應用程序和內(nèi)核之間的通信需要拷貝數(shù)據(jù),所以為了避免這個問題,需要重新考量應用與內(nèi)核間的通信方式。我們發(fā)現(xiàn),兩者通信,不是必須要拷貝,通過現(xiàn)有技術,可以讓應用與內(nèi)核共享內(nèi)存,用于彼此通信,需要生產(chǎn)者-消費者模型。
要實現(xiàn)核外與內(nèi)核的零拷貝,最佳方式就是實現(xiàn)一塊內(nèi)存映射區(qū)域,兩者共享一段內(nèi)存,核外往這段內(nèi)存寫數(shù)據(jù),然后通知內(nèi)核使用這段內(nèi)存數(shù)據(jù),或者內(nèi)核填寫這段數(shù)據(jù),核外使用這部分數(shù)據(jù)。因此,我們需要一對共享的ring buffer用于應用程序和內(nèi)核之間的通信。
共享ring buffer的設計主要帶來以下幾個好處:
提交、完成請求時節(jié)省應用和內(nèi)核之間的內(nèi)存拷貝
使用SQPOLL高級特性時,應用程序無需調用系統(tǒng)調用
無鎖操作,用memory ordering實現(xiàn)同步,通過幾個簡單的頭尾指針的移動就可以實現(xiàn)快速交互。
一塊用于核外傳遞數(shù)據(jù)給內(nèi)核,一塊是內(nèi)核傳遞數(shù)據(jù)給核外,一方只讀,一方只寫。
提交隊列SQ(submission queue)中,應用是IO提交的生產(chǎn)者,內(nèi)核是消費者。
完成隊列CQ(completion queue)中,內(nèi)核是IO完成的生產(chǎn)者,應用是消費者。
內(nèi)核控制SQ ring的head和CQ ring的tail,應用程序控制SQ ring的tail和CQ ring的head
那么他們分別需要保存的是什么數(shù)據(jù)呢?
假設A緩存區(qū)為核外寫,內(nèi)核讀,就是將IO數(shù)據(jù)寫到這個緩存區(qū),然后通知內(nèi)核來讀;再假設B緩存區(qū)為內(nèi)核寫,核外讀,他所承擔的責任就是返回完成狀態(tài),標記A緩存區(qū)的其中一個entry的完成狀態(tài)為成功或者失敗等信息。
解決“API不友好”的問題
問題在于需要多個系統(tǒng)調用才能完成,考慮是否可以把多個系統(tǒng)調用合而為一。
你可能會想到,這與上文所說的重構手法相悖,即以明確函數(shù)取代參數(shù)(Replace Parameter with Explicit Methods)——如果某個參數(shù)有多種可能的值,而函數(shù)內(nèi)又以條件表達式檢查這些參數(shù)值,并根據(jù)不同參數(shù)值做出不同的行為。
然而,手法只是手法,選擇具體的重構手法需要遵循重構原則。在不同場景下,可能事實恰恰相反——令函數(shù)攜帶參數(shù)(Parameterize Method)可能是一個好的選擇。
話說天下大勢,分久必合,合久必分。你可能會發(fā)現(xiàn)這樣的兩個函數(shù),它們做著類似的工作,但因少數(shù)幾個值致使行為略有不同。在這種情況下,你可以將這些各自分離的函數(shù)統(tǒng)一起來,并通過參數(shù)來處理那些變化情況,用以簡化問題。這樣的修改可以去除重復代碼,并提高靈活性,因為你可以用這個參數(shù)處理更多的變化情況。
也許你會發(fā)現(xiàn),你無法用這種辦法處理整個函數(shù),但可以處理函數(shù)中的一部分代碼。這種情況下,你應該首先將這部分代碼提煉到一個獨立函數(shù)中,然后再對那個提煉所得的函數(shù)使用令函數(shù)攜帶參數(shù)(Parameterize Method)。
實現(xiàn)——現(xiàn)在是什么樣子
推導完了應該是什么樣子,解析一下現(xiàn)在是什么樣子。
關鍵數(shù)據(jù)結構
程序等于數(shù)據(jù)結構加算法,這里先解析io_uring有哪些關鍵數(shù)據(jù)結構。
io_uring、io_rings結構
結構前面是一些標志位集合和掩碼,尾部是一個柔性數(shù)組。這兩個數(shù)據(jù)在前面使用mmap分配內(nèi)存的時候,對應到了不同的offset,即前面IORING_OFF_SQ_RING、IORING_OFF_CQ_RING和IORING_OFF_SQES的預定于的值。
其中io_rings結構中sq, cq成員,分別代表了提交的請求的ring和已經(jīng)完成的請求返回結構的ring。io_uring結構中是head和tail,用于控制隊列中的頭尾索引。即前文提到的,內(nèi)核控制SQ ring的head和CQ ring的tail,應用程序控制SQ ring的tail和CQ ring的head。
struct?io_uring?{u32?head?____cacheline_aligned_in_smp;u32?tail?____cacheline_aligned_in_smp; };/**?This?data?is?shared?with?the?application?through?the?mmap?at?offsets*?IORING_OFF_SQ_RING?and?IORING_OFF_CQ_RING.**?The?offsets?to?the?member?fields?are?published?through?struct*?io_sqring_offsets?when?calling?io_uring_setup.*/ struct?io_rings?{/**?Head?and?tail?offsets?into?the?ring;?the?offsets?need?to?be*?masked?to?get?valid?indices.**?The?kernel?controls?head?of?the?sq?ring?and?the?tail?of?the?cq?ring,*?and?the?application?controls?tail?of?the?sq?ring?and?the?head?of?the*?cq?ring.*/struct?io_uring??sq,?cq;/**?Bitmasks?to?apply?to?head?and?tail?offsets?(constant,?equals*?ring_entries?-?1)*/u32???sq_ring_mask,?cq_ring_mask;/*?Ring?sizes?(constant,?power?of?2)?*/u32???sq_ring_entries,?cq_ring_entries;/**?Number?of?invalid?entries?dropped?by?the?kernel?due?to*?invalid?index?stored?in?array**?Written?by?the?kernel,?shouldn't?be?modified?by?the*?application?(i.e.?get?number?of?"new?events"?by?comparing?to*?cached?value).**?After?a?new?SQ?head?value?was?read?by?the?application?this*?counter?includes?all?submissions?that?were?dropped?reaching*?the?new?SQ?head?(and?possibly?more).*/u32???sq_dropped;/**?Runtime?SQ?flags**?Written?by?the?kernel,?shouldn't?be?modified?by?the*?application.**?The?application?needs?a?full?memory?barrier?before?checking*?for?IORING_SQ_NEED_WAKEUP?after?updating?the?sq?tail.*/u32???sq_flags;/**?Runtime?CQ?flags**?Written?by?the?application,?shouldn't?be?modified?by?the*?kernel.*/u32?????????????????????cq_flags;/**?Number?of?completion?events?lost?because?the?queue?was?full;*?this?should?be?avoided?by?the?application?by?making?sure*?there?are?not?more?requests?pending?than?there?is?space?in*?the?completion?queue.**?Written?by?the?kernel,?shouldn't?be?modified?by?the*?application?(i.e.?get?number?of?"new?events"?by?comparing?to*?cached?value).**?As?completion?events?come?in?out?of?order?this?counter?is?not*?ordered?with?any?other?data.*/u32???cq_overflow;/**?Ring?buffer?of?completion?events.**?The?kernel?writes?completion?events?fresh?every?time?they?are*?produced,?so?the?application?is?allowed?to?modify?pending*?entries.*/struct?io_uring_cqe?cqes[]?____cacheline_aligned_in_smp; };Submission Queue Entry單元數(shù)據(jù)結構
Submission Queue(下稱SQ)是提交隊列,核外寫內(nèi)核讀的地方。Submission Queue Entry(下稱SQE),即提交隊列中的條目,隊列由一個個條目組成。
描述一個SQE會復雜很多,不僅是因為要描述更多的信息,也是因為可擴展性這一設計原則。
我們需要操作碼、標志集合、關聯(lián)文件描述符、地址、偏移量,另外地,可能還需要表示優(yōu)先級。
/**?IO?submission?data?structure?(Submission?Queue?Entry)*/ struct?io_uring_sqe?{__u8?opcode;??/*?type?of?operation?for?this?sqe?*/__u8?flags;??/*?IOSQE_?flags?*/__u16?ioprio;??/*?ioprio?for?the?request?*/__s32?fd;??/*?file?descriptor?to?do?IO?on?*/union?{__u64?off;?/*?offset?into?file?*/__u64?addr2;};union?{__u64?addr;?/*?pointer?to?buffer?or?iovecs?*/__u64?splice_off_in;};__u32?len;??/*?buffer?size?or?number?of?iovecs?*/union?{__kernel_rwf_t?rw_flags;__u32??fsync_flags;__u16??poll_events;?/*?compatibility?*/__u32??poll32_events;?/*?word-reversed?for?BE?*/__u32??sync_range_flags;__u32??msg_flags;__u32??timeout_flags;__u32??accept_flags;__u32??cancel_flags;__u32??open_flags;__u32??statx_flags;__u32??fadvise_advice;__u32??splice_flags;};__u64?user_data;?/*?data?to?be?passed?back?at?completion?time?*/union?{struct?{/*?pack?this?to?avoid?bogus?arm?OABI?complaints?*/union?{/*?index?into?fixed?buffers,?if?used?*/__u16?buf_index;/*?for?grouped?buffer?selection?*/__u16?buf_group;}?__attribute__((packed));/*?personality?to?use,?if?used?*/__u16?personality;__s32?splice_fd_in;};__u64?__pad2[3];}; };opcode是操作碼,例如IORING_OP_READV,代表向量讀。
flags是標志位集合。
ioprio是請求的優(yōu)先級,對于普通的讀寫,具體定義可以參照ioprio_set(2),
fd是這個請求相關的文件描述符
off是操作的偏移量
addr表示這次IO操作執(zhí)行的地址,如果操作碼opcode描述了一個傳輸數(shù)據(jù)的操作,這個操作是基于向量的,addr就指向struct iovec的數(shù)組首地址,這和前文所說的preadv系統(tǒng)調用是一樣的用法;如果不是基于向量的,那么addr必須直接包含一個地址,len這里(非向量場景)就表示這段buffer的長度,而向量場景就表示iovec的數(shù)量。
接下來的是一個union,表示一系列針對特定操作碼opcode的一些flag。例如,對于上文所提的IORING_OP_READV,隨后的flags就遵循preadv2系統(tǒng)調用。
user_data是各操作碼opcode通用的,內(nèi)核并未染指,僅僅只是拷貝給完成事件completion event
結構的最后用于內(nèi)存對齊,對齊到64字節(jié),為了更豐富的特性,未來這個請求結構應該會包含更多的內(nèi)容。
這就是核外往內(nèi)核填寫的Submission Queue Entry的數(shù)據(jù)結構,準備好這樣的一個數(shù)據(jù)結構,將它寫到對應的sqes所在的內(nèi)存位置,然后再通知內(nèi)核去對應的位置取數(shù)據(jù),這樣就完成了一次數(shù)據(jù)交接。
Completion Queue Entry單元數(shù)據(jù)結構
Completion Queue(下稱CQ)是完成隊列,內(nèi)核寫核外讀的地方。Completion Queue Entry(下稱CQE),即完成隊列中的條目,隊列由一個個條目組成。
描述一個CQE就簡單得多。
/**?IO?completion?data?structure?(Completion?Queue?Entry)*/ struct?io_uring_cqe?{__u64?user_data;?/*?sqe->data?submission?passed?back?*/__s32?res;??/*?result?code?for?this?event?*/__u32?flags; };user_data就是sqe發(fā)送時核外填寫的,只不過在完成時回傳而已,一個常見的用例就是作為一個指針,指向原始請求。從submission queue到completion queue,內(nèi)核不會動這里面的數(shù)據(jù)。
res用來保存最終的這個sqe的執(zhí)行結果,就是這個event的返回碼,可以認為是系統(tǒng)調用的返回值,表示成功或失敗等。如果接口成功的話返回傳輸?shù)淖止?jié)數(shù),如果失敗的話,就是錯誤碼。如果錯誤發(fā)生,res就等于-EIO。
flags是標志位集合。如果flags設置為IORING_CQE_F_BUFFER,則前16位是buffer ID(調用鏈:io_uring_enter -> io_iopoll_check -> io_iopoll_getevents -> io_do_iopoll -> io_iopoll_complete -> io_put_rw_kbuf -> io_put_kbuf,最終會調用io_put_kbuf,如代碼所示)。
上下文結構io_ring_ctx
前面介紹了SQE/CQE等關鍵的數(shù)據(jù)結構,他們是用來承載數(shù)據(jù)流的關鍵部分,有了數(shù)據(jù)流的關鍵數(shù)據(jù)結構我們還需要一個上下文數(shù)據(jù)結構,用于整個io_uring控制流。這就是io_ring_ctx,貫穿整個io_uring所有過程的數(shù)據(jù)結構,基本上在任何位置只需要你能持有該結構就可以找到任何數(shù)據(jù)所在的位置,例如,sq_sqes就是指向io_uring_sqe結構的指針,指向SQEs的首地址。
struct?io_ring_ctx?{struct?{struct?percpu_ref?refs;}?____cacheline_aligned_in_smp;struct?{unsigned?int??flags;unsigned?int??compat:?1;unsigned?int??limit_mem:?1;unsigned?int??cq_overflow_flushed:?1;unsigned?int??drain_next:?1;unsigned?int??eventfd_async:?1;unsigned?int??restricted:?1;/**?Ring?buffer?of?indices?into?array?of?io_uring_sqe,?which?is*?mmapped?by?the?application?using?the?IORING_OFF_SQES?offset.**?This?indirection?could?e.g.?be?used?to?assign?fixed*?io_uring_sqe?entries?to?operations?and?only?submit?them?to*?the?queue?when?needed.**?The?kernel?modifies?neither?the?indices?array?nor?the?entries*?array.*/u32???*sq_array;unsigned??cached_sq_head;unsigned??sq_entries;unsigned??sq_mask;unsigned??sq_thread_idle;unsigned??cached_sq_dropped;unsigned??cached_cq_overflow;unsigned?long??sq_check_overflow;struct?list_head?defer_list;struct?list_head?timeout_list;struct?list_head?cq_overflow_list;wait_queue_head_t?inflight_wait;struct?io_uring_sqe?*sq_sqes;}?____cacheline_aligned_in_smp;struct?io_rings?*rings;/*?IO?offload?*/struct?io_wq??*io_wq;/**?For?SQPOLL?usage?-?we?hold?a?reference?to?the?parent?task,?so?we*?have?access?to?the?->files*/struct?task_struct?*sqo_task;/*?Only?used?for?accounting?purposes?*/struct?mm_struct?*mm_account;#ifdef?CONFIG_BLK_CGROUPstruct?cgroup_subsys_state?*sqo_blkcg_css; #endifstruct?io_sq_data?*sq_data;?/*?if?using?sq?thread?polling?*/struct?wait_queue_head?sqo_sq_wait;struct?wait_queue_entry?sqo_wait_entry;struct?list_head?sqd_list;/**?If?used,?fixed?file?set.?Writers?must?ensure?that?->refs?is?dead,*?readers?must?ensure?that?->refs?is?alive?as?long?as?the?file*?is*?used.?Only?updated?through?io_uring_register(2).*/struct?fixed_file_data?*file_data;unsigned??nr_user_files;/*?if?used,?fixed?mapped?user?buffers?*/unsigned??nr_user_bufs;struct?io_mapped_ubuf?*user_bufs;struct?user_struct?*user;const?struct?cred?*creds;#ifdef?CONFIG_AUDITkuid_t???loginuid;unsigned?int??sessionid; #endifstruct?completion?ref_comp;struct?completion?sq_thread_comp;/*?if?all?else?fails...?*/struct?io_kiocb??*fallback_req;#if?defined(CONFIG_UNIX)struct?socket??*ring_sock; #endifstruct?idr??io_buffer_idr;struct?idr??personality_idr;struct?{unsigned??cached_cq_tail;unsigned??cq_entries;unsigned??cq_mask;atomic_t??cq_timeouts;unsigned?long??cq_check_overflow;struct?wait_queue_head?cq_wait;struct?fasync_struct?*cq_fasync;struct?eventfd_ctx?*cq_ev_fd;}?____cacheline_aligned_in_smp;struct?{struct?mutex??uring_lock;wait_queue_head_t?wait;}?____cacheline_aligned_in_smp;struct?{spinlock_t??completion_lock;/**?->iopoll_list?is?protected?by?the?ctx->uring_lock?for*?io_uring?instances?that?don't?use?IORING_SETUP_SQPOLL.*?For?SQPOLL,?only?the?single?threaded?io_sq_thread()?will*?manipulate?the?list,?hence?no?extra?locking?is?needed?there.*/struct?list_head?iopoll_list;struct?hlist_head?*cancel_hash;unsigned??cancel_hash_bits;bool???poll_multi_file;spinlock_t??inflight_lock;struct?list_head?inflight_list;}?____cacheline_aligned_in_smp;struct?delayed_work??file_put_work;struct?llist_head??file_put_llist;struct?work_struct??exit_work;struct?io_restriction??restrictions; };關鍵流程
數(shù)據(jù)結構定義好了,邏輯實現(xiàn)具體是如何驅動這些數(shù)據(jù)結構的呢?使用上,大體分為準備、提交、收割過程。
有幾個io_uring相關的系統(tǒng)調用:
#include?<linux/io_uring.h>int?io_uring_setup(u32?entries,?struct?io_uring_params?*p);int?io_uring_enter(unsigned?int?fd,?unsigned?int?to_submit,unsigned?int?min_complete,?unsigned?int?flags,sigset_t?*sig);int?io_uring_register(unsigned?int?fd,?unsigned?int?opcode,void?*arg,?unsigned?int?nr_args);下面分析關鍵流程。
io_uring準備階段
io_uring通過io_uring_setup完成準備階段。
int?io_uring_setup(u32?entries,?struct?io_uring_params?*p);io_uring_setup系統(tǒng)調用的過程就是初始化相關數(shù)據(jù)結構,建立好對應的緩存區(qū),然后通過系統(tǒng)調用的參數(shù)io_uring_params結構傳遞回去,告訴核外環(huán)內(nèi)存地址在哪,起始指針的地址在哪等關鍵的信息。
需要初始化內(nèi)存的內(nèi)存分為三個區(qū)域,分別是SQ,CQ,SQEs。內(nèi)核初始化SQ和CQ,此外,提交請求在SQ,CQ之間有一個間接數(shù)組,即內(nèi)核提供了一個Submission Queue Entries(SQEs)數(shù)組。之所以額外采用了一個數(shù)組保存SQEs,是為了方便通過環(huán)形緩沖區(qū)提交內(nèi)存上不連續(xù)的請求。SQ和CQ中每個節(jié)點保存的都是SQEs數(shù)組的索引,而不是實際的請求,實際的請求只保存在SQEs數(shù)組中。這樣在提交請求時,就可以批量提交一組SQEs上不連續(xù)的請求。
通常,SQE被獨立地使用,意味著它的執(zhí)行不影響在ring中的連續(xù)SQE條目。它允許全面、靈活的操作,并且使它們最高性能地并行執(zhí)行完成。一個順序的使用案例就是數(shù)據(jù)的整體寫入。它的一個通常的例子就是一系列寫,隨之的是fsync/fdatasync,應用通常轉變成程序同步-等待操作。
先從參數(shù)上來解析
核外需要告訴io_uring_setup提交的整個緩存區(qū)數(shù)組的大小。(代表 queue depth?),這里就是entries參數(shù)。
params這個參數(shù)從IO的角度看有兩種,一種是輸入?yún)?shù),一種是輸出參數(shù)。
sq_entries是輸出參數(shù),由內(nèi)核填充,讓應用程序知道這個ring支持多少SQE。
類似地,cq_entries告訴應用程序,CQ ring有多大。
sq_off和cq_off分別是io_sqring_offsets和io_cqring_offsets結構,是內(nèi)核與核外的約定,分別描述了SQ和CQ的指針在mmap中的offset
其他的結構成員涉及到高級用法,暫時按下不表。
比如params->flags,這個成員變量是用來設置當前整個io_uring 的標志的,它將決定是否啟動sq_thread,是否采用iopoll模式等等
sq_thread_cpu、sq_thread_idle也由用戶設置,用來指定io_sq_thread內(nèi)核線程CPU、idle時間。
一部分屬于輸入?yún)?shù),是用戶設置、核外傳遞給核外的,用于定義io_uring在內(nèi)核中的行為,這些都是在創(chuàng)建階段就決定了的。
還有一部分屬于輸出參數(shù),由內(nèi)核設置(io_uring_create)、傳遞數(shù)據(jù)到核外的,核外根據(jù)這些數(shù)據(jù)來使用mmap分配內(nèi)存,初始化一些數(shù)據(jù)結構。
再從實現(xiàn)上來解析,如下為io_uring_setup代碼。
/**?Sets?up?an?aio?uring?context,?and?returns?the?fd.?Applications?asks?for?a*?ring?size,?we?return?the?actual?sq/cq?ring?sizes?(among?other?things)?in?the*?params?structure?passed?in.*/ static?long?io_uring_setup(u32?entries,?struct?io_uring_params?__user?*params) {struct?io_uring_params?p;int?i;if?(copy_from_user(&p,?params,?sizeof(p)))return?-EFAULT;for?(i?=?0;?i?<?ARRAY_SIZE(p.resv);?i++)?{if?(p.resv[i])return?-EINVAL;}if?(p.flags?&?~(IORING_SETUP_IOPOLL?|?IORING_SETUP_SQPOLL?|IORING_SETUP_SQ_AFF?|?IORING_SETUP_CQSIZE?|IORING_SETUP_CLAMP?|?IORING_SETUP_ATTACH_WQ?|IORING_SETUP_R_DISABLED))return?-EINVAL;return??io_uring_create(entries,?&p,?params); }經(jīng)過標志位非法檢查之后,關鍵是調用內(nèi)部函數(shù)io_uring_create實現(xiàn)實例創(chuàng)建過程。
首先需要創(chuàng)建一個上下文結構io_ring_ctx用來管理整個會話。
隨后實現(xiàn)SQ和CQ內(nèi)存區(qū)的映射,使用IORING_OFF_CQ_RING偏移量,使用io_cqring_offsets結構的實例,即io_uring_params中cq_off這個成員,SQ使用IORING_OFF_SQES這個偏移量。
其余的是一些錯誤檢查、權限檢查、資源配額檢查等檢查邏輯。
io_sqring_offsets、io_cqring_offsets等相關結構、標志位集合。
預定義offset
如果要表征分配的是io uring相關的一些內(nèi)存,就需要預定義一些offset,如IORING_OFF_SQ_RING、IORING_OFF_SQES和IORING_OFF_CQ_RING,這些offset值定義了保存到這個三個結構保存到位置。這里mmap的時候,就使用了這些offset。
具體的實踐,可以參考如下liburing中的初始化函數(shù)io_uring_queue_init中對io_uring_setup的使用(http://git.kernel.dk/cgit/liburing/tree/src/setup.c)。
liburing中使用io_uring_setup的部分代碼
/**?Returns?-1?on?error,?or?zero?on?success.?On?success,?'ring'*?contains?the?necessary?information?to?read/write?to?the?rings.*/ int?io_uring_queue_init(unsigned?entries,?struct?io_uring?*ring,?unsigned?flags) {struct?io_uring_params?p;int?fd,?ret;memset(&p,?0,?sizeof(p));p.flags?=?flags;fd?=?io_uring_setup(entries,?&p);if?(fd?<?0)return?fd;ret?=?io_uring_queue_mmap(fd,?&p,?ring);if?(ret)close(fd);return?ret; }注意mmap的時候需要傳入MAP_POPULATE參數(shù),為文件映射通過預讀的方式準備好頁表,隨后對映射區(qū)的訪問不會被page fault。
IO提交
在初始化完成之后,應用程序就可以使用這些隊列來添加IO請求,即填充SQE。當請求都加入SQ后,應用程序還需要某種方式告訴內(nèi)核,生產(chǎn)的請求待消費,這就是提交IO請求,可以通過io_uring_enter系統(tǒng)調用。
int?io_uring_enter(unsigned?int?fd,?unsigned?int?to_submit,unsigned?int?min_complete,?unsigned?int?flags,sigset_t?*sig);內(nèi)核將SQ中的請求提交給Block層。這個系統(tǒng)調用既能提交,也能等待。
具體的實現(xiàn)是找到一個空閑的SQE,根據(jù)請求設置SQE,并將這個SQE的索引放到SQ中。SQ是一個典型的ring buffer,有head,tail兩個成員,如果head == tail,意味著隊列為空。SQE設置完成后,需要修改SQ的tail,以表示向ring buffer中插入了一個請求。
先從參數(shù)上來解析
fd即由io_uring_setup(2)返回的文件描述符,
to_submit告訴內(nèi)核待消費和提交的SQE的數(shù)量,表示一次提交多少個 IO,
min_complete請求完成請求的個數(shù)。
flags是修飾接口行為的標志集合,這里主要例舉兩個flags
如果在io_uring_setup的時候flag設置了IORING_SETUP_SQPOLL,內(nèi)核會額外啟動一個特定的內(nèi)核線程來執(zhí)行輪詢的操作,稱作SQ線程,這里使用的輪詢結構會最終對應到struct file_operations中的iopoll操作,這個操作作為一個新的接口在最近才添加到這里,Linux native aio的新功能也使用了這個iopoll。這里io _uring實際上只有vfs層的改動,其它的都是使用已經(jīng)存在的東西,而且?guī)讉€核心的東西和aio使用的相同/類似。直接通過訪問相關的隊列就可以獲取到執(zhí)行完的任務,不需要經(jīng)過系統(tǒng)調用。關于這個線程,通過io_uring_params結構中的sq_thread_cpu配置,這個內(nèi)核線程可以運行在某個指定的 CPU核心 上。這個內(nèi)核線程會不停的 Poll SQ,直到在通過sq_thread_idle配置的時間內(nèi)沒有Poll到任何請求為止。
如果flags中設置了IORING_ENTER_GETEVENTS,并且min_complete > 0,這個系統(tǒng)調用會一直 block,直到 min_complete 個 IO 已經(jīng)完成才返回。這個系統(tǒng)調用會同時處理 IO 收割。
另外的,IORING_SQ_NEED_WAKEUP可以表示在一些時候喚醒休眠中的輪詢線程。
static int io_sq_thread(void *data)即內(nèi)核輪詢線程。
同樣地,可以用這個系統(tǒng)調用等待完成。除非應用程序,內(nèi)核會直接修改CQ,因此調用io_uring_enter系統(tǒng)調用時不必使用IORING_ENTER_GETEVENTS,完成就可以被應用程序消費。
io_uring提供了submission offload模式,使得提交過程完全不需要進行系統(tǒng)調用。當程序在用戶態(tài)設置完SQE,并通過修改SQ的tail完成一次插入時,如果此時SQ線程處于喚醒狀態(tài),那么可以立刻捕獲到這次提交,這樣就避免了用戶程序調用io_uring_enter。如上所說,如果SQ線程處于休眠狀態(tài),則需要通過使用IORING_SQ_NEED_WAKEUP標志位調用io_uring_enter來喚醒SQ線程。
以io_iopoll_check為例,正常情況下執(zhí)行路線是io_iopoll_check -> io_iopoll_getevents -> io_do_iopoll -> (kiocb->ki_filp->f_op->iopoll). 在完成請求的操作之后,會調用下面這個函數(shù)提交結果到cqe數(shù)組中,這樣應用就能看到結果了。這里的io_cqring_fill_event就是獲取一個目前可以寫入到cqe,寫入數(shù)據(jù)。這里最終調用的會是io_get_cqring,可以見就是返回目前tail的后面的一個。
更詳細的內(nèi)容可以直接參考io_uring_enter(2)的man page。
內(nèi)核中io_uring_enter的相關代碼如下。
SYSCALL_DEFINE6(io_uring_enter,?unsigned?int,?fd,?u32,?to_submit,u32,?min_complete,?u32,?flags,?const?sigset_t?__user?*,?sig,size_t,?sigsz) {struct?io_ring_ctx?*ctx;long?ret?=?-EBADF;int?submitted?=?0;struct?fd?f;io_run_task_work();if?(flags?&?~(IORING_ENTER_GETEVENTS?|?IORING_ENTER_SQ_WAKEUP?|IORING_ENTER_SQ_WAIT))return?-EINVAL;f?=?fdget(fd);if?(!f.file)return?-EBADF;ret?=?-EOPNOTSUPP;if?(f.file->f_op?!=?&io_uring_fops)goto?out_fput;ret?=?-ENXIO;ctx?=?f.file->private_data;if?(!percpu_ref_tryget(&ctx->refs))goto?out_fput;ret?=?-EBADFD;if?(ctx->flags?&?IORING_SETUP_R_DISABLED)goto?out;/**?For?SQ?polling,?the?thread?will?do?all?submissions?and?completions.*?Just?return?the?requested?submit?count,?and?wake?the?thread?if*?we?were?asked?to.*/ret?=?0;if?(ctx->flags?&?IORING_SETUP_SQPOLL)?{if?(!list_empty_careful(&ctx->cq_overflow_list))io_cqring_overflow_flush(ctx,?false,?NULL,?NULL);if?(flags?&?IORING_ENTER_SQ_WAKEUP)wake_up(&ctx->sq_data->wait);if?(flags?&?IORING_ENTER_SQ_WAIT)io_sqpoll_wait_sq(ctx);submitted?=?to_submit;}?else?if?(to_submit)?{ret?=?io_uring_add_task_file(ctx,?f.file);if?(unlikely(ret))goto?out;mutex_lock(&ctx->uring_lock);submitted?=?io_submit_sqes(ctx,?to_submit);mutex_unlock(&ctx->uring_lock);if?(submitted?!=?to_submit)goto?out;}if?(flags?&?IORING_ENTER_GETEVENTS)?{min_complete?=?min(min_complete,?ctx->cq_entries);/**?When?SETUP_IOPOLL?and?SETUP_SQPOLL?are?both?enabled,?user*?space?applications?don't?need?to?do?io?completion?events*?polling?again,?they?can?rely?on?io_sq_thread?to?do?polling*?work,?which?can?reduce?cpu?usage?and?uring_lock?contention.*/if?(ctx->flags?&?IORING_SETUP_IOPOLL?&&!(ctx->flags?&?IORING_SETUP_SQPOLL))?{ret?=?io_iopoll_check(ctx,?min_complete);}?else?{ret?=?io_cqring_wait(ctx,?min_complete,?sig,?sigsz);}}out:percpu_ref_put(&ctx->refs); out_fput:fdput(f);return?submitted???submitted?:?ret; }io_iopoll_complete實現(xiàn)
/**?Find?and?free?completed?poll?iocbs*/ static?void?io_iopoll_complete(struct?io_ring_ctx?*ctx,?unsigned?int?*nr_events,struct?list_head?*done) {struct?req_batch?rb;struct?io_kiocb?*req;LIST_HEAD(again);/*?order?with?->result?store?in?io_complete_rw_iopoll()?*/smp_rmb();io_init_req_batch(&rb);while?(!list_empty(done))?{int?cflags?=?0;req?=?list_first_entry(done,?struct?io_kiocb,?inflight_entry);if?(READ_ONCE(req->result)?==?-EAGAIN)?{req->result?=?0;req->iopoll_completed?=?0;list_move_tail(&req->inflight_entry,?&again);continue;}list_del(&req->inflight_entry);if?(req->flags?&?REQ_F_BUFFER_SELECTED)cflags?=?io_put_rw_kbuf(req);__io_cqring_fill_event(req,?req->result,?cflags);(*nr_events)++;if?(refcount_dec_and_test(&req->refs))io_req_free_batch(&rb,?req);}io_commit_cqring(ctx);if?(ctx->flags?&?IORING_SETUP_SQPOLL)io_cqring_ev_posted(ctx);io_req_free_batch_finish(ctx,?&rb);if?(!list_empty(&again))io_iopoll_queue(&again); }io_get_cqring實現(xiàn)
static?struct?io_uring_cqe?*io_get_cqring(struct?io_ring_ctx?*ctx) {struct?io_rings?*rings?=?ctx->rings;unsigned?tail;tail?=?ctx->cached_cq_tail;/**?writes?to?the?cq?entry?need?to?come?after?reading?head;?the*?control?dependency?is?enough?as?we're?using?WRITE_ONCE?to*?fill?the?cq?entry*/if?(tail?-?READ_ONCE(rings->cq.head)?==?rings->cq_ring_entries)return?NULL;ctx->cached_cq_tail++;return?&rings->cqes[tail?&?ctx->cq_mask]; }IO收割
來都來了,搞點事情吧,在我們提交IO的同時,使用同一個io_uring_enter系統(tǒng)調用就可以回收完成狀態(tài),這樣的好處就是一次系統(tǒng)調用接口就完成了原本需要兩次系統(tǒng)調用的工作,大大的減少了系統(tǒng)調用的次數(shù),也就是減少了內(nèi)核核外的切換,這是一個很明顯的優(yōu)化,內(nèi)核與核外的切換極其耗時。
當IO完成時,內(nèi)核負責將完成IO在SQEs中的index放到CQ中。由于IO在提交的時候可以順便返回完成的IO,所以收割IO不需要額外系統(tǒng)調用。
如果使用了IORING_SETUP_SQPOLL參數(shù),IO收割也不需要系統(tǒng)調用的參與。由于內(nèi)核和用戶態(tài)共享內(nèi)存,所以收割的時候,用戶態(tài)遍歷[cring->head, cring->tail)區(qū)間,即已經(jīng)完成的IO隊列,然后找到相應的CQE并進行處理,最后移動head指針到tail,IO收割至此而終。
所以,在最理想的情況下,IO提交和收割都不需要使用系統(tǒng)調用。
高級特性
此外,我們可以使用一些優(yōu)化思想,進行更進一步的優(yōu)化,這些優(yōu)化,以一種可選的方式成為io_uring的其它一些高級特性。
Fixed Files模式
優(yōu)化思想
非關鍵邏輯上提至循環(huán)外,簡化關鍵路徑。
優(yōu)化實現(xiàn)
可以調用io_uring_register系統(tǒng)調用,使用IORING_REGISTER_FILES操作碼,將一組file注冊到內(nèi)核,最終調用io_sqe_files_register,這樣內(nèi)核在注冊階段就批量完成文件的一些基本操作(對于這組文件填充相應的數(shù)據(jù)結構fixed_file_data,其中fixed_file_table是維護的file表。內(nèi)核態(tài)下,如何獲得文件描述符獲取相關的信息呢,就需要通過fget,根據(jù)fd號獲得指向文件的struct file),之后的再次批量IO時就不需要重復地進行此類基本信息設置(更具體地,例如對文件進行fget/fput操作)。如果需要進行IO操作的文件相對固定(比如數(shù)據(jù)庫日志),這會節(jié)省一定量的IO時間。
fixed_file_data結構
struct?fixed_file_data?{struct?fixed_file_table??*table;struct?io_ring_ctx??*ctx;struct?fixed_file_ref_node?*node;struct?percpu_ref??refs;struct?completion??done;struct?list_head??ref_list;spinlock_t???lock; };io_sqe_files_register實現(xiàn)Fixed Files操作
static?int?io_sqe_files_register(struct?io_ring_ctx?*ctx,?void?__user?*arg,unsigned?nr_args) {__s32?__user?*fds?=?(__s32?__user?*)?arg;unsigned?nr_tables,?i;struct?file?*file;int?fd,?ret?=?-ENOMEM;struct?fixed_file_ref_node?*ref_node;struct?fixed_file_data?*file_data;if?(ctx->file_data)return?-EBUSY;if?(!nr_args)return?-EINVAL;if?(nr_args?>?IORING_MAX_FIXED_FILES)return?-EMFILE;file_data?=?kzalloc(sizeof(*ctx->file_data),?GFP_KERNEL);if?(!file_data)return?-ENOMEM;file_data->ctx?=?ctx;init_completion(&file_data->done);INIT_LIST_HEAD(&file_data->ref_list);spin_lock_init(&file_data->lock);nr_tables?=?DIV_ROUND_UP(nr_args,?IORING_MAX_FILES_TABLE);file_data->table?=?kcalloc(nr_tables,?sizeof(*file_data->table),GFP_KERNEL);if?(!file_data->table)goto?out_free;if?(percpu_ref_init(&file_data->refs,?io_file_ref_kill,PERCPU_REF_ALLOW_REINIT,?GFP_KERNEL))goto?out_free;if?(io_sqe_alloc_file_tables(file_data,?nr_tables,?nr_args))goto?out_ref;ctx->file_data?=?file_data;for?(i?=?0;?i?<?nr_args;?i++,?ctx->nr_user_files++)?{struct?fixed_file_table?*table;unsigned?index;if?(copy_from_user(&fd,?&fds[i],?sizeof(fd)))?{ret?=?-EFAULT;goto?out_fput;}/*?allow?sparse?sets?*/if?(fd?==?-1)continue;file?=?fget(fd);ret?=?-EBADF;if?(!file)goto?out_fput;/**?Don't?allow?io_uring?instances?to?be?registered.?If?UNIX*?isn't?enabled,?then?this?causes?a?reference?cycle?and?this*?instance?can?never?get?freed.?If?UNIX?is?enabled?we'll*?handle?it?just?fine,?but?there's?still?no?point?in?allowing*?a?ring?fd?as?it?doesn't?support?regular?read/write?anyway.*/if?(file->f_op?==?&io_uring_fops)?{fput(file);goto?out_fput;}table?=?&file_data->table[i?>>?IORING_FILE_TABLE_SHIFT];index?=?i?&?IORING_FILE_TABLE_MASK;table->files[index]?=?file;}ret?=?io_sqe_files_scm(ctx);if?(ret)?{io_sqe_files_unregister(ctx);return?ret;}ref_node?=?alloc_fixed_file_ref_node(ctx);if?(IS_ERR(ref_node))?{io_sqe_files_unregister(ctx);return?PTR_ERR(ref_node);}file_data->node?=?ref_node;spin_lock(&file_data->lock);list_add_tail(&ref_node->node,?&file_data->ref_list);spin_unlock(&file_data->lock);percpu_ref_get(&file_data->refs);return?ret; out_fput:for?(i?=?0;?i?<?ctx->nr_user_files;?i++)?{file?=?io_file_from_index(ctx,?i);if?(file)fput(file);}for?(i?=?0;?i?<?nr_tables;?i++)kfree(file_data->table[i].files);ctx->nr_user_files?=?0; out_ref:percpu_ref_exit(&file_data->refs); out_free:kfree(file_data->table);kfree(file_data);ctx->file_data?=?NULL;return?ret; }Fixed Buffers模式
優(yōu)化思想
優(yōu)化思想也是將非關鍵邏輯上提至循環(huán)外,簡化關鍵路徑。
優(yōu)化實現(xiàn)
如果應用提交到內(nèi)核的虛擬內(nèi)存地址是固定的,那么可以提前完成虛擬地址到物理pages的映射,將這個并不是每次都要做的非關鍵路徑從關鍵的IO 路徑中剝離,避免每次I/O都進行轉換,從而優(yōu)化性能。可以在io_uring_setup之后,調用io_uring_register,使用IORING_REGISTER_BUFFERS 操作碼,將一組buffer注冊到內(nèi)核(參數(shù)是一個指向iovec的數(shù)組,表示這些地址需要map到內(nèi)核),最終調用io_sqe_buffer_register,這樣內(nèi)核在注冊階段就批量完成buffer的一些基本操作(減小get_user_pages、put_page開銷,提前使用get_user_pages來獲得userspace虛擬地址對應的物理pages,初始化在io_ring_ctx上下文中用于管理用戶態(tài)buffer的io_mapped_ubuf數(shù)據(jù)結構,map/unmap,傳遞IOV的地址和長度等),之后的再次批量IO時就不需要重復地進行此類內(nèi)存拷貝和基礎信息檢測。
在操作IO的時,如果需要進行IO操作的buffer相對固定,提交的虛擬地址曾經(jīng)被注冊過,那么可以使用帶FIXED系列的opcode(IORING_OP_READ_FIXED/IORING_OP_WRITE_FIXED)IO,可以看到底層調用鏈:io_issue_sqe->io_read->io_import_iovec->__io_import_iovec->io_import_fixed,會直接使用已經(jīng)完成的“成果”,如此就免去了虛擬地址到pages的轉換,這會節(jié)省一定量的IO時間。
io_mapped_ubuf結構
struct?io_mapped_ubuf?{u64??ubuf;size_t??len;struct??bio_vec?*bvec;unsigned?int?nr_bvecs;unsigned?long?acct_pages; };io_sqe_buffer_register實現(xiàn)Fixed Buffers操作
static?int?io_sqe_buffer_register(struct?io_ring_ctx?*ctx,?void?__user?*arg,unsigned?nr_args) {struct?vm_area_struct?**vmas?=?NULL;struct?page?**pages?=?NULL;struct?page?*last_hpage?=?NULL;int?i,?j,?got_pages?=?0;int?ret?=?-EINVAL;if?(ctx->user_bufs)return?-EBUSY;if?(!nr_args?||?nr_args?>?UIO_MAXIOV)return?-EINVAL;ctx->user_bufs?=?kcalloc(nr_args,?sizeof(struct?io_mapped_ubuf),GFP_KERNEL);if?(!ctx->user_bufs)return?-ENOMEM;for?(i?=?0;?i?<?nr_args;?i++)?{struct?io_mapped_ubuf?*imu?=?&ctx->user_bufs[i];unsigned?long?off,?start,?end,?ubuf;int?pret,?nr_pages;struct?iovec?iov;size_t?size;ret?=?io_copy_iov(ctx,?&iov,?arg,?i);if?(ret)goto?err;/**?Don't?impose?further?limits?on?the?size?and?buffer*?constraints?here,?we'll?-EINVAL?later?when?IO?is*?submitted?if?they?are?wrong.*/ret?=?-EFAULT;if?(!iov.iov_base?||?!iov.iov_len)goto?err;/*?arbitrary?limit,?but?we?need?something?*/if?(iov.iov_len?>?SZ_1G)goto?err;ubuf?=?(unsigned?long)?iov.iov_base;end?=?(ubuf?+?iov.iov_len?+?PAGE_SIZE?-?1)?>>?PAGE_SHIFT;start?=?ubuf?>>?PAGE_SHIFT;nr_pages?=?end?-?start;ret?=?0;if?(!pages?||?nr_pages?>?got_pages)?{kvfree(vmas);kvfree(pages);pages?=?kvmalloc_array(nr_pages,?sizeof(struct?page?*),GFP_KERNEL);vmas?=?kvmalloc_array(nr_pages,sizeof(struct?vm_area_struct?*),GFP_KERNEL);if?(!pages?||?!vmas)?{ret?=?-ENOMEM;goto?err;}got_pages?=?nr_pages;}imu->bvec?=?kvmalloc_array(nr_pages,?sizeof(struct?bio_vec),GFP_KERNEL);ret?=?-ENOMEM;if?(!imu->bvec)goto?err;ret?=?0;mmap_read_lock(current->mm);pret?=?pin_user_pages(ubuf,?nr_pages,FOLL_WRITE?|?FOLL_LONGTERM,pages,?vmas);if?(pret?==?nr_pages)?{/*?don't?support?file?backed?memory?*/for?(j?=?0;?j?<?nr_pages;?j++)?{struct?vm_area_struct?*vma?=?vmas[j];if?(vma->vm_file?&&!is_file_hugepages(vma->vm_file))?{ret?=?-EOPNOTSUPP;break;}}}?else?{ret?=?pret?<?0???pret?:?-EFAULT;}mmap_read_unlock(current->mm);if?(ret)?{/**?if?we?did?partial?map,?or?found?file?backed?vmas,*?release?any?pages?we?did?get*/if?(pret?>?0)unpin_user_pages(pages,?pret);kvfree(imu->bvec);goto?err;}ret?=?io_buffer_account_pin(ctx,?pages,?pret,?imu,?&last_hpage);if?(ret)?{unpin_user_pages(pages,?pret);kvfree(imu->bvec);goto?err;}off?=?ubuf?&?~PAGE_MASK;size?=?iov.iov_len;for?(j?=?0;?j?<?nr_pages;?j++)?{size_t?vec_len;vec_len?=?min_t(size_t,?size,?PAGE_SIZE?-?off);imu->bvec[j].bv_page?=?pages[j];imu->bvec[j].bv_len?=?vec_len;imu->bvec[j].bv_offset?=?off;off?=?0;size?-=?vec_len;}/*?store?original?address?for?later?verification?*/imu->ubuf?=?ubuf;imu->len?=?iov.iov_len;imu->nr_bvecs?=?nr_pages;ctx->nr_user_bufs++;}kvfree(pages);kvfree(vmas);return?0; err:kvfree(pages);kvfree(vmas);io_sqe_buffer_unregister(ctx);return?ret; }Polled IO模式
優(yōu)化思想
將較多的CPU時間放到重要的事情上,全速完成關鍵路徑。
狀態(tài)從未完成變成已完成,就需要對完成狀態(tài)進行探測,很多時候,可以使用中斷模型,也就是等待后端數(shù)據(jù)處理完畢之后,內(nèi)核會發(fā)起一個SIGIO或eventfd的EPOLLIN狀態(tài)提醒核外有數(shù)據(jù)已經(jīng)完成了,可以開始處理。但是,中斷其實是比較耗時的,如果是高IOPS的場景,就會不停地中斷,中斷開銷就得不償失。
我們可以更激進一些,讓內(nèi)核采用Polled IO模式收割塊設備層請求。這在一定的程度上加速了IO,這在追求低延時和高IOPS的應用場景非常有用。
優(yōu)化實現(xiàn)
io_uring_enter通過正確設置IORING_ENTER_GETEVENTS,IORING_SETUP_IOPOLL等flag(如下代碼設置IORING_SETUP_IOPOLL并且不設置IORING_SETUP_SQPOLL,即沒有使用SQ線程)調用io_iopoll_check。
SYSCALL_DEFINE6(io_uring_enter,?unsigned?int,?fd,?u32,?to_submit,u32,?min_complete,?u32,?flags,?const?sigset_t?__user?*,?sig,size_t,?sigsz) {struct?io_ring_ctx?*ctx;long?ret?=?-EBADF;int?submitted?=?0;struct?fd?f;io_run_task_work();if?(flags?&?~(IORING_ENTER_GETEVENTS?|?IORING_ENTER_SQ_WAKEUP?|IORING_ENTER_SQ_WAIT))return?-EINVAL;f?=?fdget(fd);if?(!f.file)return?-EBADF;ret?=?-EOPNOTSUPP;if?(f.file->f_op?!=?&io_uring_fops)goto?out_fput;ret?=?-ENXIO;ctx?=?f.file->private_data;if?(!percpu_ref_tryget(&ctx->refs))goto?out_fput;ret?=?-EBADFD;if?(ctx->flags?&?IORING_SETUP_R_DISABLED)goto?out;/**?For?SQ?polling,?the?thread?will?do?all?submissions?and?completions.*?Just?return?the?requested?submit?count,?and?wake?the?thread?if*?we?were?asked?to.*/ret?=?0;if?(ctx->flags?&?IORING_SETUP_SQPOLL)?{if?(!list_empty_careful(&ctx->cq_overflow_list))io_cqring_overflow_flush(ctx,?false,?NULL,?NULL);if?(flags?&?IORING_ENTER_SQ_WAKEUP)wake_up(&ctx->sq_data->wait);if?(flags?&?IORING_ENTER_SQ_WAIT)io_sqpoll_wait_sq(ctx);submitted?=?to_submit;}?else?if?(to_submit)?{ret?=?io_uring_add_task_file(ctx,?f.file);if?(unlikely(ret))goto?out;mutex_lock(&ctx->uring_lock);submitted?=?io_submit_sqes(ctx,?to_submit);mutex_unlock(&ctx->uring_lock);if?(submitted?!=?to_submit)goto?out;}if?(flags?&?IORING_ENTER_GETEVENTS)?{min_complete?=?min(min_complete,?ctx->cq_entries);/**?When?SETUP_IOPOLL?and?SETUP_SQPOLL?are?both?enabled,?user*?space?applications?don't?need?to?do?io?completion?events*?polling?again,?they?can?rely?on?io_sq_thread?to?do?polling*?work,?which?can?reduce?cpu?usage?and?uring_lock?contention.*/if?(ctx->flags?&?IORING_SETUP_IOPOLL?&&!(ctx->flags?&?IORING_SETUP_SQPOLL))?{ret?=?io_iopoll_check(ctx,?min_complete);}?else?{ret?=?io_cqring_wait(ctx,?min_complete,?sig,?sigsz);}}out:percpu_ref_put(&ctx->refs); out_fput:fdput(f);return?submitted???submitted?:?ret; }io_iopoll_check開始poll核外程序可以不停的輪詢需要的完成事件數(shù)量min_complete,循環(huán)內(nèi)主要調用io_iopoll_getevents。
static?int?io_iopoll_check(struct?io_ring_ctx?*ctx,?long?min) {unsigned?int?nr_events?=?0;int?iters?=?0,?ret?=?0;/**?We?disallow?the?app?entering?submit/complete?with?polling,?but?we*?still?need?to?lock?the?ring?to?prevent?racing?with?polled?issue*?that?got?punted?to?a?workqueue.*/mutex_lock(&ctx->uring_lock);do?{/**?Don't?enter?poll?loop?if?we?already?have?events?pending.*?If?we?do,?we?can?potentially?be?spinning?for?commands?that*?already?triggered?a?CQE?(eg?in?error).*/if?(io_cqring_events(ctx,?false))break;/**?If?a?submit?got?punted?to?a?workqueue,?we?can?have?the*?application?entering?polling?for?a?command?before?it?gets*?issued.?That?app?will?hold?the?uring_lock?for?the?duration*?of?the?poll?right?here,?so?we?need?to?take?a?breather?every*?now?and?then?to?ensure?that?the?issue?has?a?chance?to?add*?the?poll?to?the?issued?list.?Otherwise?we?can?spin?here*?forever,?while?the?workqueue?is?stuck?trying?to?acquire?the*?very?same?mutex.*/if?(!(++iters?&?7))?{mutex_unlock(&ctx->uring_lock);io_run_task_work();mutex_lock(&ctx->uring_lock);}ret?=?io_iopoll_getevents(ctx,?&nr_events,?min);if?(ret?<=?0)break;ret?=?0;}?while?(min?&&?!nr_events?&&?!need_resched());mutex_unlock(&ctx->uring_lock);return?ret; }io_iopoll_getevents調用io_do_iopoll。
/**?Poll?for?a?minimum?of?'min'?events.?Note?that?if?min?==?0?we?consider?that?a*?non-spinning?poll?check?-?we'll?still?enter?the?driver?poll?loop,?but?only*?as?a?non-spinning?completion?check.*/ static?int?io_iopoll_getevents(struct?io_ring_ctx?*ctx,?unsigned?int?*nr_events,long?min) {while?(!list_empty(&ctx->iopoll_list)?&&?!need_resched())?{int?ret;ret?=?io_do_iopoll(ctx,?nr_events,?min);if?(ret?<?0)return?ret;if?(*nr_events?>=?min)return?0;}return?1; }io_do_iopoll中的kiocb->ki_filp->f_op->iopoll,即blkdev_iopoll,不斷地輪詢探測確認提交給Block層的請求的完成狀態(tài),直到足夠數(shù)量的IO完成。
static?int?io_do_iopoll(struct?io_ring_ctx?*ctx,?unsigned?int?*nr_events,long?min) {struct?io_kiocb?*req,?*tmp;LIST_HEAD(done);bool?spin;int?ret;/**?Only?spin?for?completions?if?we?don't?have?multiple?devices?hanging*?off?our?complete?list,?and?we're?under?the?requested?amount.*/spin?=?!ctx->poll_multi_file?&&?*nr_events?<?min;ret?=?0;list_for_each_entry_safe(req,?tmp,?&ctx->iopoll_list,?inflight_entry)?{struct?kiocb?*kiocb?=?&req->rw.kiocb;/**?Move?completed?and?retryable?entries?to?our?local?lists.*?If?we?find?a?request?that?requires?polling,?break?out*?and?complete?those?lists?first,?if?we?have?entries?there.*/if?(READ_ONCE(req->iopoll_completed))?{list_move_tail(&req->inflight_entry,?&done);continue;}if?(!list_empty(&done))break;ret?=?kiocb->ki_filp->f_op->iopoll(kiocb,?spin);if?(ret?<?0)break;/*?iopoll?may?have?completed?current?req?*/if?(READ_ONCE(req->iopoll_completed))list_move_tail(&req->inflight_entry,?&done);if?(ret?&&?spin)spin?=?false;ret?=?0;}if?(!list_empty(&done))io_iopoll_complete(ctx,?nr_events,?&done);return?ret; }塊設備層相關file_operations。
const?struct?file_operations?def_blk_fops?=?{.open??=?blkdev_open,.release?=?blkdev_close,.llseek??=?block_llseek,.read_iter?=?blkdev_read_iter,.write_iter?=?blkdev_write_iter,.iopoll??=?blkdev_iopoll,.mmap??=?generic_file_mmap,.fsync??=?blkdev_fsync,.unlocked_ioctl?=?block_ioctl, #ifdef?CONFIG_COMPAT.compat_ioctl?=?compat_blkdev_ioctl, #endif.splice_read?=?generic_file_splice_read,.splice_write?=?iter_file_splice_write,.fallocate?=?blkdev_fallocate, };當使用POLL IO時,大多數(shù)CPU時間花費在blkdev_iopoll上。即全速完成關鍵路徑。
static?int?blkdev_iopoll(struct?kiocb?*kiocb,?bool?wait) {struct?block_device?*bdev?=?I_BDEV(kiocb->ki_filp->f_mapping->host);struct?request_queue?*q?=?bdev_get_queue(bdev);return?blk_poll(q,?READ_ONCE(kiocb->ki_cookie),?wait); }Kernel Side Polling
IORING_SETUP_SQPOLL,當前應用更新SQ并填充一個新的SQE,內(nèi)核線程sq_thread會自動完成提交,這樣應用無需每次調用io_uring_enter系統(tǒng)調用來提交IO。應用可通過IORING_SETUP_SQ_AFF和sq_thread_cpu綁定特定的CPU。
實際機器上,不僅有高IOPS場景,還有些場景的IOPS有些時間段會非常低。為了節(jié)省無IO場景的CPU開銷,一段時間空閑,該內(nèi)核線程可以自動睡眠。核外在下發(fā)新的IO時,通過IORING_ENTER_SQ_WAKEUP喚醒該內(nèi)核線程。
小結
如上可見,內(nèi)核提供了足夠多的選擇,不同的方案有著不同角度的優(yōu)化方向,這些優(yōu)化方案可以自行組合。通過合理地使用,可以使io_uring 全速運轉。
io_uring用戶態(tài)庫liburing
正如前文所說,簡單并不一定意味著易用——io_uring的接口足夠簡單,但是相對于這種簡單,操作上需要手動mmap來映射內(nèi)存,稍顯復雜。為了更方便地使用io_uring,原作者Jens Axboe還開發(fā)了一套liburing庫。liburing庫提供了一組輔助函數(shù)實現(xiàn)設置和內(nèi)存映射,應用不必了解諸多io_uring的細節(jié)就可以簡單地使用起來。例如,無需擔心memory barrier,或者是ring buffer管理之類等。上文所提的一些高級特性,在liburing中也有封裝。
核心數(shù)據(jù)結構
liburing中,核心的結構有io_uring、io_uring_sq、io_uring_cq
/**?Library?interface?to?io_uring*/ struct?io_uring_sq?{unsigned?*khead;unsigned?*ktail;unsigned?*kring_mask;unsigned?*kring_entries;unsigned?*kflags;unsigned?*kdropped;unsigned?*array;struct?io_uring_sqe?*sqes;unsigned?sqe_head;unsigned?sqe_tail;size_t?ring_sz; };struct?io_uring_cq?{unsigned?*khead;unsigned?*ktail;unsigned?*kring_mask;unsigned?*kring_entries;unsigned?*koverflow;struct?io_uring_cqe?*cqes;size_t?ring_sz; };struct?io_uring?{struct?io_uring_sq?sq;struct?io_uring_cq?cq;int?ring_fd; };核心接口
相關接口在頭文件linux/tools/io_uring/liburing.h,如果是通過標準方式安裝的liburing,則在/usr/include/下。
/**?System?calls*/ extern?int?io_uring_setup(unsigned?entries,?struct?io_uring_params?*p); extern?int?io_uring_enter(int?fd,?unsigned?to_submit,unsigned?min_complete,?unsigned?flags,?sigset_t?*sig); extern?int?io_uring_register(int?fd,?unsigned?int?opcode,?void?*arg,unsigned?int?nr_args);/**?Library?interface*/ extern?int?io_uring_queue_init(unsigned?entries,?struct?io_uring?*ring,unsigned?flags); extern?int?io_uring_queue_mmap(int?fd,?struct?io_uring_params?*p,struct?io_uring?*ring); extern?void?io_uring_queue_exit(struct?io_uring?*ring); extern?int?io_uring_peek_cqe(struct?io_uring?*ring,struct?io_uring_cqe?**cqe_ptr); extern?int?io_uring_wait_cqe(struct?io_uring?*ring,struct?io_uring_cqe?**cqe_ptr); extern?int?io_uring_submit(struct?io_uring?*ring); extern?struct?io_uring_sqe?*io_uring_get_sqe(struct?io_uring?*ring);主要流程
使用io_uring_queue_init,完成io_uring相關結構的初始化。在這個函數(shù)的實現(xiàn)中,會調用多個mmap來初始化一些內(nèi)存。
初始化完成之后,為了提交IO請求,需要獲取里面queue的一個項,使用io_uring_get_sqe。
獲取到了空閑項之后,使用io_uring_prep_readv、io_uring_prep_writev初始化讀、寫請求。和前文所提preadv、pwritev的思想差不多,這里直接以不同的操作碼委托io_uring_prep_rw,io_uring_prep_rw只是簡單地初始化io_uring_sqe。
準備完成之后,使用io_uring_submit提交請求。
提交了IO請求時,可以通過非阻塞式函數(shù)io_uring_peek_cqe、阻塞式函數(shù)io_uring_wait_cqe獲取請求完成的情況。默認情況下,完成的IO請求還會存在內(nèi)部的隊列中,需要通過io_uring_cqe_seen表標記完成操作。
使用完成之后要通過io_uring_queue_exit來完成資源清理的工作。
核心實現(xiàn)
io_uring_queue_init的實現(xiàn),前文已略有提及。其中的操作主要就是io_uring_setup和io_uring_queue_mmap,io_uring_setup前文已解析過,這里主要看io_uring_queue_mmap。
/**?Returns?-1?on?error,?or?zero?on?success.?On?success,?'ring'*?contains?the?necessary?information?to?read/write?to?the?rings.*/ int?io_uring_queue_init(unsigned?entries,?struct?io_uring?*ring,?unsigned?flags) {struct?io_uring_params?p;int?fd,?ret;memset(&p,?0,?sizeof(p));p.flags?=?flags;fd?=?io_uring_setup(entries,?&p);if?(fd?<?0)return?fd;ret?=?io_uring_queue_mmap(fd,?&p,?ring);if?(ret)close(fd);return?ret; }io_uring_queue_mmap初始化io_uring結構,然后主要調用io_uring_mmap。
/**?For?users?that?want?to?specify?sq_thread_cpu?or?sq_thread_idle,?this*?interface?is?a?convenient?helper?for?mmap()ing?the?rings.*?Returns?-1?on?error,?or?zero?on?success.??On?success,?'ring'*?contains?the?necessary?information?to?read/write?to?the?rings.*/ int?io_uring_queue_mmap(int?fd,?struct?io_uring_params?*p,?struct?io_uring?*ring) {int?ret;memset(ring,?0,?sizeof(*ring));ret?=?io_uring_mmap(fd,?p,?&ring->sq,?&ring->cq);if?(!ret)ring->ring_fd?=?fd;return?ret; }io_uring_mmap初始化io_uring_sq結構和io_uring_cq結構的內(nèi)存,另外還會分配一個io_uring_sqe結構的數(shù)組。
static?int?io_uring_mmap(int?fd,?struct?io_uring_params?*p,struct?io_uring_sq?*sq,?struct?io_uring_cq?*cq) {size_t?size;void?*ptr;int?ret;sq->ring_sz?=?p->sq_off.array?+?p->sq_entries?*?sizeof(unsigned);ptr?=?mmap(0,?sq->ring_sz,?PROT_READ?|?PROT_WRITE,MAP_SHARED?|?MAP_POPULATE,?fd,?IORING_OFF_SQ_RING);if?(ptr?==?MAP_FAILED)return?-errno;sq->khead?=?ptr?+?p->sq_off.head;sq->ktail?=?ptr?+?p->sq_off.tail;sq->kring_mask?=?ptr?+?p->sq_off.ring_mask;sq->kring_entries?=?ptr?+?p->sq_off.ring_entries;sq->kflags?=?ptr?+?p->sq_off.flags;sq->kdropped?=?ptr?+?p->sq_off.dropped;sq->array?=?ptr?+?p->sq_off.array;size?=?p->sq_entries?*?sizeof(struct?io_uring_sqe);sq->sqes?=?mmap(0,?size,?PROT_READ?|?PROT_WRITE,MAP_SHARED?|?MAP_POPULATE,?fd,IORING_OFF_SQES);if?(sq->sqes?==?MAP_FAILED)?{ret?=?-errno; err:munmap(sq->khead,?sq->ring_sz);return?ret;}cq->ring_sz?=?p->cq_off.cqes?+?p->cq_entries?*?sizeof(struct?io_uring_cqe);ptr?=?mmap(0,?cq->ring_sz,?PROT_READ?|?PROT_WRITE,MAP_SHARED?|?MAP_POPULATE,?fd,?IORING_OFF_CQ_RING);if?(ptr?==?MAP_FAILED)?{ret?=?-errno;munmap(sq->sqes,?p->sq_entries?*?sizeof(struct?io_uring_sqe));goto?err;}cq->khead?=?ptr?+?p->cq_off.head;cq->ktail?=?ptr?+?p->cq_off.tail;cq->kring_mask?=?ptr?+?p->cq_off.ring_mask;cq->kring_entries?=?ptr?+?p->cq_off.ring_entries;cq->koverflow?=?ptr?+?p->cq_off.overflow;cq->cqes?=?ptr?+?p->cq_off.cqes;return?0; }具體例程
如下是一個基于liburing的helloworld示例。
#include?<unistd.h> #include?<fcntl.h> #include?<string.h> #include?<stdio.h> #include?<liburing.h>#define?ENTRIES?4int?main(int?argc,?char?*argv[]) {struct?io_uring?ring;struct?io_uring_sqe?*sqe;struct?io_uring_cqe?*cqe;struct?iovec?iov?=?{.iov_base?=?"Hello?World",.iov_len?=?strlen("Hello?World"),};int?fd,?ret;if?(argc?!=?2)?{printf("%s:?<testfile>\n",?argv[0]);return?1;}/*?setup?io_uring?and?do?mmap?*/ret?=?io_uring_queue_init(ENTRIES,?&ring,?0);if?(ret?<?0)?{printf("io_uring_queue_init:?%s\n",?strerror(-ret));return?1;}fd?=?open("testfile",?O_WRONLY?|?O_CREAT);if?(fd?<?0)?{printf("open?failed\n");ret?=?1;goto?exit;}/*?get?an?sqe?and?fill?in?a?WRITEV?operation?*/sqe?=?io_uring_get_sqe(&ring);if?(!sqe)?{printf("io_uring_get_sqe?failed\n");ret?=?1;goto?out;}io_uring_prep_writev(sqe,?fd,?&iov,?1,?0);/*?tell?the?kernel?we?have?an?sqe?ready?for?consumption?*/ret?=?io_uring_submit(&ring);if?(ret?<?0)?{printf("io_uring_submit:?%s\n",?strerror(-ret));goto?out;}/*?wait?for?the?sqe?to?complete?*/ret?=?io_uring_wait_cqe(&ring,?&cqe);if?(ret?<?0)?{printf("io_uring_wait_cqe:?%s\n",?strerror(-ret));goto?out;}/*?read?and?process?cqe?event?*/io_uring_cqe_seen(&ring,?cqe); out:close(fd); exit:/*?tear?down?*/io_uring_queue_exit(&ring);return?ret; }更多的示例可參考:
http://git.kernel.dk/cgit/liburing/tree/examples
https://git.kernel.dk/cgit/liburing/tree/test
性能
如上,推演過了設計與實現(xiàn),回歸到存儲的需求上來,io_uring子系統(tǒng)是否能滿足我們對高性能的極致需求呢?這一切還是需要profile。
測試方法
io_uring原作者Jens Axboe在fio中提供了ioengine=io_uring的支持,可以使用fio進行測試,使用ioengine選項指定異步IO引擎。
可以基于不同的IO棧:
libaio
kernel+io_uring
kernel+io_uring polling mode
可以基于一些硬件之上:
NVMe SSD
...
測試過程中主要4k數(shù)據(jù)的順序讀、順序寫、隨機讀、隨機寫,對比幾種IO引擎的性能及QoS等指標
io_uring polling mode測試實例:
fio?-name=testname?-filename=/mnt/vdd/testfilename?-iodepth=64?-thread?-rw=randread?-ioengine=io_uring?-sqthread_poll=1?-direct=1?-bs=4k?-size=10G?-numjobs=1?-runtime=600?-group_reporting測試結果
網(wǎng)上可以找到一些關于io uring的性能測試,這里列出部分供參考:
Improved Flash Performance Using the New Linux Kernel I/O Interface
io_uring echo server benchs
[PATCHSET v5] io_uring IO interface
...
主要有以下幾個測試結果
io_uring在非polling模式下,相比libaio,性能提升不是非常顯著。
io_uring在polling模式下,性能提升顯著,與spdk接近,在隊列深度較高時性能更好。
在meltdown和spectre漏洞沒有修復的場景下,io_uring的提升并不太高。雖然減少了大量的用戶態(tài)到內(nèi)核態(tài)的上下文切換,在meldown和spectre漏洞沒有修復的場景下,用戶態(tài)到內(nèi)核態(tài)的切換開銷本比較小,所以提升不太高。
在某些場景下使用io_uring + Kernel NVMe的驅動,效果甚至要比使用SPDK 用戶態(tài)NVMe 驅動更好
從測試中,我們可以得出結論,在存儲中使用io_uring,相比使用libaio,應用的性能會有顯著的提升。
在同樣的硬件平臺上,僅僅更換IO引擎,就可以帶來較大的提升,是很難得的,對于存儲這種延時敏感的應用而言十分寶貴。
io_uring的優(yōu)勢
綜合前文和測試,io_uring有如此出眾的性能,主要來源于以下幾個方面:
用戶態(tài)和內(nèi)核態(tài)共享提交隊列SQ和完成隊列CQ實現(xiàn)零拷貝。
IO提交和收割可以offload給Kernel,不需要經(jīng)過系統(tǒng)調用。
支持塊設備層的Polling模式。
可以提前注冊用戶態(tài)內(nèi)存地址,從而減少地址映射的開銷。
相比libaio,支持buffered IO
發(fā)展方向
事物的發(fā)展是一個哲學話題。前文闡述了io_uring作為一個新事物,發(fā)展的根本動力、內(nèi)因和外因,謹此簡述一些可預見的未來的發(fā)展方向。
普及
應用層多使用。目前主要應用在存儲的場景中,這是一個不僅需要高性能,也需要穩(wěn)定的場景,而一般來說,新事物并不具備“穩(wěn)定”的屬性。但是io_uring同樣也是穩(wěn)定的,因為雖然io_uring使用到了若干新概念,但是這些新的東西已經(jīng)有了實踐的檢驗,如eventfd通知機制,SIGIO信號機制,與AIO基本相似。它是一個質變的新事物。
就我們騰訊而言,內(nèi)核使用tlinux,tlinux3基于4.14.99主線;tlinux4基于5.4.23主線。
所以,tlinux3可以用native aio,tlinux4之后已經(jīng)可以用native io_uring。
相信通過大家的努力,正如前文所說的PostgreSQL使用彼時新接口pread,Nginx使用彼時的新接口AIO一樣,通過使用新街口,我們的工程也能獲得巨大收益。
優(yōu)化方向
降低本身的工作負載
持續(xù)降低系統(tǒng)調用開銷、拷貝開銷、框架本身的負載。
重構
"Politics are for the moment. An equation is for eternity.
——Albert Einstein
追求真理的人不可避免地追求永恒。“政治只是一時,方程卻是永恒。”——愛因斯坦如是說,時值以色列的第一任總統(tǒng)魏茲曼于1952年逝世,繼任首相古理安建議邀請愛因斯坦擔任第二任總統(tǒng)。
我們說折衷權衡、精益求精,字里行間都是永恒,然而軟件應該持續(xù)重構,這實際上并不只是io_uring需要做的,有機會我會寫一篇關于重構的文章。
總結
首先,本文簡述了Linux過往的的IO發(fā)展歷程,同步IO接口、原生異步IO接口AIO的缺陷,為何原有方式存在缺陷。其次,再從設計的角度出發(fā),介紹了最新的IO引擎io_uring的相關內(nèi)容。最后,深入最新版內(nèi)核linux-5.10中解析了io_uring的大體實現(xiàn)(關鍵數(shù)據(jù)結構、流程、特性實現(xiàn)等)。
關于
難免紕漏,歡迎交流,可以通過以下網(wǎng)址找到本文。
知乎:https://www.zhihu.com/people/linkerist-61
Github: https://github.com/Linkerist/blog/issues
內(nèi)容會更新,可以關注我的公眾號,歡迎交流。
參考
PATCH 12/19]io_uring: add support for pre-mapped user IO buffers
Add pread/pwrite support bits to match the lseek bit
Toward non-blocking asynchronous I/O
A new kernel polling interface
The rapid growth of io_uring
Ringing in a new asynchronous I/O API
Efficient IO with io_uring
The current state of kernel page-table isolation
The Linux man-pages project
https://zhuanlan.zhihu.com/p/62682475
why we need io_uring? by byteisland
Computer Systems: A Programmer's Perspective, Third Edition
Advanced Programming in the UNIX Environment, Third Edition
The Linux Programming Interface: A Linux and UNIX System Programming Handbook
Introduction to io_uring
Understanding Nginx Modules Development and Architecture Resolving(Second Edition)
總結
以上是生活随笔為你收集整理的操作系统与存储:解析Linux内核全新异步IO引擎io_uring设计与实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 云时代,我们需要怎样的数据库?
- 下一篇: 海量小文件场景下训练加速优化之路