filemap.c 83 KB

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