filemap.c 66 KB

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