filemap.c 75 KB

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