filemap.c 72 KB

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