filemap.c 74 KB

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