filemap.c 66 KB

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