virtio-blk.c 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  1. /*
  2. * Virtio Block Device
  3. *
  4. * Copyright IBM, Corp. 2007
  5. *
  6. * Authors:
  7. * Anthony Liguori <aliguori@us.ibm.com>
  8. *
  9. * This work is licensed under the terms of the GNU GPL, version 2. See
  10. * the COPYING file in the top-level directory.
  11. *
  12. */
  13. #include "qemu/osdep.h"
  14. #include "qemu/defer-call.h"
  15. #include "qapi/error.h"
  16. #include "qemu/iov.h"
  17. #include "qemu/module.h"
  18. #include "qemu/error-report.h"
  19. #include "qemu/main-loop.h"
  20. #include "block/block_int.h"
  21. #include "trace.h"
  22. #include "hw/block/block.h"
  23. #include "hw/qdev-properties.h"
  24. #include "sysemu/blockdev.h"
  25. #include "sysemu/block-ram-registrar.h"
  26. #include "sysemu/sysemu.h"
  27. #include "sysemu/runstate.h"
  28. #include "hw/virtio/virtio-blk.h"
  29. #include "scsi/constants.h"
  30. #ifdef __linux__
  31. # include <scsi/sg.h>
  32. #endif
  33. #include "hw/virtio/virtio-bus.h"
  34. #include "migration/qemu-file-types.h"
  35. #include "hw/virtio/virtio-access.h"
  36. #include "hw/virtio/virtio-blk-common.h"
  37. #include "qemu/coroutine.h"
  38. static void virtio_blk_ioeventfd_attach(VirtIOBlock *s);
  39. static void virtio_blk_init_request(VirtIOBlock *s, VirtQueue *vq,
  40. VirtIOBlockReq *req)
  41. {
  42. req->dev = s;
  43. req->vq = vq;
  44. req->qiov.size = 0;
  45. req->in_len = 0;
  46. req->next = NULL;
  47. req->mr_next = NULL;
  48. }
  49. static void virtio_blk_free_request(VirtIOBlockReq *req)
  50. {
  51. g_free(req);
  52. }
  53. static void virtio_blk_req_complete(VirtIOBlockReq *req, unsigned char status)
  54. {
  55. VirtIOBlock *s = req->dev;
  56. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  57. trace_virtio_blk_req_complete(vdev, req, status);
  58. stb_p(&req->in->status, status);
  59. iov_discard_undo(&req->inhdr_undo);
  60. iov_discard_undo(&req->outhdr_undo);
  61. virtqueue_push(req->vq, &req->elem, req->in_len);
  62. if (qemu_in_iothread()) {
  63. virtio_notify_irqfd(vdev, req->vq);
  64. } else {
  65. virtio_notify(vdev, req->vq);
  66. }
  67. }
  68. static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,
  69. bool is_read, bool acct_failed)
  70. {
  71. VirtIOBlock *s = req->dev;
  72. BlockErrorAction action = blk_get_error_action(s->blk, is_read, error);
  73. if (action == BLOCK_ERROR_ACTION_STOP) {
  74. /* Break the link as the next request is going to be parsed from the
  75. * ring again. Otherwise we may end up doing a double completion! */
  76. req->mr_next = NULL;
  77. WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
  78. req->next = s->rq;
  79. s->rq = req;
  80. }
  81. } else if (action == BLOCK_ERROR_ACTION_REPORT) {
  82. virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
  83. if (acct_failed) {
  84. block_acct_failed(blk_get_stats(s->blk), &req->acct);
  85. }
  86. virtio_blk_free_request(req);
  87. }
  88. blk_error_action(s->blk, action, is_read, error);
  89. return action != BLOCK_ERROR_ACTION_IGNORE;
  90. }
  91. static void virtio_blk_rw_complete(void *opaque, int ret)
  92. {
  93. VirtIOBlockReq *next = opaque;
  94. VirtIOBlock *s = next->dev;
  95. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  96. while (next) {
  97. VirtIOBlockReq *req = next;
  98. next = req->mr_next;
  99. trace_virtio_blk_rw_complete(vdev, req, ret);
  100. if (req->qiov.nalloc != -1) {
  101. /* If nalloc is != -1 req->qiov is a local copy of the original
  102. * external iovec. It was allocated in submit_requests to be
  103. * able to merge requests. */
  104. qemu_iovec_destroy(&req->qiov);
  105. }
  106. if (ret) {
  107. int p = virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type);
  108. bool is_read = !(p & VIRTIO_BLK_T_OUT);
  109. /* Note that memory may be dirtied on read failure. If the
  110. * virtio request is not completed here, as is the case for
  111. * BLOCK_ERROR_ACTION_STOP, the memory may not be copied
  112. * correctly during live migration. While this is ugly,
  113. * it is acceptable because the device is free to write to
  114. * the memory until the request is completed (which will
  115. * happen on the other side of the migration).
  116. */
  117. if (virtio_blk_handle_rw_error(req, -ret, is_read, true)) {
  118. continue;
  119. }
  120. }
  121. virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
  122. block_acct_done(blk_get_stats(s->blk), &req->acct);
  123. virtio_blk_free_request(req);
  124. }
  125. }
  126. static void virtio_blk_flush_complete(void *opaque, int ret)
  127. {
  128. VirtIOBlockReq *req = opaque;
  129. VirtIOBlock *s = req->dev;
  130. if (ret && virtio_blk_handle_rw_error(req, -ret, 0, true)) {
  131. return;
  132. }
  133. virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
  134. block_acct_done(blk_get_stats(s->blk), &req->acct);
  135. virtio_blk_free_request(req);
  136. }
  137. static void virtio_blk_discard_write_zeroes_complete(void *opaque, int ret)
  138. {
  139. VirtIOBlockReq *req = opaque;
  140. VirtIOBlock *s = req->dev;
  141. bool is_write_zeroes = (virtio_ldl_p(VIRTIO_DEVICE(s), &req->out.type) &
  142. ~VIRTIO_BLK_T_BARRIER) == VIRTIO_BLK_T_WRITE_ZEROES;
  143. if (ret && virtio_blk_handle_rw_error(req, -ret, false, is_write_zeroes)) {
  144. return;
  145. }
  146. virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
  147. if (is_write_zeroes) {
  148. block_acct_done(blk_get_stats(s->blk), &req->acct);
  149. }
  150. virtio_blk_free_request(req);
  151. }
  152. static VirtIOBlockReq *virtio_blk_get_request(VirtIOBlock *s, VirtQueue *vq)
  153. {
  154. VirtIOBlockReq *req = virtqueue_pop(vq, sizeof(VirtIOBlockReq));
  155. if (req) {
  156. virtio_blk_init_request(s, vq, req);
  157. }
  158. return req;
  159. }
  160. static void virtio_blk_handle_scsi(VirtIOBlockReq *req)
  161. {
  162. int status;
  163. struct virtio_scsi_inhdr *scsi;
  164. VirtIOBlock *blk = req->dev;
  165. VirtIODevice *vdev = VIRTIO_DEVICE(blk);
  166. VirtQueueElement *elem = &req->elem;
  167. /*
  168. * We require at least one output segment each for the virtio_blk_outhdr
  169. * and the SCSI command block.
  170. *
  171. * We also at least require the virtio_blk_inhdr, the virtio_scsi_inhdr
  172. * and the sense buffer pointer in the input segments.
  173. */
  174. if (elem->out_num < 2 || elem->in_num < 3) {
  175. status = VIRTIO_BLK_S_IOERR;
  176. goto fail;
  177. }
  178. /*
  179. * The scsi inhdr is placed in the second-to-last input segment, just
  180. * before the regular inhdr.
  181. *
  182. * Just put anything nonzero so that the ioctl fails in the guest.
  183. */
  184. scsi = (void *)elem->in_sg[elem->in_num - 2].iov_base;
  185. virtio_stl_p(vdev, &scsi->errors, 255);
  186. status = VIRTIO_BLK_S_UNSUPP;
  187. fail:
  188. virtio_blk_req_complete(req, status);
  189. virtio_blk_free_request(req);
  190. }
  191. static inline void submit_requests(VirtIOBlock *s, MultiReqBuffer *mrb,
  192. int start, int num_reqs, int niov)
  193. {
  194. BlockBackend *blk = s->blk;
  195. QEMUIOVector *qiov = &mrb->reqs[start]->qiov;
  196. int64_t sector_num = mrb->reqs[start]->sector_num;
  197. bool is_write = mrb->is_write;
  198. BdrvRequestFlags flags = 0;
  199. if (num_reqs > 1) {
  200. int i;
  201. struct iovec *tmp_iov = qiov->iov;
  202. int tmp_niov = qiov->niov;
  203. /* mrb->reqs[start]->qiov was initialized from external so we can't
  204. * modify it here. We need to initialize it locally and then add the
  205. * external iovecs. */
  206. qemu_iovec_init(qiov, niov);
  207. for (i = 0; i < tmp_niov; i++) {
  208. qemu_iovec_add(qiov, tmp_iov[i].iov_base, tmp_iov[i].iov_len);
  209. }
  210. for (i = start + 1; i < start + num_reqs; i++) {
  211. qemu_iovec_concat(qiov, &mrb->reqs[i]->qiov, 0,
  212. mrb->reqs[i]->qiov.size);
  213. mrb->reqs[i - 1]->mr_next = mrb->reqs[i];
  214. }
  215. trace_virtio_blk_submit_multireq(VIRTIO_DEVICE(mrb->reqs[start]->dev),
  216. mrb, start, num_reqs,
  217. sector_num << BDRV_SECTOR_BITS,
  218. qiov->size, is_write);
  219. block_acct_merge_done(blk_get_stats(blk),
  220. is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ,
  221. num_reqs - 1);
  222. }
  223. if (blk_ram_registrar_ok(&s->blk_ram_registrar)) {
  224. flags |= BDRV_REQ_REGISTERED_BUF;
  225. }
  226. if (is_write) {
  227. blk_aio_pwritev(blk, sector_num << BDRV_SECTOR_BITS, qiov,
  228. flags, virtio_blk_rw_complete,
  229. mrb->reqs[start]);
  230. } else {
  231. blk_aio_preadv(blk, sector_num << BDRV_SECTOR_BITS, qiov,
  232. flags, virtio_blk_rw_complete,
  233. mrb->reqs[start]);
  234. }
  235. }
  236. static int multireq_compare(const void *a, const void *b)
  237. {
  238. const VirtIOBlockReq *req1 = *(VirtIOBlockReq **)a,
  239. *req2 = *(VirtIOBlockReq **)b;
  240. /*
  241. * Note that we can't simply subtract sector_num1 from sector_num2
  242. * here as that could overflow the return value.
  243. */
  244. if (req1->sector_num > req2->sector_num) {
  245. return 1;
  246. } else if (req1->sector_num < req2->sector_num) {
  247. return -1;
  248. } else {
  249. return 0;
  250. }
  251. }
  252. static void virtio_blk_submit_multireq(VirtIOBlock *s, MultiReqBuffer *mrb)
  253. {
  254. int i = 0, start = 0, num_reqs = 0, niov = 0, nb_sectors = 0;
  255. uint32_t max_transfer;
  256. int64_t sector_num = 0;
  257. if (mrb->num_reqs == 1) {
  258. submit_requests(s, mrb, 0, 1, -1);
  259. mrb->num_reqs = 0;
  260. return;
  261. }
  262. max_transfer = blk_get_max_transfer(mrb->reqs[0]->dev->blk);
  263. qsort(mrb->reqs, mrb->num_reqs, sizeof(*mrb->reqs),
  264. &multireq_compare);
  265. for (i = 0; i < mrb->num_reqs; i++) {
  266. VirtIOBlockReq *req = mrb->reqs[i];
  267. if (num_reqs > 0) {
  268. /*
  269. * NOTE: We cannot merge the requests in below situations:
  270. * 1. requests are not sequential
  271. * 2. merge would exceed maximum number of IOVs
  272. * 3. merge would exceed maximum transfer length of backend device
  273. */
  274. if (sector_num + nb_sectors != req->sector_num ||
  275. niov > blk_get_max_iov(s->blk) - req->qiov.niov ||
  276. req->qiov.size > max_transfer ||
  277. nb_sectors > (max_transfer -
  278. req->qiov.size) / BDRV_SECTOR_SIZE) {
  279. submit_requests(s, mrb, start, num_reqs, niov);
  280. num_reqs = 0;
  281. }
  282. }
  283. if (num_reqs == 0) {
  284. sector_num = req->sector_num;
  285. nb_sectors = niov = 0;
  286. start = i;
  287. }
  288. nb_sectors += req->qiov.size / BDRV_SECTOR_SIZE;
  289. niov += req->qiov.niov;
  290. num_reqs++;
  291. }
  292. submit_requests(s, mrb, start, num_reqs, niov);
  293. mrb->num_reqs = 0;
  294. }
  295. static void virtio_blk_handle_flush(VirtIOBlockReq *req, MultiReqBuffer *mrb)
  296. {
  297. VirtIOBlock *s = req->dev;
  298. block_acct_start(blk_get_stats(s->blk), &req->acct, 0,
  299. BLOCK_ACCT_FLUSH);
  300. /*
  301. * Make sure all outstanding writes are posted to the backing device.
  302. */
  303. if (mrb->is_write && mrb->num_reqs > 0) {
  304. virtio_blk_submit_multireq(s, mrb);
  305. }
  306. blk_aio_flush(s->blk, virtio_blk_flush_complete, req);
  307. }
  308. static bool virtio_blk_sect_range_ok(VirtIOBlock *dev,
  309. uint64_t sector, size_t size)
  310. {
  311. uint64_t nb_sectors = size >> BDRV_SECTOR_BITS;
  312. uint64_t total_sectors;
  313. if (nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
  314. return false;
  315. }
  316. if (sector & dev->sector_mask) {
  317. return false;
  318. }
  319. if (size % dev->conf.conf.logical_block_size) {
  320. return false;
  321. }
  322. blk_get_geometry(dev->blk, &total_sectors);
  323. if (sector > total_sectors || nb_sectors > total_sectors - sector) {
  324. return false;
  325. }
  326. return true;
  327. }
  328. static uint8_t virtio_blk_handle_discard_write_zeroes(VirtIOBlockReq *req,
  329. struct virtio_blk_discard_write_zeroes *dwz_hdr, bool is_write_zeroes)
  330. {
  331. VirtIOBlock *s = req->dev;
  332. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  333. uint64_t sector;
  334. uint32_t num_sectors, flags, max_sectors;
  335. uint8_t err_status;
  336. int bytes;
  337. sector = virtio_ldq_p(vdev, &dwz_hdr->sector);
  338. num_sectors = virtio_ldl_p(vdev, &dwz_hdr->num_sectors);
  339. flags = virtio_ldl_p(vdev, &dwz_hdr->flags);
  340. max_sectors = is_write_zeroes ? s->conf.max_write_zeroes_sectors :
  341. s->conf.max_discard_sectors;
  342. /*
  343. * max_sectors is at most BDRV_REQUEST_MAX_SECTORS, this check
  344. * make us sure that "num_sectors << BDRV_SECTOR_BITS" can fit in
  345. * the integer variable.
  346. */
  347. if (unlikely(num_sectors > max_sectors)) {
  348. err_status = VIRTIO_BLK_S_IOERR;
  349. goto err;
  350. }
  351. bytes = num_sectors << BDRV_SECTOR_BITS;
  352. if (unlikely(!virtio_blk_sect_range_ok(s, sector, bytes))) {
  353. err_status = VIRTIO_BLK_S_IOERR;
  354. goto err;
  355. }
  356. /*
  357. * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for discard
  358. * and write zeroes commands if any unknown flag is set.
  359. */
  360. if (unlikely(flags & ~VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
  361. err_status = VIRTIO_BLK_S_UNSUPP;
  362. goto err;
  363. }
  364. if (is_write_zeroes) { /* VIRTIO_BLK_T_WRITE_ZEROES */
  365. int blk_aio_flags = 0;
  366. if (flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP) {
  367. blk_aio_flags |= BDRV_REQ_MAY_UNMAP;
  368. }
  369. block_acct_start(blk_get_stats(s->blk), &req->acct, bytes,
  370. BLOCK_ACCT_WRITE);
  371. blk_aio_pwrite_zeroes(s->blk, sector << BDRV_SECTOR_BITS,
  372. bytes, blk_aio_flags,
  373. virtio_blk_discard_write_zeroes_complete, req);
  374. } else { /* VIRTIO_BLK_T_DISCARD */
  375. /*
  376. * The device MUST set the status byte to VIRTIO_BLK_S_UNSUPP for
  377. * discard commands if the unmap flag is set.
  378. */
  379. if (unlikely(flags & VIRTIO_BLK_WRITE_ZEROES_FLAG_UNMAP)) {
  380. err_status = VIRTIO_BLK_S_UNSUPP;
  381. goto err;
  382. }
  383. blk_aio_pdiscard(s->blk, sector << BDRV_SECTOR_BITS, bytes,
  384. virtio_blk_discard_write_zeroes_complete, req);
  385. }
  386. return VIRTIO_BLK_S_OK;
  387. err:
  388. if (is_write_zeroes) {
  389. block_acct_invalid(blk_get_stats(s->blk), BLOCK_ACCT_WRITE);
  390. }
  391. return err_status;
  392. }
  393. typedef struct ZoneCmdData {
  394. VirtIOBlockReq *req;
  395. struct iovec *in_iov;
  396. unsigned in_num;
  397. union {
  398. struct {
  399. unsigned int nr_zones;
  400. BlockZoneDescriptor *zones;
  401. } zone_report_data;
  402. struct {
  403. int64_t offset;
  404. } zone_append_data;
  405. };
  406. } ZoneCmdData;
  407. /*
  408. * check zoned_request: error checking before issuing requests. If all checks
  409. * passed, return true.
  410. * append: true if only zone append requests issued.
  411. */
  412. static bool check_zoned_request(VirtIOBlock *s, int64_t offset, int64_t len,
  413. bool append, uint8_t *status) {
  414. BlockDriverState *bs = blk_bs(s->blk);
  415. int index;
  416. if (!virtio_has_feature(s->host_features, VIRTIO_BLK_F_ZONED)) {
  417. *status = VIRTIO_BLK_S_UNSUPP;
  418. return false;
  419. }
  420. if (offset < 0 || len < 0 || len > (bs->total_sectors << BDRV_SECTOR_BITS)
  421. || offset > (bs->total_sectors << BDRV_SECTOR_BITS) - len) {
  422. *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  423. return false;
  424. }
  425. if (append) {
  426. if (bs->bl.write_granularity) {
  427. if ((offset % bs->bl.write_granularity) != 0) {
  428. *status = VIRTIO_BLK_S_ZONE_UNALIGNED_WP;
  429. return false;
  430. }
  431. }
  432. index = offset / bs->bl.zone_size;
  433. if (BDRV_ZT_IS_CONV(bs->wps->wp[index])) {
  434. *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  435. return false;
  436. }
  437. if (len / 512 > bs->bl.max_append_sectors) {
  438. if (bs->bl.max_append_sectors == 0) {
  439. *status = VIRTIO_BLK_S_UNSUPP;
  440. } else {
  441. *status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  442. }
  443. return false;
  444. }
  445. }
  446. return true;
  447. }
  448. static void virtio_blk_zone_report_complete(void *opaque, int ret)
  449. {
  450. ZoneCmdData *data = opaque;
  451. VirtIOBlockReq *req = data->req;
  452. VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
  453. struct iovec *in_iov = data->in_iov;
  454. unsigned in_num = data->in_num;
  455. int64_t zrp_size, n, j = 0;
  456. int64_t nz = data->zone_report_data.nr_zones;
  457. int8_t err_status = VIRTIO_BLK_S_OK;
  458. struct virtio_blk_zone_report zrp_hdr = (struct virtio_blk_zone_report) {
  459. .nr_zones = cpu_to_le64(nz),
  460. };
  461. trace_virtio_blk_zone_report_complete(vdev, req, nz, ret);
  462. if (ret) {
  463. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  464. goto out;
  465. }
  466. zrp_size = sizeof(struct virtio_blk_zone_report)
  467. + sizeof(struct virtio_blk_zone_descriptor) * nz;
  468. n = iov_from_buf(in_iov, in_num, 0, &zrp_hdr, sizeof(zrp_hdr));
  469. if (n != sizeof(zrp_hdr)) {
  470. virtio_error(vdev, "Driver provided input buffer that is too small!");
  471. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  472. goto out;
  473. }
  474. for (size_t i = sizeof(zrp_hdr); i < zrp_size;
  475. i += sizeof(struct virtio_blk_zone_descriptor), ++j) {
  476. struct virtio_blk_zone_descriptor desc =
  477. (struct virtio_blk_zone_descriptor) {
  478. .z_start = cpu_to_le64(data->zone_report_data.zones[j].start
  479. >> BDRV_SECTOR_BITS),
  480. .z_cap = cpu_to_le64(data->zone_report_data.zones[j].cap
  481. >> BDRV_SECTOR_BITS),
  482. .z_wp = cpu_to_le64(data->zone_report_data.zones[j].wp
  483. >> BDRV_SECTOR_BITS),
  484. };
  485. switch (data->zone_report_data.zones[j].type) {
  486. case BLK_ZT_CONV:
  487. desc.z_type = VIRTIO_BLK_ZT_CONV;
  488. break;
  489. case BLK_ZT_SWR:
  490. desc.z_type = VIRTIO_BLK_ZT_SWR;
  491. break;
  492. case BLK_ZT_SWP:
  493. desc.z_type = VIRTIO_BLK_ZT_SWP;
  494. break;
  495. default:
  496. g_assert_not_reached();
  497. }
  498. switch (data->zone_report_data.zones[j].state) {
  499. case BLK_ZS_RDONLY:
  500. desc.z_state = VIRTIO_BLK_ZS_RDONLY;
  501. break;
  502. case BLK_ZS_OFFLINE:
  503. desc.z_state = VIRTIO_BLK_ZS_OFFLINE;
  504. break;
  505. case BLK_ZS_EMPTY:
  506. desc.z_state = VIRTIO_BLK_ZS_EMPTY;
  507. break;
  508. case BLK_ZS_CLOSED:
  509. desc.z_state = VIRTIO_BLK_ZS_CLOSED;
  510. break;
  511. case BLK_ZS_FULL:
  512. desc.z_state = VIRTIO_BLK_ZS_FULL;
  513. break;
  514. case BLK_ZS_EOPEN:
  515. desc.z_state = VIRTIO_BLK_ZS_EOPEN;
  516. break;
  517. case BLK_ZS_IOPEN:
  518. desc.z_state = VIRTIO_BLK_ZS_IOPEN;
  519. break;
  520. case BLK_ZS_NOT_WP:
  521. desc.z_state = VIRTIO_BLK_ZS_NOT_WP;
  522. break;
  523. default:
  524. g_assert_not_reached();
  525. }
  526. /* TODO: it takes O(n^2) time complexity. Optimizations required. */
  527. n = iov_from_buf(in_iov, in_num, i, &desc, sizeof(desc));
  528. if (n != sizeof(desc)) {
  529. virtio_error(vdev, "Driver provided input buffer "
  530. "for descriptors that is too small!");
  531. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  532. }
  533. }
  534. out:
  535. virtio_blk_req_complete(req, err_status);
  536. virtio_blk_free_request(req);
  537. g_free(data->zone_report_data.zones);
  538. g_free(data);
  539. }
  540. static void virtio_blk_handle_zone_report(VirtIOBlockReq *req,
  541. struct iovec *in_iov,
  542. unsigned in_num)
  543. {
  544. VirtIOBlock *s = req->dev;
  545. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  546. unsigned int nr_zones;
  547. ZoneCmdData *data;
  548. int64_t zone_size, offset;
  549. uint8_t err_status;
  550. if (req->in_len < sizeof(struct virtio_blk_inhdr) +
  551. sizeof(struct virtio_blk_zone_report) +
  552. sizeof(struct virtio_blk_zone_descriptor)) {
  553. virtio_error(vdev, "in buffer too small for zone report");
  554. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  555. goto out;
  556. }
  557. /* start byte offset of the zone report */
  558. offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
  559. if (!check_zoned_request(s, offset, 0, false, &err_status)) {
  560. goto out;
  561. }
  562. nr_zones = (req->in_len - sizeof(struct virtio_blk_inhdr) -
  563. sizeof(struct virtio_blk_zone_report)) /
  564. sizeof(struct virtio_blk_zone_descriptor);
  565. trace_virtio_blk_handle_zone_report(vdev, req,
  566. offset >> BDRV_SECTOR_BITS, nr_zones);
  567. zone_size = sizeof(BlockZoneDescriptor) * nr_zones;
  568. data = g_malloc(sizeof(ZoneCmdData));
  569. data->req = req;
  570. data->in_iov = in_iov;
  571. data->in_num = in_num;
  572. data->zone_report_data.nr_zones = nr_zones;
  573. data->zone_report_data.zones = g_malloc(zone_size),
  574. blk_aio_zone_report(s->blk, offset, &data->zone_report_data.nr_zones,
  575. data->zone_report_data.zones,
  576. virtio_blk_zone_report_complete, data);
  577. return;
  578. out:
  579. virtio_blk_req_complete(req, err_status);
  580. virtio_blk_free_request(req);
  581. }
  582. static void virtio_blk_zone_mgmt_complete(void *opaque, int ret)
  583. {
  584. VirtIOBlockReq *req = opaque;
  585. VirtIOBlock *s = req->dev;
  586. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  587. int8_t err_status = VIRTIO_BLK_S_OK;
  588. trace_virtio_blk_zone_mgmt_complete(vdev, req,ret);
  589. if (ret) {
  590. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  591. }
  592. virtio_blk_req_complete(req, err_status);
  593. virtio_blk_free_request(req);
  594. }
  595. static int virtio_blk_handle_zone_mgmt(VirtIOBlockReq *req, BlockZoneOp op)
  596. {
  597. VirtIOBlock *s = req->dev;
  598. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  599. BlockDriverState *bs = blk_bs(s->blk);
  600. int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
  601. uint64_t len;
  602. uint64_t capacity = bs->total_sectors << BDRV_SECTOR_BITS;
  603. uint8_t err_status = VIRTIO_BLK_S_OK;
  604. uint32_t type = virtio_ldl_p(vdev, &req->out.type);
  605. if (type == VIRTIO_BLK_T_ZONE_RESET_ALL) {
  606. /* Entire drive capacity */
  607. offset = 0;
  608. len = capacity;
  609. trace_virtio_blk_handle_zone_reset_all(vdev, req, 0,
  610. bs->total_sectors);
  611. } else {
  612. if (bs->bl.zone_size > capacity - offset) {
  613. /* The zoned device allows the last smaller zone. */
  614. len = capacity - bs->bl.zone_size * (bs->bl.nr_zones - 1ull);
  615. } else {
  616. len = bs->bl.zone_size;
  617. }
  618. trace_virtio_blk_handle_zone_mgmt(vdev, req, op,
  619. offset >> BDRV_SECTOR_BITS,
  620. len >> BDRV_SECTOR_BITS);
  621. }
  622. if (!check_zoned_request(s, offset, len, false, &err_status)) {
  623. goto out;
  624. }
  625. blk_aio_zone_mgmt(s->blk, op, offset, len,
  626. virtio_blk_zone_mgmt_complete, req);
  627. return 0;
  628. out:
  629. virtio_blk_req_complete(req, err_status);
  630. virtio_blk_free_request(req);
  631. return err_status;
  632. }
  633. static void virtio_blk_zone_append_complete(void *opaque, int ret)
  634. {
  635. ZoneCmdData *data = opaque;
  636. VirtIOBlockReq *req = data->req;
  637. VirtIODevice *vdev = VIRTIO_DEVICE(req->dev);
  638. int64_t append_sector, n;
  639. uint8_t err_status = VIRTIO_BLK_S_OK;
  640. if (ret) {
  641. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  642. goto out;
  643. }
  644. virtio_stq_p(vdev, &append_sector,
  645. data->zone_append_data.offset >> BDRV_SECTOR_BITS);
  646. n = iov_from_buf(data->in_iov, data->in_num, 0, &append_sector,
  647. sizeof(append_sector));
  648. if (n != sizeof(append_sector)) {
  649. virtio_error(vdev, "Driver provided input buffer less than size of "
  650. "append_sector");
  651. err_status = VIRTIO_BLK_S_ZONE_INVALID_CMD;
  652. goto out;
  653. }
  654. trace_virtio_blk_zone_append_complete(vdev, req, append_sector, ret);
  655. out:
  656. virtio_blk_req_complete(req, err_status);
  657. virtio_blk_free_request(req);
  658. g_free(data);
  659. }
  660. static int virtio_blk_handle_zone_append(VirtIOBlockReq *req,
  661. struct iovec *out_iov,
  662. struct iovec *in_iov,
  663. uint64_t out_num,
  664. unsigned in_num) {
  665. VirtIOBlock *s = req->dev;
  666. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  667. uint8_t err_status = VIRTIO_BLK_S_OK;
  668. int64_t offset = virtio_ldq_p(vdev, &req->out.sector) << BDRV_SECTOR_BITS;
  669. int64_t len = iov_size(out_iov, out_num);
  670. ZoneCmdData *data;
  671. trace_virtio_blk_handle_zone_append(vdev, req, offset >> BDRV_SECTOR_BITS);
  672. if (!check_zoned_request(s, offset, len, true, &err_status)) {
  673. goto out;
  674. }
  675. data = g_malloc(sizeof(ZoneCmdData));
  676. data->req = req;
  677. data->in_iov = in_iov;
  678. data->in_num = in_num;
  679. data->zone_append_data.offset = offset;
  680. qemu_iovec_init_external(&req->qiov, out_iov, out_num);
  681. block_acct_start(blk_get_stats(s->blk), &req->acct, len,
  682. BLOCK_ACCT_ZONE_APPEND);
  683. blk_aio_zone_append(s->blk, &data->zone_append_data.offset, &req->qiov, 0,
  684. virtio_blk_zone_append_complete, data);
  685. return 0;
  686. out:
  687. virtio_blk_req_complete(req, err_status);
  688. virtio_blk_free_request(req);
  689. return err_status;
  690. }
  691. static int virtio_blk_handle_request(VirtIOBlockReq *req, MultiReqBuffer *mrb)
  692. {
  693. uint32_t type;
  694. struct iovec *in_iov = req->elem.in_sg;
  695. struct iovec *out_iov = req->elem.out_sg;
  696. unsigned in_num = req->elem.in_num;
  697. unsigned out_num = req->elem.out_num;
  698. VirtIOBlock *s = req->dev;
  699. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  700. if (req->elem.out_num < 1 || req->elem.in_num < 1) {
  701. virtio_error(vdev, "virtio-blk missing headers");
  702. return -1;
  703. }
  704. if (unlikely(iov_to_buf(out_iov, out_num, 0, &req->out,
  705. sizeof(req->out)) != sizeof(req->out))) {
  706. virtio_error(vdev, "virtio-blk request outhdr too short");
  707. return -1;
  708. }
  709. iov_discard_front_undoable(&out_iov, &out_num, sizeof(req->out),
  710. &req->outhdr_undo);
  711. if (in_iov[in_num - 1].iov_len < sizeof(struct virtio_blk_inhdr)) {
  712. virtio_error(vdev, "virtio-blk request inhdr too short");
  713. iov_discard_undo(&req->outhdr_undo);
  714. return -1;
  715. }
  716. /* We always touch the last byte, so just see how big in_iov is. */
  717. req->in_len = iov_size(in_iov, in_num);
  718. req->in = (void *)in_iov[in_num - 1].iov_base
  719. + in_iov[in_num - 1].iov_len
  720. - sizeof(struct virtio_blk_inhdr);
  721. iov_discard_back_undoable(in_iov, &in_num, sizeof(struct virtio_blk_inhdr),
  722. &req->inhdr_undo);
  723. type = virtio_ldl_p(vdev, &req->out.type);
  724. /* VIRTIO_BLK_T_OUT defines the command direction. VIRTIO_BLK_T_BARRIER
  725. * is an optional flag. Although a guest should not send this flag if
  726. * not negotiated we ignored it in the past. So keep ignoring it. */
  727. switch (type & ~(VIRTIO_BLK_T_OUT | VIRTIO_BLK_T_BARRIER)) {
  728. case VIRTIO_BLK_T_IN:
  729. {
  730. bool is_write = type & VIRTIO_BLK_T_OUT;
  731. req->sector_num = virtio_ldq_p(vdev, &req->out.sector);
  732. if (is_write) {
  733. qemu_iovec_init_external(&req->qiov, out_iov, out_num);
  734. trace_virtio_blk_handle_write(vdev, req, req->sector_num,
  735. req->qiov.size / BDRV_SECTOR_SIZE);
  736. } else {
  737. qemu_iovec_init_external(&req->qiov, in_iov, in_num);
  738. trace_virtio_blk_handle_read(vdev, req, req->sector_num,
  739. req->qiov.size / BDRV_SECTOR_SIZE);
  740. }
  741. if (!virtio_blk_sect_range_ok(s, req->sector_num, req->qiov.size)) {
  742. virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);
  743. block_acct_invalid(blk_get_stats(s->blk),
  744. is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
  745. virtio_blk_free_request(req);
  746. return 0;
  747. }
  748. block_acct_start(blk_get_stats(s->blk), &req->acct, req->qiov.size,
  749. is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ);
  750. /* merge would exceed maximum number of requests or IO direction
  751. * changes */
  752. if (mrb->num_reqs > 0 && (mrb->num_reqs == VIRTIO_BLK_MAX_MERGE_REQS ||
  753. is_write != mrb->is_write ||
  754. !s->conf.request_merging)) {
  755. virtio_blk_submit_multireq(s, mrb);
  756. }
  757. assert(mrb->num_reqs < VIRTIO_BLK_MAX_MERGE_REQS);
  758. mrb->reqs[mrb->num_reqs++] = req;
  759. mrb->is_write = is_write;
  760. break;
  761. }
  762. case VIRTIO_BLK_T_FLUSH:
  763. virtio_blk_handle_flush(req, mrb);
  764. break;
  765. case VIRTIO_BLK_T_ZONE_REPORT:
  766. virtio_blk_handle_zone_report(req, in_iov, in_num);
  767. break;
  768. case VIRTIO_BLK_T_ZONE_OPEN:
  769. virtio_blk_handle_zone_mgmt(req, BLK_ZO_OPEN);
  770. break;
  771. case VIRTIO_BLK_T_ZONE_CLOSE:
  772. virtio_blk_handle_zone_mgmt(req, BLK_ZO_CLOSE);
  773. break;
  774. case VIRTIO_BLK_T_ZONE_FINISH:
  775. virtio_blk_handle_zone_mgmt(req, BLK_ZO_FINISH);
  776. break;
  777. case VIRTIO_BLK_T_ZONE_RESET:
  778. virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
  779. break;
  780. case VIRTIO_BLK_T_ZONE_RESET_ALL:
  781. virtio_blk_handle_zone_mgmt(req, BLK_ZO_RESET);
  782. break;
  783. case VIRTIO_BLK_T_SCSI_CMD:
  784. virtio_blk_handle_scsi(req);
  785. break;
  786. case VIRTIO_BLK_T_GET_ID:
  787. {
  788. /*
  789. * NB: per existing s/n string convention the string is
  790. * terminated by '\0' only when shorter than buffer.
  791. */
  792. const char *serial = s->conf.serial ? s->conf.serial : "";
  793. size_t size = MIN(strlen(serial) + 1,
  794. MIN(iov_size(in_iov, in_num),
  795. VIRTIO_BLK_ID_BYTES));
  796. iov_from_buf(in_iov, in_num, 0, serial, size);
  797. virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);
  798. virtio_blk_free_request(req);
  799. break;
  800. }
  801. case VIRTIO_BLK_T_ZONE_APPEND & ~VIRTIO_BLK_T_OUT:
  802. /*
  803. * Passing out_iov/out_num and in_iov/in_num is not safe
  804. * to access req->elem.out_sg directly because it may be
  805. * modified by virtio_blk_handle_request().
  806. */
  807. virtio_blk_handle_zone_append(req, out_iov, in_iov, out_num, in_num);
  808. break;
  809. /*
  810. * VIRTIO_BLK_T_DISCARD and VIRTIO_BLK_T_WRITE_ZEROES are defined with
  811. * VIRTIO_BLK_T_OUT flag set. We masked this flag in the switch statement,
  812. * so we must mask it for these requests, then we will check if it is set.
  813. */
  814. case VIRTIO_BLK_T_DISCARD & ~VIRTIO_BLK_T_OUT:
  815. case VIRTIO_BLK_T_WRITE_ZEROES & ~VIRTIO_BLK_T_OUT:
  816. {
  817. struct virtio_blk_discard_write_zeroes dwz_hdr;
  818. size_t out_len = iov_size(out_iov, out_num);
  819. bool is_write_zeroes = (type & ~VIRTIO_BLK_T_BARRIER) ==
  820. VIRTIO_BLK_T_WRITE_ZEROES;
  821. uint8_t err_status;
  822. /*
  823. * Unsupported if VIRTIO_BLK_T_OUT is not set or the request contains
  824. * more than one segment.
  825. */
  826. if (unlikely(!(type & VIRTIO_BLK_T_OUT) ||
  827. out_len > sizeof(dwz_hdr))) {
  828. virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
  829. virtio_blk_free_request(req);
  830. return 0;
  831. }
  832. if (unlikely(iov_to_buf(out_iov, out_num, 0, &dwz_hdr,
  833. sizeof(dwz_hdr)) != sizeof(dwz_hdr))) {
  834. iov_discard_undo(&req->inhdr_undo);
  835. iov_discard_undo(&req->outhdr_undo);
  836. virtio_error(vdev, "virtio-blk discard/write_zeroes header"
  837. " too short");
  838. return -1;
  839. }
  840. err_status = virtio_blk_handle_discard_write_zeroes(req, &dwz_hdr,
  841. is_write_zeroes);
  842. if (err_status != VIRTIO_BLK_S_OK) {
  843. virtio_blk_req_complete(req, err_status);
  844. virtio_blk_free_request(req);
  845. }
  846. break;
  847. }
  848. default:
  849. virtio_blk_req_complete(req, VIRTIO_BLK_S_UNSUPP);
  850. virtio_blk_free_request(req);
  851. }
  852. return 0;
  853. }
  854. void virtio_blk_handle_vq(VirtIOBlock *s, VirtQueue *vq)
  855. {
  856. VirtIOBlockReq *req;
  857. MultiReqBuffer mrb = {};
  858. bool suppress_notifications = virtio_queue_get_notification(vq);
  859. defer_call_begin();
  860. do {
  861. if (suppress_notifications) {
  862. virtio_queue_set_notification(vq, 0);
  863. }
  864. while ((req = virtio_blk_get_request(s, vq))) {
  865. if (virtio_blk_handle_request(req, &mrb)) {
  866. virtqueue_detach_element(req->vq, &req->elem, 0);
  867. virtio_blk_free_request(req);
  868. break;
  869. }
  870. }
  871. if (suppress_notifications) {
  872. virtio_queue_set_notification(vq, 1);
  873. }
  874. } while (!virtio_queue_empty(vq));
  875. if (mrb.num_reqs) {
  876. virtio_blk_submit_multireq(s, &mrb);
  877. }
  878. defer_call_end();
  879. }
  880. static void virtio_blk_handle_output(VirtIODevice *vdev, VirtQueue *vq)
  881. {
  882. VirtIOBlock *s = (VirtIOBlock *)vdev;
  883. if (!s->ioeventfd_disabled && !s->ioeventfd_started) {
  884. /* Some guests kick before setting VIRTIO_CONFIG_S_DRIVER_OK so start
  885. * ioeventfd here instead of waiting for .set_status().
  886. */
  887. virtio_device_start_ioeventfd(vdev);
  888. if (!s->ioeventfd_disabled) {
  889. return;
  890. }
  891. }
  892. virtio_blk_handle_vq(s, vq);
  893. }
  894. static void virtio_blk_dma_restart_bh(void *opaque)
  895. {
  896. VirtIOBlockReq *req = opaque;
  897. VirtIOBlock *s = req->dev; /* we're called with at least one request */
  898. MultiReqBuffer mrb = {};
  899. while (req) {
  900. VirtIOBlockReq *next = req->next;
  901. if (virtio_blk_handle_request(req, &mrb)) {
  902. /* Device is now broken and won't do any processing until it gets
  903. * reset. Already queued requests will be lost: let's purge them.
  904. */
  905. while (req) {
  906. next = req->next;
  907. virtqueue_detach_element(req->vq, &req->elem, 0);
  908. virtio_blk_free_request(req);
  909. req = next;
  910. }
  911. break;
  912. }
  913. req = next;
  914. }
  915. if (mrb.num_reqs) {
  916. virtio_blk_submit_multireq(s, &mrb);
  917. }
  918. /* Paired with inc in virtio_blk_dma_restart_cb() */
  919. blk_dec_in_flight(s->conf.conf.blk);
  920. }
  921. static void virtio_blk_dma_restart_cb(void *opaque, bool running,
  922. RunState state)
  923. {
  924. VirtIOBlock *s = opaque;
  925. uint16_t num_queues = s->conf.num_queues;
  926. g_autofree VirtIOBlockReq **vq_rq = NULL;
  927. VirtIOBlockReq *rq = NULL;
  928. if (!running) {
  929. return;
  930. }
  931. /* Split the device-wide s->rq request list into per-vq request lists */
  932. vq_rq = g_new0(VirtIOBlockReq *, num_queues);
  933. WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
  934. rq = s->rq;
  935. s->rq = NULL;
  936. }
  937. while (rq) {
  938. VirtIOBlockReq *next = rq->next;
  939. uint16_t idx = virtio_get_queue_index(rq->vq);
  940. /* Only num_queues vqs were created so vq_rq[idx] is within bounds */
  941. assert(idx < num_queues);
  942. rq->next = vq_rq[idx];
  943. vq_rq[idx] = rq;
  944. rq = next;
  945. }
  946. /* Schedule a BH to submit the requests in each vq's AioContext */
  947. for (uint16_t i = 0; i < num_queues; i++) {
  948. if (!vq_rq[i]) {
  949. continue;
  950. }
  951. /* Paired with dec in virtio_blk_dma_restart_bh() */
  952. blk_inc_in_flight(s->conf.conf.blk);
  953. aio_bh_schedule_oneshot(s->vq_aio_context[i],
  954. virtio_blk_dma_restart_bh,
  955. vq_rq[i]);
  956. }
  957. }
  958. static void virtio_blk_reset(VirtIODevice *vdev)
  959. {
  960. VirtIOBlock *s = VIRTIO_BLK(vdev);
  961. VirtIOBlockReq *req;
  962. /* Dataplane has stopped... */
  963. assert(!s->ioeventfd_started);
  964. /* ...but requests may still be in flight. */
  965. blk_drain(s->blk);
  966. /* We drop queued requests after blk_drain() because blk_drain() itself can
  967. * produce them. */
  968. WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
  969. while (s->rq) {
  970. req = s->rq;
  971. s->rq = req->next;
  972. /* No other threads can access req->vq here */
  973. virtqueue_detach_element(req->vq, &req->elem, 0);
  974. virtio_blk_free_request(req);
  975. }
  976. }
  977. blk_set_enable_write_cache(s->blk, s->original_wce);
  978. }
  979. /* coalesce internal state, copy to pci i/o region 0
  980. */
  981. static void virtio_blk_update_config(VirtIODevice *vdev, uint8_t *config)
  982. {
  983. VirtIOBlock *s = VIRTIO_BLK(vdev);
  984. BlockConf *conf = &s->conf.conf;
  985. BlockDriverState *bs = blk_bs(s->blk);
  986. struct virtio_blk_config blkcfg;
  987. uint64_t capacity;
  988. int64_t length;
  989. int blk_size = conf->logical_block_size;
  990. blk_get_geometry(s->blk, &capacity);
  991. memset(&blkcfg, 0, sizeof(blkcfg));
  992. virtio_stq_p(vdev, &blkcfg.capacity, capacity);
  993. virtio_stl_p(vdev, &blkcfg.seg_max,
  994. s->conf.seg_max_adjust ? s->conf.queue_size - 2 : 128 - 2);
  995. virtio_stw_p(vdev, &blkcfg.geometry.cylinders, conf->cyls);
  996. virtio_stl_p(vdev, &blkcfg.blk_size, blk_size);
  997. virtio_stw_p(vdev, &blkcfg.min_io_size, conf->min_io_size / blk_size);
  998. virtio_stl_p(vdev, &blkcfg.opt_io_size, conf->opt_io_size / blk_size);
  999. blkcfg.geometry.heads = conf->heads;
  1000. /*
  1001. * We must ensure that the block device capacity is a multiple of
  1002. * the logical block size. If that is not the case, let's use
  1003. * sector_mask to adopt the geometry to have a correct picture.
  1004. * For those devices where the capacity is ok for the given geometry
  1005. * we don't touch the sector value of the geometry, since some devices
  1006. * (like s390 dasd) need a specific value. Here the capacity is already
  1007. * cyls*heads*secs*blk_size and the sector value is not block size
  1008. * divided by 512 - instead it is the amount of blk_size blocks
  1009. * per track (cylinder).
  1010. */
  1011. length = blk_getlength(s->blk);
  1012. if (length > 0 && length / conf->heads / conf->secs % blk_size) {
  1013. blkcfg.geometry.sectors = conf->secs & ~s->sector_mask;
  1014. } else {
  1015. blkcfg.geometry.sectors = conf->secs;
  1016. }
  1017. blkcfg.size_max = 0;
  1018. blkcfg.physical_block_exp = get_physical_block_exp(conf);
  1019. blkcfg.alignment_offset = 0;
  1020. blkcfg.wce = blk_enable_write_cache(s->blk);
  1021. virtio_stw_p(vdev, &blkcfg.num_queues, s->conf.num_queues);
  1022. if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD)) {
  1023. uint32_t discard_granularity = conf->discard_granularity;
  1024. if (discard_granularity == -1 || !s->conf.report_discard_granularity) {
  1025. discard_granularity = blk_size;
  1026. }
  1027. virtio_stl_p(vdev, &blkcfg.max_discard_sectors,
  1028. s->conf.max_discard_sectors);
  1029. virtio_stl_p(vdev, &blkcfg.discard_sector_alignment,
  1030. discard_granularity >> BDRV_SECTOR_BITS);
  1031. /*
  1032. * We support only one segment per request since multiple segments
  1033. * are not widely used and there are no userspace APIs that allow
  1034. * applications to submit multiple segments in a single call.
  1035. */
  1036. virtio_stl_p(vdev, &blkcfg.max_discard_seg, 1);
  1037. }
  1038. if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES)) {
  1039. virtio_stl_p(vdev, &blkcfg.max_write_zeroes_sectors,
  1040. s->conf.max_write_zeroes_sectors);
  1041. blkcfg.write_zeroes_may_unmap = 1;
  1042. virtio_stl_p(vdev, &blkcfg.max_write_zeroes_seg, 1);
  1043. }
  1044. if (bs->bl.zoned != BLK_Z_NONE) {
  1045. switch (bs->bl.zoned) {
  1046. case BLK_Z_HM:
  1047. blkcfg.zoned.model = VIRTIO_BLK_Z_HM;
  1048. break;
  1049. case BLK_Z_HA:
  1050. blkcfg.zoned.model = VIRTIO_BLK_Z_HA;
  1051. break;
  1052. default:
  1053. g_assert_not_reached();
  1054. }
  1055. virtio_stl_p(vdev, &blkcfg.zoned.zone_sectors,
  1056. bs->bl.zone_size / 512);
  1057. virtio_stl_p(vdev, &blkcfg.zoned.max_active_zones,
  1058. bs->bl.max_active_zones);
  1059. virtio_stl_p(vdev, &blkcfg.zoned.max_open_zones,
  1060. bs->bl.max_open_zones);
  1061. virtio_stl_p(vdev, &blkcfg.zoned.write_granularity, blk_size);
  1062. virtio_stl_p(vdev, &blkcfg.zoned.max_append_sectors,
  1063. bs->bl.max_append_sectors);
  1064. } else {
  1065. blkcfg.zoned.model = VIRTIO_BLK_Z_NONE;
  1066. }
  1067. memcpy(config, &blkcfg, s->config_size);
  1068. }
  1069. static void virtio_blk_set_config(VirtIODevice *vdev, const uint8_t *config)
  1070. {
  1071. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1072. struct virtio_blk_config blkcfg;
  1073. memcpy(&blkcfg, config, s->config_size);
  1074. blk_set_enable_write_cache(s->blk, blkcfg.wce != 0);
  1075. }
  1076. static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,
  1077. Error **errp)
  1078. {
  1079. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1080. /* Firstly sync all virtio-blk possible supported features */
  1081. features |= s->host_features;
  1082. virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);
  1083. virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);
  1084. virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);
  1085. virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);
  1086. if (!virtio_has_feature(features, VIRTIO_F_VERSION_1)) {
  1087. virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);
  1088. /* Added for historical reasons, removing it could break migration. */
  1089. virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);
  1090. }
  1091. if (blk_enable_write_cache(s->blk) ||
  1092. (s->conf.x_enable_wce_if_config_wce &&
  1093. virtio_has_feature(features, VIRTIO_BLK_F_CONFIG_WCE))) {
  1094. virtio_add_feature(&features, VIRTIO_BLK_F_WCE);
  1095. }
  1096. if (!blk_is_writable(s->blk)) {
  1097. virtio_add_feature(&features, VIRTIO_BLK_F_RO);
  1098. }
  1099. if (s->conf.num_queues > 1) {
  1100. virtio_add_feature(&features, VIRTIO_BLK_F_MQ);
  1101. }
  1102. return features;
  1103. }
  1104. static void virtio_blk_set_status(VirtIODevice *vdev, uint8_t status)
  1105. {
  1106. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1107. if (!(status & (VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_DRIVER_OK))) {
  1108. assert(!s->ioeventfd_started);
  1109. }
  1110. if (!(status & VIRTIO_CONFIG_S_DRIVER_OK)) {
  1111. return;
  1112. }
  1113. /* A guest that supports VIRTIO_BLK_F_CONFIG_WCE must be able to send
  1114. * cache flushes. Thus, the "auto writethrough" behavior is never
  1115. * necessary for guests that support the VIRTIO_BLK_F_CONFIG_WCE feature.
  1116. * Leaving it enabled would break the following sequence:
  1117. *
  1118. * Guest started with "-drive cache=writethrough"
  1119. * Guest sets status to 0
  1120. * Guest sets DRIVER bit in status field
  1121. * Guest reads host features (WCE=0, CONFIG_WCE=1)
  1122. * Guest writes guest features (WCE=0, CONFIG_WCE=1)
  1123. * Guest writes 1 to the WCE configuration field (writeback mode)
  1124. * Guest sets DRIVER_OK bit in status field
  1125. *
  1126. * s->blk would erroneously be placed in writethrough mode.
  1127. */
  1128. if (!virtio_vdev_has_feature(vdev, VIRTIO_BLK_F_CONFIG_WCE)) {
  1129. blk_set_enable_write_cache(s->blk,
  1130. virtio_vdev_has_feature(vdev,
  1131. VIRTIO_BLK_F_WCE));
  1132. }
  1133. }
  1134. static void virtio_blk_save_device(VirtIODevice *vdev, QEMUFile *f)
  1135. {
  1136. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1137. WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
  1138. VirtIOBlockReq *req = s->rq;
  1139. while (req) {
  1140. qemu_put_sbyte(f, 1);
  1141. if (s->conf.num_queues > 1) {
  1142. qemu_put_be32(f, virtio_get_queue_index(req->vq));
  1143. }
  1144. qemu_put_virtqueue_element(vdev, f, &req->elem);
  1145. req = req->next;
  1146. }
  1147. }
  1148. qemu_put_sbyte(f, 0);
  1149. }
  1150. static int virtio_blk_load_device(VirtIODevice *vdev, QEMUFile *f,
  1151. int version_id)
  1152. {
  1153. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1154. while (qemu_get_sbyte(f)) {
  1155. unsigned nvqs = s->conf.num_queues;
  1156. unsigned vq_idx = 0;
  1157. VirtIOBlockReq *req;
  1158. if (nvqs > 1) {
  1159. vq_idx = qemu_get_be32(f);
  1160. if (vq_idx >= nvqs) {
  1161. error_report("Invalid virtqueue index in request list: %#x",
  1162. vq_idx);
  1163. return -EINVAL;
  1164. }
  1165. }
  1166. req = qemu_get_virtqueue_element(vdev, f, sizeof(VirtIOBlockReq));
  1167. virtio_blk_init_request(s, virtio_get_queue(vdev, vq_idx), req);
  1168. WITH_QEMU_LOCK_GUARD(&s->rq_lock) {
  1169. req->next = s->rq;
  1170. s->rq = req;
  1171. }
  1172. }
  1173. return 0;
  1174. }
  1175. static void virtio_resize_cb(void *opaque)
  1176. {
  1177. VirtIODevice *vdev = opaque;
  1178. assert(qemu_get_current_aio_context() == qemu_get_aio_context());
  1179. virtio_notify_config(vdev);
  1180. }
  1181. static void virtio_blk_resize(void *opaque)
  1182. {
  1183. VirtIODevice *vdev = VIRTIO_DEVICE(opaque);
  1184. /*
  1185. * virtio_notify_config() needs to acquire the BQL,
  1186. * so it can't be called from an iothread. Instead, schedule
  1187. * it to be run in the main context BH.
  1188. */
  1189. aio_bh_schedule_oneshot(qemu_get_aio_context(), virtio_resize_cb, vdev);
  1190. }
  1191. static void virtio_blk_ioeventfd_detach(VirtIOBlock *s)
  1192. {
  1193. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  1194. for (uint16_t i = 0; i < s->conf.num_queues; i++) {
  1195. VirtQueue *vq = virtio_get_queue(vdev, i);
  1196. virtio_queue_aio_detach_host_notifier(vq, s->vq_aio_context[i]);
  1197. }
  1198. }
  1199. static void virtio_blk_ioeventfd_attach(VirtIOBlock *s)
  1200. {
  1201. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  1202. for (uint16_t i = 0; i < s->conf.num_queues; i++) {
  1203. VirtQueue *vq = virtio_get_queue(vdev, i);
  1204. virtio_queue_aio_attach_host_notifier(vq, s->vq_aio_context[i]);
  1205. }
  1206. }
  1207. /* Suspend virtqueue ioeventfd processing during drain */
  1208. static void virtio_blk_drained_begin(void *opaque)
  1209. {
  1210. VirtIOBlock *s = opaque;
  1211. if (s->ioeventfd_started) {
  1212. virtio_blk_ioeventfd_detach(s);
  1213. }
  1214. }
  1215. /* Resume virtqueue ioeventfd processing after drain */
  1216. static void virtio_blk_drained_end(void *opaque)
  1217. {
  1218. VirtIOBlock *s = opaque;
  1219. if (s->ioeventfd_started) {
  1220. virtio_blk_ioeventfd_attach(s);
  1221. }
  1222. }
  1223. static const BlockDevOps virtio_block_ops = {
  1224. .resize_cb = virtio_blk_resize,
  1225. .drained_begin = virtio_blk_drained_begin,
  1226. .drained_end = virtio_blk_drained_end,
  1227. };
  1228. static bool
  1229. validate_iothread_vq_mapping_list(IOThreadVirtQueueMappingList *list,
  1230. uint16_t num_queues, Error **errp)
  1231. {
  1232. g_autofree unsigned long *vqs = bitmap_new(num_queues);
  1233. g_autoptr(GHashTable) iothreads =
  1234. g_hash_table_new(g_str_hash, g_str_equal);
  1235. for (IOThreadVirtQueueMappingList *node = list; node; node = node->next) {
  1236. const char *name = node->value->iothread;
  1237. uint16List *vq;
  1238. if (!iothread_by_id(name)) {
  1239. error_setg(errp, "IOThread \"%s\" object does not exist", name);
  1240. return false;
  1241. }
  1242. if (!g_hash_table_add(iothreads, (gpointer)name)) {
  1243. error_setg(errp,
  1244. "duplicate IOThread name \"%s\" in iothread-vq-mapping",
  1245. name);
  1246. return false;
  1247. }
  1248. if (node != list) {
  1249. if (!!node->value->vqs != !!list->value->vqs) {
  1250. error_setg(errp, "either all items in iothread-vq-mapping "
  1251. "must have vqs or none of them must have it");
  1252. return false;
  1253. }
  1254. }
  1255. for (vq = node->value->vqs; vq; vq = vq->next) {
  1256. if (vq->value >= num_queues) {
  1257. error_setg(errp, "vq index %u for IOThread \"%s\" must be "
  1258. "less than num_queues %u in iothread-vq-mapping",
  1259. vq->value, name, num_queues);
  1260. return false;
  1261. }
  1262. if (test_and_set_bit(vq->value, vqs)) {
  1263. error_setg(errp, "cannot assign vq %u to IOThread \"%s\" "
  1264. "because it is already assigned", vq->value, name);
  1265. return false;
  1266. }
  1267. }
  1268. }
  1269. if (list->value->vqs) {
  1270. for (uint16_t i = 0; i < num_queues; i++) {
  1271. if (!test_bit(i, vqs)) {
  1272. error_setg(errp,
  1273. "missing vq %u IOThread assignment in iothread-vq-mapping",
  1274. i);
  1275. return false;
  1276. }
  1277. }
  1278. }
  1279. return true;
  1280. }
  1281. /**
  1282. * apply_iothread_vq_mapping:
  1283. * @iothread_vq_mapping_list: The mapping of virtqueues to IOThreads.
  1284. * @vq_aio_context: The array of AioContext pointers to fill in.
  1285. * @num_queues: The length of @vq_aio_context.
  1286. * @errp: If an error occurs, a pointer to the area to store the error.
  1287. *
  1288. * Fill in the AioContext for each virtqueue in the @vq_aio_context array given
  1289. * the iothread-vq-mapping parameter in @iothread_vq_mapping_list.
  1290. *
  1291. * Returns: %true on success, %false on failure.
  1292. **/
  1293. static bool apply_iothread_vq_mapping(
  1294. IOThreadVirtQueueMappingList *iothread_vq_mapping_list,
  1295. AioContext **vq_aio_context,
  1296. uint16_t num_queues,
  1297. Error **errp)
  1298. {
  1299. IOThreadVirtQueueMappingList *node;
  1300. size_t num_iothreads = 0;
  1301. size_t cur_iothread = 0;
  1302. if (!validate_iothread_vq_mapping_list(iothread_vq_mapping_list,
  1303. num_queues, errp)) {
  1304. return false;
  1305. }
  1306. for (node = iothread_vq_mapping_list; node; node = node->next) {
  1307. num_iothreads++;
  1308. }
  1309. for (node = iothread_vq_mapping_list; node; node = node->next) {
  1310. IOThread *iothread = iothread_by_id(node->value->iothread);
  1311. AioContext *ctx = iothread_get_aio_context(iothread);
  1312. /* Released in virtio_blk_vq_aio_context_cleanup() */
  1313. object_ref(OBJECT(iothread));
  1314. if (node->value->vqs) {
  1315. uint16List *vq;
  1316. /* Explicit vq:IOThread assignment */
  1317. for (vq = node->value->vqs; vq; vq = vq->next) {
  1318. assert(vq->value < num_queues);
  1319. vq_aio_context[vq->value] = ctx;
  1320. }
  1321. } else {
  1322. /* Round-robin vq:IOThread assignment */
  1323. for (unsigned i = cur_iothread; i < num_queues;
  1324. i += num_iothreads) {
  1325. vq_aio_context[i] = ctx;
  1326. }
  1327. }
  1328. cur_iothread++;
  1329. }
  1330. return true;
  1331. }
  1332. /* Context: BQL held */
  1333. static bool virtio_blk_vq_aio_context_init(VirtIOBlock *s, Error **errp)
  1334. {
  1335. ERRP_GUARD();
  1336. VirtIODevice *vdev = VIRTIO_DEVICE(s);
  1337. VirtIOBlkConf *conf = &s->conf;
  1338. BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(vdev)));
  1339. VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
  1340. if (conf->iothread && conf->iothread_vq_mapping_list) {
  1341. error_setg(errp,
  1342. "iothread and iothread-vq-mapping properties cannot be set "
  1343. "at the same time");
  1344. return false;
  1345. }
  1346. if (conf->iothread || conf->iothread_vq_mapping_list) {
  1347. if (!k->set_guest_notifiers || !k->ioeventfd_assign) {
  1348. error_setg(errp,
  1349. "device is incompatible with iothread "
  1350. "(transport does not support notifiers)");
  1351. return false;
  1352. }
  1353. if (!virtio_device_ioeventfd_enabled(vdev)) {
  1354. error_setg(errp, "ioeventfd is required for iothread");
  1355. return false;
  1356. }
  1357. /*
  1358. * If ioeventfd is (re-)enabled while the guest is running there could
  1359. * be block jobs that can conflict.
  1360. */
  1361. if (blk_op_is_blocked(conf->conf.blk, BLOCK_OP_TYPE_DATAPLANE, errp)) {
  1362. error_prepend(errp, "cannot start virtio-blk ioeventfd: ");
  1363. return false;
  1364. }
  1365. }
  1366. s->vq_aio_context = g_new(AioContext *, conf->num_queues);
  1367. if (conf->iothread_vq_mapping_list) {
  1368. if (!apply_iothread_vq_mapping(conf->iothread_vq_mapping_list,
  1369. s->vq_aio_context,
  1370. conf->num_queues,
  1371. errp)) {
  1372. g_free(s->vq_aio_context);
  1373. s->vq_aio_context = NULL;
  1374. return false;
  1375. }
  1376. } else if (conf->iothread) {
  1377. AioContext *ctx = iothread_get_aio_context(conf->iothread);
  1378. for (unsigned i = 0; i < conf->num_queues; i++) {
  1379. s->vq_aio_context[i] = ctx;
  1380. }
  1381. /* Released in virtio_blk_vq_aio_context_cleanup() */
  1382. object_ref(OBJECT(conf->iothread));
  1383. } else {
  1384. AioContext *ctx = qemu_get_aio_context();
  1385. for (unsigned i = 0; i < conf->num_queues; i++) {
  1386. s->vq_aio_context[i] = ctx;
  1387. }
  1388. }
  1389. return true;
  1390. }
  1391. /* Context: BQL held */
  1392. static void virtio_blk_vq_aio_context_cleanup(VirtIOBlock *s)
  1393. {
  1394. VirtIOBlkConf *conf = &s->conf;
  1395. assert(!s->ioeventfd_started);
  1396. if (conf->iothread_vq_mapping_list) {
  1397. IOThreadVirtQueueMappingList *node;
  1398. for (node = conf->iothread_vq_mapping_list; node; node = node->next) {
  1399. IOThread *iothread = iothread_by_id(node->value->iothread);
  1400. object_unref(OBJECT(iothread));
  1401. }
  1402. }
  1403. if (conf->iothread) {
  1404. object_unref(OBJECT(conf->iothread));
  1405. }
  1406. g_free(s->vq_aio_context);
  1407. s->vq_aio_context = NULL;
  1408. }
  1409. /* Context: BQL held */
  1410. static int virtio_blk_start_ioeventfd(VirtIODevice *vdev)
  1411. {
  1412. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1413. BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));
  1414. VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
  1415. unsigned i;
  1416. unsigned nvqs = s->conf.num_queues;
  1417. Error *local_err = NULL;
  1418. int r;
  1419. if (s->ioeventfd_started || s->ioeventfd_starting) {
  1420. return 0;
  1421. }
  1422. s->ioeventfd_starting = true;
  1423. /* Set up guest notifier (irq) */
  1424. r = k->set_guest_notifiers(qbus->parent, nvqs, true);
  1425. if (r != 0) {
  1426. error_report("virtio-blk failed to set guest notifier (%d), "
  1427. "ensure -accel kvm is set.", r);
  1428. goto fail_guest_notifiers;
  1429. }
  1430. /*
  1431. * Batch all the host notifiers in a single transaction to avoid
  1432. * quadratic time complexity in address_space_update_ioeventfds().
  1433. */
  1434. memory_region_transaction_begin();
  1435. /* Set up virtqueue notify */
  1436. for (i = 0; i < nvqs; i++) {
  1437. r = virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, true);
  1438. if (r != 0) {
  1439. int j = i;
  1440. fprintf(stderr, "virtio-blk failed to set host notifier (%d)\n", r);
  1441. while (i--) {
  1442. virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, false);
  1443. }
  1444. /*
  1445. * The transaction expects the ioeventfds to be open when it
  1446. * commits. Do it now, before the cleanup loop.
  1447. */
  1448. memory_region_transaction_commit();
  1449. while (j--) {
  1450. virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), j);
  1451. }
  1452. goto fail_host_notifiers;
  1453. }
  1454. }
  1455. memory_region_transaction_commit();
  1456. /*
  1457. * Try to change the AioContext so that block jobs and other operations can
  1458. * co-locate their activity in the same AioContext. If it fails, nevermind.
  1459. */
  1460. assert(nvqs > 0); /* enforced during ->realize() */
  1461. r = blk_set_aio_context(s->conf.conf.blk, s->vq_aio_context[0],
  1462. &local_err);
  1463. if (r < 0) {
  1464. warn_report_err(local_err);
  1465. }
  1466. /*
  1467. * These fields must be visible to the IOThread when it processes the
  1468. * virtqueue, otherwise it will think ioeventfd has not started yet.
  1469. *
  1470. * Make sure ->ioeventfd_started is false when blk_set_aio_context() is
  1471. * called above so that draining does not cause the host notifier to be
  1472. * detached/attached prematurely.
  1473. */
  1474. s->ioeventfd_starting = false;
  1475. s->ioeventfd_started = true;
  1476. smp_wmb(); /* paired with aio_notify_accept() on the read side */
  1477. /*
  1478. * Get this show started by hooking up our callbacks. If drained now,
  1479. * virtio_blk_drained_end() will do this later.
  1480. * Attaching the notifier also kicks the virtqueues, processing any requests
  1481. * they may already have.
  1482. */
  1483. if (!blk_in_drain(s->conf.conf.blk)) {
  1484. virtio_blk_ioeventfd_attach(s);
  1485. }
  1486. return 0;
  1487. fail_host_notifiers:
  1488. k->set_guest_notifiers(qbus->parent, nvqs, false);
  1489. fail_guest_notifiers:
  1490. s->ioeventfd_disabled = true;
  1491. s->ioeventfd_starting = false;
  1492. return -ENOSYS;
  1493. }
  1494. /* Stop notifications for new requests from guest.
  1495. *
  1496. * Context: BH in IOThread
  1497. */
  1498. static void virtio_blk_ioeventfd_stop_vq_bh(void *opaque)
  1499. {
  1500. VirtQueue *vq = opaque;
  1501. EventNotifier *host_notifier = virtio_queue_get_host_notifier(vq);
  1502. virtio_queue_aio_detach_host_notifier(vq, qemu_get_current_aio_context());
  1503. /*
  1504. * Test and clear notifier after disabling event, in case poll callback
  1505. * didn't have time to run.
  1506. */
  1507. virtio_queue_host_notifier_read(host_notifier);
  1508. }
  1509. /* Context: BQL held */
  1510. static void virtio_blk_stop_ioeventfd(VirtIODevice *vdev)
  1511. {
  1512. VirtIOBlock *s = VIRTIO_BLK(vdev);
  1513. BusState *qbus = qdev_get_parent_bus(DEVICE(s));
  1514. VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);
  1515. unsigned i;
  1516. unsigned nvqs = s->conf.num_queues;
  1517. if (!s->ioeventfd_started || s->ioeventfd_stopping) {
  1518. return;
  1519. }
  1520. /* Better luck next time. */
  1521. if (s->ioeventfd_disabled) {
  1522. s->ioeventfd_disabled = false;
  1523. s->ioeventfd_started = false;
  1524. return;
  1525. }
  1526. s->ioeventfd_stopping = true;
  1527. if (!blk_in_drain(s->conf.conf.blk)) {
  1528. for (i = 0; i < nvqs; i++) {
  1529. VirtQueue *vq = virtio_get_queue(vdev, i);
  1530. AioContext *ctx = s->vq_aio_context[i];
  1531. aio_wait_bh_oneshot(ctx, virtio_blk_ioeventfd_stop_vq_bh, vq);
  1532. }
  1533. }
  1534. /*
  1535. * Batch all the host notifiers in a single transaction to avoid
  1536. * quadratic time complexity in address_space_update_ioeventfds().
  1537. */
  1538. memory_region_transaction_begin();
  1539. for (i = 0; i < nvqs; i++) {
  1540. virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, false);
  1541. }
  1542. /*
  1543. * The transaction expects the ioeventfds to be open when it
  1544. * commits. Do it now, before the cleanup loop.
  1545. */
  1546. memory_region_transaction_commit();
  1547. for (i = 0; i < nvqs; i++) {
  1548. virtio_bus_cleanup_host_notifier(VIRTIO_BUS(qbus), i);
  1549. }
  1550. /*
  1551. * Set ->ioeventfd_started to false before draining so that host notifiers
  1552. * are not detached/attached anymore.
  1553. */
  1554. s->ioeventfd_started = false;
  1555. /* Wait for virtio_blk_dma_restart_bh() and in flight I/O to complete */
  1556. blk_drain(s->conf.conf.blk);
  1557. /*
  1558. * Try to switch bs back to the QEMU main loop. If other users keep the
  1559. * BlockBackend in the iothread, that's ok
  1560. */
  1561. blk_set_aio_context(s->conf.conf.blk, qemu_get_aio_context(), NULL);
  1562. /* Clean up guest notifier (irq) */
  1563. k->set_guest_notifiers(qbus->parent, nvqs, false);
  1564. s->ioeventfd_stopping = false;
  1565. }
  1566. static void virtio_blk_device_realize(DeviceState *dev, Error **errp)
  1567. {
  1568. VirtIODevice *vdev = VIRTIO_DEVICE(dev);
  1569. VirtIOBlock *s = VIRTIO_BLK(dev);
  1570. VirtIOBlkConf *conf = &s->conf;
  1571. BlockDriverState *bs;
  1572. Error *err = NULL;
  1573. unsigned i;
  1574. if (!conf->conf.blk) {
  1575. error_setg(errp, "drive property not set");
  1576. return;
  1577. }
  1578. if (!blk_is_inserted(conf->conf.blk)) {
  1579. error_setg(errp, "Device needs media, but drive is empty");
  1580. return;
  1581. }
  1582. if (conf->num_queues == VIRTIO_BLK_AUTO_NUM_QUEUES) {
  1583. conf->num_queues = 1;
  1584. }
  1585. if (!conf->num_queues) {
  1586. error_setg(errp, "num-queues property must be larger than 0");
  1587. return;
  1588. }
  1589. if (conf->queue_size <= 2) {
  1590. error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
  1591. "must be > 2", conf->queue_size);
  1592. return;
  1593. }
  1594. if (!is_power_of_2(conf->queue_size) ||
  1595. conf->queue_size > VIRTQUEUE_MAX_SIZE) {
  1596. error_setg(errp, "invalid queue-size property (%" PRIu16 "), "
  1597. "must be a power of 2 (max %d)",
  1598. conf->queue_size, VIRTQUEUE_MAX_SIZE);
  1599. return;
  1600. }
  1601. if (!blkconf_apply_backend_options(&conf->conf,
  1602. !blk_supports_write_perm(conf->conf.blk),
  1603. true, errp)) {
  1604. return;
  1605. }
  1606. s->original_wce = blk_enable_write_cache(conf->conf.blk);
  1607. if (!blkconf_geometry(&conf->conf, NULL, 65535, 255, 255, errp)) {
  1608. return;
  1609. }
  1610. if (!blkconf_blocksizes(&conf->conf, errp)) {
  1611. return;
  1612. }
  1613. bs = blk_bs(conf->conf.blk);
  1614. if (bs->bl.zoned != BLK_Z_NONE) {
  1615. virtio_add_feature(&s->host_features, VIRTIO_BLK_F_ZONED);
  1616. if (bs->bl.zoned == BLK_Z_HM) {
  1617. virtio_clear_feature(&s->host_features, VIRTIO_BLK_F_DISCARD);
  1618. }
  1619. }
  1620. if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_DISCARD) &&
  1621. (!conf->max_discard_sectors ||
  1622. conf->max_discard_sectors > BDRV_REQUEST_MAX_SECTORS)) {
  1623. error_setg(errp, "invalid max-discard-sectors property (%" PRIu32 ")"
  1624. ", must be between 1 and %d",
  1625. conf->max_discard_sectors, (int)BDRV_REQUEST_MAX_SECTORS);
  1626. return;
  1627. }
  1628. if (virtio_has_feature(s->host_features, VIRTIO_BLK_F_WRITE_ZEROES) &&
  1629. (!conf->max_write_zeroes_sectors ||
  1630. conf->max_write_zeroes_sectors > BDRV_REQUEST_MAX_SECTORS)) {
  1631. error_setg(errp, "invalid max-write-zeroes-sectors property (%" PRIu32
  1632. "), must be between 1 and %d",
  1633. conf->max_write_zeroes_sectors,
  1634. (int)BDRV_REQUEST_MAX_SECTORS);
  1635. return;
  1636. }
  1637. s->config_size = virtio_get_config_size(&virtio_blk_cfg_size_params,
  1638. s->host_features);
  1639. virtio_init(vdev, VIRTIO_ID_BLOCK, s->config_size);
  1640. qemu_mutex_init(&s->rq_lock);
  1641. s->blk = conf->conf.blk;
  1642. s->rq = NULL;
  1643. s->sector_mask = (s->conf.conf.logical_block_size / BDRV_SECTOR_SIZE) - 1;
  1644. for (i = 0; i < conf->num_queues; i++) {
  1645. virtio_add_queue(vdev, conf->queue_size, virtio_blk_handle_output);
  1646. }
  1647. qemu_coroutine_inc_pool_size(conf->num_queues * conf->queue_size / 2);
  1648. /* Don't start ioeventfd if transport does not support notifiers. */
  1649. if (!virtio_device_ioeventfd_enabled(vdev)) {
  1650. s->ioeventfd_disabled = true;
  1651. }
  1652. virtio_blk_vq_aio_context_init(s, &err);
  1653. if (err != NULL) {
  1654. error_propagate(errp, err);
  1655. for (i = 0; i < conf->num_queues; i++) {
  1656. virtio_del_queue(vdev, i);
  1657. }
  1658. virtio_cleanup(vdev);
  1659. return;
  1660. }
  1661. /*
  1662. * This must be after virtio_init() so virtio_blk_dma_restart_cb() gets
  1663. * called after ->start_ioeventfd() has already set blk's AioContext.
  1664. */
  1665. s->change =
  1666. qdev_add_vm_change_state_handler(dev, virtio_blk_dma_restart_cb, s);
  1667. blk_ram_registrar_init(&s->blk_ram_registrar, s->blk);
  1668. blk_set_dev_ops(s->blk, &virtio_block_ops, s);
  1669. blk_iostatus_enable(s->blk);
  1670. add_boot_device_lchs(dev, "/disk@0,0",
  1671. conf->conf.lcyls,
  1672. conf->conf.lheads,
  1673. conf->conf.lsecs);
  1674. }
  1675. static void virtio_blk_device_unrealize(DeviceState *dev)
  1676. {
  1677. VirtIODevice *vdev = VIRTIO_DEVICE(dev);
  1678. VirtIOBlock *s = VIRTIO_BLK(dev);
  1679. VirtIOBlkConf *conf = &s->conf;
  1680. unsigned i;
  1681. blk_drain(s->blk);
  1682. del_boot_device_lchs(dev, "/disk@0,0");
  1683. virtio_blk_vq_aio_context_cleanup(s);
  1684. for (i = 0; i < conf->num_queues; i++) {
  1685. virtio_del_queue(vdev, i);
  1686. }
  1687. qemu_coroutine_dec_pool_size(conf->num_queues * conf->queue_size / 2);
  1688. qemu_mutex_destroy(&s->rq_lock);
  1689. blk_ram_registrar_destroy(&s->blk_ram_registrar);
  1690. qemu_del_vm_change_state_handler(s->change);
  1691. blockdev_mark_auto_del(s->blk);
  1692. virtio_cleanup(vdev);
  1693. }
  1694. static void virtio_blk_instance_init(Object *obj)
  1695. {
  1696. VirtIOBlock *s = VIRTIO_BLK(obj);
  1697. device_add_bootindex_property(obj, &s->conf.conf.bootindex,
  1698. "bootindex", "/disk@0,0",
  1699. DEVICE(obj));
  1700. }
  1701. static const VMStateDescription vmstate_virtio_blk = {
  1702. .name = "virtio-blk",
  1703. .minimum_version_id = 2,
  1704. .version_id = 2,
  1705. .fields = (const VMStateField[]) {
  1706. VMSTATE_VIRTIO_DEVICE,
  1707. VMSTATE_END_OF_LIST()
  1708. },
  1709. };
  1710. static const Property virtio_blk_properties[] = {
  1711. DEFINE_BLOCK_PROPERTIES(VirtIOBlock, conf.conf),
  1712. DEFINE_BLOCK_ERROR_PROPERTIES(VirtIOBlock, conf.conf),
  1713. DEFINE_BLOCK_CHS_PROPERTIES(VirtIOBlock, conf.conf),
  1714. DEFINE_PROP_STRING("serial", VirtIOBlock, conf.serial),
  1715. DEFINE_PROP_BIT64("config-wce", VirtIOBlock, host_features,
  1716. VIRTIO_BLK_F_CONFIG_WCE, true),
  1717. DEFINE_PROP_BIT("request-merging", VirtIOBlock, conf.request_merging, 0,
  1718. true),
  1719. DEFINE_PROP_UINT16("num-queues", VirtIOBlock, conf.num_queues,
  1720. VIRTIO_BLK_AUTO_NUM_QUEUES),
  1721. DEFINE_PROP_UINT16("queue-size", VirtIOBlock, conf.queue_size, 256),
  1722. DEFINE_PROP_BOOL("seg-max-adjust", VirtIOBlock, conf.seg_max_adjust, true),
  1723. DEFINE_PROP_LINK("iothread", VirtIOBlock, conf.iothread, TYPE_IOTHREAD,
  1724. IOThread *),
  1725. DEFINE_PROP_IOTHREAD_VQ_MAPPING_LIST("iothread-vq-mapping", VirtIOBlock,
  1726. conf.iothread_vq_mapping_list),
  1727. DEFINE_PROP_BIT64("discard", VirtIOBlock, host_features,
  1728. VIRTIO_BLK_F_DISCARD, true),
  1729. DEFINE_PROP_BOOL("report-discard-granularity", VirtIOBlock,
  1730. conf.report_discard_granularity, true),
  1731. DEFINE_PROP_BIT64("write-zeroes", VirtIOBlock, host_features,
  1732. VIRTIO_BLK_F_WRITE_ZEROES, true),
  1733. DEFINE_PROP_UINT32("max-discard-sectors", VirtIOBlock,
  1734. conf.max_discard_sectors, BDRV_REQUEST_MAX_SECTORS),
  1735. DEFINE_PROP_UINT32("max-write-zeroes-sectors", VirtIOBlock,
  1736. conf.max_write_zeroes_sectors, BDRV_REQUEST_MAX_SECTORS),
  1737. DEFINE_PROP_BOOL("x-enable-wce-if-config-wce", VirtIOBlock,
  1738. conf.x_enable_wce_if_config_wce, true),
  1739. };
  1740. static void virtio_blk_class_init(ObjectClass *klass, void *data)
  1741. {
  1742. DeviceClass *dc = DEVICE_CLASS(klass);
  1743. VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);
  1744. device_class_set_props(dc, virtio_blk_properties);
  1745. dc->vmsd = &vmstate_virtio_blk;
  1746. set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
  1747. vdc->realize = virtio_blk_device_realize;
  1748. vdc->unrealize = virtio_blk_device_unrealize;
  1749. vdc->get_config = virtio_blk_update_config;
  1750. vdc->set_config = virtio_blk_set_config;
  1751. vdc->get_features = virtio_blk_get_features;
  1752. vdc->set_status = virtio_blk_set_status;
  1753. vdc->reset = virtio_blk_reset;
  1754. vdc->save = virtio_blk_save_device;
  1755. vdc->load = virtio_blk_load_device;
  1756. vdc->start_ioeventfd = virtio_blk_start_ioeventfd;
  1757. vdc->stop_ioeventfd = virtio_blk_stop_ioeventfd;
  1758. }
  1759. static const TypeInfo virtio_blk_info = {
  1760. .name = TYPE_VIRTIO_BLK,
  1761. .parent = TYPE_VIRTIO_DEVICE,
  1762. .instance_size = sizeof(VirtIOBlock),
  1763. .instance_init = virtio_blk_instance_init,
  1764. .class_init = virtio_blk_class_init,
  1765. };
  1766. static void virtio_register_types(void)
  1767. {
  1768. type_register_static(&virtio_blk_info);
  1769. }
  1770. type_init(virtio_register_types)