filemap.c 71 KB

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