filemap.c 80 KB

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