filemap.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672
  1. /*
  2. * linux/mm/filemap.c
  3. *
  4. * Copyright (C) 1994-1999 Linus Torvalds
  5. */
  6. /*
  7. * This file handles the generic file mmap semantics used by
  8. * most "normal" filesystems (but you don't /have/ to use this:
  9. * the NFS filesystem used to do this differently, for example)
  10. */
  11. #include <linux/module.h>
  12. #include <linux/compiler.h>
  13. #include <linux/fs.h>
  14. #include <linux/uaccess.h>
  15. #include <linux/aio.h>
  16. #include <linux/capability.h>
  17. #include <linux/kernel_stat.h>
  18. #include <linux/gfp.h>
  19. #include <linux/mm.h>
  20. #include <linux/swap.h>
  21. #include <linux/mman.h>
  22. #include <linux/pagemap.h>
  23. #include <linux/file.h>
  24. #include <linux/uio.h>
  25. #include <linux/hash.h>
  26. #include <linux/writeback.h>
  27. #include <linux/backing-dev.h>
  28. #include <linux/pagevec.h>
  29. #include <linux/blkdev.h>
  30. #include <linux/security.h>
  31. #include <linux/syscalls.h>
  32. #include <linux/cpuset.h>
  33. #include <linux/hardirq.h> /* for BUG_ON(!in_atomic()) only */
  34. #include <linux/memcontrol.h>
  35. #include <linux/cleancache.h>
  36. #include "internal.h"
  37. /*
  38. * FIXME: remove all knowledge of the buffer layer from the core VM
  39. */
  40. #include <linux/buffer_head.h> /* for try_to_free_buffers */
  41. #include <asm/mman.h>
  42. /*
  43. * Shared mappings implemented 30.11.1994. It's not fully working yet,
  44. * though.
  45. *
  46. * Shared mappings now work. 15.8.1995 Bruno.
  47. *
  48. * finished 'unifying' the page and buffer cache and SMP-threaded the
  49. * page-cache, 21.05.1999, Ingo Molnar <mingo@redhat.com>
  50. *
  51. * SMP-threaded pagemap-LRU 1999, Andrea Arcangeli <andrea@suse.de>
  52. */
  53. /*
  54. * Lock ordering:
  55. *
  56. * ->i_mmap_mutex (truncate_pagecache)
  57. * ->private_lock (__free_pte->__set_page_dirty_buffers)
  58. * ->swap_lock (exclusive_swap_page, others)
  59. * ->mapping->tree_lock
  60. *
  61. * ->i_mutex
  62. * ->i_mmap_mutex (truncate->unmap_mapping_range)
  63. *
  64. * ->mmap_sem
  65. * ->i_mmap_mutex
  66. * ->page_table_lock or pte_lock (various, mainly in memory.c)
  67. * ->mapping->tree_lock (arch-dependent flush_dcache_mmap_lock)
  68. *
  69. * ->mmap_sem
  70. * ->lock_page (access_process_vm)
  71. *
  72. * ->i_mutex (generic_file_buffered_write)
  73. * ->mmap_sem (fault_in_pages_readable->do_page_fault)
  74. *
  75. * bdi->wb.list_lock
  76. * sb_lock (fs/fs-writeback.c)
  77. * ->mapping->tree_lock (__sync_single_inode)
  78. *
  79. * ->i_mmap_mutex
  80. * ->anon_vma.lock (vma_adjust)
  81. *
  82. * ->anon_vma.lock
  83. * ->page_table_lock or pte_lock (anon_vma_prepare and various)
  84. *
  85. * ->page_table_lock or pte_lock
  86. * ->swap_lock (try_to_unmap_one)
  87. * ->private_lock (try_to_unmap_one)
  88. * ->tree_lock (try_to_unmap_one)
  89. * ->zone.lru_lock (follow_page->mark_page_accessed)
  90. * ->zone.lru_lock (check_pte_range->isolate_lru_page)
  91. * ->private_lock (page_remove_rmap->set_page_dirty)
  92. * ->tree_lock (page_remove_rmap->set_page_dirty)
  93. * bdi.wb->list_lock (page_remove_rmap->set_page_dirty)
  94. * ->inode->i_lock (page_remove_rmap->set_page_dirty)
  95. * bdi.wb->list_lock (zap_pte_range->set_page_dirty)
  96. * ->inode->i_lock (zap_pte_range->set_page_dirty)
  97. * ->private_lock (zap_pte_range->__set_page_dirty_buffers)
  98. *
  99. * (code doesn't rely on that order, so you could switch it around)
  100. * ->tasklist_lock (memory_failure, collect_procs_ao)
  101. * ->i_mmap_mutex
  102. */
  103. /*
  104. * Delete a page from the page cache and free it. Caller has to make
  105. * sure the page is locked and that nobody else uses it - or that usage
  106. * is safe. The caller must hold the mapping's tree_lock.
  107. */
  108. void __delete_from_page_cache(struct page *page)
  109. {
  110. struct address_space *mapping = page->mapping;
  111. /*
  112. * if we're uptodate, flush out into the cleancache, otherwise
  113. * invalidate any existing cleancache entries. We can't leave
  114. * stale data around in the cleancache once our page is gone
  115. */
  116. if (PageUptodate(page) && PageMappedToDisk(page))
  117. cleancache_put_page(page);
  118. else
  119. cleancache_flush_page(mapping, page);
  120. radix_tree_delete(&mapping->page_tree, page->index);
  121. page->mapping = NULL;
  122. /* Leave page->index set: truncation lookup relies upon it */
  123. mapping->nrpages--;
  124. __dec_zone_page_state(page, NR_FILE_PAGES);
  125. if (PageSwapBacked(page))
  126. __dec_zone_page_state(page, NR_SHMEM);
  127. BUG_ON(page_mapped(page));
  128. /*
  129. * Some filesystems seem to re-dirty the page even after
  130. * the VM has canceled the dirty bit (eg ext3 journaling).
  131. *
  132. * Fix it up by doing a final dirty accounting check after
  133. * having removed the page entirely.
  134. */
  135. if (PageDirty(page) && mapping_cap_account_dirty(mapping)) {
  136. dec_zone_page_state(page, NR_FILE_DIRTY);
  137. dec_bdi_stat(mapping->backing_dev_info, BDI_RECLAIMABLE);
  138. }
  139. }
  140. /**
  141. * delete_from_page_cache - delete page from page cache
  142. * @page: the page which the kernel is trying to remove from page cache
  143. *
  144. * This must be called only on pages that have been verified to be in the page
  145. * cache and locked. It will never put the page into the free list, the caller
  146. * has a reference on the page.
  147. */
  148. void delete_from_page_cache(struct page *page)
  149. {
  150. struct address_space *mapping = page->mapping;
  151. void (*freepage)(struct page *);
  152. BUG_ON(!PageLocked(page));
  153. freepage = mapping->a_ops->freepage;
  154. spin_lock_irq(&mapping->tree_lock);
  155. __delete_from_page_cache(page);
  156. spin_unlock_irq(&mapping->tree_lock);
  157. mem_cgroup_uncharge_cache_page(page);
  158. if (freepage)
  159. freepage(page);
  160. page_cache_release(page);
  161. }
  162. EXPORT_SYMBOL(delete_from_page_cache);
  163. static int sleep_on_page(void *word)
  164. {
  165. io_schedule();
  166. return 0;
  167. }
  168. static int sleep_on_page_killable(void *word)
  169. {
  170. sleep_on_page(word);
  171. return fatal_signal_pending(current) ? -EINTR : 0;
  172. }
  173. /**
  174. * __filemap_fdatawrite_range - start writeback on mapping dirty pages in range
  175. * @mapping: address space structure to write
  176. * @start: offset in bytes where the range starts
  177. * @end: offset in bytes where the range ends (inclusive)
  178. * @sync_mode: enable synchronous operation
  179. *
  180. * Start writeback against all of a mapping's dirty pages that lie
  181. * within the byte offsets <start, end> inclusive.
  182. *
  183. * If sync_mode is WB_SYNC_ALL then this is a "data integrity" operation, as
  184. * opposed to a regular memory cleansing writeback. The difference between
  185. * these two operations is that if a dirty page/buffer is encountered, it must
  186. * be waited upon, and not just skipped over.
  187. */
  188. int __filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  189. loff_t end, int sync_mode)
  190. {
  191. int ret;
  192. struct writeback_control wbc = {
  193. .sync_mode = sync_mode,
  194. .nr_to_write = LONG_MAX,
  195. .range_start = start,
  196. .range_end = end,
  197. };
  198. if (!mapping_cap_writeback_dirty(mapping))
  199. return 0;
  200. ret = do_writepages(mapping, &wbc);
  201. return ret;
  202. }
  203. static inline int __filemap_fdatawrite(struct address_space *mapping,
  204. int sync_mode)
  205. {
  206. return __filemap_fdatawrite_range(mapping, 0, LLONG_MAX, sync_mode);
  207. }
  208. int filemap_fdatawrite(struct address_space *mapping)
  209. {
  210. return __filemap_fdatawrite(mapping, WB_SYNC_ALL);
  211. }
  212. EXPORT_SYMBOL(filemap_fdatawrite);
  213. int filemap_fdatawrite_range(struct address_space *mapping, loff_t start,
  214. loff_t end)
  215. {
  216. return __filemap_fdatawrite_range(mapping, start, end, WB_SYNC_ALL);
  217. }
  218. EXPORT_SYMBOL(filemap_fdatawrite_range);
  219. /**
  220. * filemap_flush - mostly a non-blocking flush
  221. * @mapping: target address_space
  222. *
  223. * This is a mostly non-blocking flush. Not suitable for data-integrity
  224. * purposes - I/O may not be started against all dirty pages.
  225. */
  226. int filemap_flush(struct address_space *mapping)
  227. {
  228. return __filemap_fdatawrite(mapping, WB_SYNC_NONE);
  229. }
  230. EXPORT_SYMBOL(filemap_flush);
  231. /**
  232. * filemap_fdatawait_range - wait for writeback to complete
  233. * @mapping: address space structure to wait for
  234. * @start_byte: offset in bytes where the range starts
  235. * @end_byte: offset in bytes where the range ends (inclusive)
  236. *
  237. * Walk the list of under-writeback pages of the given address space
  238. * in the given range and wait for all of them.
  239. */
  240. int filemap_fdatawait_range(struct address_space *mapping, loff_t start_byte,
  241. loff_t end_byte)
  242. {
  243. pgoff_t index = start_byte >> PAGE_CACHE_SHIFT;
  244. pgoff_t end = end_byte >> PAGE_CACHE_SHIFT;
  245. struct pagevec pvec;
  246. int nr_pages;
  247. int ret = 0;
  248. if (end_byte < start_byte)
  249. return 0;
  250. pagevec_init(&pvec, 0);
  251. while ((index <= end) &&
  252. (nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  253. PAGECACHE_TAG_WRITEBACK,
  254. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1)) != 0) {
  255. unsigned i;
  256. for (i = 0; i < nr_pages; i++) {
  257. struct page *page = pvec.pages[i];
  258. /* until radix tree lookup accepts end_index */
  259. if (page->index > end)
  260. continue;
  261. wait_on_page_writeback(page);
  262. if (TestClearPageError(page))
  263. ret = -EIO;
  264. }
  265. pagevec_release(&pvec);
  266. cond_resched();
  267. }
  268. /* Check for outstanding write errors */
  269. if (test_and_clear_bit(AS_ENOSPC, &mapping->flags))
  270. ret = -ENOSPC;
  271. if (test_and_clear_bit(AS_EIO, &mapping->flags))
  272. ret = -EIO;
  273. return ret;
  274. }
  275. EXPORT_SYMBOL(filemap_fdatawait_range);
  276. /**
  277. * filemap_fdatawait - wait for all under-writeback pages to complete
  278. * @mapping: address space structure to wait for
  279. *
  280. * Walk the list of under-writeback pages of the given address space
  281. * and wait for all of them.
  282. */
  283. int filemap_fdatawait(struct address_space *mapping)
  284. {
  285. loff_t i_size = i_size_read(mapping->host);
  286. if (i_size == 0)
  287. return 0;
  288. return filemap_fdatawait_range(mapping, 0, i_size - 1);
  289. }
  290. EXPORT_SYMBOL(filemap_fdatawait);
  291. int filemap_write_and_wait(struct address_space *mapping)
  292. {
  293. int err = 0;
  294. if (mapping->nrpages) {
  295. err = filemap_fdatawrite(mapping);
  296. /*
  297. * Even if the above returned error, the pages may be
  298. * written partially (e.g. -ENOSPC), so we wait for it.
  299. * But the -EIO is special case, it may indicate the worst
  300. * thing (e.g. bug) happened, so we avoid waiting for it.
  301. */
  302. if (err != -EIO) {
  303. int err2 = filemap_fdatawait(mapping);
  304. if (!err)
  305. err = err2;
  306. }
  307. }
  308. return err;
  309. }
  310. EXPORT_SYMBOL(filemap_write_and_wait);
  311. /**
  312. * filemap_write_and_wait_range - write out & wait on a file range
  313. * @mapping: the address_space for the pages
  314. * @lstart: offset in bytes where the range starts
  315. * @lend: offset in bytes where the range ends (inclusive)
  316. *
  317. * Write out and wait upon file offsets lstart->lend, inclusive.
  318. *
  319. * Note that `lend' is inclusive (describes the last byte to be written) so
  320. * that this function can be used to write to the very end-of-file (end = -1).
  321. */
  322. int filemap_write_and_wait_range(struct address_space *mapping,
  323. loff_t lstart, loff_t lend)
  324. {
  325. int err = 0;
  326. if (mapping->nrpages) {
  327. err = __filemap_fdatawrite_range(mapping, lstart, lend,
  328. WB_SYNC_ALL);
  329. /* See comment of filemap_write_and_wait() */
  330. if (err != -EIO) {
  331. int err2 = filemap_fdatawait_range(mapping,
  332. lstart, lend);
  333. if (!err)
  334. err = err2;
  335. }
  336. }
  337. return err;
  338. }
  339. EXPORT_SYMBOL(filemap_write_and_wait_range);
  340. /**
  341. * replace_page_cache_page - replace a pagecache page with a new one
  342. * @old: page to be replaced
  343. * @new: page to replace with
  344. * @gfp_mask: allocation mode
  345. *
  346. * This function replaces a page in the pagecache with a new one. On
  347. * success it acquires the pagecache reference for the new page and
  348. * drops it for the old page. Both the old and new pages must be
  349. * locked. This function does not add the new page to the LRU, the
  350. * caller must do that.
  351. *
  352. * The remove + add is atomic. The only way this function can fail is
  353. * memory allocation failure.
  354. */
  355. int replace_page_cache_page(struct page *old, struct page *new, gfp_t gfp_mask)
  356. {
  357. int error;
  358. struct mem_cgroup *memcg = NULL;
  359. VM_BUG_ON(!PageLocked(old));
  360. VM_BUG_ON(!PageLocked(new));
  361. VM_BUG_ON(new->mapping);
  362. /*
  363. * This is not page migration, but prepare_migration and
  364. * end_migration does enough work for charge replacement.
  365. *
  366. * In the longer term we probably want a specialized function
  367. * for moving the charge from old to new in a more efficient
  368. * manner.
  369. */
  370. error = mem_cgroup_prepare_migration(old, new, &memcg, gfp_mask);
  371. if (error)
  372. return error;
  373. error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
  374. if (!error) {
  375. struct address_space *mapping = old->mapping;
  376. void (*freepage)(struct page *);
  377. pgoff_t offset = old->index;
  378. freepage = mapping->a_ops->freepage;
  379. page_cache_get(new);
  380. new->mapping = mapping;
  381. new->index = offset;
  382. spin_lock_irq(&mapping->tree_lock);
  383. __delete_from_page_cache(old);
  384. error = radix_tree_insert(&mapping->page_tree, offset, new);
  385. BUG_ON(error);
  386. mapping->nrpages++;
  387. __inc_zone_page_state(new, NR_FILE_PAGES);
  388. if (PageSwapBacked(new))
  389. __inc_zone_page_state(new, NR_SHMEM);
  390. spin_unlock_irq(&mapping->tree_lock);
  391. radix_tree_preload_end();
  392. if (freepage)
  393. freepage(old);
  394. page_cache_release(old);
  395. mem_cgroup_end_migration(memcg, old, new, true);
  396. } else {
  397. mem_cgroup_end_migration(memcg, old, new, false);
  398. }
  399. return error;
  400. }
  401. EXPORT_SYMBOL_GPL(replace_page_cache_page);
  402. /**
  403. * add_to_page_cache_locked - add a locked page to the pagecache
  404. * @page: page to add
  405. * @mapping: the page's address_space
  406. * @offset: page index
  407. * @gfp_mask: page allocation mode
  408. *
  409. * This function is used to add a page to the pagecache. It must be locked.
  410. * This function does not add the page to the LRU. The caller must do that.
  411. */
  412. int add_to_page_cache_locked(struct page *page, struct address_space *mapping,
  413. pgoff_t offset, gfp_t gfp_mask)
  414. {
  415. int error;
  416. VM_BUG_ON(!PageLocked(page));
  417. VM_BUG_ON(PageSwapBacked(page));
  418. error = mem_cgroup_cache_charge(page, current->mm,
  419. gfp_mask & GFP_RECLAIM_MASK);
  420. if (error)
  421. goto out;
  422. error = radix_tree_preload(gfp_mask & ~__GFP_HIGHMEM);
  423. if (error == 0) {
  424. page_cache_get(page);
  425. page->mapping = mapping;
  426. page->index = offset;
  427. spin_lock_irq(&mapping->tree_lock);
  428. error = radix_tree_insert(&mapping->page_tree, offset, page);
  429. if (likely(!error)) {
  430. mapping->nrpages++;
  431. __inc_zone_page_state(page, NR_FILE_PAGES);
  432. spin_unlock_irq(&mapping->tree_lock);
  433. } else {
  434. page->mapping = NULL;
  435. /* Leave page->index set: truncation relies upon it */
  436. spin_unlock_irq(&mapping->tree_lock);
  437. mem_cgroup_uncharge_cache_page(page);
  438. page_cache_release(page);
  439. }
  440. radix_tree_preload_end();
  441. } else
  442. mem_cgroup_uncharge_cache_page(page);
  443. out:
  444. return error;
  445. }
  446. EXPORT_SYMBOL(add_to_page_cache_locked);
  447. int add_to_page_cache_lru(struct page *page, struct address_space *mapping,
  448. pgoff_t offset, gfp_t gfp_mask)
  449. {
  450. int ret;
  451. ret = add_to_page_cache(page, mapping, offset, gfp_mask);
  452. if (ret == 0)
  453. lru_cache_add_file(page);
  454. return ret;
  455. }
  456. EXPORT_SYMBOL_GPL(add_to_page_cache_lru);
  457. #ifdef CONFIG_NUMA
  458. struct page *__page_cache_alloc(gfp_t gfp)
  459. {
  460. int n;
  461. struct page *page;
  462. if (cpuset_do_page_mem_spread()) {
  463. get_mems_allowed();
  464. n = cpuset_mem_spread_node();
  465. page = alloc_pages_exact_node(n, gfp, 0);
  466. put_mems_allowed();
  467. return page;
  468. }
  469. return alloc_pages(gfp, 0);
  470. }
  471. EXPORT_SYMBOL(__page_cache_alloc);
  472. #endif
  473. /*
  474. * In order to wait for pages to become available there must be
  475. * waitqueues associated with pages. By using a hash table of
  476. * waitqueues where the bucket discipline is to maintain all
  477. * waiters on the same queue and wake all when any of the pages
  478. * become available, and for the woken contexts to check to be
  479. * sure the appropriate page became available, this saves space
  480. * at a cost of "thundering herd" phenomena during rare hash
  481. * collisions.
  482. */
  483. static wait_queue_head_t *page_waitqueue(struct page *page)
  484. {
  485. const struct zone *zone = page_zone(page);
  486. return &zone->wait_table[hash_ptr(page, zone->wait_table_bits)];
  487. }
  488. static inline void wake_up_page(struct page *page, int bit)
  489. {
  490. __wake_up_bit(page_waitqueue(page), &page->flags, bit);
  491. }
  492. void wait_on_page_bit(struct page *page, int bit_nr)
  493. {
  494. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  495. if (test_bit(bit_nr, &page->flags))
  496. __wait_on_bit(page_waitqueue(page), &wait, sleep_on_page,
  497. TASK_UNINTERRUPTIBLE);
  498. }
  499. EXPORT_SYMBOL(wait_on_page_bit);
  500. int wait_on_page_bit_killable(struct page *page, int bit_nr)
  501. {
  502. DEFINE_WAIT_BIT(wait, &page->flags, bit_nr);
  503. if (!test_bit(bit_nr, &page->flags))
  504. return 0;
  505. return __wait_on_bit(page_waitqueue(page), &wait,
  506. sleep_on_page_killable, TASK_KILLABLE);
  507. }
  508. /**
  509. * add_page_wait_queue - Add an arbitrary waiter to a page's wait queue
  510. * @page: Page defining the wait queue of interest
  511. * @waiter: Waiter to add to the queue
  512. *
  513. * Add an arbitrary @waiter to the wait queue for the nominated @page.
  514. */
  515. void add_page_wait_queue(struct page *page, wait_queue_t *waiter)
  516. {
  517. wait_queue_head_t *q = page_waitqueue(page);
  518. unsigned long flags;
  519. spin_lock_irqsave(&q->lock, flags);
  520. __add_wait_queue(q, waiter);
  521. spin_unlock_irqrestore(&q->lock, flags);
  522. }
  523. EXPORT_SYMBOL_GPL(add_page_wait_queue);
  524. /**
  525. * unlock_page - unlock a locked page
  526. * @page: the page
  527. *
  528. * Unlocks the page and wakes up sleepers in ___wait_on_page_locked().
  529. * Also wakes sleepers in wait_on_page_writeback() because the wakeup
  530. * mechananism between PageLocked pages and PageWriteback pages is shared.
  531. * But that's OK - sleepers in wait_on_page_writeback() just go back to sleep.
  532. *
  533. * The mb is necessary to enforce ordering between the clear_bit and the read
  534. * of the waitqueue (to avoid SMP races with a parallel wait_on_page_locked()).
  535. */
  536. void unlock_page(struct page *page)
  537. {
  538. VM_BUG_ON(!PageLocked(page));
  539. clear_bit_unlock(PG_locked, &page->flags);
  540. smp_mb__after_clear_bit();
  541. wake_up_page(page, PG_locked);
  542. }
  543. EXPORT_SYMBOL(unlock_page);
  544. /**
  545. * end_page_writeback - end writeback against a page
  546. * @page: the page
  547. */
  548. void end_page_writeback(struct page *page)
  549. {
  550. if (TestClearPageReclaim(page))
  551. rotate_reclaimable_page(page);
  552. if (!test_clear_page_writeback(page))
  553. BUG();
  554. smp_mb__after_clear_bit();
  555. wake_up_page(page, PG_writeback);
  556. }
  557. EXPORT_SYMBOL(end_page_writeback);
  558. /**
  559. * __lock_page - get a lock on the page, assuming we need to sleep to get it
  560. * @page: the page to lock
  561. */
  562. void __lock_page(struct page *page)
  563. {
  564. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  565. __wait_on_bit_lock(page_waitqueue(page), &wait, sleep_on_page,
  566. TASK_UNINTERRUPTIBLE);
  567. }
  568. EXPORT_SYMBOL(__lock_page);
  569. int __lock_page_killable(struct page *page)
  570. {
  571. DEFINE_WAIT_BIT(wait, &page->flags, PG_locked);
  572. return __wait_on_bit_lock(page_waitqueue(page), &wait,
  573. sleep_on_page_killable, TASK_KILLABLE);
  574. }
  575. EXPORT_SYMBOL_GPL(__lock_page_killable);
  576. int __lock_page_or_retry(struct page *page, struct mm_struct *mm,
  577. unsigned int flags)
  578. {
  579. if (flags & FAULT_FLAG_ALLOW_RETRY) {
  580. /*
  581. * CAUTION! In this case, mmap_sem is not released
  582. * even though return 0.
  583. */
  584. if (flags & FAULT_FLAG_RETRY_NOWAIT)
  585. return 0;
  586. up_read(&mm->mmap_sem);
  587. if (flags & FAULT_FLAG_KILLABLE)
  588. wait_on_page_locked_killable(page);
  589. else
  590. wait_on_page_locked(page);
  591. return 0;
  592. } else {
  593. if (flags & FAULT_FLAG_KILLABLE) {
  594. int ret;
  595. ret = __lock_page_killable(page);
  596. if (ret) {
  597. up_read(&mm->mmap_sem);
  598. return 0;
  599. }
  600. } else
  601. __lock_page(page);
  602. return 1;
  603. }
  604. }
  605. /**
  606. * find_get_page - find and get a page reference
  607. * @mapping: the address_space to search
  608. * @offset: the page index
  609. *
  610. * Is there a pagecache struct page at the given (mapping, offset) tuple?
  611. * If yes, increment its refcount and return it; if no, return NULL.
  612. */
  613. struct page *find_get_page(struct address_space *mapping, pgoff_t offset)
  614. {
  615. void **pagep;
  616. struct page *page;
  617. rcu_read_lock();
  618. repeat:
  619. page = NULL;
  620. pagep = radix_tree_lookup_slot(&mapping->page_tree, offset);
  621. if (pagep) {
  622. page = radix_tree_deref_slot(pagep);
  623. if (unlikely(!page))
  624. goto out;
  625. if (radix_tree_exception(page)) {
  626. if (radix_tree_deref_retry(page))
  627. goto repeat;
  628. /*
  629. * Otherwise, shmem/tmpfs must be storing a swap entry
  630. * here as an exceptional entry: so return it without
  631. * attempting to raise page count.
  632. */
  633. goto out;
  634. }
  635. if (!page_cache_get_speculative(page))
  636. goto repeat;
  637. /*
  638. * Has the page moved?
  639. * This is part of the lockless pagecache protocol. See
  640. * include/linux/pagemap.h for details.
  641. */
  642. if (unlikely(page != *pagep)) {
  643. page_cache_release(page);
  644. goto repeat;
  645. }
  646. }
  647. out:
  648. rcu_read_unlock();
  649. return page;
  650. }
  651. EXPORT_SYMBOL(find_get_page);
  652. /**
  653. * find_lock_page - locate, pin and lock a pagecache page
  654. * @mapping: the address_space to search
  655. * @offset: the page index
  656. *
  657. * Locates the desired pagecache page, locks it, increments its reference
  658. * count and returns its address.
  659. *
  660. * Returns zero if the page was not present. find_lock_page() may sleep.
  661. */
  662. struct page *find_lock_page(struct address_space *mapping, pgoff_t offset)
  663. {
  664. struct page *page;
  665. repeat:
  666. page = find_get_page(mapping, offset);
  667. if (page && !radix_tree_exception(page)) {
  668. lock_page(page);
  669. /* Has the page been truncated? */
  670. if (unlikely(page->mapping != mapping)) {
  671. unlock_page(page);
  672. page_cache_release(page);
  673. goto repeat;
  674. }
  675. VM_BUG_ON(page->index != offset);
  676. }
  677. return page;
  678. }
  679. EXPORT_SYMBOL(find_lock_page);
  680. /**
  681. * find_or_create_page - locate or add a pagecache page
  682. * @mapping: the page's address_space
  683. * @index: the page's index into the mapping
  684. * @gfp_mask: page allocation mode
  685. *
  686. * Locates a page in the pagecache. If the page is not present, a new page
  687. * is allocated using @gfp_mask and is added to the pagecache and to the VM's
  688. * LRU list. The returned page is locked and has its reference count
  689. * incremented.
  690. *
  691. * find_or_create_page() may sleep, even if @gfp_flags specifies an atomic
  692. * allocation!
  693. *
  694. * find_or_create_page() returns the desired page's address, or zero on
  695. * memory exhaustion.
  696. */
  697. struct page *find_or_create_page(struct address_space *mapping,
  698. pgoff_t index, gfp_t gfp_mask)
  699. {
  700. struct page *page;
  701. int err;
  702. repeat:
  703. page = find_lock_page(mapping, index);
  704. if (!page) {
  705. page = __page_cache_alloc(gfp_mask);
  706. if (!page)
  707. return NULL;
  708. /*
  709. * We want a regular kernel memory (not highmem or DMA etc)
  710. * allocation for the radix tree nodes, but we need to honour
  711. * the context-specific requirements the caller has asked for.
  712. * GFP_RECLAIM_MASK collects those requirements.
  713. */
  714. err = add_to_page_cache_lru(page, mapping, index,
  715. (gfp_mask & GFP_RECLAIM_MASK));
  716. if (unlikely(err)) {
  717. page_cache_release(page);
  718. page = NULL;
  719. if (err == -EEXIST)
  720. goto repeat;
  721. }
  722. }
  723. return page;
  724. }
  725. EXPORT_SYMBOL(find_or_create_page);
  726. /**
  727. * find_get_pages - gang pagecache lookup
  728. * @mapping: The address_space to search
  729. * @start: The starting page index
  730. * @nr_pages: The maximum number of pages
  731. * @pages: Where the resulting pages are placed
  732. *
  733. * find_get_pages() will search for and return a group of up to
  734. * @nr_pages pages in the mapping. The pages are placed at @pages.
  735. * find_get_pages() takes a reference against the returned pages.
  736. *
  737. * The search returns a group of mapping-contiguous pages with ascending
  738. * indexes. There may be holes in the indices due to not-present pages.
  739. *
  740. * find_get_pages() returns the number of pages which were found.
  741. */
  742. unsigned find_get_pages(struct address_space *mapping, pgoff_t start,
  743. unsigned int nr_pages, struct page **pages)
  744. {
  745. unsigned int i;
  746. unsigned int ret;
  747. unsigned int nr_found;
  748. rcu_read_lock();
  749. restart:
  750. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  751. (void ***)pages, NULL, start, nr_pages);
  752. ret = 0;
  753. for (i = 0; i < nr_found; i++) {
  754. struct page *page;
  755. repeat:
  756. page = radix_tree_deref_slot((void **)pages[i]);
  757. if (unlikely(!page))
  758. continue;
  759. if (radix_tree_exception(page)) {
  760. if (radix_tree_deref_retry(page)) {
  761. /*
  762. * Transient condition which can only trigger
  763. * when entry at index 0 moves out of or back
  764. * to root: none yet gotten, safe to restart.
  765. */
  766. WARN_ON(start | i);
  767. goto restart;
  768. }
  769. /*
  770. * Otherwise, shmem/tmpfs must be storing a swap entry
  771. * here as an exceptional entry: so skip over it -
  772. * we only reach this from invalidate_mapping_pages().
  773. */
  774. continue;
  775. }
  776. if (!page_cache_get_speculative(page))
  777. goto repeat;
  778. /* Has the page moved? */
  779. if (unlikely(page != *((void **)pages[i]))) {
  780. page_cache_release(page);
  781. goto repeat;
  782. }
  783. pages[ret] = page;
  784. ret++;
  785. }
  786. /*
  787. * If all entries were removed before we could secure them,
  788. * try again, because callers stop trying once 0 is returned.
  789. */
  790. if (unlikely(!ret && nr_found))
  791. goto restart;
  792. rcu_read_unlock();
  793. return ret;
  794. }
  795. /**
  796. * find_get_pages_contig - gang contiguous pagecache lookup
  797. * @mapping: The address_space to search
  798. * @index: The starting page index
  799. * @nr_pages: The maximum number of pages
  800. * @pages: Where the resulting pages are placed
  801. *
  802. * find_get_pages_contig() works exactly like find_get_pages(), except
  803. * that the returned number of pages are guaranteed to be contiguous.
  804. *
  805. * find_get_pages_contig() returns the number of pages which were found.
  806. */
  807. unsigned find_get_pages_contig(struct address_space *mapping, pgoff_t index,
  808. unsigned int nr_pages, struct page **pages)
  809. {
  810. unsigned int i;
  811. unsigned int ret;
  812. unsigned int nr_found;
  813. rcu_read_lock();
  814. restart:
  815. nr_found = radix_tree_gang_lookup_slot(&mapping->page_tree,
  816. (void ***)pages, NULL, index, nr_pages);
  817. ret = 0;
  818. for (i = 0; i < nr_found; i++) {
  819. struct page *page;
  820. repeat:
  821. page = radix_tree_deref_slot((void **)pages[i]);
  822. if (unlikely(!page))
  823. continue;
  824. if (radix_tree_exception(page)) {
  825. if (radix_tree_deref_retry(page)) {
  826. /*
  827. * Transient condition which can only trigger
  828. * when entry at index 0 moves out of or back
  829. * to root: none yet gotten, safe to restart.
  830. */
  831. goto restart;
  832. }
  833. /*
  834. * Otherwise, shmem/tmpfs must be storing a swap entry
  835. * here as an exceptional entry: so stop looking for
  836. * contiguous pages.
  837. */
  838. break;
  839. }
  840. if (!page_cache_get_speculative(page))
  841. goto repeat;
  842. /* Has the page moved? */
  843. if (unlikely(page != *((void **)pages[i]))) {
  844. page_cache_release(page);
  845. goto repeat;
  846. }
  847. /*
  848. * must check mapping and index after taking the ref.
  849. * otherwise we can get both false positives and false
  850. * negatives, which is just confusing to the caller.
  851. */
  852. if (page->mapping == NULL || page->index != index) {
  853. page_cache_release(page);
  854. break;
  855. }
  856. pages[ret] = page;
  857. ret++;
  858. index++;
  859. }
  860. rcu_read_unlock();
  861. return ret;
  862. }
  863. EXPORT_SYMBOL(find_get_pages_contig);
  864. /**
  865. * find_get_pages_tag - find and return pages that match @tag
  866. * @mapping: the address_space to search
  867. * @index: the starting page index
  868. * @tag: the tag index
  869. * @nr_pages: the maximum number of pages
  870. * @pages: where the resulting pages are placed
  871. *
  872. * Like find_get_pages, except we only return pages which are tagged with
  873. * @tag. We update @index to index the next page for the traversal.
  874. */
  875. unsigned find_get_pages_tag(struct address_space *mapping, pgoff_t *index,
  876. int tag, unsigned int nr_pages, struct page **pages)
  877. {
  878. unsigned int i;
  879. unsigned int ret;
  880. unsigned int nr_found;
  881. rcu_read_lock();
  882. restart:
  883. nr_found = radix_tree_gang_lookup_tag_slot(&mapping->page_tree,
  884. (void ***)pages, *index, nr_pages, tag);
  885. ret = 0;
  886. for (i = 0; i < nr_found; i++) {
  887. struct page *page;
  888. repeat:
  889. page = radix_tree_deref_slot((void **)pages[i]);
  890. if (unlikely(!page))
  891. continue;
  892. if (radix_tree_exception(page)) {
  893. if (radix_tree_deref_retry(page)) {
  894. /*
  895. * Transient condition which can only trigger
  896. * when entry at index 0 moves out of or back
  897. * to root: none yet gotten, safe to restart.
  898. */
  899. goto restart;
  900. }
  901. /*
  902. * This function is never used on a shmem/tmpfs
  903. * mapping, so a swap entry won't be found here.
  904. */
  905. BUG();
  906. }
  907. if (!page_cache_get_speculative(page))
  908. goto repeat;
  909. /* Has the page moved? */
  910. if (unlikely(page != *((void **)pages[i]))) {
  911. page_cache_release(page);
  912. goto repeat;
  913. }
  914. pages[ret] = page;
  915. ret++;
  916. }
  917. /*
  918. * If all entries were removed before we could secure them,
  919. * try again, because callers stop trying once 0 is returned.
  920. */
  921. if (unlikely(!ret && nr_found))
  922. goto restart;
  923. rcu_read_unlock();
  924. if (ret)
  925. *index = pages[ret - 1]->index + 1;
  926. return ret;
  927. }
  928. EXPORT_SYMBOL(find_get_pages_tag);
  929. /**
  930. * grab_cache_page_nowait - returns locked page at given index in given cache
  931. * @mapping: target address_space
  932. * @index: the page index
  933. *
  934. * Same as grab_cache_page(), but do not wait if the page is unavailable.
  935. * This is intended for speculative data generators, where the data can
  936. * be regenerated if the page couldn't be grabbed. This routine should
  937. * be safe to call while holding the lock for another page.
  938. *
  939. * Clear __GFP_FS when allocating the page to avoid recursion into the fs
  940. * and deadlock against the caller's locked page.
  941. */
  942. struct page *
  943. grab_cache_page_nowait(struct address_space *mapping, pgoff_t index)
  944. {
  945. struct page *page = find_get_page(mapping, index);
  946. if (page) {
  947. if (trylock_page(page))
  948. return page;
  949. page_cache_release(page);
  950. return NULL;
  951. }
  952. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~__GFP_FS);
  953. if (page && add_to_page_cache_lru(page, mapping, index, GFP_NOFS)) {
  954. page_cache_release(page);
  955. page = NULL;
  956. }
  957. return page;
  958. }
  959. EXPORT_SYMBOL(grab_cache_page_nowait);
  960. /*
  961. * CD/DVDs are error prone. When a medium error occurs, the driver may fail
  962. * a _large_ part of the i/o request. Imagine the worst scenario:
  963. *
  964. * ---R__________________________________________B__________
  965. * ^ reading here ^ bad block(assume 4k)
  966. *
  967. * read(R) => miss => readahead(R...B) => media error => frustrating retries
  968. * => failing the whole request => read(R) => read(R+1) =>
  969. * readahead(R+1...B+1) => bang => read(R+2) => read(R+3) =>
  970. * readahead(R+3...B+2) => bang => read(R+3) => read(R+4) =>
  971. * readahead(R+4...B+3) => bang => read(R+4) => read(R+5) => ......
  972. *
  973. * It is going insane. Fix it by quickly scaling down the readahead size.
  974. */
  975. static void shrink_readahead_size_eio(struct file *filp,
  976. struct file_ra_state *ra)
  977. {
  978. ra->ra_pages /= 4;
  979. }
  980. /**
  981. * do_generic_file_read - generic file read routine
  982. * @filp: the file to read
  983. * @ppos: current file position
  984. * @desc: read_descriptor
  985. * @actor: read method
  986. *
  987. * This is a generic file read routine, and uses the
  988. * mapping->a_ops->readpage() function for the actual low-level stuff.
  989. *
  990. * This is really ugly. But the goto's actually try to clarify some
  991. * of the logic when it comes to error handling etc.
  992. */
  993. static void do_generic_file_read(struct file *filp, loff_t *ppos,
  994. read_descriptor_t *desc, read_actor_t actor)
  995. {
  996. struct address_space *mapping = filp->f_mapping;
  997. struct inode *inode = mapping->host;
  998. struct file_ra_state *ra = &filp->f_ra;
  999. pgoff_t index;
  1000. pgoff_t last_index;
  1001. pgoff_t prev_index;
  1002. unsigned long offset; /* offset into pagecache page */
  1003. unsigned int prev_offset;
  1004. int error;
  1005. index = *ppos >> PAGE_CACHE_SHIFT;
  1006. prev_index = ra->prev_pos >> PAGE_CACHE_SHIFT;
  1007. prev_offset = ra->prev_pos & (PAGE_CACHE_SIZE-1);
  1008. last_index = (*ppos + desc->count + PAGE_CACHE_SIZE-1) >> PAGE_CACHE_SHIFT;
  1009. offset = *ppos & ~PAGE_CACHE_MASK;
  1010. for (;;) {
  1011. struct page *page;
  1012. pgoff_t end_index;
  1013. loff_t isize;
  1014. unsigned long nr, ret;
  1015. cond_resched();
  1016. find_page:
  1017. page = find_get_page(mapping, index);
  1018. if (!page) {
  1019. page_cache_sync_readahead(mapping,
  1020. ra, filp,
  1021. index, last_index - index);
  1022. page = find_get_page(mapping, index);
  1023. if (unlikely(page == NULL))
  1024. goto no_cached_page;
  1025. }
  1026. if (PageReadahead(page)) {
  1027. page_cache_async_readahead(mapping,
  1028. ra, filp, page,
  1029. index, last_index - index);
  1030. }
  1031. if (!PageUptodate(page)) {
  1032. if (inode->i_blkbits == PAGE_CACHE_SHIFT ||
  1033. !mapping->a_ops->is_partially_uptodate)
  1034. goto page_not_up_to_date;
  1035. if (!trylock_page(page))
  1036. goto page_not_up_to_date;
  1037. /* Did it get truncated before we got the lock? */
  1038. if (!page->mapping)
  1039. goto page_not_up_to_date_locked;
  1040. if (!mapping->a_ops->is_partially_uptodate(page,
  1041. desc, offset))
  1042. goto page_not_up_to_date_locked;
  1043. unlock_page(page);
  1044. }
  1045. page_ok:
  1046. /*
  1047. * i_size must be checked after we know the page is Uptodate.
  1048. *
  1049. * Checking i_size after the check allows us to calculate
  1050. * the correct value for "nr", which means the zero-filled
  1051. * part of the page is not copied back to userspace (unless
  1052. * another truncate extends the file - this is desired though).
  1053. */
  1054. isize = i_size_read(inode);
  1055. end_index = (isize - 1) >> PAGE_CACHE_SHIFT;
  1056. if (unlikely(!isize || index > end_index)) {
  1057. page_cache_release(page);
  1058. goto out;
  1059. }
  1060. /* nr is the maximum number of bytes to copy from this page */
  1061. nr = PAGE_CACHE_SIZE;
  1062. if (index == end_index) {
  1063. nr = ((isize - 1) & ~PAGE_CACHE_MASK) + 1;
  1064. if (nr <= offset) {
  1065. page_cache_release(page);
  1066. goto out;
  1067. }
  1068. }
  1069. nr = nr - offset;
  1070. /* If users can be writing to this page using arbitrary
  1071. * virtual addresses, take care about potential aliasing
  1072. * before reading the page on the kernel side.
  1073. */
  1074. if (mapping_writably_mapped(mapping))
  1075. flush_dcache_page(page);
  1076. /*
  1077. * When a sequential read accesses a page several times,
  1078. * only mark it as accessed the first time.
  1079. */
  1080. if (prev_index != index || offset != prev_offset)
  1081. mark_page_accessed(page);
  1082. prev_index = index;
  1083. /*
  1084. * Ok, we have the page, and it's up-to-date, so
  1085. * now we can copy it to user space...
  1086. *
  1087. * The actor routine returns how many bytes were actually used..
  1088. * NOTE! This may not be the same as how much of a user buffer
  1089. * we filled up (we may be padding etc), so we can only update
  1090. * "pos" here (the actor routine has to update the user buffer
  1091. * pointers and the remaining count).
  1092. */
  1093. ret = actor(desc, page, offset, nr);
  1094. offset += ret;
  1095. index += offset >> PAGE_CACHE_SHIFT;
  1096. offset &= ~PAGE_CACHE_MASK;
  1097. prev_offset = offset;
  1098. page_cache_release(page);
  1099. if (ret == nr && desc->count)
  1100. continue;
  1101. goto out;
  1102. page_not_up_to_date:
  1103. /* Get exclusive access to the page ... */
  1104. error = lock_page_killable(page);
  1105. if (unlikely(error))
  1106. goto readpage_error;
  1107. page_not_up_to_date_locked:
  1108. /* Did it get truncated before we got the lock? */
  1109. if (!page->mapping) {
  1110. unlock_page(page);
  1111. page_cache_release(page);
  1112. continue;
  1113. }
  1114. /* Did somebody else fill it already? */
  1115. if (PageUptodate(page)) {
  1116. unlock_page(page);
  1117. goto page_ok;
  1118. }
  1119. readpage:
  1120. /*
  1121. * A previous I/O error may have been due to temporary
  1122. * failures, eg. multipath errors.
  1123. * PG_error will be set again if readpage fails.
  1124. */
  1125. ClearPageError(page);
  1126. /* Start the actual read. The read will unlock the page. */
  1127. error = mapping->a_ops->readpage(filp, page);
  1128. if (unlikely(error)) {
  1129. if (error == AOP_TRUNCATED_PAGE) {
  1130. page_cache_release(page);
  1131. goto find_page;
  1132. }
  1133. goto readpage_error;
  1134. }
  1135. if (!PageUptodate(page)) {
  1136. error = lock_page_killable(page);
  1137. if (unlikely(error))
  1138. goto readpage_error;
  1139. if (!PageUptodate(page)) {
  1140. if (page->mapping == NULL) {
  1141. /*
  1142. * invalidate_mapping_pages got it
  1143. */
  1144. unlock_page(page);
  1145. page_cache_release(page);
  1146. goto find_page;
  1147. }
  1148. unlock_page(page);
  1149. shrink_readahead_size_eio(filp, ra);
  1150. error = -EIO;
  1151. goto readpage_error;
  1152. }
  1153. unlock_page(page);
  1154. }
  1155. goto page_ok;
  1156. readpage_error:
  1157. /* UHHUH! A synchronous read error occurred. Report it */
  1158. desc->error = error;
  1159. page_cache_release(page);
  1160. goto out;
  1161. no_cached_page:
  1162. /*
  1163. * Ok, it wasn't cached, so we need to create a new
  1164. * page..
  1165. */
  1166. page = page_cache_alloc_cold(mapping);
  1167. if (!page) {
  1168. desc->error = -ENOMEM;
  1169. goto out;
  1170. }
  1171. error = add_to_page_cache_lru(page, mapping,
  1172. index, GFP_KERNEL);
  1173. if (error) {
  1174. page_cache_release(page);
  1175. if (error == -EEXIST)
  1176. goto find_page;
  1177. desc->error = error;
  1178. goto out;
  1179. }
  1180. goto readpage;
  1181. }
  1182. out:
  1183. ra->prev_pos = prev_index;
  1184. ra->prev_pos <<= PAGE_CACHE_SHIFT;
  1185. ra->prev_pos |= prev_offset;
  1186. *ppos = ((loff_t)index << PAGE_CACHE_SHIFT) + offset;
  1187. file_accessed(filp);
  1188. }
  1189. int file_read_actor(read_descriptor_t *desc, struct page *page,
  1190. unsigned long offset, unsigned long size)
  1191. {
  1192. char *kaddr;
  1193. unsigned long left, count = desc->count;
  1194. if (size > count)
  1195. size = count;
  1196. /*
  1197. * Faults on the destination of a read are common, so do it before
  1198. * taking the kmap.
  1199. */
  1200. if (!fault_in_pages_writeable(desc->arg.buf, size)) {
  1201. kaddr = kmap_atomic(page, KM_USER0);
  1202. left = __copy_to_user_inatomic(desc->arg.buf,
  1203. kaddr + offset, size);
  1204. kunmap_atomic(kaddr, KM_USER0);
  1205. if (left == 0)
  1206. goto success;
  1207. }
  1208. /* Do it the slow way */
  1209. kaddr = kmap(page);
  1210. left = __copy_to_user(desc->arg.buf, kaddr + offset, size);
  1211. kunmap(page);
  1212. if (left) {
  1213. size -= left;
  1214. desc->error = -EFAULT;
  1215. }
  1216. success:
  1217. desc->count = count - size;
  1218. desc->written += size;
  1219. desc->arg.buf += size;
  1220. return size;
  1221. }
  1222. /*
  1223. * Performs necessary checks before doing a write
  1224. * @iov: io vector request
  1225. * @nr_segs: number of segments in the iovec
  1226. * @count: number of bytes to write
  1227. * @access_flags: type of access: %VERIFY_READ or %VERIFY_WRITE
  1228. *
  1229. * Adjust number of segments and amount of bytes to write (nr_segs should be
  1230. * properly initialized first). Returns appropriate error code that caller
  1231. * should return or zero in case that write should be allowed.
  1232. */
  1233. int generic_segment_checks(const struct iovec *iov,
  1234. unsigned long *nr_segs, size_t *count, int access_flags)
  1235. {
  1236. unsigned long seg;
  1237. size_t cnt = 0;
  1238. for (seg = 0; seg < *nr_segs; seg++) {
  1239. const struct iovec *iv = &iov[seg];
  1240. /*
  1241. * If any segment has a negative length, or the cumulative
  1242. * length ever wraps negative then return -EINVAL.
  1243. */
  1244. cnt += iv->iov_len;
  1245. if (unlikely((ssize_t)(cnt|iv->iov_len) < 0))
  1246. return -EINVAL;
  1247. if (access_ok(access_flags, iv->iov_base, iv->iov_len))
  1248. continue;
  1249. if (seg == 0)
  1250. return -EFAULT;
  1251. *nr_segs = seg;
  1252. cnt -= iv->iov_len; /* This segment is no good */
  1253. break;
  1254. }
  1255. *count = cnt;
  1256. return 0;
  1257. }
  1258. EXPORT_SYMBOL(generic_segment_checks);
  1259. /**
  1260. * generic_file_aio_read - generic filesystem read routine
  1261. * @iocb: kernel I/O control block
  1262. * @iov: io vector request
  1263. * @nr_segs: number of segments in the iovec
  1264. * @pos: current file position
  1265. *
  1266. * This is the "read()" routine for all filesystems
  1267. * that can use the page cache directly.
  1268. */
  1269. ssize_t
  1270. generic_file_aio_read(struct kiocb *iocb, const struct iovec *iov,
  1271. unsigned long nr_segs, loff_t pos)
  1272. {
  1273. struct file *filp = iocb->ki_filp;
  1274. ssize_t retval;
  1275. unsigned long seg = 0;
  1276. size_t count;
  1277. loff_t *ppos = &iocb->ki_pos;
  1278. struct blk_plug plug;
  1279. count = 0;
  1280. retval = generic_segment_checks(iov, &nr_segs, &count, VERIFY_WRITE);
  1281. if (retval)
  1282. return retval;
  1283. blk_start_plug(&plug);
  1284. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  1285. if (filp->f_flags & O_DIRECT) {
  1286. loff_t size;
  1287. struct address_space *mapping;
  1288. struct inode *inode;
  1289. mapping = filp->f_mapping;
  1290. inode = mapping->host;
  1291. if (!count)
  1292. goto out; /* skip atime */
  1293. size = i_size_read(inode);
  1294. if (pos < size) {
  1295. retval = filemap_write_and_wait_range(mapping, pos,
  1296. pos + iov_length(iov, nr_segs) - 1);
  1297. if (!retval) {
  1298. retval = mapping->a_ops->direct_IO(READ, iocb,
  1299. iov, pos, nr_segs);
  1300. }
  1301. if (retval > 0) {
  1302. *ppos = pos + retval;
  1303. count -= retval;
  1304. }
  1305. /*
  1306. * Btrfs can have a short DIO read if we encounter
  1307. * compressed extents, so if there was an error, or if
  1308. * we've already read everything we wanted to, or if
  1309. * there was a short read because we hit EOF, go ahead
  1310. * and return. Otherwise fallthrough to buffered io for
  1311. * the rest of the read.
  1312. */
  1313. if (retval < 0 || !count || *ppos >= size) {
  1314. file_accessed(filp);
  1315. goto out;
  1316. }
  1317. }
  1318. }
  1319. count = retval;
  1320. for (seg = 0; seg < nr_segs; seg++) {
  1321. read_descriptor_t desc;
  1322. loff_t offset = 0;
  1323. /*
  1324. * If we did a short DIO read we need to skip the section of the
  1325. * iov that we've already read data into.
  1326. */
  1327. if (count) {
  1328. if (count > iov[seg].iov_len) {
  1329. count -= iov[seg].iov_len;
  1330. continue;
  1331. }
  1332. offset = count;
  1333. count = 0;
  1334. }
  1335. desc.written = 0;
  1336. desc.arg.buf = iov[seg].iov_base + offset;
  1337. desc.count = iov[seg].iov_len - offset;
  1338. if (desc.count == 0)
  1339. continue;
  1340. desc.error = 0;
  1341. do_generic_file_read(filp, ppos, &desc, file_read_actor);
  1342. retval += desc.written;
  1343. if (desc.error) {
  1344. retval = retval ?: desc.error;
  1345. break;
  1346. }
  1347. if (desc.count > 0)
  1348. break;
  1349. }
  1350. out:
  1351. blk_finish_plug(&plug);
  1352. return retval;
  1353. }
  1354. EXPORT_SYMBOL(generic_file_aio_read);
  1355. static ssize_t
  1356. do_readahead(struct address_space *mapping, struct file *filp,
  1357. pgoff_t index, unsigned long nr)
  1358. {
  1359. if (!mapping || !mapping->a_ops || !mapping->a_ops->readpage)
  1360. return -EINVAL;
  1361. force_page_cache_readahead(mapping, filp, index, nr);
  1362. return 0;
  1363. }
  1364. SYSCALL_DEFINE(readahead)(int fd, loff_t offset, size_t count)
  1365. {
  1366. ssize_t ret;
  1367. struct file *file;
  1368. ret = -EBADF;
  1369. file = fget(fd);
  1370. if (file) {
  1371. if (file->f_mode & FMODE_READ) {
  1372. struct address_space *mapping = file->f_mapping;
  1373. pgoff_t start = offset >> PAGE_CACHE_SHIFT;
  1374. pgoff_t end = (offset + count - 1) >> PAGE_CACHE_SHIFT;
  1375. unsigned long len = end - start + 1;
  1376. ret = do_readahead(mapping, file, start, len);
  1377. }
  1378. fput(file);
  1379. }
  1380. return ret;
  1381. }
  1382. #ifdef CONFIG_HAVE_SYSCALL_WRAPPERS
  1383. asmlinkage long SyS_readahead(long fd, loff_t offset, long count)
  1384. {
  1385. return SYSC_readahead((int) fd, offset, (size_t) count);
  1386. }
  1387. SYSCALL_ALIAS(sys_readahead, SyS_readahead);
  1388. #endif
  1389. #ifdef CONFIG_MMU
  1390. /**
  1391. * page_cache_read - adds requested page to the page cache if not already there
  1392. * @file: file to read
  1393. * @offset: page index
  1394. *
  1395. * This adds the requested page to the page cache if it isn't already there,
  1396. * and schedules an I/O to read in its contents from disk.
  1397. */
  1398. static int page_cache_read(struct file *file, pgoff_t offset)
  1399. {
  1400. struct address_space *mapping = file->f_mapping;
  1401. struct page *page;
  1402. int ret;
  1403. do {
  1404. page = page_cache_alloc_cold(mapping);
  1405. if (!page)
  1406. return -ENOMEM;
  1407. ret = add_to_page_cache_lru(page, mapping, offset, GFP_KERNEL);
  1408. if (ret == 0)
  1409. ret = mapping->a_ops->readpage(file, page);
  1410. else if (ret == -EEXIST)
  1411. ret = 0; /* losing race to add is OK */
  1412. page_cache_release(page);
  1413. } while (ret == AOP_TRUNCATED_PAGE);
  1414. return ret;
  1415. }
  1416. #define MMAP_LOTSAMISS (100)
  1417. /*
  1418. * Synchronous readahead happens when we don't even find
  1419. * a page in the page cache at all.
  1420. */
  1421. static void do_sync_mmap_readahead(struct vm_area_struct *vma,
  1422. struct file_ra_state *ra,
  1423. struct file *file,
  1424. pgoff_t offset)
  1425. {
  1426. unsigned long ra_pages;
  1427. struct address_space *mapping = file->f_mapping;
  1428. /* If we don't want any read-ahead, don't bother */
  1429. if (VM_RandomReadHint(vma))
  1430. return;
  1431. if (!ra->ra_pages)
  1432. return;
  1433. if (VM_SequentialReadHint(vma)) {
  1434. page_cache_sync_readahead(mapping, ra, file, offset,
  1435. ra->ra_pages);
  1436. return;
  1437. }
  1438. /* Avoid banging the cache line if not needed */
  1439. if (ra->mmap_miss < MMAP_LOTSAMISS * 10)
  1440. ra->mmap_miss++;
  1441. /*
  1442. * Do we miss much more than hit in this file? If so,
  1443. * stop bothering with read-ahead. It will only hurt.
  1444. */
  1445. if (ra->mmap_miss > MMAP_LOTSAMISS)
  1446. return;
  1447. /*
  1448. * mmap read-around
  1449. */
  1450. ra_pages = max_sane_readahead(ra->ra_pages);
  1451. ra->start = max_t(long, 0, offset - ra_pages / 2);
  1452. ra->size = ra_pages;
  1453. ra->async_size = ra_pages / 4;
  1454. ra_submit(ra, mapping, file);
  1455. }
  1456. /*
  1457. * Asynchronous readahead happens when we find the page and PG_readahead,
  1458. * so we want to possibly extend the readahead further..
  1459. */
  1460. static void do_async_mmap_readahead(struct vm_area_struct *vma,
  1461. struct file_ra_state *ra,
  1462. struct file *file,
  1463. struct page *page,
  1464. pgoff_t offset)
  1465. {
  1466. struct address_space *mapping = file->f_mapping;
  1467. /* If we don't want any read-ahead, don't bother */
  1468. if (VM_RandomReadHint(vma))
  1469. return;
  1470. if (ra->mmap_miss > 0)
  1471. ra->mmap_miss--;
  1472. if (PageReadahead(page))
  1473. page_cache_async_readahead(mapping, ra, file,
  1474. page, offset, ra->ra_pages);
  1475. }
  1476. /**
  1477. * filemap_fault - read in file data for page fault handling
  1478. * @vma: vma in which the fault was taken
  1479. * @vmf: struct vm_fault containing details of the fault
  1480. *
  1481. * filemap_fault() is invoked via the vma operations vector for a
  1482. * mapped memory region to read in file data during a page fault.
  1483. *
  1484. * The goto's are kind of ugly, but this streamlines the normal case of having
  1485. * it in the page cache, and handles the special cases reasonably without
  1486. * having a lot of duplicated code.
  1487. */
  1488. int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
  1489. {
  1490. int error;
  1491. struct file *file = vma->vm_file;
  1492. struct address_space *mapping = file->f_mapping;
  1493. struct file_ra_state *ra = &file->f_ra;
  1494. struct inode *inode = mapping->host;
  1495. pgoff_t offset = vmf->pgoff;
  1496. struct page *page;
  1497. pgoff_t size;
  1498. int ret = 0;
  1499. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1500. if (offset >= size)
  1501. return VM_FAULT_SIGBUS;
  1502. /*
  1503. * Do we have something in the page cache already?
  1504. */
  1505. page = find_get_page(mapping, offset);
  1506. if (likely(page)) {
  1507. /*
  1508. * We found the page, so try async readahead before
  1509. * waiting for the lock.
  1510. */
  1511. do_async_mmap_readahead(vma, ra, file, page, offset);
  1512. } else {
  1513. /* No page in the page cache at all */
  1514. do_sync_mmap_readahead(vma, ra, file, offset);
  1515. count_vm_event(PGMAJFAULT);
  1516. mem_cgroup_count_vm_event(vma->vm_mm, PGMAJFAULT);
  1517. ret = VM_FAULT_MAJOR;
  1518. retry_find:
  1519. page = find_get_page(mapping, offset);
  1520. if (!page)
  1521. goto no_cached_page;
  1522. }
  1523. if (!lock_page_or_retry(page, vma->vm_mm, vmf->flags)) {
  1524. page_cache_release(page);
  1525. return ret | VM_FAULT_RETRY;
  1526. }
  1527. /* Did it get truncated? */
  1528. if (unlikely(page->mapping != mapping)) {
  1529. unlock_page(page);
  1530. put_page(page);
  1531. goto retry_find;
  1532. }
  1533. VM_BUG_ON(page->index != offset);
  1534. /*
  1535. * We have a locked page in the page cache, now we need to check
  1536. * that it's up-to-date. If not, it is going to be due to an error.
  1537. */
  1538. if (unlikely(!PageUptodate(page)))
  1539. goto page_not_uptodate;
  1540. /*
  1541. * Found the page and have a reference on it.
  1542. * We must recheck i_size under page lock.
  1543. */
  1544. size = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
  1545. if (unlikely(offset >= size)) {
  1546. unlock_page(page);
  1547. page_cache_release(page);
  1548. return VM_FAULT_SIGBUS;
  1549. }
  1550. vmf->page = page;
  1551. return ret | VM_FAULT_LOCKED;
  1552. no_cached_page:
  1553. /*
  1554. * We're only likely to ever get here if MADV_RANDOM is in
  1555. * effect.
  1556. */
  1557. error = page_cache_read(file, offset);
  1558. /*
  1559. * The page we want has now been added to the page cache.
  1560. * In the unlikely event that someone removed it in the
  1561. * meantime, we'll just come back here and read it again.
  1562. */
  1563. if (error >= 0)
  1564. goto retry_find;
  1565. /*
  1566. * An error return from page_cache_read can result if the
  1567. * system is low on memory, or a problem occurs while trying
  1568. * to schedule I/O.
  1569. */
  1570. if (error == -ENOMEM)
  1571. return VM_FAULT_OOM;
  1572. return VM_FAULT_SIGBUS;
  1573. page_not_uptodate:
  1574. /*
  1575. * Umm, take care of errors if the page isn't up-to-date.
  1576. * Try to re-read it _once_. We do this synchronously,
  1577. * because there really aren't any performance issues here
  1578. * and we need to check for errors.
  1579. */
  1580. ClearPageError(page);
  1581. error = mapping->a_ops->readpage(file, page);
  1582. if (!error) {
  1583. wait_on_page_locked(page);
  1584. if (!PageUptodate(page))
  1585. error = -EIO;
  1586. }
  1587. page_cache_release(page);
  1588. if (!error || error == AOP_TRUNCATED_PAGE)
  1589. goto retry_find;
  1590. /* Things didn't work out. Return zero to tell the mm layer so. */
  1591. shrink_readahead_size_eio(file, ra);
  1592. return VM_FAULT_SIGBUS;
  1593. }
  1594. EXPORT_SYMBOL(filemap_fault);
  1595. const struct vm_operations_struct generic_file_vm_ops = {
  1596. .fault = filemap_fault,
  1597. };
  1598. /* This is used for a general mmap of a disk file */
  1599. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1600. {
  1601. struct address_space *mapping = file->f_mapping;
  1602. if (!mapping->a_ops->readpage)
  1603. return -ENOEXEC;
  1604. file_accessed(file);
  1605. vma->vm_ops = &generic_file_vm_ops;
  1606. vma->vm_flags |= VM_CAN_NONLINEAR;
  1607. return 0;
  1608. }
  1609. /*
  1610. * This is for filesystems which do not implement ->writepage.
  1611. */
  1612. int generic_file_readonly_mmap(struct file *file, struct vm_area_struct *vma)
  1613. {
  1614. if ((vma->vm_flags & VM_SHARED) && (vma->vm_flags & VM_MAYWRITE))
  1615. return -EINVAL;
  1616. return generic_file_mmap(file, vma);
  1617. }
  1618. #else
  1619. int generic_file_mmap(struct file * file, struct vm_area_struct * vma)
  1620. {
  1621. return -ENOSYS;
  1622. }
  1623. int generic_file_readonly_mmap(struct file * file, struct vm_area_struct * vma)
  1624. {
  1625. return -ENOSYS;
  1626. }
  1627. #endif /* CONFIG_MMU */
  1628. EXPORT_SYMBOL(generic_file_mmap);
  1629. EXPORT_SYMBOL(generic_file_readonly_mmap);
  1630. static struct page *__read_cache_page(struct address_space *mapping,
  1631. pgoff_t index,
  1632. int (*filler)(void *, struct page *),
  1633. void *data,
  1634. gfp_t gfp)
  1635. {
  1636. struct page *page;
  1637. int err;
  1638. repeat:
  1639. page = find_get_page(mapping, index);
  1640. if (!page) {
  1641. page = __page_cache_alloc(gfp | __GFP_COLD);
  1642. if (!page)
  1643. return ERR_PTR(-ENOMEM);
  1644. err = add_to_page_cache_lru(page, mapping, index, GFP_KERNEL);
  1645. if (unlikely(err)) {
  1646. page_cache_release(page);
  1647. if (err == -EEXIST)
  1648. goto repeat;
  1649. /* Presumably ENOMEM for radix tree node */
  1650. return ERR_PTR(err);
  1651. }
  1652. err = filler(data, page);
  1653. if (err < 0) {
  1654. page_cache_release(page);
  1655. page = ERR_PTR(err);
  1656. }
  1657. }
  1658. return page;
  1659. }
  1660. static struct page *do_read_cache_page(struct address_space *mapping,
  1661. pgoff_t index,
  1662. int (*filler)(void *, struct page *),
  1663. void *data,
  1664. gfp_t gfp)
  1665. {
  1666. struct page *page;
  1667. int err;
  1668. retry:
  1669. page = __read_cache_page(mapping, index, filler, data, gfp);
  1670. if (IS_ERR(page))
  1671. return page;
  1672. if (PageUptodate(page))
  1673. goto out;
  1674. lock_page(page);
  1675. if (!page->mapping) {
  1676. unlock_page(page);
  1677. page_cache_release(page);
  1678. goto retry;
  1679. }
  1680. if (PageUptodate(page)) {
  1681. unlock_page(page);
  1682. goto out;
  1683. }
  1684. err = filler(data, page);
  1685. if (err < 0) {
  1686. page_cache_release(page);
  1687. return ERR_PTR(err);
  1688. }
  1689. out:
  1690. mark_page_accessed(page);
  1691. return page;
  1692. }
  1693. /**
  1694. * read_cache_page_async - read into page cache, fill it if needed
  1695. * @mapping: the page's address_space
  1696. * @index: the page index
  1697. * @filler: function to perform the read
  1698. * @data: first arg to filler(data, page) function, often left as NULL
  1699. *
  1700. * Same as read_cache_page, but don't wait for page to become unlocked
  1701. * after submitting it to the filler.
  1702. *
  1703. * Read into the page cache. If a page already exists, and PageUptodate() is
  1704. * not set, try to fill the page but don't wait for it to become unlocked.
  1705. *
  1706. * If the page does not get brought uptodate, return -EIO.
  1707. */
  1708. struct page *read_cache_page_async(struct address_space *mapping,
  1709. pgoff_t index,
  1710. int (*filler)(void *, struct page *),
  1711. void *data)
  1712. {
  1713. return do_read_cache_page(mapping, index, filler, data, mapping_gfp_mask(mapping));
  1714. }
  1715. EXPORT_SYMBOL(read_cache_page_async);
  1716. static struct page *wait_on_page_read(struct page *page)
  1717. {
  1718. if (!IS_ERR(page)) {
  1719. wait_on_page_locked(page);
  1720. if (!PageUptodate(page)) {
  1721. page_cache_release(page);
  1722. page = ERR_PTR(-EIO);
  1723. }
  1724. }
  1725. return page;
  1726. }
  1727. /**
  1728. * read_cache_page_gfp - read into page cache, using specified page allocation flags.
  1729. * @mapping: the page's address_space
  1730. * @index: the page index
  1731. * @gfp: the page allocator flags to use if allocating
  1732. *
  1733. * This is the same as "read_mapping_page(mapping, index, NULL)", but with
  1734. * any new page allocations done using the specified allocation flags. Note
  1735. * that the Radix tree operations will still use GFP_KERNEL, so you can't
  1736. * expect to do this atomically or anything like that - but you can pass in
  1737. * other page requirements.
  1738. *
  1739. * If the page does not get brought uptodate, return -EIO.
  1740. */
  1741. struct page *read_cache_page_gfp(struct address_space *mapping,
  1742. pgoff_t index,
  1743. gfp_t gfp)
  1744. {
  1745. filler_t *filler = (filler_t *)mapping->a_ops->readpage;
  1746. return wait_on_page_read(do_read_cache_page(mapping, index, filler, NULL, gfp));
  1747. }
  1748. EXPORT_SYMBOL(read_cache_page_gfp);
  1749. /**
  1750. * read_cache_page - read into page cache, fill it if needed
  1751. * @mapping: the page's address_space
  1752. * @index: the page index
  1753. * @filler: function to perform the read
  1754. * @data: first arg to filler(data, page) function, often left as NULL
  1755. *
  1756. * Read into the page cache. If a page already exists, and PageUptodate() is
  1757. * not set, try to fill the page then wait for it to become unlocked.
  1758. *
  1759. * If the page does not get brought uptodate, return -EIO.
  1760. */
  1761. struct page *read_cache_page(struct address_space *mapping,
  1762. pgoff_t index,
  1763. int (*filler)(void *, struct page *),
  1764. void *data)
  1765. {
  1766. return wait_on_page_read(read_cache_page_async(mapping, index, filler, data));
  1767. }
  1768. EXPORT_SYMBOL(read_cache_page);
  1769. /*
  1770. * The logic we want is
  1771. *
  1772. * if suid or (sgid and xgrp)
  1773. * remove privs
  1774. */
  1775. int should_remove_suid(struct dentry *dentry)
  1776. {
  1777. mode_t mode = dentry->d_inode->i_mode;
  1778. int kill = 0;
  1779. /* suid always must be killed */
  1780. if (unlikely(mode & S_ISUID))
  1781. kill = ATTR_KILL_SUID;
  1782. /*
  1783. * sgid without any exec bits is just a mandatory locking mark; leave
  1784. * it alone. If some exec bits are set, it's a real sgid; kill it.
  1785. */
  1786. if (unlikely((mode & S_ISGID) && (mode & S_IXGRP)))
  1787. kill |= ATTR_KILL_SGID;
  1788. if (unlikely(kill && !capable(CAP_FSETID) && S_ISREG(mode)))
  1789. return kill;
  1790. return 0;
  1791. }
  1792. EXPORT_SYMBOL(should_remove_suid);
  1793. static int __remove_suid(struct dentry *dentry, int kill)
  1794. {
  1795. struct iattr newattrs;
  1796. newattrs.ia_valid = ATTR_FORCE | kill;
  1797. return notify_change(dentry, &newattrs);
  1798. }
  1799. int file_remove_suid(struct file *file)
  1800. {
  1801. struct dentry *dentry = file->f_path.dentry;
  1802. struct inode *inode = dentry->d_inode;
  1803. int killsuid;
  1804. int killpriv;
  1805. int error = 0;
  1806. /* Fast path for nothing security related */
  1807. if (IS_NOSEC(inode))
  1808. return 0;
  1809. killsuid = should_remove_suid(dentry);
  1810. killpriv = security_inode_need_killpriv(dentry);
  1811. if (killpriv < 0)
  1812. return killpriv;
  1813. if (killpriv)
  1814. error = security_inode_killpriv(dentry);
  1815. if (!error && killsuid)
  1816. error = __remove_suid(dentry, killsuid);
  1817. if (!error && (inode->i_sb->s_flags & MS_NOSEC))
  1818. inode->i_flags |= S_NOSEC;
  1819. return error;
  1820. }
  1821. EXPORT_SYMBOL(file_remove_suid);
  1822. static size_t __iovec_copy_from_user_inatomic(char *vaddr,
  1823. const struct iovec *iov, size_t base, size_t bytes)
  1824. {
  1825. size_t copied = 0, left = 0;
  1826. while (bytes) {
  1827. char __user *buf = iov->iov_base + base;
  1828. int copy = min(bytes, iov->iov_len - base);
  1829. base = 0;
  1830. left = __copy_from_user_inatomic(vaddr, buf, copy);
  1831. copied += copy;
  1832. bytes -= copy;
  1833. vaddr += copy;
  1834. iov++;
  1835. if (unlikely(left))
  1836. break;
  1837. }
  1838. return copied - left;
  1839. }
  1840. /*
  1841. * Copy as much as we can into the page and return the number of bytes which
  1842. * were successfully copied. If a fault is encountered then return the number of
  1843. * bytes which were copied.
  1844. */
  1845. size_t iov_iter_copy_from_user_atomic(struct page *page,
  1846. struct iov_iter *i, unsigned long offset, size_t bytes)
  1847. {
  1848. char *kaddr;
  1849. size_t copied;
  1850. BUG_ON(!in_atomic());
  1851. kaddr = kmap_atomic(page, KM_USER0);
  1852. if (likely(i->nr_segs == 1)) {
  1853. int left;
  1854. char __user *buf = i->iov->iov_base + i->iov_offset;
  1855. left = __copy_from_user_inatomic(kaddr + offset, buf, bytes);
  1856. copied = bytes - left;
  1857. } else {
  1858. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1859. i->iov, i->iov_offset, bytes);
  1860. }
  1861. kunmap_atomic(kaddr, KM_USER0);
  1862. return copied;
  1863. }
  1864. EXPORT_SYMBOL(iov_iter_copy_from_user_atomic);
  1865. /*
  1866. * This has the same sideeffects and return value as
  1867. * iov_iter_copy_from_user_atomic().
  1868. * The difference is that it attempts to resolve faults.
  1869. * Page must not be locked.
  1870. */
  1871. size_t iov_iter_copy_from_user(struct page *page,
  1872. struct iov_iter *i, unsigned long offset, size_t bytes)
  1873. {
  1874. char *kaddr;
  1875. size_t copied;
  1876. kaddr = kmap(page);
  1877. if (likely(i->nr_segs == 1)) {
  1878. int left;
  1879. char __user *buf = i->iov->iov_base + i->iov_offset;
  1880. left = __copy_from_user(kaddr + offset, buf, bytes);
  1881. copied = bytes - left;
  1882. } else {
  1883. copied = __iovec_copy_from_user_inatomic(kaddr + offset,
  1884. i->iov, i->iov_offset, bytes);
  1885. }
  1886. kunmap(page);
  1887. return copied;
  1888. }
  1889. EXPORT_SYMBOL(iov_iter_copy_from_user);
  1890. void iov_iter_advance(struct iov_iter *i, size_t bytes)
  1891. {
  1892. BUG_ON(i->count < bytes);
  1893. if (likely(i->nr_segs == 1)) {
  1894. i->iov_offset += bytes;
  1895. i->count -= bytes;
  1896. } else {
  1897. const struct iovec *iov = i->iov;
  1898. size_t base = i->iov_offset;
  1899. /*
  1900. * The !iov->iov_len check ensures we skip over unlikely
  1901. * zero-length segments (without overruning the iovec).
  1902. */
  1903. while (bytes || unlikely(i->count && !iov->iov_len)) {
  1904. int copy;
  1905. copy = min(bytes, iov->iov_len - base);
  1906. BUG_ON(!i->count || i->count < copy);
  1907. i->count -= copy;
  1908. bytes -= copy;
  1909. base += copy;
  1910. if (iov->iov_len == base) {
  1911. iov++;
  1912. base = 0;
  1913. }
  1914. }
  1915. i->iov = iov;
  1916. i->iov_offset = base;
  1917. }
  1918. }
  1919. EXPORT_SYMBOL(iov_iter_advance);
  1920. /*
  1921. * Fault in the first iovec of the given iov_iter, to a maximum length
  1922. * of bytes. Returns 0 on success, or non-zero if the memory could not be
  1923. * accessed (ie. because it is an invalid address).
  1924. *
  1925. * writev-intensive code may want this to prefault several iovecs -- that
  1926. * would be possible (callers must not rely on the fact that _only_ the
  1927. * first iovec will be faulted with the current implementation).
  1928. */
  1929. int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes)
  1930. {
  1931. char __user *buf = i->iov->iov_base + i->iov_offset;
  1932. bytes = min(bytes, i->iov->iov_len - i->iov_offset);
  1933. return fault_in_pages_readable(buf, bytes);
  1934. }
  1935. EXPORT_SYMBOL(iov_iter_fault_in_readable);
  1936. /*
  1937. * Return the count of just the current iov_iter segment.
  1938. */
  1939. size_t iov_iter_single_seg_count(struct iov_iter *i)
  1940. {
  1941. const struct iovec *iov = i->iov;
  1942. if (i->nr_segs == 1)
  1943. return i->count;
  1944. else
  1945. return min(i->count, iov->iov_len - i->iov_offset);
  1946. }
  1947. EXPORT_SYMBOL(iov_iter_single_seg_count);
  1948. /*
  1949. * Performs necessary checks before doing a write
  1950. *
  1951. * Can adjust writing position or amount of bytes to write.
  1952. * Returns appropriate error code that caller should return or
  1953. * zero in case that write should be allowed.
  1954. */
  1955. inline int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk)
  1956. {
  1957. struct inode *inode = file->f_mapping->host;
  1958. unsigned long limit = rlimit(RLIMIT_FSIZE);
  1959. if (unlikely(*pos < 0))
  1960. return -EINVAL;
  1961. if (!isblk) {
  1962. /* FIXME: this is for backwards compatibility with 2.4 */
  1963. if (file->f_flags & O_APPEND)
  1964. *pos = i_size_read(inode);
  1965. if (limit != RLIM_INFINITY) {
  1966. if (*pos >= limit) {
  1967. send_sig(SIGXFSZ, current, 0);
  1968. return -EFBIG;
  1969. }
  1970. if (*count > limit - (typeof(limit))*pos) {
  1971. *count = limit - (typeof(limit))*pos;
  1972. }
  1973. }
  1974. }
  1975. /*
  1976. * LFS rule
  1977. */
  1978. if (unlikely(*pos + *count > MAX_NON_LFS &&
  1979. !(file->f_flags & O_LARGEFILE))) {
  1980. if (*pos >= MAX_NON_LFS) {
  1981. return -EFBIG;
  1982. }
  1983. if (*count > MAX_NON_LFS - (unsigned long)*pos) {
  1984. *count = MAX_NON_LFS - (unsigned long)*pos;
  1985. }
  1986. }
  1987. /*
  1988. * Are we about to exceed the fs block limit ?
  1989. *
  1990. * If we have written data it becomes a short write. If we have
  1991. * exceeded without writing data we send a signal and return EFBIG.
  1992. * Linus frestrict idea will clean these up nicely..
  1993. */
  1994. if (likely(!isblk)) {
  1995. if (unlikely(*pos >= inode->i_sb->s_maxbytes)) {
  1996. if (*count || *pos > inode->i_sb->s_maxbytes) {
  1997. return -EFBIG;
  1998. }
  1999. /* zero-length writes at ->s_maxbytes are OK */
  2000. }
  2001. if (unlikely(*pos + *count > inode->i_sb->s_maxbytes))
  2002. *count = inode->i_sb->s_maxbytes - *pos;
  2003. } else {
  2004. #ifdef CONFIG_BLOCK
  2005. loff_t isize;
  2006. if (bdev_read_only(I_BDEV(inode)))
  2007. return -EPERM;
  2008. isize = i_size_read(inode);
  2009. if (*pos >= isize) {
  2010. if (*count || *pos > isize)
  2011. return -ENOSPC;
  2012. }
  2013. if (*pos + *count > isize)
  2014. *count = isize - *pos;
  2015. #else
  2016. return -EPERM;
  2017. #endif
  2018. }
  2019. return 0;
  2020. }
  2021. EXPORT_SYMBOL(generic_write_checks);
  2022. int pagecache_write_begin(struct file *file, struct address_space *mapping,
  2023. loff_t pos, unsigned len, unsigned flags,
  2024. struct page **pagep, void **fsdata)
  2025. {
  2026. const struct address_space_operations *aops = mapping->a_ops;
  2027. return aops->write_begin(file, mapping, pos, len, flags,
  2028. pagep, fsdata);
  2029. }
  2030. EXPORT_SYMBOL(pagecache_write_begin);
  2031. int pagecache_write_end(struct file *file, struct address_space *mapping,
  2032. loff_t pos, unsigned len, unsigned copied,
  2033. struct page *page, void *fsdata)
  2034. {
  2035. const struct address_space_operations *aops = mapping->a_ops;
  2036. mark_page_accessed(page);
  2037. return aops->write_end(file, mapping, pos, len, copied, page, fsdata);
  2038. }
  2039. EXPORT_SYMBOL(pagecache_write_end);
  2040. ssize_t
  2041. generic_file_direct_write(struct kiocb *iocb, const struct iovec *iov,
  2042. unsigned long *nr_segs, loff_t pos, loff_t *ppos,
  2043. size_t count, size_t ocount)
  2044. {
  2045. struct file *file = iocb->ki_filp;
  2046. struct address_space *mapping = file->f_mapping;
  2047. struct inode *inode = mapping->host;
  2048. ssize_t written;
  2049. size_t write_len;
  2050. pgoff_t end;
  2051. if (count != ocount)
  2052. *nr_segs = iov_shorten((struct iovec *)iov, *nr_segs, count);
  2053. write_len = iov_length(iov, *nr_segs);
  2054. end = (pos + write_len - 1) >> PAGE_CACHE_SHIFT;
  2055. written = filemap_write_and_wait_range(mapping, pos, pos + write_len - 1);
  2056. if (written)
  2057. goto out;
  2058. /*
  2059. * After a write we want buffered reads to be sure to go to disk to get
  2060. * the new data. We invalidate clean cached page from the region we're
  2061. * about to write. We do this *before* the write so that we can return
  2062. * without clobbering -EIOCBQUEUED from ->direct_IO().
  2063. */
  2064. if (mapping->nrpages) {
  2065. written = invalidate_inode_pages2_range(mapping,
  2066. pos >> PAGE_CACHE_SHIFT, end);
  2067. /*
  2068. * If a page can not be invalidated, return 0 to fall back
  2069. * to buffered write.
  2070. */
  2071. if (written) {
  2072. if (written == -EBUSY)
  2073. return 0;
  2074. goto out;
  2075. }
  2076. }
  2077. written = mapping->a_ops->direct_IO(WRITE, iocb, iov, pos, *nr_segs);
  2078. /*
  2079. * Finally, try again to invalidate clean pages which might have been
  2080. * cached by non-direct readahead, or faulted in by get_user_pages()
  2081. * if the source of the write was an mmap'ed region of the file
  2082. * we're writing. Either one is a pretty crazy thing to do,
  2083. * so we don't support it 100%. If this invalidation
  2084. * fails, tough, the write still worked...
  2085. */
  2086. if (mapping->nrpages) {
  2087. invalidate_inode_pages2_range(mapping,
  2088. pos >> PAGE_CACHE_SHIFT, end);
  2089. }
  2090. if (written > 0) {
  2091. pos += written;
  2092. if (pos > i_size_read(inode) && !S_ISBLK(inode->i_mode)) {
  2093. i_size_write(inode, pos);
  2094. mark_inode_dirty(inode);
  2095. }
  2096. *ppos = pos;
  2097. }
  2098. out:
  2099. return written;
  2100. }
  2101. EXPORT_SYMBOL(generic_file_direct_write);
  2102. /*
  2103. * Find or create a page at the given pagecache position. Return the locked
  2104. * page. This function is specifically for buffered writes.
  2105. */
  2106. struct page *grab_cache_page_write_begin(struct address_space *mapping,
  2107. pgoff_t index, unsigned flags)
  2108. {
  2109. int status;
  2110. struct page *page;
  2111. gfp_t gfp_notmask = 0;
  2112. if (flags & AOP_FLAG_NOFS)
  2113. gfp_notmask = __GFP_FS;
  2114. repeat:
  2115. page = find_lock_page(mapping, index);
  2116. if (page)
  2117. goto found;
  2118. page = __page_cache_alloc(mapping_gfp_mask(mapping) & ~gfp_notmask);
  2119. if (!page)
  2120. return NULL;
  2121. status = add_to_page_cache_lru(page, mapping, index,
  2122. GFP_KERNEL & ~gfp_notmask);
  2123. if (unlikely(status)) {
  2124. page_cache_release(page);
  2125. if (status == -EEXIST)
  2126. goto repeat;
  2127. return NULL;
  2128. }
  2129. found:
  2130. wait_on_page_writeback(page);
  2131. return page;
  2132. }
  2133. EXPORT_SYMBOL(grab_cache_page_write_begin);
  2134. static ssize_t generic_perform_write(struct file *file,
  2135. struct iov_iter *i, loff_t pos)
  2136. {
  2137. struct address_space *mapping = file->f_mapping;
  2138. const struct address_space_operations *a_ops = mapping->a_ops;
  2139. long status = 0;
  2140. ssize_t written = 0;
  2141. unsigned int flags = 0;
  2142. /*
  2143. * Copies from kernel address space cannot fail (NFSD is a big user).
  2144. */
  2145. if (segment_eq(get_fs(), KERNEL_DS))
  2146. flags |= AOP_FLAG_UNINTERRUPTIBLE;
  2147. do {
  2148. struct page *page;
  2149. unsigned long offset; /* Offset into pagecache page */
  2150. unsigned long bytes; /* Bytes to write to page */
  2151. size_t copied; /* Bytes copied from user */
  2152. void *fsdata;
  2153. offset = (pos & (PAGE_CACHE_SIZE - 1));
  2154. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2155. iov_iter_count(i));
  2156. again:
  2157. /*
  2158. * Bring in the user page that we will copy from _first_.
  2159. * Otherwise there's a nasty deadlock on copying from the
  2160. * same page as we're writing to, without it being marked
  2161. * up-to-date.
  2162. *
  2163. * Not only is this an optimisation, but it is also required
  2164. * to check that the address is actually valid, when atomic
  2165. * usercopies are used, below.
  2166. */
  2167. if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
  2168. status = -EFAULT;
  2169. break;
  2170. }
  2171. status = a_ops->write_begin(file, mapping, pos, bytes, flags,
  2172. &page, &fsdata);
  2173. if (unlikely(status))
  2174. break;
  2175. if (mapping_writably_mapped(mapping))
  2176. flush_dcache_page(page);
  2177. pagefault_disable();
  2178. copied = iov_iter_copy_from_user_atomic(page, i, offset, bytes);
  2179. pagefault_enable();
  2180. flush_dcache_page(page);
  2181. mark_page_accessed(page);
  2182. status = a_ops->write_end(file, mapping, pos, bytes, copied,
  2183. page, fsdata);
  2184. if (unlikely(status < 0))
  2185. break;
  2186. copied = status;
  2187. cond_resched();
  2188. iov_iter_advance(i, copied);
  2189. if (unlikely(copied == 0)) {
  2190. /*
  2191. * If we were unable to copy any data at all, we must
  2192. * fall back to a single segment length write.
  2193. *
  2194. * If we didn't fallback here, we could livelock
  2195. * because not all segments in the iov can be copied at
  2196. * once without a pagefault.
  2197. */
  2198. bytes = min_t(unsigned long, PAGE_CACHE_SIZE - offset,
  2199. iov_iter_single_seg_count(i));
  2200. goto again;
  2201. }
  2202. pos += copied;
  2203. written += copied;
  2204. balance_dirty_pages_ratelimited(mapping);
  2205. } while (iov_iter_count(i));
  2206. return written ? written : status;
  2207. }
  2208. ssize_t
  2209. generic_file_buffered_write(struct kiocb *iocb, const struct iovec *iov,
  2210. unsigned long nr_segs, loff_t pos, loff_t *ppos,
  2211. size_t count, ssize_t written)
  2212. {
  2213. struct file *file = iocb->ki_filp;
  2214. ssize_t status;
  2215. struct iov_iter i;
  2216. iov_iter_init(&i, iov, nr_segs, count, written);
  2217. status = generic_perform_write(file, &i, pos);
  2218. if (likely(status >= 0)) {
  2219. written += status;
  2220. *ppos = pos + status;
  2221. }
  2222. return written ? written : status;
  2223. }
  2224. EXPORT_SYMBOL(generic_file_buffered_write);
  2225. /**
  2226. * __generic_file_aio_write - write data to a file
  2227. * @iocb: IO state structure (file, offset, etc.)
  2228. * @iov: vector with data to write
  2229. * @nr_segs: number of segments in the vector
  2230. * @ppos: position where to write
  2231. *
  2232. * This function does all the work needed for actually writing data to a
  2233. * file. It does all basic checks, removes SUID from the file, updates
  2234. * modification times and calls proper subroutines depending on whether we
  2235. * do direct IO or a standard buffered write.
  2236. *
  2237. * It expects i_mutex to be grabbed unless we work on a block device or similar
  2238. * object which does not need locking at all.
  2239. *
  2240. * This function does *not* take care of syncing data in case of O_SYNC write.
  2241. * A caller has to handle it. This is mainly due to the fact that we want to
  2242. * avoid syncing under i_mutex.
  2243. */
  2244. ssize_t __generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2245. unsigned long nr_segs, loff_t *ppos)
  2246. {
  2247. struct file *file = iocb->ki_filp;
  2248. struct address_space * mapping = file->f_mapping;
  2249. size_t ocount; /* original count */
  2250. size_t count; /* after file limit checks */
  2251. struct inode *inode = mapping->host;
  2252. loff_t pos;
  2253. ssize_t written;
  2254. ssize_t err;
  2255. ocount = 0;
  2256. err = generic_segment_checks(iov, &nr_segs, &ocount, VERIFY_READ);
  2257. if (err)
  2258. return err;
  2259. count = ocount;
  2260. pos = *ppos;
  2261. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  2262. /* We can write back this queue in page reclaim */
  2263. current->backing_dev_info = mapping->backing_dev_info;
  2264. written = 0;
  2265. err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
  2266. if (err)
  2267. goto out;
  2268. if (count == 0)
  2269. goto out;
  2270. err = file_remove_suid(file);
  2271. if (err)
  2272. goto out;
  2273. file_update_time(file);
  2274. /* coalesce the iovecs and go direct-to-BIO for O_DIRECT */
  2275. if (unlikely(file->f_flags & O_DIRECT)) {
  2276. loff_t endbyte;
  2277. ssize_t written_buffered;
  2278. written = generic_file_direct_write(iocb, iov, &nr_segs, pos,
  2279. ppos, count, ocount);
  2280. if (written < 0 || written == count)
  2281. goto out;
  2282. /*
  2283. * direct-io write to a hole: fall through to buffered I/O
  2284. * for completing the rest of the request.
  2285. */
  2286. pos += written;
  2287. count -= written;
  2288. written_buffered = generic_file_buffered_write(iocb, iov,
  2289. nr_segs, pos, ppos, count,
  2290. written);
  2291. /*
  2292. * If generic_file_buffered_write() retuned a synchronous error
  2293. * then we want to return the number of bytes which were
  2294. * direct-written, or the error code if that was zero. Note
  2295. * that this differs from normal direct-io semantics, which
  2296. * will return -EFOO even if some bytes were written.
  2297. */
  2298. if (written_buffered < 0) {
  2299. err = written_buffered;
  2300. goto out;
  2301. }
  2302. /*
  2303. * We need to ensure that the page cache pages are written to
  2304. * disk and invalidated to preserve the expected O_DIRECT
  2305. * semantics.
  2306. */
  2307. endbyte = pos + written_buffered - written - 1;
  2308. err = filemap_write_and_wait_range(file->f_mapping, pos, endbyte);
  2309. if (err == 0) {
  2310. written = written_buffered;
  2311. invalidate_mapping_pages(mapping,
  2312. pos >> PAGE_CACHE_SHIFT,
  2313. endbyte >> PAGE_CACHE_SHIFT);
  2314. } else {
  2315. /*
  2316. * We don't know how much we wrote, so just return
  2317. * the number of bytes which were direct-written
  2318. */
  2319. }
  2320. } else {
  2321. written = generic_file_buffered_write(iocb, iov, nr_segs,
  2322. pos, ppos, count, written);
  2323. }
  2324. out:
  2325. current->backing_dev_info = NULL;
  2326. return written ? written : err;
  2327. }
  2328. EXPORT_SYMBOL(__generic_file_aio_write);
  2329. /**
  2330. * generic_file_aio_write - write data to a file
  2331. * @iocb: IO state structure
  2332. * @iov: vector with data to write
  2333. * @nr_segs: number of segments in the vector
  2334. * @pos: position in file where to write
  2335. *
  2336. * This is a wrapper around __generic_file_aio_write() to be used by most
  2337. * filesystems. It takes care of syncing the file in case of O_SYNC file
  2338. * and acquires i_mutex as needed.
  2339. */
  2340. ssize_t generic_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
  2341. unsigned long nr_segs, loff_t pos)
  2342. {
  2343. struct file *file = iocb->ki_filp;
  2344. struct inode *inode = file->f_mapping->host;
  2345. struct blk_plug plug;
  2346. ssize_t ret;
  2347. BUG_ON(iocb->ki_pos != pos);
  2348. mutex_lock(&inode->i_mutex);
  2349. blk_start_plug(&plug);
  2350. ret = __generic_file_aio_write(iocb, iov, nr_segs, &iocb->ki_pos);
  2351. mutex_unlock(&inode->i_mutex);
  2352. if (ret > 0 || ret == -EIOCBQUEUED) {
  2353. ssize_t err;
  2354. err = generic_write_sync(file, pos, ret);
  2355. if (err < 0 && ret > 0)
  2356. ret = err;
  2357. }
  2358. blk_finish_plug(&plug);
  2359. return ret;
  2360. }
  2361. EXPORT_SYMBOL(generic_file_aio_write);
  2362. /**
  2363. * try_to_release_page() - release old fs-specific metadata on a page
  2364. *
  2365. * @page: the page which the kernel is trying to free
  2366. * @gfp_mask: memory allocation flags (and I/O mode)
  2367. *
  2368. * The address_space is to try to release any data against the page
  2369. * (presumably at page->private). If the release was successful, return `1'.
  2370. * Otherwise return zero.
  2371. *
  2372. * This may also be called if PG_fscache is set on a page, indicating that the
  2373. * page is known to the local caching routines.
  2374. *
  2375. * The @gfp_mask argument specifies whether I/O may be performed to release
  2376. * this page (__GFP_IO), and whether the call may block (__GFP_WAIT & __GFP_FS).
  2377. *
  2378. */
  2379. int try_to_release_page(struct page *page, gfp_t gfp_mask)
  2380. {
  2381. struct address_space * const mapping = page->mapping;
  2382. BUG_ON(!PageLocked(page));
  2383. if (PageWriteback(page))
  2384. return 0;
  2385. if (mapping && mapping->a_ops->releasepage)
  2386. return mapping->a_ops->releasepage(page, gfp_mask);
  2387. return try_to_free_buffers(page);
  2388. }
  2389. EXPORT_SYMBOL(try_to_release_page);