filemap.c 89 KB

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