filemap.c 70 KB

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