filemap.c 89 KB

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