filemap.c 90 KB

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