filemap.c 90 KB

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