filemap.c 80 KB

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