filemap.c 66 KB

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