direct-io.c 40 KB

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