direct-io.c 34 KB

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