filemap.c 67 KB

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