filemap.c 72 KB

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