filemap.c 79 KB

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