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