filemap.c 72 KB

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