2 * This file is part of UBIFS.
4 * Copyright (C) 2006-2008 Nokia Corporation.
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published by
8 * the Free Software Foundation.
10 * This program is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc., 51
17 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Authors: Artem Bityutskiy (Битюцкий Артём)
24 * This file implements VFS file and inode operations for regular files, device
25 * nodes and symlinks as well as address space operations.
27 * UBIFS uses 2 page flags: @PG_private and @PG_checked. @PG_private is set if
28 * the page is dirty and is used for optimization purposes - dirty pages are
29 * not budgeted so the flag shows that 'ubifs_write_end()' should not release
30 * the budget for this page. The @PG_checked flag is set if full budgeting is
31 * required for the page e.g., when it corresponds to a file hole or it is
32 * beyond the file size. The budgeting is done in 'ubifs_write_begin()', because
33 * it is OK to fail in this function, and the budget is released in
34 * 'ubifs_write_end()'. So the @PG_private and @PG_checked flags carry
35 * information about how the page was budgeted, to make it possible to release
36 * the budget properly.
38 * A thing to keep in mind: inode @i_mutex is locked in most VFS operations we
39 * implement. However, this is not true for 'ubifs_writepage()', which may be
40 * called with @i_mutex unlocked. For example, when pdflush is doing background
41 * write-back, it calls 'ubifs_writepage()' with unlocked @i_mutex. At "normal"
42 * work-paths the @i_mutex is locked in 'ubifs_writepage()', e.g. in the
43 * "sys_write -> alloc_pages -> direct reclaim path". So, in 'ubifs_writepage()'
44 * we are only guaranteed that the page is locked.
46 * Similarly, @i_mutex is not always locked in 'ubifs_readpage()', e.g., the
47 * read-ahead path does not lock it ("sys_read -> generic_file_aio_read ->
48 * ondemand_readahead -> readpage"). In case of readahead, @I_LOCK flag is not
49 * set as well. However, UBIFS disables readahead.
53 #include <linux/mount.h>
54 #include <linux/namei.h>
56 static int read_block(struct inode *inode, void *addr, unsigned int block,
57 struct ubifs_data_node *dn)
59 struct ubifs_info *c = inode->i_sb->s_fs_info;
60 int err, len, out_len;
64 data_key_init(c, &key, inode->i_ino, block);
65 err = ubifs_tnc_lookup(c, &key, dn);
68 /* Not found, so it must be a hole */
69 memset(addr, 0, UBIFS_BLOCK_SIZE);
73 ubifs_assert(le64_to_cpu(dn->ch.sqnum) >
74 ubifs_inode(inode)->creat_sqnum);
75 len = le32_to_cpu(dn->size);
76 if (len <= 0 || len > UBIFS_BLOCK_SIZE)
79 dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
80 out_len = UBIFS_BLOCK_SIZE;
81 err = ubifs_decompress(&dn->data, dlen, addr, &out_len,
82 le16_to_cpu(dn->compr_type));
83 if (err || len != out_len)
87 * Data length can be less than a full block, even for blocks that are
88 * not the last in the file (e.g., as a result of making a hole and
89 * appending data). Ensure that the remainder is zeroed out.
91 if (len < UBIFS_BLOCK_SIZE)
92 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
97 ubifs_err("bad data node (block %u, inode %lu)",
103 static int do_readpage(struct page *page)
107 unsigned int block, beyond;
108 struct ubifs_data_node *dn;
109 struct inode *inode = page->mapping->host;
110 loff_t i_size = i_size_read(inode);
112 dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
113 inode->i_ino, page->index, i_size, page->flags);
114 ubifs_assert(!PageChecked(page));
115 ubifs_assert(!PagePrivate(page));
119 block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
120 beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
121 if (block >= beyond) {
122 /* Reading beyond inode */
123 SetPageChecked(page);
124 memset(addr, 0, PAGE_CACHE_SIZE);
128 dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS);
138 if (block >= beyond) {
139 /* Reading beyond inode */
141 memset(addr, 0, UBIFS_BLOCK_SIZE);
143 ret = read_block(inode, addr, block, dn);
148 } else if (block + 1 == beyond) {
149 int dlen = le32_to_cpu(dn->size);
150 int ilen = i_size & (UBIFS_BLOCK_SIZE - 1);
152 if (ilen && ilen < dlen)
153 memset(addr + ilen, 0, dlen - ilen);
156 if (++i >= UBIFS_BLOCKS_PER_PAGE)
159 addr += UBIFS_BLOCK_SIZE;
162 if (err == -ENOENT) {
163 /* Not found, so it must be a hole */
164 SetPageChecked(page);
168 ubifs_err("cannot read page %lu of inode %lu, error %d",
169 page->index, inode->i_ino, err);
176 SetPageUptodate(page);
177 ClearPageError(page);
178 flush_dcache_page(page);
184 ClearPageUptodate(page);
186 flush_dcache_page(page);
192 * release_new_page_budget - release budget of a new page.
193 * @c: UBIFS file-system description object
195 * This is a helper function which releases budget corresponding to the budget
196 * of one new page of data.
198 static void release_new_page_budget(struct ubifs_info *c)
200 struct ubifs_budget_req req = { .recalculate = 1, .new_page = 1 };
202 ubifs_release_budget(c, &req);
206 * release_existing_page_budget - release budget of an existing page.
207 * @c: UBIFS file-system description object
209 * This is a helper function which releases budget corresponding to the budget
210 * of changing one one page of data which already exists on the flash media.
212 static void release_existing_page_budget(struct ubifs_info *c)
214 struct ubifs_budget_req req = { .dd_growth = c->page_budget};
216 ubifs_release_budget(c, &req);
219 static int write_begin_slow(struct address_space *mapping,
220 loff_t pos, unsigned len, struct page **pagep,
223 struct inode *inode = mapping->host;
224 struct ubifs_info *c = inode->i_sb->s_fs_info;
225 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
226 struct ubifs_budget_req req = { .new_page = 1 };
227 int uninitialized_var(err), appending = !!(pos + len > inode->i_size);
230 dbg_gen("ino %lu, pos %llu, len %u, i_size %lld",
231 inode->i_ino, pos, len, inode->i_size);
234 * At the slow path we have to budget before locking the page, because
235 * budgeting may force write-back, which would wait on locked pages and
236 * deadlock if we had the page locked. At this point we do not know
237 * anything about the page, so assume that this is a new page which is
238 * written to a hole. This corresponds to largest budget. Later the
239 * budget will be amended if this is not true.
242 /* We are appending data, budget for inode change */
245 err = ubifs_budget_space(c, &req);
249 page = grab_cache_page_write_begin(mapping, index, flags);
250 if (unlikely(!page)) {
251 ubifs_release_budget(c, &req);
255 if (!PageUptodate(page)) {
256 if (!(pos & ~PAGE_CACHE_MASK) && len == PAGE_CACHE_SIZE)
257 SetPageChecked(page);
259 err = do_readpage(page);
262 page_cache_release(page);
267 SetPageUptodate(page);
268 ClearPageError(page);
271 if (PagePrivate(page))
273 * The page is dirty, which means it was budgeted twice:
274 * o first time the budget was allocated by the task which
275 * made the page dirty and set the PG_private flag;
276 * o and then we budgeted for it for the second time at the
277 * very beginning of this function.
279 * So what we have to do is to release the page budget we
282 release_new_page_budget(c);
283 else if (!PageChecked(page))
285 * We are changing a page which already exists on the media.
286 * This means that changing the page does not make the amount
287 * of indexing information larger, and this part of the budget
288 * which we have already acquired may be released.
290 ubifs_convert_page_budget(c);
293 struct ubifs_inode *ui = ubifs_inode(inode);
296 * 'ubifs_write_end()' is optimized from the fast-path part of
297 * 'ubifs_write_begin()' and expects the @ui_mutex to be locked
298 * if data is appended.
300 mutex_lock(&ui->ui_mutex);
303 * The inode is dirty already, so we may free the
304 * budget we allocated.
306 ubifs_release_dirty_inode_budget(c, ui);
314 * allocate_budget - allocate budget for 'ubifs_write_begin()'.
315 * @c: UBIFS file-system description object
316 * @page: page to allocate budget for
317 * @ui: UBIFS inode object the page belongs to
318 * @appending: non-zero if the page is appended
320 * This is a helper function for 'ubifs_write_begin()' which allocates budget
321 * for the operation. The budget is allocated differently depending on whether
322 * this is appending, whether the page is dirty or not, and so on. This
323 * function leaves the @ui->ui_mutex locked in case of appending. Returns zero
324 * in case of success and %-ENOSPC in case of failure.
326 static int allocate_budget(struct ubifs_info *c, struct page *page,
327 struct ubifs_inode *ui, int appending)
329 struct ubifs_budget_req req = { .fast = 1 };
331 if (PagePrivate(page)) {
334 * The page is dirty and we are not appending, which
335 * means no budget is needed at all.
339 mutex_lock(&ui->ui_mutex);
342 * The page is dirty and we are appending, so the inode
343 * has to be marked as dirty. However, it is already
344 * dirty, so we do not need any budget. We may return,
345 * but @ui->ui_mutex hast to be left locked because we
346 * should prevent write-back from flushing the inode
347 * and freeing the budget. The lock will be released in
348 * 'ubifs_write_end()'.
353 * The page is dirty, we are appending, the inode is clean, so
354 * we need to budget the inode change.
358 if (PageChecked(page))
360 * The page corresponds to a hole and does not
361 * exist on the media. So changing it makes
362 * make the amount of indexing information
363 * larger, and we have to budget for a new
369 * Not a hole, the change will not add any new
370 * indexing information, budget for page
373 req.dirtied_page = 1;
376 mutex_lock(&ui->ui_mutex);
379 * The inode is clean but we will have to mark
380 * it as dirty because we are appending. This
387 return ubifs_budget_space(c, &req);
391 * This function is called when a page of data is going to be written. Since
392 * the page of data will not necessarily go to the flash straight away, UBIFS
393 * has to reserve space on the media for it, which is done by means of
396 * This is the hot-path of the file-system and we are trying to optimize it as
397 * much as possible. For this reasons it is split on 2 parts - slow and fast.
399 * There many budgeting cases:
400 * o a new page is appended - we have to budget for a new page and for
401 * changing the inode; however, if the inode is already dirty, there is
402 * no need to budget for it;
403 * o an existing clean page is changed - we have budget for it; if the page
404 * does not exist on the media (a hole), we have to budget for a new
405 * page; otherwise, we may budget for changing an existing page; the
406 * difference between these cases is that changing an existing page does
407 * not introduce anything new to the FS indexing information, so it does
408 * not grow, and smaller budget is acquired in this case;
409 * o an existing dirty page is changed - no need to budget at all, because
410 * the page budget has been acquired by earlier, when the page has been
413 * UBIFS budgeting sub-system may force write-back if it thinks there is no
414 * space to reserve. This imposes some locking restrictions and makes it
415 * impossible to take into account the above cases, and makes it impossible to
416 * optimize budgeting.
418 * The solution for this is that the fast path of 'ubifs_write_begin()' assumes
419 * there is a plenty of flash space and the budget will be acquired quickly,
420 * without forcing write-back. The slow path does not make this assumption.
422 static int ubifs_write_begin(struct file *file, struct address_space *mapping,
423 loff_t pos, unsigned len, unsigned flags,
424 struct page **pagep, void **fsdata)
426 struct inode *inode = mapping->host;
427 struct ubifs_info *c = inode->i_sb->s_fs_info;
428 struct ubifs_inode *ui = ubifs_inode(inode);
429 pgoff_t index = pos >> PAGE_CACHE_SHIFT;
430 int uninitialized_var(err), appending = !!(pos + len > inode->i_size);
431 int skipped_read = 0;
434 ubifs_assert(ubifs_inode(inode)->ui_size == inode->i_size);
436 if (unlikely(c->ro_media))
439 /* Try out the fast-path part first */
440 page = grab_cache_page_write_begin(mapping, index, flags);
444 if (!PageUptodate(page)) {
445 /* The page is not loaded from the flash */
446 if (!(pos & ~PAGE_CACHE_MASK) && len == PAGE_CACHE_SIZE) {
448 * We change whole page so no need to load it. But we
449 * have to set the @PG_checked flag to make the further
450 * code know that the page is new. This might be not
451 * true, but it is better to budget more than to read
452 * the page from the media.
454 SetPageChecked(page);
457 err = do_readpage(page);
460 page_cache_release(page);
465 SetPageUptodate(page);
466 ClearPageError(page);
469 err = allocate_budget(c, page, ui, appending);
471 ubifs_assert(err == -ENOSPC);
473 * If we skipped reading the page because we were going to
474 * write all of it, then it is not up to date.
477 ClearPageChecked(page);
478 ClearPageUptodate(page);
481 * Budgeting failed which means it would have to force
482 * write-back but didn't, because we set the @fast flag in the
483 * request. Write-back cannot be done now, while we have the
484 * page locked, because it would deadlock. Unlock and free
485 * everything and fall-back to slow-path.
488 ubifs_assert(mutex_is_locked(&ui->ui_mutex));
489 mutex_unlock(&ui->ui_mutex);
492 page_cache_release(page);
494 return write_begin_slow(mapping, pos, len, pagep, flags);
498 * Whee, we acquired budgeting quickly - without involving
499 * garbage-collection, committing or forcing write-back. We return
500 * with @ui->ui_mutex locked if we are appending pages, and unlocked
501 * otherwise. This is an optimization (slightly hacky though).
509 * cancel_budget - cancel budget.
510 * @c: UBIFS file-system description object
511 * @page: page to cancel budget for
512 * @ui: UBIFS inode object the page belongs to
513 * @appending: non-zero if the page is appended
515 * This is a helper function for a page write operation. It unlocks the
516 * @ui->ui_mutex in case of appending.
518 static void cancel_budget(struct ubifs_info *c, struct page *page,
519 struct ubifs_inode *ui, int appending)
523 ubifs_release_dirty_inode_budget(c, ui);
524 mutex_unlock(&ui->ui_mutex);
526 if (!PagePrivate(page)) {
527 if (PageChecked(page))
528 release_new_page_budget(c);
530 release_existing_page_budget(c);
534 static int ubifs_write_end(struct file *file, struct address_space *mapping,
535 loff_t pos, unsigned len, unsigned copied,
536 struct page *page, void *fsdata)
538 struct inode *inode = mapping->host;
539 struct ubifs_inode *ui = ubifs_inode(inode);
540 struct ubifs_info *c = inode->i_sb->s_fs_info;
541 loff_t end_pos = pos + len;
542 int appending = !!(end_pos > inode->i_size);
544 dbg_gen("ino %lu, pos %llu, pg %lu, len %u, copied %d, i_size %lld",
545 inode->i_ino, pos, page->index, len, copied, inode->i_size);
547 if (unlikely(copied < len && len == PAGE_CACHE_SIZE)) {
549 * VFS copied less data to the page that it intended and
550 * declared in its '->write_begin()' call via the @len
551 * argument. If the page was not up-to-date, and @len was
552 * @PAGE_CACHE_SIZE, the 'ubifs_write_begin()' function did
553 * not load it from the media (for optimization reasons). This
554 * means that part of the page contains garbage. So read the
557 dbg_gen("copied %d instead of %d, read page and repeat",
559 cancel_budget(c, page, ui, appending);
562 * Return 0 to force VFS to repeat the whole operation, or the
563 * error code if 'do_readpage()' fails.
565 copied = do_readpage(page);
569 if (!PagePrivate(page)) {
570 SetPagePrivate(page);
571 atomic_long_inc(&c->dirty_pg_cnt);
572 __set_page_dirty_nobuffers(page);
576 i_size_write(inode, end_pos);
577 ui->ui_size = end_pos;
579 * Note, we do not set @I_DIRTY_PAGES (which means that the
580 * inode has dirty pages), this has been done in
581 * '__set_page_dirty_nobuffers()'.
583 __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
584 ubifs_assert(mutex_is_locked(&ui->ui_mutex));
585 mutex_unlock(&ui->ui_mutex);
590 page_cache_release(page);
595 * populate_page - copy data nodes into a page for bulk-read.
596 * @c: UBIFS file-system description object
598 * @bu: bulk-read information
599 * @n: next zbranch slot
601 * This function returns %0 on success and a negative error code on failure.
603 static int populate_page(struct ubifs_info *c, struct page *page,
604 struct bu_info *bu, int *n)
606 int i = 0, nn = *n, offs = bu->zbranch[0].offs, hole = 0, read = 0;
607 struct inode *inode = page->mapping->host;
608 loff_t i_size = i_size_read(inode);
609 unsigned int page_block;
613 dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
614 inode->i_ino, page->index, i_size, page->flags);
616 addr = zaddr = kmap(page);
618 end_index = (i_size - 1) >> PAGE_CACHE_SHIFT;
619 if (!i_size || page->index > end_index) {
621 memset(addr, 0, PAGE_CACHE_SIZE);
625 page_block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
627 int err, len, out_len, dlen;
631 memset(addr, 0, UBIFS_BLOCK_SIZE);
632 } else if (key_block(c, &bu->zbranch[nn].key) == page_block) {
633 struct ubifs_data_node *dn;
635 dn = bu->buf + (bu->zbranch[nn].offs - offs);
637 ubifs_assert(le64_to_cpu(dn->ch.sqnum) >
638 ubifs_inode(inode)->creat_sqnum);
640 len = le32_to_cpu(dn->size);
641 if (len <= 0 || len > UBIFS_BLOCK_SIZE)
644 dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
645 out_len = UBIFS_BLOCK_SIZE;
646 err = ubifs_decompress(&dn->data, dlen, addr, &out_len,
647 le16_to_cpu(dn->compr_type));
648 if (err || len != out_len)
651 if (len < UBIFS_BLOCK_SIZE)
652 memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);
655 read = (i << UBIFS_BLOCK_SHIFT) + len;
656 } else if (key_block(c, &bu->zbranch[nn].key) < page_block) {
661 memset(addr, 0, UBIFS_BLOCK_SIZE);
663 if (++i >= UBIFS_BLOCKS_PER_PAGE)
665 addr += UBIFS_BLOCK_SIZE;
669 if (end_index == page->index) {
670 int len = i_size & (PAGE_CACHE_SIZE - 1);
672 if (len && len < read)
673 memset(zaddr + len, 0, read - len);
678 SetPageChecked(page);
682 SetPageUptodate(page);
683 ClearPageError(page);
684 flush_dcache_page(page);
690 ClearPageUptodate(page);
692 flush_dcache_page(page);
694 ubifs_err("bad data node (block %u, inode %lu)",
695 page_block, inode->i_ino);
700 * ubifs_do_bulk_read - do bulk-read.
701 * @c: UBIFS file-system description object
702 * @bu: bulk-read information
703 * @page1: first page to read
705 * This function returns %1 if the bulk-read is done, otherwise %0 is returned.
707 static int ubifs_do_bulk_read(struct ubifs_info *c, struct bu_info *bu,
710 pgoff_t offset = page1->index, end_index;
711 struct address_space *mapping = page1->mapping;
712 struct inode *inode = mapping->host;
713 struct ubifs_inode *ui = ubifs_inode(inode);
714 int err, page_idx, page_cnt, ret = 0, n = 0;
715 int allocate = bu->buf ? 0 : 1;
718 err = ubifs_tnc_get_bu_keys(c, bu);
723 /* Turn off bulk-read at the end of the file */
724 ui->read_in_a_row = 1;
728 page_cnt = bu->blk_cnt >> UBIFS_BLOCKS_PER_PAGE_SHIFT;
731 * This happens when there are multiple blocks per page and the
732 * blocks for the first page we are looking for, are not
733 * together. If all the pages were like this, bulk-read would
734 * reduce performance, so we turn it off for a while.
742 * Allocate bulk-read buffer depending on how many data
743 * nodes we are going to read.
745 bu->buf_len = bu->zbranch[bu->cnt - 1].offs +
746 bu->zbranch[bu->cnt - 1].len -
748 ubifs_assert(bu->buf_len > 0);
749 ubifs_assert(bu->buf_len <= c->leb_size);
750 bu->buf = kmalloc(bu->buf_len, GFP_NOFS | __GFP_NOWARN);
755 err = ubifs_tnc_bulk_read(c, bu);
760 err = populate_page(c, page1, bu, &n);
767 isize = i_size_read(inode);
770 end_index = ((isize - 1) >> PAGE_CACHE_SHIFT);
772 for (page_idx = 1; page_idx < page_cnt; page_idx++) {
773 pgoff_t page_offset = offset + page_idx;
776 if (page_offset > end_index)
778 page = find_or_create_page(mapping, page_offset,
779 GFP_NOFS | __GFP_COLD);
782 if (!PageUptodate(page))
783 err = populate_page(c, page, bu, &n);
785 page_cache_release(page);
790 ui->last_page_read = offset + page_idx - 1;
798 ubifs_warn("ignoring error %d and skipping bulk-read", err);
802 ui->read_in_a_row = ui->bulk_read = 0;
807 * ubifs_bulk_read - determine whether to bulk-read and, if so, do it.
808 * @page: page from which to start bulk-read.
810 * Some flash media are capable of reading sequentially at faster rates. UBIFS
811 * bulk-read facility is designed to take advantage of that, by reading in one
812 * go consecutive data nodes that are also located consecutively in the same
813 * LEB. This function returns %1 if a bulk-read is done and %0 otherwise.
815 static int ubifs_bulk_read(struct page *page)
817 struct inode *inode = page->mapping->host;
818 struct ubifs_info *c = inode->i_sb->s_fs_info;
819 struct ubifs_inode *ui = ubifs_inode(inode);
820 pgoff_t index = page->index, last_page_read = ui->last_page_read;
822 int err = 0, allocated = 0;
824 ui->last_page_read = index;
829 * Bulk-read is protected by @ui->ui_mutex, but it is an optimization,
830 * so don't bother if we cannot lock the mutex.
832 if (!mutex_trylock(&ui->ui_mutex))
835 if (index != last_page_read + 1) {
836 /* Turn off bulk-read if we stop reading sequentially */
837 ui->read_in_a_row = 1;
843 if (!ui->bulk_read) {
844 ui->read_in_a_row += 1;
845 if (ui->read_in_a_row < 3)
847 /* Three reads in a row, so switch on bulk-read */
852 * If possible, try to use pre-allocated bulk-read information, which
853 * is protected by @c->bu_mutex.
855 if (mutex_trylock(&c->bu_mutex))
858 bu = kmalloc(sizeof(struct bu_info), GFP_NOFS | __GFP_NOWARN);
866 bu->buf_len = c->max_bu_buf_len;
867 data_key_init(c, &bu->key, inode->i_ino,
868 page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT);
869 err = ubifs_do_bulk_read(c, bu, page);
872 mutex_unlock(&c->bu_mutex);
877 mutex_unlock(&ui->ui_mutex);
881 static int ubifs_readpage(struct file *file, struct page *page)
883 if (ubifs_bulk_read(page))
890 static int do_writepage(struct page *page, int len)
892 int err = 0, i, blen;
896 struct inode *inode = page->mapping->host;
897 struct ubifs_info *c = inode->i_sb->s_fs_info;
900 spin_lock(&ui->ui_lock);
901 ubifs_assert(page->index <= ui->synced_i_size << PAGE_CACHE_SIZE);
902 spin_unlock(&ui->ui_lock);
905 /* Update radix tree tags */
906 set_page_writeback(page);
909 block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
912 blen = min_t(int, len, UBIFS_BLOCK_SIZE);
913 data_key_init(c, &key, inode->i_ino, block);
914 err = ubifs_jnl_write_data(c, inode, &key, addr, blen);
917 if (++i >= UBIFS_BLOCKS_PER_PAGE)
925 ubifs_err("cannot write page %lu of inode %lu, error %d",
926 page->index, inode->i_ino, err);
927 ubifs_ro_mode(c, err);
930 ubifs_assert(PagePrivate(page));
931 if (PageChecked(page))
932 release_new_page_budget(c);
934 release_existing_page_budget(c);
936 atomic_long_dec(&c->dirty_pg_cnt);
937 ClearPagePrivate(page);
938 ClearPageChecked(page);
942 end_page_writeback(page);
947 * When writing-back dirty inodes, VFS first writes-back pages belonging to the
948 * inode, then the inode itself. For UBIFS this may cause a problem. Consider a
949 * situation when a we have an inode with size 0, then a megabyte of data is
950 * appended to the inode, then write-back starts and flushes some amount of the
951 * dirty pages, the journal becomes full, commit happens and finishes, and then
952 * an unclean reboot happens. When the file system is mounted next time, the
953 * inode size would still be 0, but there would be many pages which are beyond
954 * the inode size, they would be indexed and consume flash space. Because the
955 * journal has been committed, the replay would not be able to detect this
956 * situation and correct the inode size. This means UBIFS would have to scan
957 * whole index and correct all inode sizes, which is long an unacceptable.
959 * To prevent situations like this, UBIFS writes pages back only if they are
960 * within the last synchronized inode size, i.e. the size which has been
961 * written to the flash media last time. Otherwise, UBIFS forces inode
962 * write-back, thus making sure the on-flash inode contains current inode size,
963 * and then keeps writing pages back.
965 * Some locking issues explanation. 'ubifs_writepage()' first is called with
966 * the page locked, and it locks @ui_mutex. However, write-back does take inode
967 * @i_mutex, which means other VFS operations may be run on this inode at the
968 * same time. And the problematic one is truncation to smaller size, from where
969 * we have to call 'vmtruncate()', which first changes @inode->i_size, then
970 * drops the truncated pages. And while dropping the pages, it takes the page
971 * lock. This means that 'do_truncation()' cannot call 'vmtruncate()' with
972 * @ui_mutex locked, because it would deadlock with 'ubifs_writepage()'. This
973 * means that @inode->i_size is changed while @ui_mutex is unlocked.
975 * But in 'ubifs_writepage()' we have to guarantee that we do not write beyond
976 * inode size. How do we do this if @inode->i_size may became smaller while we
977 * are in the middle of 'ubifs_writepage()'? The UBIFS solution is the
978 * @ui->ui_isize "shadow" field which UBIFS uses instead of @inode->i_size
979 * internally and updates it under @ui_mutex.
981 * Q: why we do not worry that if we race with truncation, we may end up with a
982 * situation when the inode is truncated while we are in the middle of
983 * 'do_writepage()', so we do write beyond inode size?
984 * A: If we are in the middle of 'do_writepage()', truncation would be locked
985 * on the page lock and it would not write the truncated inode node to the
986 * journal before we have finished.
988 static int ubifs_writepage(struct page *page, struct writeback_control *wbc)
990 struct inode *inode = page->mapping->host;
991 struct ubifs_inode *ui = ubifs_inode(inode);
992 loff_t i_size = i_size_read(inode), synced_i_size;
993 pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT;
994 int err, len = i_size & (PAGE_CACHE_SIZE - 1);
997 dbg_gen("ino %lu, pg %lu, pg flags %#lx",
998 inode->i_ino, page->index, page->flags);
999 ubifs_assert(PagePrivate(page));
1001 /* Is the page fully outside @i_size? (truncate in progress) */
1002 if (page->index > end_index || (page->index == end_index && !len)) {
1007 spin_lock(&ui->ui_lock);
1008 synced_i_size = ui->synced_i_size;
1009 spin_unlock(&ui->ui_lock);
1011 /* Is the page fully inside @i_size? */
1012 if (page->index < end_index) {
1013 if (page->index >= synced_i_size >> PAGE_CACHE_SHIFT) {
1014 err = inode->i_sb->s_op->write_inode(inode, 1);
1018 * The inode has been written, but the write-buffer has
1019 * not been synchronized, so in case of an unclean
1020 * reboot we may end up with some pages beyond inode
1021 * size, but they would be in the journal (because
1022 * commit flushes write buffers) and recovery would deal
1026 return do_writepage(page, PAGE_CACHE_SIZE);
1030 * The page straddles @i_size. It must be zeroed out on each and every
1031 * writepage invocation because it may be mmapped. "A file is mapped
1032 * in multiples of the page size. For a file that is not a multiple of
1033 * the page size, the remaining memory is zeroed when mapped, and
1034 * writes to that region are not written out to the file."
1036 kaddr = kmap_atomic(page, KM_USER0);
1037 memset(kaddr + len, 0, PAGE_CACHE_SIZE - len);
1038 flush_dcache_page(page);
1039 kunmap_atomic(kaddr, KM_USER0);
1041 if (i_size > synced_i_size) {
1042 err = inode->i_sb->s_op->write_inode(inode, 1);
1047 return do_writepage(page, len);
1055 * do_attr_changes - change inode attributes.
1056 * @inode: inode to change attributes for
1057 * @attr: describes attributes to change
1059 static void do_attr_changes(struct inode *inode, const struct iattr *attr)
1061 if (attr->ia_valid & ATTR_UID)
1062 inode->i_uid = attr->ia_uid;
1063 if (attr->ia_valid & ATTR_GID)
1064 inode->i_gid = attr->ia_gid;
1065 if (attr->ia_valid & ATTR_ATIME)
1066 inode->i_atime = timespec_trunc(attr->ia_atime,
1067 inode->i_sb->s_time_gran);
1068 if (attr->ia_valid & ATTR_MTIME)
1069 inode->i_mtime = timespec_trunc(attr->ia_mtime,
1070 inode->i_sb->s_time_gran);
1071 if (attr->ia_valid & ATTR_CTIME)
1072 inode->i_ctime = timespec_trunc(attr->ia_ctime,
1073 inode->i_sb->s_time_gran);
1074 if (attr->ia_valid & ATTR_MODE) {
1075 umode_t mode = attr->ia_mode;
1077 if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
1079 inode->i_mode = mode;
1084 * do_truncation - truncate an inode.
1085 * @c: UBIFS file-system description object
1086 * @inode: inode to truncate
1087 * @attr: inode attribute changes description
1089 * This function implements VFS '->setattr()' call when the inode is truncated
1090 * to a smaller size. Returns zero in case of success and a negative error code
1091 * in case of failure.
1093 static int do_truncation(struct ubifs_info *c, struct inode *inode,
1094 const struct iattr *attr)
1097 struct ubifs_budget_req req;
1098 loff_t old_size = inode->i_size, new_size = attr->ia_size;
1099 int offset = new_size & (UBIFS_BLOCK_SIZE - 1), budgeted = 1;
1100 struct ubifs_inode *ui = ubifs_inode(inode);
1102 dbg_gen("ino %lu, size %lld -> %lld", inode->i_ino, old_size, new_size);
1103 memset(&req, 0, sizeof(struct ubifs_budget_req));
1106 * If this is truncation to a smaller size, and we do not truncate on a
1107 * block boundary, budget for changing one data block, because the last
1108 * block will be re-written.
1110 if (new_size & (UBIFS_BLOCK_SIZE - 1))
1111 req.dirtied_page = 1;
1113 req.dirtied_ino = 1;
1114 /* A funny way to budget for truncation node */
1115 req.dirtied_ino_d = UBIFS_TRUN_NODE_SZ;
1116 err = ubifs_budget_space(c, &req);
1119 * Treat truncations to zero as deletion and always allow them,
1120 * just like we do for '->unlink()'.
1122 if (new_size || err != -ENOSPC)
1127 err = vmtruncate(inode, new_size);
1132 pgoff_t index = new_size >> PAGE_CACHE_SHIFT;
1135 page = find_lock_page(inode->i_mapping, index);
1137 if (PageDirty(page)) {
1139 * 'ubifs_jnl_truncate()' will try to truncate
1140 * the last data node, but it contains
1141 * out-of-date data because the page is dirty.
1142 * Write the page now, so that
1143 * 'ubifs_jnl_truncate()' will see an already
1144 * truncated (and up to date) data node.
1146 ubifs_assert(PagePrivate(page));
1148 clear_page_dirty_for_io(page);
1149 if (UBIFS_BLOCKS_PER_PAGE_SHIFT)
1151 (PAGE_CACHE_SIZE - 1);
1152 err = do_writepage(page, offset);
1153 page_cache_release(page);
1157 * We could now tell 'ubifs_jnl_truncate()' not
1158 * to read the last block.
1162 * We could 'kmap()' the page and pass the data
1163 * to 'ubifs_jnl_truncate()' to save it from
1164 * having to read it.
1167 page_cache_release(page);
1172 mutex_lock(&ui->ui_mutex);
1173 ui->ui_size = inode->i_size;
1174 /* Truncation changes inode [mc]time */
1175 inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
1176 /* Other attributes may be changed at the same time as well */
1177 do_attr_changes(inode, attr);
1178 err = ubifs_jnl_truncate(c, inode, old_size, new_size);
1179 mutex_unlock(&ui->ui_mutex);
1183 ubifs_release_budget(c, &req);
1185 c->nospace = c->nospace_rp = 0;
1192 * do_setattr - change inode attributes.
1193 * @c: UBIFS file-system description object
1194 * @inode: inode to change attributes for
1195 * @attr: inode attribute changes description
1197 * This function implements VFS '->setattr()' call for all cases except
1198 * truncations to smaller size. Returns zero in case of success and a negative
1199 * error code in case of failure.
1201 static int do_setattr(struct ubifs_info *c, struct inode *inode,
1202 const struct iattr *attr)
1205 loff_t new_size = attr->ia_size;
1206 struct ubifs_inode *ui = ubifs_inode(inode);
1207 struct ubifs_budget_req req = { .dirtied_ino = 1,
1208 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1210 err = ubifs_budget_space(c, &req);
1214 if (attr->ia_valid & ATTR_SIZE) {
1215 dbg_gen("size %lld -> %lld", inode->i_size, new_size);
1216 err = vmtruncate(inode, new_size);
1221 mutex_lock(&ui->ui_mutex);
1222 if (attr->ia_valid & ATTR_SIZE) {
1223 /* Truncation changes inode [mc]time */
1224 inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
1225 /* 'vmtruncate()' changed @i_size, update @ui_size */
1226 ui->ui_size = inode->i_size;
1229 do_attr_changes(inode, attr);
1231 release = ui->dirty;
1232 if (attr->ia_valid & ATTR_SIZE)
1234 * Inode length changed, so we have to make sure
1235 * @I_DIRTY_DATASYNC is set.
1237 __mark_inode_dirty(inode, I_DIRTY_SYNC | I_DIRTY_DATASYNC);
1239 mark_inode_dirty_sync(inode);
1240 mutex_unlock(&ui->ui_mutex);
1243 ubifs_release_budget(c, &req);
1245 err = inode->i_sb->s_op->write_inode(inode, 1);
1249 ubifs_release_budget(c, &req);
1253 int ubifs_setattr(struct dentry *dentry, struct iattr *attr)
1256 struct inode *inode = dentry->d_inode;
1257 struct ubifs_info *c = inode->i_sb->s_fs_info;
1259 dbg_gen("ino %lu, mode %#x, ia_valid %#x",
1260 inode->i_ino, inode->i_mode, attr->ia_valid);
1261 err = inode_change_ok(inode, attr);
1265 err = dbg_check_synced_i_size(inode);
1269 if ((attr->ia_valid & ATTR_SIZE) && attr->ia_size < inode->i_size)
1270 /* Truncation to a smaller size */
1271 err = do_truncation(c, inode, attr);
1273 err = do_setattr(c, inode, attr);
1278 static void ubifs_invalidatepage(struct page *page, unsigned long offset)
1280 struct inode *inode = page->mapping->host;
1281 struct ubifs_info *c = inode->i_sb->s_fs_info;
1283 ubifs_assert(PagePrivate(page));
1285 /* Partial page remains dirty */
1288 if (PageChecked(page))
1289 release_new_page_budget(c);
1291 release_existing_page_budget(c);
1293 atomic_long_dec(&c->dirty_pg_cnt);
1294 ClearPagePrivate(page);
1295 ClearPageChecked(page);
1298 static void *ubifs_follow_link(struct dentry *dentry, struct nameidata *nd)
1300 struct ubifs_inode *ui = ubifs_inode(dentry->d_inode);
1302 nd_set_link(nd, ui->data);
1306 int ubifs_fsync(struct file *file, struct dentry *dentry, int datasync)
1308 struct inode *inode = dentry->d_inode;
1309 struct ubifs_info *c = inode->i_sb->s_fs_info;
1312 dbg_gen("syncing inode %lu", inode->i_ino);
1315 * VFS has already synchronized dirty pages for this inode. Synchronize
1316 * the inode unless this is a 'datasync()' call.
1318 if (!datasync || (inode->i_state & I_DIRTY_DATASYNC)) {
1319 err = inode->i_sb->s_op->write_inode(inode, 1);
1325 * Nodes related to this inode may still sit in a write-buffer. Flush
1328 err = ubifs_sync_wbufs_by_inode(c, inode);
1336 * mctime_update_needed - check if mtime or ctime update is needed.
1337 * @inode: the inode to do the check for
1338 * @now: current time
1340 * This helper function checks if the inode mtime/ctime should be updated or
1341 * not. If current values of the time-stamps are within the UBIFS inode time
1342 * granularity, they are not updated. This is an optimization.
1344 static inline int mctime_update_needed(const struct inode *inode,
1345 const struct timespec *now)
1347 if (!timespec_equal(&inode->i_mtime, now) ||
1348 !timespec_equal(&inode->i_ctime, now))
1354 * update_ctime - update mtime and ctime of an inode.
1355 * @c: UBIFS file-system description object
1356 * @inode: inode to update
1358 * This function updates mtime and ctime of the inode if it is not equivalent to
1359 * current time. Returns zero in case of success and a negative error code in
1362 static int update_mctime(struct ubifs_info *c, struct inode *inode)
1364 struct timespec now = ubifs_current_time(inode);
1365 struct ubifs_inode *ui = ubifs_inode(inode);
1367 if (mctime_update_needed(inode, &now)) {
1369 struct ubifs_budget_req req = { .dirtied_ino = 1,
1370 .dirtied_ino_d = ALIGN(ui->data_len, 8) };
1372 err = ubifs_budget_space(c, &req);
1376 mutex_lock(&ui->ui_mutex);
1377 inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
1378 release = ui->dirty;
1379 mark_inode_dirty_sync(inode);
1380 mutex_unlock(&ui->ui_mutex);
1382 ubifs_release_budget(c, &req);
1388 static ssize_t ubifs_aio_write(struct kiocb *iocb, const struct iovec *iov,
1389 unsigned long nr_segs, loff_t pos)
1393 struct inode *inode = iocb->ki_filp->f_mapping->host;
1394 struct ubifs_info *c = inode->i_sb->s_fs_info;
1396 err = update_mctime(c, inode);
1400 ret = generic_file_aio_write(iocb, iov, nr_segs, pos);
1404 if (ret > 0 && (IS_SYNC(inode) || iocb->ki_filp->f_flags & O_SYNC)) {
1405 err = ubifs_sync_wbufs_by_inode(c, inode);
1413 static int ubifs_set_page_dirty(struct page *page)
1417 ret = __set_page_dirty_nobuffers(page);
1419 * An attempt to dirty a page without budgeting for it - should not
1422 ubifs_assert(ret == 0);
1426 static int ubifs_releasepage(struct page *page, gfp_t unused_gfp_flags)
1429 * An attempt to release a dirty page without budgeting for it - should
1432 if (PageWriteback(page))
1434 ubifs_assert(PagePrivate(page));
1436 ClearPagePrivate(page);
1437 ClearPageChecked(page);
1442 * mmap()d file has taken write protection fault and is being made
1443 * writable. UBIFS must ensure page is budgeted for.
1445 static int ubifs_vm_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
1447 struct page *page = vmf->page;
1448 struct inode *inode = vma->vm_file->f_path.dentry->d_inode;
1449 struct ubifs_info *c = inode->i_sb->s_fs_info;
1450 struct timespec now = ubifs_current_time(inode);
1451 struct ubifs_budget_req req = { .new_page = 1 };
1452 int err, update_time;
1454 dbg_gen("ino %lu, pg %lu, i_size %lld", inode->i_ino, page->index,
1455 i_size_read(inode));
1456 ubifs_assert(!(inode->i_sb->s_flags & MS_RDONLY));
1458 if (unlikely(c->ro_media))
1459 return VM_FAULT_SIGBUS; /* -EROFS */
1462 * We have not locked @page so far so we may budget for changing the
1463 * page. Note, we cannot do this after we locked the page, because
1464 * budgeting may cause write-back which would cause deadlock.
1466 * At the moment we do not know whether the page is dirty or not, so we
1467 * assume that it is not and budget for a new page. We could look at
1468 * the @PG_private flag and figure this out, but we may race with write
1469 * back and the page state may change by the time we lock it, so this
1470 * would need additional care. We do not bother with this at the
1471 * moment, although it might be good idea to do. Instead, we allocate
1472 * budget for a new page and amend it later on if the page was in fact
1475 * The budgeting-related logic of this function is similar to what we
1476 * do in 'ubifs_write_begin()' and 'ubifs_write_end()'. Glance there
1477 * for more comments.
1479 update_time = mctime_update_needed(inode, &now);
1482 * We have to change inode time stamp which requires extra
1485 req.dirtied_ino = 1;
1487 err = ubifs_budget_space(c, &req);
1488 if (unlikely(err)) {
1490 ubifs_warn("out of space for mmapped file "
1491 "(inode number %lu)", inode->i_ino);
1492 return VM_FAULT_SIGBUS;
1496 if (unlikely(page->mapping != inode->i_mapping ||
1497 page_offset(page) > i_size_read(inode))) {
1498 /* Page got truncated out from underneath us */
1503 if (PagePrivate(page))
1504 release_new_page_budget(c);
1506 if (!PageChecked(page))
1507 ubifs_convert_page_budget(c);
1508 SetPagePrivate(page);
1509 atomic_long_inc(&c->dirty_pg_cnt);
1510 __set_page_dirty_nobuffers(page);
1515 struct ubifs_inode *ui = ubifs_inode(inode);
1517 mutex_lock(&ui->ui_mutex);
1518 inode->i_mtime = inode->i_ctime = ubifs_current_time(inode);
1519 release = ui->dirty;
1520 mark_inode_dirty_sync(inode);
1521 mutex_unlock(&ui->ui_mutex);
1523 ubifs_release_dirty_inode_budget(c, ui);
1531 ubifs_release_budget(c, &req);
1533 err = VM_FAULT_SIGBUS;
1537 static const struct vm_operations_struct ubifs_file_vm_ops = {
1538 .fault = filemap_fault,
1539 .page_mkwrite = ubifs_vm_page_mkwrite,
1542 static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma)
1546 /* 'generic_file_mmap()' takes care of NOMMU case */
1547 err = generic_file_mmap(file, vma);
1550 vma->vm_ops = &ubifs_file_vm_ops;
1554 const struct address_space_operations ubifs_file_address_operations = {
1555 .readpage = ubifs_readpage,
1556 .writepage = ubifs_writepage,
1557 .write_begin = ubifs_write_begin,
1558 .write_end = ubifs_write_end,
1559 .invalidatepage = ubifs_invalidatepage,
1560 .set_page_dirty = ubifs_set_page_dirty,
1561 .releasepage = ubifs_releasepage,
1564 const struct inode_operations ubifs_file_inode_operations = {
1565 .setattr = ubifs_setattr,
1566 .getattr = ubifs_getattr,
1567 #ifdef CONFIG_UBIFS_FS_XATTR
1568 .setxattr = ubifs_setxattr,
1569 .getxattr = ubifs_getxattr,
1570 .listxattr = ubifs_listxattr,
1571 .removexattr = ubifs_removexattr,
1575 const struct inode_operations ubifs_symlink_inode_operations = {
1576 .readlink = generic_readlink,
1577 .follow_link = ubifs_follow_link,
1578 .setattr = ubifs_setattr,
1579 .getattr = ubifs_getattr,
1582 const struct file_operations ubifs_file_operations = {
1583 .llseek = generic_file_llseek,
1584 .read = do_sync_read,
1585 .write = do_sync_write,
1586 .aio_read = generic_file_aio_read,
1587 .aio_write = ubifs_aio_write,
1588 .mmap = ubifs_file_mmap,
1589 .fsync = ubifs_fsync,
1590 .unlocked_ioctl = ubifs_ioctl,
1591 .splice_read = generic_file_splice_read,
1592 .splice_write = generic_file_splice_write,
1593 #ifdef CONFIG_COMPAT
1594 .compat_ioctl = ubifs_compat_ioctl,