filemap.c 76 KB

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