filemap.c 65 KB

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