filemap.c 90 KB

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