direct-io.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * fs/direct-io.c
  4. *
  5. * Copyright (C) 2002, Linus Torvalds.
  6. *
  7. * O_DIRECT
  8. *
  9. * 04Jul2002 Andrew Morton
  10. * Initial version
  11. * 11Sep2002 janetinc@us.ibm.com
  12. * added readv/writev support.
  13. * 29Oct2002 Andrew Morton
  14. * rewrote bio_add_page() support.
  15. * 30Oct2002 pbadari@us.ibm.com
  16. * added support for non-aligned IO.
  17. * 06Nov2002 pbadari@us.ibm.com
  18. * added asynchronous IO support.
  19. * 21Jul2003 nathans@sgi.com
  20. * added IO completion notifier.
  21. */
  22. #include <linux/kernel.h>
  23. #include <linux/module.h>
  24. #include <linux/types.h>
  25. #include <linux/fs.h>
  26. #include <linux/fscrypt.h>
  27. #include <linux/mm.h>
  28. #include <linux/slab.h>
  29. #include <linux/highmem.h>
  30. #include <linux/pagemap.h>
  31. #include <linux/task_io_accounting_ops.h>
  32. #include <linux/bio.h>
  33. #include <linux/wait.h>
  34. #include <linux/err.h>
  35. #include <linux/blkdev.h>
  36. #include <linux/buffer_head.h>
  37. #include <linux/rwsem.h>
  38. #include <linux/uio.h>
  39. #include <linux/atomic.h>
  40. #include <linux/prefetch.h>
  41. #include "internal.h"
  42. /*
  43. * How many user pages to map in one call to get_user_pages(). This determines
  44. * the size of a structure in the slab cache
  45. */
  46. #define DIO_PAGES 64
  47. /*
  48. * Flags for dio_complete()
  49. */
  50. #define DIO_COMPLETE_ASYNC 0x01 /* This is async IO */
  51. #define DIO_COMPLETE_INVALIDATE 0x02 /* Can invalidate pages */
  52. /*
  53. * This code generally works in units of "dio_blocks". A dio_block is
  54. * somewhere between the hard sector size and the filesystem block size. it
  55. * is determined on a per-invocation basis. When talking to the filesystem
  56. * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
  57. * down by dio->blkfactor. Similarly, fs-blocksize quantities are converted
  58. * to bio_block quantities by shifting left by blkfactor.
  59. *
  60. * If blkfactor is zero then the user's request was aligned to the filesystem's
  61. * blocksize.
  62. */
  63. /* dio_state only used in the submission path */
  64. struct dio_submit {
  65. struct bio *bio; /* bio under assembly */
  66. unsigned blkbits; /* doesn't change */
  67. unsigned blkfactor; /* When we're using an alignment which
  68. is finer than the filesystem's soft
  69. blocksize, this specifies how much
  70. finer. blkfactor=2 means 1/4-block
  71. alignment. Does not change */
  72. unsigned start_zero_done; /* flag: sub-blocksize zeroing has
  73. been performed at the start of a
  74. write */
  75. int pages_in_io; /* approximate total IO pages */
  76. sector_t block_in_file; /* Current offset into the underlying
  77. file in dio_block units. */
  78. unsigned blocks_available; /* At block_in_file. changes */
  79. int reap_counter; /* rate limit reaping */
  80. sector_t final_block_in_request;/* doesn't change */
  81. int boundary; /* prev block is at a boundary */
  82. get_block_t *get_block; /* block mapping function */
  83. dio_submit_t *submit_io; /* IO submition function */
  84. loff_t logical_offset_in_bio; /* current first logical block in bio */
  85. sector_t final_block_in_bio; /* current final block in bio + 1 */
  86. sector_t next_block_for_io; /* next block to be put under IO,
  87. in dio_blocks units */
  88. /*
  89. * Deferred addition of a page to the dio. These variables are
  90. * private to dio_send_cur_page(), submit_page_section() and
  91. * dio_bio_add_page().
  92. */
  93. struct page *cur_page; /* The page */
  94. unsigned cur_page_offset; /* Offset into it, in bytes */
  95. unsigned cur_page_len; /* Nr of bytes at cur_page_offset */
  96. sector_t cur_page_block; /* Where it starts */
  97. loff_t cur_page_fs_offset; /* Offset in file */
  98. struct iov_iter *iter;
  99. /*
  100. * Page queue. These variables belong to dio_refill_pages() and
  101. * dio_get_page().
  102. */
  103. unsigned head; /* next page to process */
  104. unsigned tail; /* last valid page + 1 */
  105. size_t from, to;
  106. };
  107. /* dio_state communicated between submission path and end_io */
  108. struct dio {
  109. int flags; /* doesn't change */
  110. int op;
  111. int op_flags;
  112. blk_qc_t bio_cookie;
  113. struct gendisk *bio_disk;
  114. struct inode *inode;
  115. loff_t i_size; /* i_size when submitted */
  116. dio_iodone_t *end_io; /* IO completion function */
  117. void *private; /* copy from map_bh.b_private */
  118. /* BIO completion state */
  119. spinlock_t bio_lock; /* protects BIO fields below */
  120. int page_errors; /* errno from get_user_pages() */
  121. int is_async; /* is IO async ? */
  122. bool defer_completion; /* defer AIO completion to workqueue? */
  123. bool should_dirty; /* if pages should be dirtied */
  124. int io_error; /* IO error in completion path */
  125. unsigned long refcount; /* direct_io_worker() and bios */
  126. struct bio *bio_list; /* singly linked via bi_private */
  127. struct task_struct *waiter; /* waiting task (NULL if none) */
  128. /* AIO related stuff */
  129. struct kiocb *iocb; /* kiocb */
  130. ssize_t result; /* IO result */
  131. /*
  132. * pages[] (and any fields placed after it) are not zeroed out at
  133. * allocation time. Don't add new fields after pages[] unless you
  134. * wish that they not be zeroed.
  135. */
  136. union {
  137. struct page *pages[DIO_PAGES]; /* page buffer */
  138. struct work_struct complete_work;/* deferred AIO completion */
  139. };
  140. } ____cacheline_aligned_in_smp;
  141. static struct kmem_cache *dio_cache __read_mostly;
  142. /*
  143. * How many pages are in the queue?
  144. */
  145. static inline unsigned dio_pages_present(struct dio_submit *sdio)
  146. {
  147. return sdio->tail - sdio->head;
  148. }
  149. /*
  150. * Go grab and pin some userspace pages. Typically we'll get 64 at a time.
  151. */
  152. static inline int dio_refill_pages(struct dio *dio, struct dio_submit *sdio)
  153. {
  154. ssize_t ret;
  155. ret = iov_iter_get_pages(sdio->iter, dio->pages, LONG_MAX, DIO_PAGES,
  156. &sdio->from);
  157. if (ret < 0 && sdio->blocks_available && (dio->op == REQ_OP_WRITE)) {
  158. struct page *page = ZERO_PAGE(0);
  159. /*
  160. * A memory fault, but the filesystem has some outstanding
  161. * mapped blocks. We need to use those blocks up to avoid
  162. * leaking stale data in the file.
  163. */
  164. if (dio->page_errors == 0)
  165. dio->page_errors = ret;
  166. get_page(page);
  167. dio->pages[0] = page;
  168. sdio->head = 0;
  169. sdio->tail = 1;
  170. sdio->from = 0;
  171. sdio->to = PAGE_SIZE;
  172. return 0;
  173. }
  174. if (ret >= 0) {
  175. iov_iter_advance(sdio->iter, ret);
  176. ret += sdio->from;
  177. sdio->head = 0;
  178. sdio->tail = (ret + PAGE_SIZE - 1) / PAGE_SIZE;
  179. sdio->to = ((ret - 1) & (PAGE_SIZE - 1)) + 1;
  180. return 0;
  181. }
  182. return ret;
  183. }
  184. /*
  185. * Get another userspace page. Returns an ERR_PTR on error. Pages are
  186. * buffered inside the dio so that we can call get_user_pages() against a
  187. * decent number of pages, less frequently. To provide nicer use of the
  188. * L1 cache.
  189. */
  190. static inline struct page *dio_get_page(struct dio *dio,
  191. struct dio_submit *sdio)
  192. {
  193. if (dio_pages_present(sdio) == 0) {
  194. int ret;
  195. ret = dio_refill_pages(dio, sdio);
  196. if (ret)
  197. return ERR_PTR(ret);
  198. BUG_ON(dio_pages_present(sdio) == 0);
  199. }
  200. return dio->pages[sdio->head];
  201. }
  202. /*
  203. * dio_complete() - called when all DIO BIO I/O has been completed
  204. *
  205. * This drops i_dio_count, lets interested parties know that a DIO operation
  206. * has completed, and calculates the resulting return code for the operation.
  207. *
  208. * It lets the filesystem know if it registered an interest earlier via
  209. * get_block. Pass the private field of the map buffer_head so that
  210. * filesystems can use it to hold additional state between get_block calls and
  211. * dio_complete.
  212. */
  213. static ssize_t dio_complete(struct dio *dio, ssize_t ret, unsigned int flags)
  214. {
  215. loff_t offset = dio->iocb->ki_pos;
  216. ssize_t transferred = 0;
  217. int err;
  218. /*
  219. * AIO submission can race with bio completion to get here while
  220. * expecting to have the last io completed by bio completion.
  221. * In that case -EIOCBQUEUED is in fact not an error we want
  222. * to preserve through this call.
  223. */
  224. if (ret == -EIOCBQUEUED)
  225. ret = 0;
  226. if (dio->result) {
  227. transferred = dio->result;
  228. /* Check for short read case */
  229. if ((dio->op == REQ_OP_READ) &&
  230. ((offset + transferred) > dio->i_size))
  231. transferred = dio->i_size - offset;
  232. /* ignore EFAULT if some IO has been done */
  233. if (unlikely(ret == -EFAULT) && transferred)
  234. ret = 0;
  235. }
  236. if (ret == 0)
  237. ret = dio->page_errors;
  238. if (ret == 0)
  239. ret = dio->io_error;
  240. if (ret == 0)
  241. ret = transferred;
  242. if (dio->end_io) {
  243. // XXX: ki_pos??
  244. err = dio->end_io(dio->iocb, offset, ret, dio->private);
  245. if (err)
  246. ret = err;
  247. }
  248. /*
  249. * Try again to invalidate clean pages which might have been cached by
  250. * non-direct readahead, or faulted in by get_user_pages() if the source
  251. * of the write was an mmap'ed region of the file we're writing. Either
  252. * one is a pretty crazy thing to do, so we don't support it 100%. If
  253. * this invalidation fails, tough, the write still worked...
  254. *
  255. * And this page cache invalidation has to be after dio->end_io(), as
  256. * some filesystems convert unwritten extents to real allocations in
  257. * end_io() when necessary, otherwise a racing buffer read would cache
  258. * zeros from unwritten extents.
  259. */
  260. if (flags & DIO_COMPLETE_INVALIDATE &&
  261. ret > 0 && dio->op == REQ_OP_WRITE &&
  262. dio->inode->i_mapping->nrpages) {
  263. err = invalidate_inode_pages2_range(dio->inode->i_mapping,
  264. offset >> PAGE_SHIFT,
  265. (offset + ret - 1) >> PAGE_SHIFT);
  266. if (err)
  267. dio_warn_stale_pagecache(dio->iocb->ki_filp);
  268. }
  269. inode_dio_end(dio->inode);
  270. if (flags & DIO_COMPLETE_ASYNC) {
  271. /*
  272. * generic_write_sync expects ki_pos to have been updated
  273. * already, but the submission path only does this for
  274. * synchronous I/O.
  275. */
  276. dio->iocb->ki_pos += transferred;
  277. if (ret > 0 && dio->op == REQ_OP_WRITE)
  278. ret = generic_write_sync(dio->iocb, ret);
  279. dio->iocb->ki_complete(dio->iocb, ret, 0);
  280. }
  281. kmem_cache_free(dio_cache, dio);
  282. return ret;
  283. }
  284. static void dio_aio_complete_work(struct work_struct *work)
  285. {
  286. struct dio *dio = container_of(work, struct dio, complete_work);
  287. dio_complete(dio, 0, DIO_COMPLETE_ASYNC | DIO_COMPLETE_INVALIDATE);
  288. }
  289. static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio);
  290. /*
  291. * Asynchronous IO callback.
  292. */
  293. static void dio_bio_end_aio(struct bio *bio)
  294. {
  295. struct dio *dio = bio->bi_private;
  296. unsigned long remaining;
  297. unsigned long flags;
  298. bool defer_completion = false;
  299. /* cleanup the bio */
  300. dio_bio_complete(dio, bio);
  301. spin_lock_irqsave(&dio->bio_lock, flags);
  302. remaining = --dio->refcount;
  303. if (remaining == 1 && dio->waiter)
  304. wake_up_process(dio->waiter);
  305. spin_unlock_irqrestore(&dio->bio_lock, flags);
  306. if (remaining == 0) {
  307. /*
  308. * Defer completion when defer_completion is set or
  309. * when the inode has pages mapped and this is AIO write.
  310. * We need to invalidate those pages because there is a
  311. * chance they contain stale data in the case buffered IO
  312. * went in between AIO submission and completion into the
  313. * same region.
  314. */
  315. if (dio->result)
  316. defer_completion = dio->defer_completion ||
  317. (dio->op == REQ_OP_WRITE &&
  318. dio->inode->i_mapping->nrpages);
  319. if (defer_completion) {
  320. INIT_WORK(&dio->complete_work, dio_aio_complete_work);
  321. queue_work(dio->inode->i_sb->s_dio_done_wq,
  322. &dio->complete_work);
  323. } else {
  324. dio_complete(dio, 0, DIO_COMPLETE_ASYNC);
  325. }
  326. }
  327. }
  328. /*
  329. * The BIO completion handler simply queues the BIO up for the process-context
  330. * handler.
  331. *
  332. * During I/O bi_private points at the dio. After I/O, bi_private is used to
  333. * implement a singly-linked list of completed BIOs, at dio->bio_list.
  334. */
  335. static void dio_bio_end_io(struct bio *bio)
  336. {
  337. struct dio *dio = bio->bi_private;
  338. unsigned long flags;
  339. spin_lock_irqsave(&dio->bio_lock, flags);
  340. bio->bi_private = dio->bio_list;
  341. dio->bio_list = bio;
  342. if (--dio->refcount == 1 && dio->waiter)
  343. wake_up_process(dio->waiter);
  344. spin_unlock_irqrestore(&dio->bio_lock, flags);
  345. }
  346. static inline void
  347. dio_bio_alloc(struct dio *dio, struct dio_submit *sdio,
  348. struct block_device *bdev,
  349. sector_t first_sector, int nr_vecs)
  350. {
  351. struct bio *bio;
  352. struct inode *inode = dio->inode;
  353. /*
  354. * bio_alloc() is guaranteed to return a bio when allowed to sleep and
  355. * we request a valid number of vectors.
  356. */
  357. bio = bio_alloc(GFP_KERNEL, nr_vecs);
  358. fscrypt_set_bio_crypt_ctx(bio, inode,
  359. sdio->cur_page_fs_offset >> inode->i_blkbits,
  360. GFP_KERNEL);
  361. bio_set_dev(bio, bdev);
  362. bio->bi_iter.bi_sector = first_sector;
  363. bio_set_op_attrs(bio, dio->op, dio->op_flags);
  364. if (dio->is_async)
  365. bio->bi_end_io = dio_bio_end_aio;
  366. else
  367. bio->bi_end_io = dio_bio_end_io;
  368. bio->bi_write_hint = dio->iocb->ki_hint;
  369. sdio->bio = bio;
  370. sdio->logical_offset_in_bio = sdio->cur_page_fs_offset;
  371. }
  372. /*
  373. * In the AIO read case we speculatively dirty the pages before starting IO.
  374. * During IO completion, any of these pages which happen to have been written
  375. * back will be redirtied by bio_check_pages_dirty().
  376. *
  377. * bios hold a dio reference between submit_bio and ->end_io.
  378. */
  379. static inline void dio_bio_submit(struct dio *dio, struct dio_submit *sdio)
  380. {
  381. struct bio *bio = sdio->bio;
  382. unsigned long flags;
  383. bio->bi_private = dio;
  384. spin_lock_irqsave(&dio->bio_lock, flags);
  385. dio->refcount++;
  386. spin_unlock_irqrestore(&dio->bio_lock, flags);
  387. if (dio->is_async && dio->op == REQ_OP_READ && dio->should_dirty)
  388. bio_set_pages_dirty(bio);
  389. dio->bio_disk = bio->bi_disk;
  390. if (sdio->submit_io) {
  391. sdio->submit_io(bio, dio->inode, sdio->logical_offset_in_bio);
  392. dio->bio_cookie = BLK_QC_T_NONE;
  393. } else
  394. dio->bio_cookie = submit_bio(bio);
  395. sdio->bio = NULL;
  396. sdio->boundary = 0;
  397. sdio->logical_offset_in_bio = 0;
  398. }
  399. /*
  400. * Release any resources in case of a failure
  401. */
  402. static inline void dio_cleanup(struct dio *dio, struct dio_submit *sdio)
  403. {
  404. while (sdio->head < sdio->tail)
  405. put_page(dio->pages[sdio->head++]);
  406. }
  407. /*
  408. * Wait for the next BIO to complete. Remove it and return it. NULL is
  409. * returned once all BIOs have been completed. This must only be called once
  410. * all bios have been issued so that dio->refcount can only decrease. This
  411. * requires that that the caller hold a reference on the dio.
  412. */
  413. static struct bio *dio_await_one(struct dio *dio)
  414. {
  415. unsigned long flags;
  416. struct bio *bio = NULL;
  417. spin_lock_irqsave(&dio->bio_lock, flags);
  418. /*
  419. * Wait as long as the list is empty and there are bios in flight. bio
  420. * completion drops the count, maybe adds to the list, and wakes while
  421. * holding the bio_lock so we don't need set_current_state()'s barrier
  422. * and can call it after testing our condition.
  423. */
  424. while (dio->refcount > 1 && dio->bio_list == NULL) {
  425. __set_current_state(TASK_UNINTERRUPTIBLE);
  426. dio->waiter = current;
  427. spin_unlock_irqrestore(&dio->bio_lock, flags);
  428. if (!(dio->iocb->ki_flags & IOCB_HIPRI) ||
  429. !blk_poll(dio->bio_disk->queue, dio->bio_cookie, true))
  430. blk_io_schedule();
  431. /* wake up sets us TASK_RUNNING */
  432. spin_lock_irqsave(&dio->bio_lock, flags);
  433. dio->waiter = NULL;
  434. }
  435. if (dio->bio_list) {
  436. bio = dio->bio_list;
  437. dio->bio_list = bio->bi_private;
  438. }
  439. spin_unlock_irqrestore(&dio->bio_lock, flags);
  440. return bio;
  441. }
  442. /*
  443. * Process one completed BIO. No locks are held.
  444. */
  445. static blk_status_t dio_bio_complete(struct dio *dio, struct bio *bio)
  446. {
  447. blk_status_t err = bio->bi_status;
  448. bool should_dirty = dio->op == REQ_OP_READ && dio->should_dirty;
  449. if (err) {
  450. if (err == BLK_STS_AGAIN && (bio->bi_opf & REQ_NOWAIT))
  451. dio->io_error = -EAGAIN;
  452. else
  453. dio->io_error = -EIO;
  454. }
  455. if (dio->is_async && should_dirty) {
  456. bio_check_pages_dirty(bio); /* transfers ownership */
  457. } else {
  458. bio_release_pages(bio, should_dirty);
  459. bio_put(bio);
  460. }
  461. return err;
  462. }
  463. /*
  464. * Wait on and process all in-flight BIOs. This must only be called once
  465. * all bios have been issued so that the refcount can only decrease.
  466. * This just waits for all bios to make it through dio_bio_complete. IO
  467. * errors are propagated through dio->io_error and should be propagated via
  468. * dio_complete().
  469. */
  470. static void dio_await_completion(struct dio *dio)
  471. {
  472. struct bio *bio;
  473. do {
  474. bio = dio_await_one(dio);
  475. if (bio)
  476. dio_bio_complete(dio, bio);
  477. } while (bio);
  478. }
  479. /*
  480. * A really large O_DIRECT read or write can generate a lot of BIOs. So
  481. * to keep the memory consumption sane we periodically reap any completed BIOs
  482. * during the BIO generation phase.
  483. *
  484. * This also helps to limit the peak amount of pinned userspace memory.
  485. */
  486. static inline int dio_bio_reap(struct dio *dio, struct dio_submit *sdio)
  487. {
  488. int ret = 0;
  489. if (sdio->reap_counter++ >= 64) {
  490. while (dio->bio_list) {
  491. unsigned long flags;
  492. struct bio *bio;
  493. int ret2;
  494. spin_lock_irqsave(&dio->bio_lock, flags);
  495. bio = dio->bio_list;
  496. dio->bio_list = bio->bi_private;
  497. spin_unlock_irqrestore(&dio->bio_lock, flags);
  498. ret2 = blk_status_to_errno(dio_bio_complete(dio, bio));
  499. if (ret == 0)
  500. ret = ret2;
  501. }
  502. sdio->reap_counter = 0;
  503. }
  504. return ret;
  505. }
  506. /*
  507. * Create workqueue for deferred direct IO completions. We allocate the
  508. * workqueue when it's first needed. This avoids creating workqueue for
  509. * filesystems that don't need it and also allows us to create the workqueue
  510. * late enough so the we can include s_id in the name of the workqueue.
  511. */
  512. int sb_init_dio_done_wq(struct super_block *sb)
  513. {
  514. struct workqueue_struct *old;
  515. struct workqueue_struct *wq = alloc_workqueue("dio/%s",
  516. WQ_MEM_RECLAIM, 0,
  517. sb->s_id);
  518. if (!wq)
  519. return -ENOMEM;
  520. /*
  521. * This has to be atomic as more DIOs can race to create the workqueue
  522. */
  523. old = cmpxchg(&sb->s_dio_done_wq, NULL, wq);
  524. /* Someone created workqueue before us? Free ours... */
  525. if (old)
  526. destroy_workqueue(wq);
  527. return 0;
  528. }
  529. static int dio_set_defer_completion(struct dio *dio)
  530. {
  531. struct super_block *sb = dio->inode->i_sb;
  532. if (dio->defer_completion)
  533. return 0;
  534. dio->defer_completion = true;
  535. if (!sb->s_dio_done_wq)
  536. return sb_init_dio_done_wq(sb);
  537. return 0;
  538. }
  539. /*
  540. * Call into the fs to map some more disk blocks. We record the current number
  541. * of available blocks at sdio->blocks_available. These are in units of the
  542. * fs blocksize, i_blocksize(inode).
  543. *
  544. * The fs is allowed to map lots of blocks at once. If it wants to do that,
  545. * it uses the passed inode-relative block number as the file offset, as usual.
  546. *
  547. * get_block() is passed the number of i_blkbits-sized blocks which direct_io
  548. * has remaining to do. The fs should not map more than this number of blocks.
  549. *
  550. * If the fs has mapped a lot of blocks, it should populate bh->b_size to
  551. * indicate how much contiguous disk space has been made available at
  552. * bh->b_blocknr.
  553. *
  554. * If *any* of the mapped blocks are new, then the fs must set buffer_new().
  555. * This isn't very efficient...
  556. *
  557. * In the case of filesystem holes: the fs may return an arbitrarily-large
  558. * hole by returning an appropriate value in b_size and by clearing
  559. * buffer_mapped(). However the direct-io code will only process holes one
  560. * block at a time - it will repeatedly call get_block() as it walks the hole.
  561. */
  562. static int get_more_blocks(struct dio *dio, struct dio_submit *sdio,
  563. struct buffer_head *map_bh)
  564. {
  565. int ret;
  566. sector_t fs_startblk; /* Into file, in filesystem-sized blocks */
  567. sector_t fs_endblk; /* Into file, in filesystem-sized blocks */
  568. unsigned long fs_count; /* Number of filesystem-sized blocks */
  569. int create;
  570. unsigned int i_blkbits = sdio->blkbits + sdio->blkfactor;
  571. loff_t i_size;
  572. /*
  573. * If there was a memory error and we've overwritten all the
  574. * mapped blocks then we can now return that memory error
  575. */
  576. ret = dio->page_errors;
  577. if (ret == 0) {
  578. BUG_ON(sdio->block_in_file >= sdio->final_block_in_request);
  579. fs_startblk = sdio->block_in_file >> sdio->blkfactor;
  580. fs_endblk = (sdio->final_block_in_request - 1) >>
  581. sdio->blkfactor;
  582. fs_count = fs_endblk - fs_startblk + 1;
  583. map_bh->b_state = 0;
  584. map_bh->b_size = fs_count << i_blkbits;
  585. /*
  586. * For writes that could fill holes inside i_size on a
  587. * DIO_SKIP_HOLES filesystem we forbid block creations: only
  588. * overwrites are permitted. We will return early to the caller
  589. * once we see an unmapped buffer head returned, and the caller
  590. * will fall back to buffered I/O.
  591. *
  592. * Otherwise the decision is left to the get_blocks method,
  593. * which may decide to handle it or also return an unmapped
  594. * buffer head.
  595. */
  596. create = dio->op == REQ_OP_WRITE;
  597. if (dio->flags & DIO_SKIP_HOLES) {
  598. i_size = i_size_read(dio->inode);
  599. if (i_size && fs_startblk <= (i_size - 1) >> i_blkbits)
  600. create = 0;
  601. }
  602. ret = (*sdio->get_block)(dio->inode, fs_startblk,
  603. map_bh, create);
  604. /* Store for completion */
  605. dio->private = map_bh->b_private;
  606. if (ret == 0 && buffer_defer_completion(map_bh))
  607. ret = dio_set_defer_completion(dio);
  608. }
  609. return ret;
  610. }
  611. /*
  612. * There is no bio. Make one now.
  613. */
  614. static inline int dio_new_bio(struct dio *dio, struct dio_submit *sdio,
  615. sector_t start_sector, struct buffer_head *map_bh)
  616. {
  617. sector_t sector;
  618. int ret, nr_pages;
  619. ret = dio_bio_reap(dio, sdio);
  620. if (ret)
  621. goto out;
  622. sector = start_sector << (sdio->blkbits - 9);
  623. nr_pages = min(sdio->pages_in_io, BIO_MAX_PAGES);
  624. BUG_ON(nr_pages <= 0);
  625. dio_bio_alloc(dio, sdio, map_bh->b_bdev, sector, nr_pages);
  626. sdio->boundary = 0;
  627. out:
  628. return ret;
  629. }
  630. /*
  631. * Attempt to put the current chunk of 'cur_page' into the current BIO. If
  632. * that was successful then update final_block_in_bio and take a ref against
  633. * the just-added page.
  634. *
  635. * Return zero on success. Non-zero means the caller needs to start a new BIO.
  636. */
  637. static inline int dio_bio_add_page(struct dio_submit *sdio)
  638. {
  639. int ret;
  640. ret = bio_add_page(sdio->bio, sdio->cur_page,
  641. sdio->cur_page_len, sdio->cur_page_offset);
  642. if (ret == sdio->cur_page_len) {
  643. /*
  644. * Decrement count only, if we are done with this page
  645. */
  646. if ((sdio->cur_page_len + sdio->cur_page_offset) == PAGE_SIZE)
  647. sdio->pages_in_io--;
  648. get_page(sdio->cur_page);
  649. sdio->final_block_in_bio = sdio->cur_page_block +
  650. (sdio->cur_page_len >> sdio->blkbits);
  651. ret = 0;
  652. } else {
  653. ret = 1;
  654. }
  655. return ret;
  656. }
  657. /*
  658. * Put cur_page under IO. The section of cur_page which is described by
  659. * cur_page_offset,cur_page_len is put into a BIO. The section of cur_page
  660. * starts on-disk at cur_page_block.
  661. *
  662. * We take a ref against the page here (on behalf of its presence in the bio).
  663. *
  664. * The caller of this function is responsible for removing cur_page from the
  665. * dio, and for dropping the refcount which came from that presence.
  666. */
  667. static inline int dio_send_cur_page(struct dio *dio, struct dio_submit *sdio,
  668. struct buffer_head *map_bh)
  669. {
  670. int ret = 0;
  671. if (sdio->bio) {
  672. loff_t cur_offset = sdio->cur_page_fs_offset;
  673. loff_t bio_next_offset = sdio->logical_offset_in_bio +
  674. sdio->bio->bi_iter.bi_size;
  675. /*
  676. * See whether this new request is contiguous with the old.
  677. *
  678. * Btrfs cannot handle having logically non-contiguous requests
  679. * submitted. For example if you have
  680. *
  681. * Logical: [0-4095][HOLE][8192-12287]
  682. * Physical: [0-4095] [4096-8191]
  683. *
  684. * We cannot submit those pages together as one BIO. So if our
  685. * current logical offset in the file does not equal what would
  686. * be the next logical offset in the bio, submit the bio we
  687. * have.
  688. *
  689. * When fscrypt inline encryption is used, data unit number
  690. * (DUN) contiguity is also required. Normally that's implied
  691. * by logical contiguity. However, certain IV generation
  692. * methods (e.g. IV_INO_LBLK_32) don't guarantee it. So, we
  693. * must explicitly check fscrypt_mergeable_bio() too.
  694. */
  695. if (sdio->final_block_in_bio != sdio->cur_page_block ||
  696. cur_offset != bio_next_offset ||
  697. !fscrypt_mergeable_bio(sdio->bio, dio->inode,
  698. cur_offset >> dio->inode->i_blkbits))
  699. dio_bio_submit(dio, sdio);
  700. }
  701. if (sdio->bio == NULL) {
  702. ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
  703. if (ret)
  704. goto out;
  705. }
  706. if (dio_bio_add_page(sdio) != 0) {
  707. dio_bio_submit(dio, sdio);
  708. ret = dio_new_bio(dio, sdio, sdio->cur_page_block, map_bh);
  709. if (ret == 0) {
  710. ret = dio_bio_add_page(sdio);
  711. BUG_ON(ret != 0);
  712. }
  713. }
  714. out:
  715. return ret;
  716. }
  717. /*
  718. * An autonomous function to put a chunk of a page under deferred IO.
  719. *
  720. * The caller doesn't actually know (or care) whether this piece of page is in
  721. * a BIO, or is under IO or whatever. We just take care of all possible
  722. * situations here. The separation between the logic of do_direct_IO() and
  723. * that of submit_page_section() is important for clarity. Please don't break.
  724. *
  725. * The chunk of page starts on-disk at blocknr.
  726. *
  727. * We perform deferred IO, by recording the last-submitted page inside our
  728. * private part of the dio structure. If possible, we just expand the IO
  729. * across that page here.
  730. *
  731. * If that doesn't work out then we put the old page into the bio and add this
  732. * page to the dio instead.
  733. */
  734. static inline int
  735. submit_page_section(struct dio *dio, struct dio_submit *sdio, struct page *page,
  736. unsigned offset, unsigned len, sector_t blocknr,
  737. struct buffer_head *map_bh)
  738. {
  739. int ret = 0;
  740. int boundary = sdio->boundary; /* dio_send_cur_page may clear it */
  741. if (dio->op == REQ_OP_WRITE) {
  742. /*
  743. * Read accounting is performed in submit_bio()
  744. */
  745. task_io_account_write(len);
  746. }
  747. /*
  748. * Can we just grow the current page's presence in the dio?
  749. */
  750. if (sdio->cur_page == page &&
  751. sdio->cur_page_offset + sdio->cur_page_len == offset &&
  752. sdio->cur_page_block +
  753. (sdio->cur_page_len >> sdio->blkbits) == blocknr) {
  754. sdio->cur_page_len += len;
  755. goto out;
  756. }
  757. /*
  758. * If there's a deferred page already there then send it.
  759. */
  760. if (sdio->cur_page) {
  761. ret = dio_send_cur_page(dio, sdio, map_bh);
  762. put_page(sdio->cur_page);
  763. sdio->cur_page = NULL;
  764. if (ret)
  765. return ret;
  766. }
  767. get_page(page); /* It is in dio */
  768. sdio->cur_page = page;
  769. sdio->cur_page_offset = offset;
  770. sdio->cur_page_len = len;
  771. sdio->cur_page_block = blocknr;
  772. sdio->cur_page_fs_offset = sdio->block_in_file << sdio->blkbits;
  773. out:
  774. /*
  775. * If boundary then we want to schedule the IO now to
  776. * avoid metadata seeks.
  777. */
  778. if (boundary) {
  779. ret = dio_send_cur_page(dio, sdio, map_bh);
  780. if (sdio->bio)
  781. dio_bio_submit(dio, sdio);
  782. put_page(sdio->cur_page);
  783. sdio->cur_page = NULL;
  784. }
  785. return ret;
  786. }
  787. /*
  788. * If we are not writing the entire block and get_block() allocated
  789. * the block for us, we need to fill-in the unused portion of the
  790. * block with zeros. This happens only if user-buffer, fileoffset or
  791. * io length is not filesystem block-size multiple.
  792. *
  793. * `end' is zero if we're doing the start of the IO, 1 at the end of the
  794. * IO.
  795. */
  796. static inline void dio_zero_block(struct dio *dio, struct dio_submit *sdio,
  797. int end, struct buffer_head *map_bh)
  798. {
  799. unsigned dio_blocks_per_fs_block;
  800. unsigned this_chunk_blocks; /* In dio_blocks */
  801. unsigned this_chunk_bytes;
  802. struct page *page;
  803. sdio->start_zero_done = 1;
  804. if (!sdio->blkfactor || !buffer_new(map_bh))
  805. return;
  806. dio_blocks_per_fs_block = 1 << sdio->blkfactor;
  807. this_chunk_blocks = sdio->block_in_file & (dio_blocks_per_fs_block - 1);
  808. if (!this_chunk_blocks)
  809. return;
  810. /*
  811. * We need to zero out part of an fs block. It is either at the
  812. * beginning or the end of the fs block.
  813. */
  814. if (end)
  815. this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
  816. this_chunk_bytes = this_chunk_blocks << sdio->blkbits;
  817. page = ZERO_PAGE(0);
  818. if (submit_page_section(dio, sdio, page, 0, this_chunk_bytes,
  819. sdio->next_block_for_io, map_bh))
  820. return;
  821. sdio->next_block_for_io += this_chunk_blocks;
  822. }
  823. /*
  824. * Walk the user pages, and the file, mapping blocks to disk and generating
  825. * a sequence of (page,offset,len,block) mappings. These mappings are injected
  826. * into submit_page_section(), which takes care of the next stage of submission
  827. *
  828. * Direct IO against a blockdev is different from a file. Because we can
  829. * happily perform page-sized but 512-byte aligned IOs. It is important that
  830. * blockdev IO be able to have fine alignment and large sizes.
  831. *
  832. * So what we do is to permit the ->get_block function to populate bh.b_size
  833. * with the size of IO which is permitted at this offset and this i_blkbits.
  834. *
  835. * For best results, the blockdev should be set up with 512-byte i_blkbits and
  836. * it should set b_size to PAGE_SIZE or more inside get_block(). This gives
  837. * fine alignment but still allows this function to work in PAGE_SIZE units.
  838. */
  839. static int do_direct_IO(struct dio *dio, struct dio_submit *sdio,
  840. struct buffer_head *map_bh)
  841. {
  842. const unsigned blkbits = sdio->blkbits;
  843. const unsigned i_blkbits = blkbits + sdio->blkfactor;
  844. int ret = 0;
  845. while (sdio->block_in_file < sdio->final_block_in_request) {
  846. struct page *page;
  847. size_t from, to;
  848. page = dio_get_page(dio, sdio);
  849. if (IS_ERR(page)) {
  850. ret = PTR_ERR(page);
  851. goto out;
  852. }
  853. from = sdio->head ? 0 : sdio->from;
  854. to = (sdio->head == sdio->tail - 1) ? sdio->to : PAGE_SIZE;
  855. sdio->head++;
  856. while (from < to) {
  857. unsigned this_chunk_bytes; /* # of bytes mapped */
  858. unsigned this_chunk_blocks; /* # of blocks */
  859. unsigned u;
  860. if (sdio->blocks_available == 0) {
  861. /*
  862. * Need to go and map some more disk
  863. */
  864. unsigned long blkmask;
  865. unsigned long dio_remainder;
  866. ret = get_more_blocks(dio, sdio, map_bh);
  867. if (ret) {
  868. put_page(page);
  869. goto out;
  870. }
  871. if (!buffer_mapped(map_bh))
  872. goto do_holes;
  873. sdio->blocks_available =
  874. map_bh->b_size >> blkbits;
  875. sdio->next_block_for_io =
  876. map_bh->b_blocknr << sdio->blkfactor;
  877. if (buffer_new(map_bh)) {
  878. clean_bdev_aliases(
  879. map_bh->b_bdev,
  880. map_bh->b_blocknr,
  881. map_bh->b_size >> i_blkbits);
  882. }
  883. if (!sdio->blkfactor)
  884. goto do_holes;
  885. blkmask = (1 << sdio->blkfactor) - 1;
  886. dio_remainder = (sdio->block_in_file & blkmask);
  887. /*
  888. * If we are at the start of IO and that IO
  889. * starts partway into a fs-block,
  890. * dio_remainder will be non-zero. If the IO
  891. * is a read then we can simply advance the IO
  892. * cursor to the first block which is to be
  893. * read. But if the IO is a write and the
  894. * block was newly allocated we cannot do that;
  895. * the start of the fs block must be zeroed out
  896. * on-disk
  897. */
  898. if (!buffer_new(map_bh))
  899. sdio->next_block_for_io += dio_remainder;
  900. sdio->blocks_available -= dio_remainder;
  901. }
  902. do_holes:
  903. /* Handle holes */
  904. if (!buffer_mapped(map_bh)) {
  905. loff_t i_size_aligned;
  906. /* AKPM: eargh, -ENOTBLK is a hack */
  907. if (dio->op == REQ_OP_WRITE) {
  908. put_page(page);
  909. return -ENOTBLK;
  910. }
  911. /*
  912. * Be sure to account for a partial block as the
  913. * last block in the file
  914. */
  915. i_size_aligned = ALIGN(i_size_read(dio->inode),
  916. 1 << blkbits);
  917. if (sdio->block_in_file >=
  918. i_size_aligned >> blkbits) {
  919. /* We hit eof */
  920. put_page(page);
  921. goto out;
  922. }
  923. zero_user(page, from, 1 << blkbits);
  924. sdio->block_in_file++;
  925. from += 1 << blkbits;
  926. dio->result += 1 << blkbits;
  927. goto next_block;
  928. }
  929. /*
  930. * If we're performing IO which has an alignment which
  931. * is finer than the underlying fs, go check to see if
  932. * we must zero out the start of this block.
  933. */
  934. if (unlikely(sdio->blkfactor && !sdio->start_zero_done))
  935. dio_zero_block(dio, sdio, 0, map_bh);
  936. /*
  937. * Work out, in this_chunk_blocks, how much disk we
  938. * can add to this page
  939. */
  940. this_chunk_blocks = sdio->blocks_available;
  941. u = (to - from) >> blkbits;
  942. if (this_chunk_blocks > u)
  943. this_chunk_blocks = u;
  944. u = sdio->final_block_in_request - sdio->block_in_file;
  945. if (this_chunk_blocks > u)
  946. this_chunk_blocks = u;
  947. this_chunk_bytes = this_chunk_blocks << blkbits;
  948. BUG_ON(this_chunk_bytes == 0);
  949. if (this_chunk_blocks == sdio->blocks_available)
  950. sdio->boundary = buffer_boundary(map_bh);
  951. ret = submit_page_section(dio, sdio, page,
  952. from,
  953. this_chunk_bytes,
  954. sdio->next_block_for_io,
  955. map_bh);
  956. if (ret) {
  957. put_page(page);
  958. goto out;
  959. }
  960. sdio->next_block_for_io += this_chunk_blocks;
  961. sdio->block_in_file += this_chunk_blocks;
  962. from += this_chunk_bytes;
  963. dio->result += this_chunk_bytes;
  964. sdio->blocks_available -= this_chunk_blocks;
  965. next_block:
  966. BUG_ON(sdio->block_in_file > sdio->final_block_in_request);
  967. if (sdio->block_in_file == sdio->final_block_in_request)
  968. break;
  969. }
  970. /* Drop the ref which was taken in get_user_pages() */
  971. put_page(page);
  972. }
  973. out:
  974. return ret;
  975. }
  976. static inline int drop_refcount(struct dio *dio)
  977. {
  978. int ret2;
  979. unsigned long flags;
  980. /*
  981. * Sync will always be dropping the final ref and completing the
  982. * operation. AIO can if it was a broken operation described above or
  983. * in fact if all the bios race to complete before we get here. In
  984. * that case dio_complete() translates the EIOCBQUEUED into the proper
  985. * return code that the caller will hand to ->complete().
  986. *
  987. * This is managed by the bio_lock instead of being an atomic_t so that
  988. * completion paths can drop their ref and use the remaining count to
  989. * decide to wake the submission path atomically.
  990. */
  991. spin_lock_irqsave(&dio->bio_lock, flags);
  992. ret2 = --dio->refcount;
  993. spin_unlock_irqrestore(&dio->bio_lock, flags);
  994. return ret2;
  995. }
  996. /*
  997. * This is a library function for use by filesystem drivers.
  998. *
  999. * The locking rules are governed by the flags parameter:
  1000. * - if the flags value contains DIO_LOCKING we use a fancy locking
  1001. * scheme for dumb filesystems.
  1002. * For writes this function is called under i_mutex and returns with
  1003. * i_mutex held, for reads, i_mutex is not held on entry, but it is
  1004. * taken and dropped again before returning.
  1005. * - if the flags value does NOT contain DIO_LOCKING we don't use any
  1006. * internal locking but rather rely on the filesystem to synchronize
  1007. * direct I/O reads/writes versus each other and truncate.
  1008. *
  1009. * To help with locking against truncate we incremented the i_dio_count
  1010. * counter before starting direct I/O, and decrement it once we are done.
  1011. * Truncate can wait for it to reach zero to provide exclusion. It is
  1012. * expected that filesystem provide exclusion between new direct I/O
  1013. * and truncates. For DIO_LOCKING filesystems this is done by i_mutex,
  1014. * but other filesystems need to take care of this on their own.
  1015. *
  1016. * NOTE: if you pass "sdio" to anything by pointer make sure that function
  1017. * is always inlined. Otherwise gcc is unable to split the structure into
  1018. * individual fields and will generate much worse code. This is important
  1019. * for the whole file.
  1020. */
  1021. static inline ssize_t
  1022. do_blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
  1023. struct block_device *bdev, struct iov_iter *iter,
  1024. get_block_t get_block, dio_iodone_t end_io,
  1025. dio_submit_t submit_io, int flags)
  1026. {
  1027. unsigned i_blkbits = READ_ONCE(inode->i_blkbits);
  1028. unsigned blkbits = i_blkbits;
  1029. unsigned blocksize_mask = (1 << blkbits) - 1;
  1030. ssize_t retval = -EINVAL;
  1031. const size_t count = iov_iter_count(iter);
  1032. loff_t offset = iocb->ki_pos;
  1033. const loff_t end = offset + count;
  1034. struct dio *dio;
  1035. struct dio_submit sdio = { 0, };
  1036. struct buffer_head map_bh = { 0, };
  1037. struct blk_plug plug;
  1038. unsigned long align = offset | iov_iter_alignment(iter);
  1039. /*
  1040. * Avoid references to bdev if not absolutely needed to give
  1041. * the early prefetch in the caller enough time.
  1042. */
  1043. /* watch out for a 0 len io from a tricksy fs */
  1044. if (iov_iter_rw(iter) == READ && !count)
  1045. return 0;
  1046. dio = kmem_cache_alloc(dio_cache, GFP_KERNEL);
  1047. if (!dio)
  1048. return -ENOMEM;
  1049. /*
  1050. * Believe it or not, zeroing out the page array caused a .5%
  1051. * performance regression in a database benchmark. So, we take
  1052. * care to only zero out what's needed.
  1053. */
  1054. memset(dio, 0, offsetof(struct dio, pages));
  1055. dio->flags = flags;
  1056. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
  1057. /* will be released by direct_io_worker */
  1058. inode_lock(inode);
  1059. }
  1060. /* Once we sampled i_size check for reads beyond EOF */
  1061. dio->i_size = i_size_read(inode);
  1062. if (iov_iter_rw(iter) == READ && offset >= dio->i_size) {
  1063. retval = 0;
  1064. goto fail_dio;
  1065. }
  1066. if (align & blocksize_mask) {
  1067. if (bdev)
  1068. blkbits = blksize_bits(bdev_logical_block_size(bdev));
  1069. blocksize_mask = (1 << blkbits) - 1;
  1070. if (align & blocksize_mask)
  1071. goto fail_dio;
  1072. }
  1073. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ) {
  1074. struct address_space *mapping = iocb->ki_filp->f_mapping;
  1075. retval = filemap_write_and_wait_range(mapping, offset, end - 1);
  1076. if (retval)
  1077. goto fail_dio;
  1078. }
  1079. /*
  1080. * For file extending writes updating i_size before data writeouts
  1081. * complete can expose uninitialized blocks in dumb filesystems.
  1082. * In that case we need to wait for I/O completion even if asked
  1083. * for an asynchronous write.
  1084. */
  1085. if (is_sync_kiocb(iocb))
  1086. dio->is_async = false;
  1087. else if (iov_iter_rw(iter) == WRITE && end > i_size_read(inode))
  1088. dio->is_async = false;
  1089. else
  1090. dio->is_async = true;
  1091. dio->inode = inode;
  1092. if (iov_iter_rw(iter) == WRITE) {
  1093. dio->op = REQ_OP_WRITE;
  1094. dio->op_flags = REQ_SYNC | REQ_IDLE;
  1095. if (iocb->ki_flags & IOCB_NOWAIT)
  1096. dio->op_flags |= REQ_NOWAIT;
  1097. } else {
  1098. dio->op = REQ_OP_READ;
  1099. }
  1100. if (iocb->ki_flags & IOCB_HIPRI)
  1101. dio->op_flags |= REQ_HIPRI;
  1102. /*
  1103. * For AIO O_(D)SYNC writes we need to defer completions to a workqueue
  1104. * so that we can call ->fsync.
  1105. */
  1106. if (dio->is_async && iov_iter_rw(iter) == WRITE) {
  1107. retval = 0;
  1108. if (iocb->ki_flags & IOCB_DSYNC)
  1109. retval = dio_set_defer_completion(dio);
  1110. else if (!dio->inode->i_sb->s_dio_done_wq) {
  1111. /*
  1112. * In case of AIO write racing with buffered read we
  1113. * need to defer completion. We can't decide this now,
  1114. * however the workqueue needs to be initialized here.
  1115. */
  1116. retval = sb_init_dio_done_wq(dio->inode->i_sb);
  1117. }
  1118. if (retval)
  1119. goto fail_dio;
  1120. }
  1121. /*
  1122. * Will be decremented at I/O completion time.
  1123. */
  1124. inode_dio_begin(inode);
  1125. retval = 0;
  1126. sdio.blkbits = blkbits;
  1127. sdio.blkfactor = i_blkbits - blkbits;
  1128. sdio.block_in_file = offset >> blkbits;
  1129. sdio.get_block = get_block;
  1130. dio->end_io = end_io;
  1131. sdio.submit_io = submit_io;
  1132. sdio.final_block_in_bio = -1;
  1133. sdio.next_block_for_io = -1;
  1134. dio->iocb = iocb;
  1135. spin_lock_init(&dio->bio_lock);
  1136. dio->refcount = 1;
  1137. dio->should_dirty = iter_is_iovec(iter) && iov_iter_rw(iter) == READ;
  1138. sdio.iter = iter;
  1139. sdio.final_block_in_request = end >> blkbits;
  1140. /*
  1141. * In case of non-aligned buffers, we may need 2 more
  1142. * pages since we need to zero out first and last block.
  1143. */
  1144. if (unlikely(sdio.blkfactor))
  1145. sdio.pages_in_io = 2;
  1146. sdio.pages_in_io += iov_iter_npages(iter, INT_MAX);
  1147. blk_start_plug(&plug);
  1148. retval = do_direct_IO(dio, &sdio, &map_bh);
  1149. if (retval)
  1150. dio_cleanup(dio, &sdio);
  1151. if (retval == -ENOTBLK) {
  1152. /*
  1153. * The remaining part of the request will be
  1154. * be handled by buffered I/O when we return
  1155. */
  1156. retval = 0;
  1157. }
  1158. /*
  1159. * There may be some unwritten disk at the end of a part-written
  1160. * fs-block-sized block. Go zero that now.
  1161. */
  1162. dio_zero_block(dio, &sdio, 1, &map_bh);
  1163. if (sdio.cur_page) {
  1164. ssize_t ret2;
  1165. ret2 = dio_send_cur_page(dio, &sdio, &map_bh);
  1166. if (retval == 0)
  1167. retval = ret2;
  1168. put_page(sdio.cur_page);
  1169. sdio.cur_page = NULL;
  1170. }
  1171. if (sdio.bio)
  1172. dio_bio_submit(dio, &sdio);
  1173. blk_finish_plug(&plug);
  1174. /*
  1175. * It is possible that, we return short IO due to end of file.
  1176. * In that case, we need to release all the pages we got hold on.
  1177. */
  1178. dio_cleanup(dio, &sdio);
  1179. /*
  1180. * All block lookups have been performed. For READ requests
  1181. * we can let i_mutex go now that its achieved its purpose
  1182. * of protecting us from looking up uninitialized blocks.
  1183. */
  1184. if (iov_iter_rw(iter) == READ && (dio->flags & DIO_LOCKING))
  1185. inode_unlock(dio->inode);
  1186. /*
  1187. * The only time we want to leave bios in flight is when a successful
  1188. * partial aio read or full aio write have been setup. In that case
  1189. * bio completion will call aio_complete. The only time it's safe to
  1190. * call aio_complete is when we return -EIOCBQUEUED, so we key on that.
  1191. * This had *better* be the only place that raises -EIOCBQUEUED.
  1192. */
  1193. BUG_ON(retval == -EIOCBQUEUED);
  1194. if (dio->is_async && retval == 0 && dio->result &&
  1195. (iov_iter_rw(iter) == READ || dio->result == count))
  1196. retval = -EIOCBQUEUED;
  1197. else
  1198. dio_await_completion(dio);
  1199. if (drop_refcount(dio) == 0) {
  1200. retval = dio_complete(dio, retval, DIO_COMPLETE_INVALIDATE);
  1201. } else
  1202. BUG_ON(retval != -EIOCBQUEUED);
  1203. return retval;
  1204. fail_dio:
  1205. if (dio->flags & DIO_LOCKING && iov_iter_rw(iter) == READ)
  1206. inode_unlock(inode);
  1207. kmem_cache_free(dio_cache, dio);
  1208. return retval;
  1209. }
  1210. ssize_t __blockdev_direct_IO(struct kiocb *iocb, struct inode *inode,
  1211. struct block_device *bdev, struct iov_iter *iter,
  1212. get_block_t get_block,
  1213. dio_iodone_t end_io, dio_submit_t submit_io,
  1214. int flags)
  1215. {
  1216. /*
  1217. * The block device state is needed in the end to finally
  1218. * submit everything. Since it's likely to be cache cold
  1219. * prefetch it here as first thing to hide some of the
  1220. * latency.
  1221. *
  1222. * Attempt to prefetch the pieces we likely need later.
  1223. */
  1224. prefetch(&bdev->bd_disk->part_tbl);
  1225. prefetch(bdev->bd_disk->queue);
  1226. prefetch((char *)bdev->bd_disk->queue + SMP_CACHE_BYTES);
  1227. return do_blockdev_direct_IO(iocb, inode, bdev, iter, get_block,
  1228. end_io, submit_io, flags);
  1229. }
  1230. EXPORT_SYMBOL_NS(__blockdev_direct_IO, ANDROID_GKI_VFS_EXPORT_ONLY);
  1231. static __init int dio_init(void)
  1232. {
  1233. dio_cache = KMEM_CACHE(dio, SLAB_PANIC);
  1234. return 0;
  1235. }
  1236. module_init(dio_init)