PageRenderTime 63ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/fs/direct-io.c

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