direct-io.c 34 KB

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