direct-io.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  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/bio.h>
  30. #include <linux/wait.h>
  31. #include <linux/err.h>
  32. #include <linux/blkdev.h>
  33. #include <linux/buffer_head.h>
  34. #include <linux/rwsem.h>
  35. #include <linux/uio.h>
  36. #include <asm/atomic.h>
  37. /*
  38. * How many user pages to map in one call to get_user_pages(). This determines
  39. * the size of a structure on the stack.
  40. */
  41. #define DIO_PAGES 64
  42. /*
  43. * This code generally works in units of "dio_blocks". A dio_block is
  44. * somewhere between the hard sector size and the filesystem block size. it
  45. * is determined on a per-invocation basis. When talking to the filesystem
  46. * we need to convert dio_blocks to fs_blocks by scaling the dio_block quantity
  47. * down by dio->blkfactor. Similarly, fs-blocksize quantities are converted
  48. * to bio_block quantities by shifting left by blkfactor.
  49. *
  50. * If blkfactor is zero then the user's request was aligned to the filesystem's
  51. * blocksize.
  52. *
  53. * lock_type is DIO_LOCKING for regular files on direct-IO-naive filesystems.
  54. * This determines whether we need to do the fancy locking which prevents
  55. * direct-IO from being able to read uninitialised disk blocks. If its zero
  56. * (blockdev) this locking is not done, and if it is DIO_OWN_LOCKING i_mutex is
  57. * not held for the entire direct write (taken briefly, initially, during a
  58. * direct read though, but its never held for the duration of a direct-IO).
  59. */
  60. struct dio {
  61. /* BIO submission state */
  62. struct bio *bio; /* bio under assembly */
  63. struct inode *inode;
  64. int rw;
  65. loff_t i_size; /* i_size when submitted */
  66. int lock_type; /* doesn't change */
  67. unsigned blkbits; /* doesn't change */
  68. unsigned blkfactor; /* When we're using an alignment which
  69. is finer than the filesystem's soft
  70. blocksize, this specifies how much
  71. finer. blkfactor=2 means 1/4-block
  72. alignment. Does not change */
  73. unsigned start_zero_done; /* flag: sub-blocksize zeroing has
  74. been performed at the start of a
  75. write */
  76. int pages_in_io; /* approximate total IO pages */
  77. size_t size; /* total request size (doesn't change)*/
  78. sector_t block_in_file; /* Current offset into the underlying
  79. file in dio_block units. */
  80. unsigned blocks_available; /* At block_in_file. changes */
  81. sector_t final_block_in_request;/* doesn't change */
  82. unsigned first_block_in_page; /* doesn't change, Used only once */
  83. int boundary; /* prev block is at a boundary */
  84. int reap_counter; /* rate limit reaping */
  85. get_blocks_t *get_blocks; /* block mapping function */
  86. dio_iodone_t *end_io; /* IO completion function */
  87. sector_t final_block_in_bio; /* current final block in bio + 1 */
  88. sector_t next_block_for_io; /* next block to be put under IO,
  89. in dio_blocks units */
  90. struct buffer_head map_bh; /* last get_blocks() result */
  91. /*
  92. * Deferred addition of a page to the dio. These variables are
  93. * private to dio_send_cur_page(), submit_page_section() and
  94. * dio_bio_add_page().
  95. */
  96. struct page *cur_page; /* The page */
  97. unsigned cur_page_offset; /* Offset into it, in bytes */
  98. unsigned cur_page_len; /* Nr of bytes at cur_page_offset */
  99. sector_t cur_page_block; /* Where it starts */
  100. /*
  101. * Page fetching state. These variables belong to dio_refill_pages().
  102. */
  103. int curr_page; /* changes */
  104. int total_pages; /* doesn't change */
  105. unsigned long curr_user_address;/* changes */
  106. /*
  107. * Page queue. These variables belong to dio_refill_pages() and
  108. * dio_get_page().
  109. */
  110. struct page *pages[DIO_PAGES]; /* page buffer */
  111. unsigned head; /* next page to process */
  112. unsigned tail; /* last valid page + 1 */
  113. int page_errors; /* errno from get_user_pages() */
  114. /* BIO completion state */
  115. spinlock_t bio_lock; /* protects BIO fields below */
  116. int bio_count; /* nr bios to be completed */
  117. int bios_in_flight; /* nr bios in flight */
  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. ssize_t result; /* IO result */
  124. };
  125. /*
  126. * How many pages are in the queue?
  127. */
  128. static inline unsigned dio_pages_present(struct dio *dio)
  129. {
  130. return dio->tail - dio->head;
  131. }
  132. /*
  133. * Go grab and pin some userspace pages. Typically we'll get 64 at a time.
  134. */
  135. static int dio_refill_pages(struct dio *dio)
  136. {
  137. int ret;
  138. int nr_pages;
  139. nr_pages = min(dio->total_pages - dio->curr_page, DIO_PAGES);
  140. down_read(&current->mm->mmap_sem);
  141. ret = get_user_pages(
  142. current, /* Task for fault acounting */
  143. current->mm, /* whose pages? */
  144. dio->curr_user_address, /* Where from? */
  145. nr_pages, /* How many pages? */
  146. dio->rw == READ, /* Write to memory? */
  147. 0, /* force (?) */
  148. &dio->pages[0],
  149. NULL); /* vmas */
  150. up_read(&current->mm->mmap_sem);
  151. if (ret < 0 && dio->blocks_available && (dio->rw == WRITE)) {
  152. struct page *page = ZERO_PAGE(dio->curr_user_address);
  153. /*
  154. * A memory fault, but the filesystem has some outstanding
  155. * mapped blocks. We need to use those blocks up to avoid
  156. * leaking stale data in the file.
  157. */
  158. if (dio->page_errors == 0)
  159. dio->page_errors = ret;
  160. page_cache_get(page);
  161. dio->pages[0] = page;
  162. dio->head = 0;
  163. dio->tail = 1;
  164. ret = 0;
  165. goto out;
  166. }
  167. if (ret >= 0) {
  168. dio->curr_user_address += ret * PAGE_SIZE;
  169. dio->curr_page += ret;
  170. dio->head = 0;
  171. dio->tail = ret;
  172. ret = 0;
  173. }
  174. out:
  175. return ret;
  176. }
  177. /*
  178. * Get another userspace page. Returns an ERR_PTR on error. Pages are
  179. * buffered inside the dio so that we can call get_user_pages() against a
  180. * decent number of pages, less frequently. To provide nicer use of the
  181. * L1 cache.
  182. */
  183. static struct page *dio_get_page(struct dio *dio)
  184. {
  185. if (dio_pages_present(dio) == 0) {
  186. int ret;
  187. ret = dio_refill_pages(dio);
  188. if (ret)
  189. return ERR_PTR(ret);
  190. BUG_ON(dio_pages_present(dio) == 0);
  191. }
  192. return dio->pages[dio->head++];
  193. }
  194. /*
  195. * Called when all DIO BIO I/O has been completed - let the filesystem
  196. * know, if it registered an interest earlier via get_blocks. Pass the
  197. * private field of the map buffer_head so that filesystems can use it
  198. * to hold additional state between get_blocks calls and dio_complete.
  199. */
  200. static void dio_complete(struct dio *dio, loff_t offset, ssize_t bytes)
  201. {
  202. if (dio->end_io && dio->result)
  203. dio->end_io(dio->iocb, offset, bytes, dio->map_bh.b_private);
  204. if (dio->lock_type == DIO_LOCKING)
  205. up_read(&dio->inode->i_alloc_sem);
  206. }
  207. /*
  208. * Called when a BIO has been processed. If the count goes to zero then IO is
  209. * complete and we can signal this to the AIO layer.
  210. */
  211. static void finished_one_bio(struct dio *dio)
  212. {
  213. unsigned long flags;
  214. spin_lock_irqsave(&dio->bio_lock, flags);
  215. if (dio->bio_count == 1) {
  216. if (dio->is_async) {
  217. ssize_t transferred;
  218. loff_t offset;
  219. /*
  220. * Last reference to the dio is going away.
  221. * Drop spinlock and complete the DIO.
  222. */
  223. spin_unlock_irqrestore(&dio->bio_lock, flags);
  224. /* Check for short read case */
  225. transferred = dio->result;
  226. offset = dio->iocb->ki_pos;
  227. if ((dio->rw == READ) &&
  228. ((offset + transferred) > dio->i_size))
  229. transferred = dio->i_size - offset;
  230. dio_complete(dio, offset, transferred);
  231. /* Complete AIO later if falling back to buffered i/o */
  232. if (dio->result == dio->size ||
  233. ((dio->rw == READ) && dio->result)) {
  234. aio_complete(dio->iocb, transferred, 0);
  235. kfree(dio);
  236. return;
  237. } else {
  238. /*
  239. * Falling back to buffered
  240. */
  241. spin_lock_irqsave(&dio->bio_lock, flags);
  242. dio->bio_count--;
  243. if (dio->waiter)
  244. wake_up_process(dio->waiter);
  245. spin_unlock_irqrestore(&dio->bio_lock, flags);
  246. return;
  247. }
  248. }
  249. }
  250. dio->bio_count--;
  251. spin_unlock_irqrestore(&dio->bio_lock, flags);
  252. }
  253. static int dio_bio_complete(struct dio *dio, struct bio *bio);
  254. /*
  255. * Asynchronous IO callback.
  256. */
  257. static int dio_bio_end_aio(struct bio *bio, unsigned int bytes_done, int error)
  258. {
  259. struct dio *dio = bio->bi_private;
  260. if (bio->bi_size)
  261. return 1;
  262. /* cleanup the bio */
  263. dio_bio_complete(dio, bio);
  264. return 0;
  265. }
  266. /*
  267. * The BIO completion handler simply queues the BIO up for the process-context
  268. * handler.
  269. *
  270. * During I/O bi_private points at the dio. After I/O, bi_private is used to
  271. * implement a singly-linked list of completed BIOs, at dio->bio_list.
  272. */
  273. static int dio_bio_end_io(struct bio *bio, unsigned int bytes_done, int error)
  274. {
  275. struct dio *dio = bio->bi_private;
  276. unsigned long flags;
  277. if (bio->bi_size)
  278. return 1;
  279. spin_lock_irqsave(&dio->bio_lock, flags);
  280. bio->bi_private = dio->bio_list;
  281. dio->bio_list = bio;
  282. dio->bios_in_flight--;
  283. if (dio->waiter && dio->bios_in_flight == 0)
  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. static void dio_bio_submit(struct dio *dio)
  311. {
  312. struct bio *bio = dio->bio;
  313. unsigned long flags;
  314. bio->bi_private = dio;
  315. spin_lock_irqsave(&dio->bio_lock, flags);
  316. dio->bio_count++;
  317. dio->bios_in_flight++;
  318. spin_unlock_irqrestore(&dio->bio_lock, flags);
  319. if (dio->is_async && dio->rw == READ)
  320. bio_set_pages_dirty(bio);
  321. submit_bio(dio->rw, bio);
  322. dio->bio = NULL;
  323. dio->boundary = 0;
  324. }
  325. /*
  326. * Release any resources in case of a failure
  327. */
  328. static void dio_cleanup(struct dio *dio)
  329. {
  330. while (dio_pages_present(dio))
  331. page_cache_release(dio_get_page(dio));
  332. }
  333. /*
  334. * Wait for the next BIO to complete. Remove it and return it.
  335. */
  336. static struct bio *dio_await_one(struct dio *dio)
  337. {
  338. unsigned long flags;
  339. struct bio *bio;
  340. spin_lock_irqsave(&dio->bio_lock, flags);
  341. while (dio->bio_list == NULL) {
  342. set_current_state(TASK_UNINTERRUPTIBLE);
  343. if (dio->bio_list == NULL) {
  344. dio->waiter = current;
  345. spin_unlock_irqrestore(&dio->bio_lock, flags);
  346. blk_run_address_space(dio->inode->i_mapping);
  347. io_schedule();
  348. spin_lock_irqsave(&dio->bio_lock, flags);
  349. dio->waiter = NULL;
  350. }
  351. set_current_state(TASK_RUNNING);
  352. }
  353. bio = dio->bio_list;
  354. dio->bio_list = bio->bi_private;
  355. spin_unlock_irqrestore(&dio->bio_lock, flags);
  356. return bio;
  357. }
  358. /*
  359. * Process one completed BIO. No locks are held.
  360. */
  361. static int dio_bio_complete(struct dio *dio, struct bio *bio)
  362. {
  363. const int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags);
  364. struct bio_vec *bvec = bio->bi_io_vec;
  365. int page_no;
  366. if (!uptodate)
  367. dio->result = -EIO;
  368. if (dio->is_async && dio->rw == READ) {
  369. bio_check_pages_dirty(bio); /* transfers ownership */
  370. } else {
  371. for (page_no = 0; page_no < bio->bi_vcnt; page_no++) {
  372. struct page *page = bvec[page_no].bv_page;
  373. if (dio->rw == READ && !PageCompound(page))
  374. set_page_dirty_lock(page);
  375. page_cache_release(page);
  376. }
  377. bio_put(bio);
  378. }
  379. finished_one_bio(dio);
  380. return uptodate ? 0 : -EIO;
  381. }
  382. /*
  383. * Wait on and process all in-flight BIOs.
  384. */
  385. static int dio_await_completion(struct dio *dio)
  386. {
  387. int ret = 0;
  388. if (dio->bio)
  389. dio_bio_submit(dio);
  390. /*
  391. * The bio_lock is not held for the read of bio_count.
  392. * This is ok since it is the dio_bio_complete() that changes
  393. * bio_count.
  394. */
  395. while (dio->bio_count) {
  396. struct bio *bio = dio_await_one(dio);
  397. int ret2;
  398. ret2 = dio_bio_complete(dio, bio);
  399. if (ret == 0)
  400. ret = ret2;
  401. }
  402. return ret;
  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_blocks() 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_blocks() 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. map_bh->b_state = 0;
  470. map_bh->b_size = 0;
  471. BUG_ON(dio->block_in_file >= dio->final_block_in_request);
  472. fs_startblk = dio->block_in_file >> dio->blkfactor;
  473. dio_count = dio->final_block_in_request - dio->block_in_file;
  474. fs_count = dio_count >> dio->blkfactor;
  475. blkmask = (1 << dio->blkfactor) - 1;
  476. if (dio_count & blkmask)
  477. fs_count++;
  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_blocks)(dio->inode, fs_startblk, fs_count,
  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. /*
  607. * Can we just grow the current page's presence in the dio?
  608. */
  609. if ( (dio->cur_page == page) &&
  610. (dio->cur_page_offset + dio->cur_page_len == offset) &&
  611. (dio->cur_page_block +
  612. (dio->cur_page_len >> dio->blkbits) == blocknr)) {
  613. dio->cur_page_len += len;
  614. /*
  615. * If dio->boundary then we want to schedule the IO now to
  616. * avoid metadata seeks.
  617. */
  618. if (dio->boundary) {
  619. ret = dio_send_cur_page(dio);
  620. page_cache_release(dio->cur_page);
  621. dio->cur_page = NULL;
  622. }
  623. goto out;
  624. }
  625. /*
  626. * If there's a deferred page already there then send it.
  627. */
  628. if (dio->cur_page) {
  629. ret = dio_send_cur_page(dio);
  630. page_cache_release(dio->cur_page);
  631. dio->cur_page = NULL;
  632. if (ret)
  633. goto out;
  634. }
  635. page_cache_get(page); /* It is in dio */
  636. dio->cur_page = page;
  637. dio->cur_page_offset = offset;
  638. dio->cur_page_len = len;
  639. dio->cur_page_block = blocknr;
  640. out:
  641. return ret;
  642. }
  643. /*
  644. * Clean any dirty buffers in the blockdev mapping which alias newly-created
  645. * file blocks. Only called for S_ISREG files - blockdevs do not set
  646. * buffer_new
  647. */
  648. static void clean_blockdev_aliases(struct dio *dio)
  649. {
  650. unsigned i;
  651. unsigned nblocks;
  652. nblocks = dio->map_bh.b_size >> dio->inode->i_blkbits;
  653. for (i = 0; i < nblocks; i++) {
  654. unmap_underlying_metadata(dio->map_bh.b_bdev,
  655. dio->map_bh.b_blocknr + i);
  656. }
  657. }
  658. /*
  659. * If we are not writing the entire block and get_block() allocated
  660. * the block for us, we need to fill-in the unused portion of the
  661. * block with zeros. This happens only if user-buffer, fileoffset or
  662. * io length is not filesystem block-size multiple.
  663. *
  664. * `end' is zero if we're doing the start of the IO, 1 at the end of the
  665. * IO.
  666. */
  667. static void dio_zero_block(struct dio *dio, int end)
  668. {
  669. unsigned dio_blocks_per_fs_block;
  670. unsigned this_chunk_blocks; /* In dio_blocks */
  671. unsigned this_chunk_bytes;
  672. struct page *page;
  673. dio->start_zero_done = 1;
  674. if (!dio->blkfactor || !buffer_new(&dio->map_bh))
  675. return;
  676. dio_blocks_per_fs_block = 1 << dio->blkfactor;
  677. this_chunk_blocks = dio->block_in_file & (dio_blocks_per_fs_block - 1);
  678. if (!this_chunk_blocks)
  679. return;
  680. /*
  681. * We need to zero out part of an fs block. It is either at the
  682. * beginning or the end of the fs block.
  683. */
  684. if (end)
  685. this_chunk_blocks = dio_blocks_per_fs_block - this_chunk_blocks;
  686. this_chunk_bytes = this_chunk_blocks << dio->blkbits;
  687. page = ZERO_PAGE(dio->curr_user_address);
  688. if (submit_page_section(dio, page, 0, this_chunk_bytes,
  689. dio->next_block_for_io))
  690. return;
  691. dio->next_block_for_io += this_chunk_blocks;
  692. }
  693. /*
  694. * Walk the user pages, and the file, mapping blocks to disk and generating
  695. * a sequence of (page,offset,len,block) mappings. These mappings are injected
  696. * into submit_page_section(), which takes care of the next stage of submission
  697. *
  698. * Direct IO against a blockdev is different from a file. Because we can
  699. * happily perform page-sized but 512-byte aligned IOs. It is important that
  700. * blockdev IO be able to have fine alignment and large sizes.
  701. *
  702. * So what we do is to permit the ->get_blocks function to populate bh.b_size
  703. * with the size of IO which is permitted at this offset and this i_blkbits.
  704. *
  705. * For best results, the blockdev should be set up with 512-byte i_blkbits and
  706. * it should set b_size to PAGE_SIZE or more inside get_blocks(). This gives
  707. * fine alignment but still allows this function to work in PAGE_SIZE units.
  708. */
  709. static int do_direct_IO(struct dio *dio)
  710. {
  711. const unsigned blkbits = dio->blkbits;
  712. const unsigned blocks_per_page = PAGE_SIZE >> blkbits;
  713. struct page *page;
  714. unsigned block_in_page;
  715. struct buffer_head *map_bh = &dio->map_bh;
  716. int ret = 0;
  717. /* The I/O can start at any block offset within the first page */
  718. block_in_page = dio->first_block_in_page;
  719. while (dio->block_in_file < dio->final_block_in_request) {
  720. page = dio_get_page(dio);
  721. if (IS_ERR(page)) {
  722. ret = PTR_ERR(page);
  723. goto out;
  724. }
  725. while (block_in_page < blocks_per_page) {
  726. unsigned offset_in_page = block_in_page << blkbits;
  727. unsigned this_chunk_bytes; /* # of bytes mapped */
  728. unsigned this_chunk_blocks; /* # of blocks */
  729. unsigned u;
  730. if (dio->blocks_available == 0) {
  731. /*
  732. * Need to go and map some more disk
  733. */
  734. unsigned long blkmask;
  735. unsigned long dio_remainder;
  736. ret = get_more_blocks(dio);
  737. if (ret) {
  738. page_cache_release(page);
  739. goto out;
  740. }
  741. if (!buffer_mapped(map_bh))
  742. goto do_holes;
  743. dio->blocks_available =
  744. map_bh->b_size >> dio->blkbits;
  745. dio->next_block_for_io =
  746. map_bh->b_blocknr << dio->blkfactor;
  747. if (buffer_new(map_bh))
  748. clean_blockdev_aliases(dio);
  749. if (!dio->blkfactor)
  750. goto do_holes;
  751. blkmask = (1 << dio->blkfactor) - 1;
  752. dio_remainder = (dio->block_in_file & blkmask);
  753. /*
  754. * If we are at the start of IO and that IO
  755. * starts partway into a fs-block,
  756. * dio_remainder will be non-zero. If the IO
  757. * is a read then we can simply advance the IO
  758. * cursor to the first block which is to be
  759. * read. But if the IO is a write and the
  760. * block was newly allocated we cannot do that;
  761. * the start of the fs block must be zeroed out
  762. * on-disk
  763. */
  764. if (!buffer_new(map_bh))
  765. dio->next_block_for_io += dio_remainder;
  766. dio->blocks_available -= dio_remainder;
  767. }
  768. do_holes:
  769. /* Handle holes */
  770. if (!buffer_mapped(map_bh)) {
  771. char *kaddr;
  772. /* AKPM: eargh, -ENOTBLK is a hack */
  773. if (dio->rw == WRITE) {
  774. page_cache_release(page);
  775. return -ENOTBLK;
  776. }
  777. if (dio->block_in_file >=
  778. i_size_read(dio->inode)>>blkbits) {
  779. /* We hit eof */
  780. page_cache_release(page);
  781. goto out;
  782. }
  783. kaddr = kmap_atomic(page, KM_USER0);
  784. memset(kaddr + (block_in_page << blkbits),
  785. 0, 1 << blkbits);
  786. flush_dcache_page(page);
  787. kunmap_atomic(kaddr, KM_USER0);
  788. dio->block_in_file++;
  789. block_in_page++;
  790. goto next_block;
  791. }
  792. /*
  793. * If we're performing IO which has an alignment which
  794. * is finer than the underlying fs, go check to see if
  795. * we must zero out the start of this block.
  796. */
  797. if (unlikely(dio->blkfactor && !dio->start_zero_done))
  798. dio_zero_block(dio, 0);
  799. /*
  800. * Work out, in this_chunk_blocks, how much disk we
  801. * can add to this page
  802. */
  803. this_chunk_blocks = dio->blocks_available;
  804. u = (PAGE_SIZE - offset_in_page) >> blkbits;
  805. if (this_chunk_blocks > u)
  806. this_chunk_blocks = u;
  807. u = dio->final_block_in_request - dio->block_in_file;
  808. if (this_chunk_blocks > u)
  809. this_chunk_blocks = u;
  810. this_chunk_bytes = this_chunk_blocks << blkbits;
  811. BUG_ON(this_chunk_bytes == 0);
  812. dio->boundary = buffer_boundary(map_bh);
  813. ret = submit_page_section(dio, page, offset_in_page,
  814. this_chunk_bytes, dio->next_block_for_io);
  815. if (ret) {
  816. page_cache_release(page);
  817. goto out;
  818. }
  819. dio->next_block_for_io += this_chunk_blocks;
  820. dio->block_in_file += this_chunk_blocks;
  821. block_in_page += this_chunk_blocks;
  822. dio->blocks_available -= this_chunk_blocks;
  823. next_block:
  824. if (dio->block_in_file > dio->final_block_in_request)
  825. BUG();
  826. if (dio->block_in_file == dio->final_block_in_request)
  827. break;
  828. }
  829. /* Drop the ref which was taken in get_user_pages() */
  830. page_cache_release(page);
  831. block_in_page = 0;
  832. }
  833. out:
  834. return ret;
  835. }
  836. /*
  837. * Releases both i_mutex and i_alloc_sem
  838. */
  839. static ssize_t
  840. direct_io_worker(int rw, struct kiocb *iocb, struct inode *inode,
  841. const struct iovec *iov, loff_t offset, unsigned long nr_segs,
  842. unsigned blkbits, get_blocks_t get_blocks, dio_iodone_t end_io,
  843. struct dio *dio)
  844. {
  845. unsigned long user_addr;
  846. int seg;
  847. ssize_t ret = 0;
  848. ssize_t ret2;
  849. size_t bytes;
  850. dio->bio = NULL;
  851. dio->inode = inode;
  852. dio->rw = rw;
  853. dio->blkbits = blkbits;
  854. dio->blkfactor = inode->i_blkbits - blkbits;
  855. dio->start_zero_done = 0;
  856. dio->size = 0;
  857. dio->block_in_file = offset >> blkbits;
  858. dio->blocks_available = 0;
  859. dio->cur_page = NULL;
  860. dio->boundary = 0;
  861. dio->reap_counter = 0;
  862. dio->get_blocks = get_blocks;
  863. dio->end_io = end_io;
  864. dio->map_bh.b_private = NULL;
  865. dio->final_block_in_bio = -1;
  866. dio->next_block_for_io = -1;
  867. dio->page_errors = 0;
  868. dio->result = 0;
  869. dio->iocb = iocb;
  870. dio->i_size = i_size_read(inode);
  871. /*
  872. * BIO completion state.
  873. *
  874. * ->bio_count starts out at one, and we decrement it to zero after all
  875. * BIOs are submitted. This to avoid the situation where a really fast
  876. * (or synchronous) device could take the count to zero while we're
  877. * still submitting BIOs.
  878. */
  879. dio->bio_count = 1;
  880. dio->bios_in_flight = 0;
  881. spin_lock_init(&dio->bio_lock);
  882. dio->bio_list = NULL;
  883. dio->waiter = NULL;
  884. /*
  885. * In case of non-aligned buffers, we may need 2 more
  886. * pages since we need to zero out first and last block.
  887. */
  888. if (unlikely(dio->blkfactor))
  889. dio->pages_in_io = 2;
  890. else
  891. dio->pages_in_io = 0;
  892. for (seg = 0; seg < nr_segs; seg++) {
  893. user_addr = (unsigned long)iov[seg].iov_base;
  894. dio->pages_in_io +=
  895. ((user_addr+iov[seg].iov_len +PAGE_SIZE-1)/PAGE_SIZE
  896. - user_addr/PAGE_SIZE);
  897. }
  898. for (seg = 0; seg < nr_segs; seg++) {
  899. user_addr = (unsigned long)iov[seg].iov_base;
  900. dio->size += bytes = iov[seg].iov_len;
  901. /* Index into the first page of the first block */
  902. dio->first_block_in_page = (user_addr & ~PAGE_MASK) >> blkbits;
  903. dio->final_block_in_request = dio->block_in_file +
  904. (bytes >> blkbits);
  905. /* Page fetching state */
  906. dio->head = 0;
  907. dio->tail = 0;
  908. dio->curr_page = 0;
  909. dio->total_pages = 0;
  910. if (user_addr & (PAGE_SIZE-1)) {
  911. dio->total_pages++;
  912. bytes -= PAGE_SIZE - (user_addr & (PAGE_SIZE - 1));
  913. }
  914. dio->total_pages += (bytes + PAGE_SIZE - 1) / PAGE_SIZE;
  915. dio->curr_user_address = user_addr;
  916. ret = do_direct_IO(dio);
  917. dio->result += iov[seg].iov_len -
  918. ((dio->final_block_in_request - dio->block_in_file) <<
  919. blkbits);
  920. if (ret) {
  921. dio_cleanup(dio);
  922. break;
  923. }
  924. } /* end iovec loop */
  925. if (ret == -ENOTBLK && rw == WRITE) {
  926. /*
  927. * The remaining part of the request will be
  928. * be handled by buffered I/O when we return
  929. */
  930. ret = 0;
  931. }
  932. /*
  933. * There may be some unwritten disk at the end of a part-written
  934. * fs-block-sized block. Go zero that now.
  935. */
  936. dio_zero_block(dio, 1);
  937. if (dio->cur_page) {
  938. ret2 = dio_send_cur_page(dio);
  939. if (ret == 0)
  940. ret = ret2;
  941. page_cache_release(dio->cur_page);
  942. dio->cur_page = NULL;
  943. }
  944. if (dio->bio)
  945. dio_bio_submit(dio);
  946. /*
  947. * It is possible that, we return short IO due to end of file.
  948. * In that case, we need to release all the pages we got hold on.
  949. */
  950. dio_cleanup(dio);
  951. /*
  952. * All block lookups have been performed. For READ requests
  953. * we can let i_mutex go now that its achieved its purpose
  954. * of protecting us from looking up uninitialized blocks.
  955. */
  956. if ((rw == READ) && (dio->lock_type == DIO_LOCKING))
  957. mutex_unlock(&dio->inode->i_mutex);
  958. /*
  959. * OK, all BIOs are submitted, so we can decrement bio_count to truly
  960. * reflect the number of to-be-processed BIOs.
  961. */
  962. if (dio->is_async) {
  963. int should_wait = 0;
  964. if (dio->result < dio->size && rw == WRITE) {
  965. dio->waiter = current;
  966. should_wait = 1;
  967. }
  968. if (ret == 0)
  969. ret = dio->result;
  970. finished_one_bio(dio); /* This can free the dio */
  971. blk_run_address_space(inode->i_mapping);
  972. if (should_wait) {
  973. unsigned long flags;
  974. /*
  975. * Wait for already issued I/O to drain out and
  976. * release its references to user-space pages
  977. * before returning to fallback on buffered I/O
  978. */
  979. spin_lock_irqsave(&dio->bio_lock, flags);
  980. set_current_state(TASK_UNINTERRUPTIBLE);
  981. while (dio->bio_count) {
  982. spin_unlock_irqrestore(&dio->bio_lock, flags);
  983. io_schedule();
  984. spin_lock_irqsave(&dio->bio_lock, flags);
  985. set_current_state(TASK_UNINTERRUPTIBLE);
  986. }
  987. spin_unlock_irqrestore(&dio->bio_lock, flags);
  988. set_current_state(TASK_RUNNING);
  989. kfree(dio);
  990. }
  991. } else {
  992. ssize_t transferred = 0;
  993. finished_one_bio(dio);
  994. ret2 = dio_await_completion(dio);
  995. if (ret == 0)
  996. ret = ret2;
  997. if (ret == 0)
  998. ret = dio->page_errors;
  999. if (dio->result) {
  1000. loff_t i_size = i_size_read(inode);
  1001. transferred = dio->result;
  1002. /*
  1003. * Adjust the return value if the read crossed a
  1004. * non-block-aligned EOF.
  1005. */
  1006. if (rw == READ && (offset + transferred > i_size))
  1007. transferred = i_size - offset;
  1008. }
  1009. dio_complete(dio, offset, transferred);
  1010. if (ret == 0)
  1011. ret = transferred;
  1012. /* We could have also come here on an AIO file extend */
  1013. if (!is_sync_kiocb(iocb) && rw == WRITE &&
  1014. ret >= 0 && dio->result == dio->size)
  1015. /*
  1016. * For AIO writes where we have completed the
  1017. * i/o, we have to mark the the aio complete.
  1018. */
  1019. aio_complete(iocb, ret, 0);
  1020. kfree(dio);
  1021. }
  1022. return ret;
  1023. }
  1024. /*
  1025. * This is a library function for use by filesystem drivers.
  1026. * The locking rules are governed by the dio_lock_type parameter.
  1027. *
  1028. * DIO_NO_LOCKING (no locking, for raw block device access)
  1029. * For writes, i_mutex is not held on entry; it is never taken.
  1030. *
  1031. * DIO_LOCKING (simple locking for regular files)
  1032. * For writes we are called under i_mutex and return with i_mutex held, even though
  1033. * it is internally dropped.
  1034. * For reads, i_mutex is not held on entry, but it is taken and dropped before
  1035. * returning.
  1036. *
  1037. * DIO_OWN_LOCKING (filesystem provides synchronisation and handling of
  1038. * uninitialised data, allowing parallel direct readers and writers)
  1039. * For writes we are called without i_mutex, return without it, never touch it.
  1040. * For reads, i_mutex is held on entry and will be released before returning.
  1041. *
  1042. * Additional i_alloc_sem locking requirements described inline below.
  1043. */
  1044. ssize_t
  1045. __blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
  1046. struct block_device *bdev, const struct iovec *iov, loff_t offset,
  1047. unsigned long nr_segs, get_blocks_t get_blocks, dio_iodone_t end_io,
  1048. int dio_lock_type)
  1049. {
  1050. int seg;
  1051. size_t size;
  1052. unsigned long addr;
  1053. unsigned blkbits = inode->i_blkbits;
  1054. unsigned bdev_blkbits = 0;
  1055. unsigned blocksize_mask = (1 << blkbits) - 1;
  1056. ssize_t retval = -EINVAL;
  1057. loff_t end = offset;
  1058. struct dio *dio;
  1059. int reader_with_isem = (rw == READ && dio_lock_type == DIO_OWN_LOCKING);
  1060. if (rw & WRITE)
  1061. current->flags |= PF_SYNCWRITE;
  1062. if (bdev)
  1063. bdev_blkbits = blksize_bits(bdev_hardsect_size(bdev));
  1064. if (offset & blocksize_mask) {
  1065. if (bdev)
  1066. blkbits = bdev_blkbits;
  1067. blocksize_mask = (1 << blkbits) - 1;
  1068. if (offset & blocksize_mask)
  1069. goto out;
  1070. }
  1071. /* Check the memory alignment. Blocks cannot straddle pages */
  1072. for (seg = 0; seg < nr_segs; seg++) {
  1073. addr = (unsigned long)iov[seg].iov_base;
  1074. size = iov[seg].iov_len;
  1075. end += size;
  1076. if ((addr & blocksize_mask) || (size & blocksize_mask)) {
  1077. if (bdev)
  1078. blkbits = bdev_blkbits;
  1079. blocksize_mask = (1 << blkbits) - 1;
  1080. if ((addr & blocksize_mask) || (size & blocksize_mask))
  1081. goto out;
  1082. }
  1083. }
  1084. dio = kmalloc(sizeof(*dio), GFP_KERNEL);
  1085. retval = -ENOMEM;
  1086. if (!dio)
  1087. goto out;
  1088. /*
  1089. * For block device access DIO_NO_LOCKING is used,
  1090. * neither readers nor writers do any locking at all
  1091. * For regular files using DIO_LOCKING,
  1092. * readers need to grab i_mutex and i_alloc_sem
  1093. * writers need to grab i_alloc_sem only (i_mutex is already held)
  1094. * For regular files using DIO_OWN_LOCKING,
  1095. * neither readers nor writers take any locks here
  1096. * (i_mutex is already held and release for writers here)
  1097. */
  1098. dio->lock_type = dio_lock_type;
  1099. if (dio_lock_type != DIO_NO_LOCKING) {
  1100. /* watch out for a 0 len io from a tricksy fs */
  1101. if (rw == READ && end > offset) {
  1102. struct address_space *mapping;
  1103. mapping = iocb->ki_filp->f_mapping;
  1104. if (dio_lock_type != DIO_OWN_LOCKING) {
  1105. mutex_lock(&inode->i_mutex);
  1106. reader_with_isem = 1;
  1107. }
  1108. retval = filemap_write_and_wait_range(mapping, offset,
  1109. end - 1);
  1110. if (retval) {
  1111. kfree(dio);
  1112. goto out;
  1113. }
  1114. if (dio_lock_type == DIO_OWN_LOCKING) {
  1115. mutex_unlock(&inode->i_mutex);
  1116. reader_with_isem = 0;
  1117. }
  1118. }
  1119. if (dio_lock_type == DIO_LOCKING)
  1120. down_read(&inode->i_alloc_sem);
  1121. }
  1122. /*
  1123. * For file extending writes updating i_size before data
  1124. * writeouts complete can expose uninitialized blocks. So
  1125. * even for AIO, we need to wait for i/o to complete before
  1126. * returning in this case.
  1127. */
  1128. dio->is_async = !is_sync_kiocb(iocb) && !((rw == WRITE) &&
  1129. (end > i_size_read(inode)));
  1130. retval = direct_io_worker(rw, iocb, inode, iov, offset,
  1131. nr_segs, blkbits, get_blocks, end_io, dio);
  1132. if (rw == READ && dio_lock_type == DIO_LOCKING)
  1133. reader_with_isem = 0;
  1134. out:
  1135. if (reader_with_isem)
  1136. mutex_unlock(&inode->i_mutex);
  1137. if (rw & WRITE)
  1138. current->flags &= ~PF_SYNCWRITE;
  1139. return retval;
  1140. }
  1141. EXPORT_SYMBOL(__blockdev_direct_IO);