filemap.c 76 KB

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