filemap.c 76 KB

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