filemap.c 81 KB

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