filemap.c 80 KB

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