file.c 46.8 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2 3 4 5 6 7 8 9 10 11
/*
 * This file is part of UBIFS.
 *
 * Copyright (C) 2006-2008 Nokia Corporation.
 *
 * Authors: Artem Bityutskiy (Битюцкий Артём)
 *          Adrian Hunter
 */

/*
A
Artem Bityutskiy 已提交
12
 * This file implements VFS file and inode operations for regular files, device
13 14
 * nodes and symlinks as well as address space operations.
 *
A
Artem Bityutskiy 已提交
15 16 17 18 19 20 21 22 23 24
 * UBIFS uses 2 page flags: @PG_private and @PG_checked. @PG_private is set if
 * the page is dirty and is used for optimization purposes - dirty pages are
 * not budgeted so the flag shows that 'ubifs_write_end()' should not release
 * the budget for this page. The @PG_checked flag is set if full budgeting is
 * required for the page e.g., when it corresponds to a file hole or it is
 * beyond the file size. The budgeting is done in 'ubifs_write_begin()', because
 * it is OK to fail in this function, and the budget is released in
 * 'ubifs_write_end()'. So the @PG_private and @PG_checked flags carry
 * information about how the page was budgeted, to make it possible to release
 * the budget properly.
25
 *
A
Artem Bityutskiy 已提交
26 27
 * A thing to keep in mind: inode @i_mutex is locked in most VFS operations we
 * implement. However, this is not true for 'ubifs_writepage()', which may be
28 29 30 31 32
 * called with @i_mutex unlocked. For example, when flusher thread is doing
 * background write-back, it calls 'ubifs_writepage()' with unlocked @i_mutex.
 * At "normal" work-paths the @i_mutex is locked in 'ubifs_writepage()', e.g.
 * in the "sys_write -> alloc_pages -> direct reclaim path". So, in
 * 'ubifs_writepage()' we are only guaranteed that the page is locked.
33
 *
A
Artem Bityutskiy 已提交
34 35
 * Similarly, @i_mutex is not always locked in 'ubifs_readpage()', e.g., the
 * read-ahead path does not lock it ("sys_read -> generic_file_aio_read ->
C
Christoph Hellwig 已提交
36
 * ondemand_readahead -> readpage"). In case of readahead, @I_SYNC flag is not
A
Artem Bityutskiy 已提交
37
 * set as well. However, UBIFS disables readahead.
38 39 40 41
 */

#include "ubifs.h"
#include <linux/mount.h>
42
#include <linux/slab.h>
43
#include <linux/migrate.h>
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

static int read_block(struct inode *inode, void *addr, unsigned int block,
		      struct ubifs_data_node *dn)
{
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	int err, len, out_len;
	union ubifs_key key;
	unsigned int dlen;

	data_key_init(c, &key, inode->i_ino, block);
	err = ubifs_tnc_lookup(c, &key, dn);
	if (err) {
		if (err == -ENOENT)
			/* Not found, so it must be a hole */
			memset(addr, 0, UBIFS_BLOCK_SIZE);
		return err;
	}

62
	ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
63
		     ubifs_inode(inode)->creat_sqnum);
64 65 66 67 68
	len = le32_to_cpu(dn->size);
	if (len <= 0 || len > UBIFS_BLOCK_SIZE)
		goto dump;

	dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
69

70
	if (IS_ENCRYPTED(inode)) {
71 72 73 74 75
		err = ubifs_decrypt(inode, dn, &dlen, block);
		if (err)
			goto dump;
	}

76
	out_len = UBIFS_BLOCK_SIZE;
77
	err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
			       le16_to_cpu(dn->compr_type));
	if (err || len != out_len)
		goto dump;

	/*
	 * Data length can be less than a full block, even for blocks that are
	 * not the last in the file (e.g., as a result of making a hole and
	 * appending data). Ensure that the remainder is zeroed out.
	 */
	if (len < UBIFS_BLOCK_SIZE)
		memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);

	return 0;

dump:
93
	ubifs_err(c, "bad data node (block %u, inode %lu)",
94
		  block, inode->i_ino);
95
	ubifs_dump_node(c, dn, UBIFS_MAX_DATA_NODE_SZ);
96 97 98 99 100 101 102 103 104 105
	return -EINVAL;
}

static int do_readpage(struct page *page)
{
	void *addr;
	int err = 0, i;
	unsigned int block, beyond;
	struct ubifs_data_node *dn;
	struct inode *inode = page->mapping->host;
106
	struct ubifs_info *c = inode->i_sb->s_fs_info;
107 108 109 110
	loff_t i_size = i_size_read(inode);

	dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
		inode->i_ino, page->index, i_size, page->flags);
111 112
	ubifs_assert(c, !PageChecked(page));
	ubifs_assert(c, !PagePrivate(page));
113 114 115 116 117 118 119 120

	addr = kmap(page);

	block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
	beyond = (i_size + UBIFS_BLOCK_SIZE - 1) >> UBIFS_BLOCK_SHIFT;
	if (block >= beyond) {
		/* Reading beyond inode */
		SetPageChecked(page);
121
		memset(addr, 0, PAGE_SIZE);
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
		goto out;
	}

	dn = kmalloc(UBIFS_MAX_DATA_NODE_SZ, GFP_NOFS);
	if (!dn) {
		err = -ENOMEM;
		goto error;
	}

	i = 0;
	while (1) {
		int ret;

		if (block >= beyond) {
			/* Reading beyond inode */
			err = -ENOENT;
			memset(addr, 0, UBIFS_BLOCK_SIZE);
		} else {
			ret = read_block(inode, addr, block, dn);
			if (ret) {
				err = ret;
				if (err != -ENOENT)
					break;
145 146 147 148 149 150
			} else if (block + 1 == beyond) {
				int dlen = le32_to_cpu(dn->size);
				int ilen = i_size & (UBIFS_BLOCK_SIZE - 1);

				if (ilen && ilen < dlen)
					memset(addr + ilen, 0, dlen - ilen);
151 152 153 154 155 156 157 158
			}
		}
		if (++i >= UBIFS_BLOCKS_PER_PAGE)
			break;
		block += 1;
		addr += UBIFS_BLOCK_SIZE;
	}
	if (err) {
159
		struct ubifs_info *c = inode->i_sb->s_fs_info;
160 161 162 163 164 165
		if (err == -ENOENT) {
			/* Not found, so it must be a hole */
			SetPageChecked(page);
			dbg_gen("hole");
			goto out_free;
		}
166
		ubifs_err(c, "cannot read page %lu of inode %lu, error %d",
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			  page->index, inode->i_ino, err);
		goto error;
	}

out_free:
	kfree(dn);
out:
	SetPageUptodate(page);
	ClearPageError(page);
	flush_dcache_page(page);
	kunmap(page);
	return 0;

error:
	kfree(dn);
	ClearPageUptodate(page);
	SetPageError(page);
	flush_dcache_page(page);
	kunmap(page);
	return err;
}

/**
 * release_new_page_budget - release budget of a new page.
 * @c: UBIFS file-system description object
 *
 * This is a helper function which releases budget corresponding to the budget
 * of one new page of data.
 */
static void release_new_page_budget(struct ubifs_info *c)
{
	struct ubifs_budget_req req = { .recalculate = 1, .new_page = 1 };

	ubifs_release_budget(c, &req);
}

/**
 * release_existing_page_budget - release budget of an existing page.
 * @c: UBIFS file-system description object
 *
 * This is a helper function which releases budget corresponding to the budget
208
 * of changing one page of data which already exists on the flash media.
209 210 211
 */
static void release_existing_page_budget(struct ubifs_info *c)
{
212
	struct ubifs_budget_req req = { .dd_growth = c->bi.page_budget};
213 214 215 216 217

	ubifs_release_budget(c, &req);
}

static int write_begin_slow(struct address_space *mapping,
218 219
			    loff_t pos, unsigned len, struct page **pagep,
			    unsigned flags)
220 221 222
{
	struct inode *inode = mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;
223
	pgoff_t index = pos >> PAGE_SHIFT;
224
	struct ubifs_budget_req req = { .new_page = 1 };
225
	int err, appending = !!(pos + len > inode->i_size);
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
	struct page *page;

	dbg_gen("ino %lu, pos %llu, len %u, i_size %lld",
		inode->i_ino, pos, len, inode->i_size);

	/*
	 * At the slow path we have to budget before locking the page, because
	 * budgeting may force write-back, which would wait on locked pages and
	 * deadlock if we had the page locked. At this point we do not know
	 * anything about the page, so assume that this is a new page which is
	 * written to a hole. This corresponds to largest budget. Later the
	 * budget will be amended if this is not true.
	 */
	if (appending)
		/* We are appending data, budget for inode change */
		req.dirtied_ino = 1;

	err = ubifs_budget_space(c, &req);
	if (unlikely(err))
		return err;

247
	page = grab_cache_page_write_begin(mapping, index, flags);
248 249 250 251 252 253
	if (unlikely(!page)) {
		ubifs_release_budget(c, &req);
		return -ENOMEM;
	}

	if (!PageUptodate(page)) {
254
		if (!(pos & ~PAGE_MASK) && len == PAGE_SIZE)
255 256 257 258 259
			SetPageChecked(page);
		else {
			err = do_readpage(page);
			if (err) {
				unlock_page(page);
260
				put_page(page);
261
				ubifs_release_budget(c, &req);
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
				return err;
			}
		}

		SetPageUptodate(page);
		ClearPageError(page);
	}

	if (PagePrivate(page))
		/*
		 * The page is dirty, which means it was budgeted twice:
		 *   o first time the budget was allocated by the task which
		 *     made the page dirty and set the PG_private flag;
		 *   o and then we budgeted for it for the second time at the
		 *     very beginning of this function.
		 *
		 * So what we have to do is to release the page budget we
		 * allocated.
		 */
		release_new_page_budget(c);
	else if (!PageChecked(page))
		/*
		 * We are changing a page which already exists on the media.
		 * This means that changing the page does not make the amount
		 * of indexing information larger, and this part of the budget
		 * which we have already acquired may be released.
		 */
		ubifs_convert_page_budget(c);

	if (appending) {
		struct ubifs_inode *ui = ubifs_inode(inode);

		/*
		 * 'ubifs_write_end()' is optimized from the fast-path part of
		 * 'ubifs_write_begin()' and expects the @ui_mutex to be locked
		 * if data is appended.
		 */
		mutex_lock(&ui->ui_mutex);
		if (ui->dirty)
			/*
			 * The inode is dirty already, so we may free the
			 * budget we allocated.
			 */
			ubifs_release_dirty_inode_budget(c, ui);
	}

	*pagep = page;
	return 0;
}

/**
 * allocate_budget - allocate budget for 'ubifs_write_begin()'.
 * @c: UBIFS file-system description object
 * @page: page to allocate budget for
 * @ui: UBIFS inode object the page belongs to
 * @appending: non-zero if the page is appended
 *
 * This is a helper function for 'ubifs_write_begin()' which allocates budget
 * for the operation. The budget is allocated differently depending on whether
 * this is appending, whether the page is dirty or not, and so on. This
 * function leaves the @ui->ui_mutex locked in case of appending. Returns zero
 * in case of success and %-ENOSPC in case of failure.
 */
static int allocate_budget(struct ubifs_info *c, struct page *page,
			   struct ubifs_inode *ui, int appending)
{
	struct ubifs_budget_req req = { .fast = 1 };

	if (PagePrivate(page)) {
		if (!appending)
			/*
			 * The page is dirty and we are not appending, which
			 * means no budget is needed at all.
			 */
			return 0;

		mutex_lock(&ui->ui_mutex);
		if (ui->dirty)
			/*
			 * The page is dirty and we are appending, so the inode
			 * has to be marked as dirty. However, it is already
			 * dirty, so we do not need any budget. We may return,
			 * but @ui->ui_mutex hast to be left locked because we
			 * should prevent write-back from flushing the inode
			 * and freeing the budget. The lock will be released in
			 * 'ubifs_write_end()'.
			 */
			return 0;

		/*
		 * The page is dirty, we are appending, the inode is clean, so
		 * we need to budget the inode change.
		 */
		req.dirtied_ino = 1;
	} else {
		if (PageChecked(page))
			/*
			 * The page corresponds to a hole and does not
			 * exist on the media. So changing it makes
			 * make the amount of indexing information
			 * larger, and we have to budget for a new
			 * page.
			 */
			req.new_page = 1;
		else
			/*
			 * Not a hole, the change will not add any new
			 * indexing information, budget for page
			 * change.
			 */
			req.dirtied_page = 1;

		if (appending) {
			mutex_lock(&ui->ui_mutex);
			if (!ui->dirty)
				/*
				 * The inode is clean but we will have to mark
				 * it as dirty because we are appending. This
				 * needs a budget.
				 */
				req.dirtied_ino = 1;
		}
	}

	return ubifs_budget_space(c, &req);
}

/*
 * This function is called when a page of data is going to be written. Since
 * the page of data will not necessarily go to the flash straight away, UBIFS
 * has to reserve space on the media for it, which is done by means of
 * budgeting.
 *
 * This is the hot-path of the file-system and we are trying to optimize it as
 * much as possible. For this reasons it is split on 2 parts - slow and fast.
 *
 * There many budgeting cases:
 *     o a new page is appended - we have to budget for a new page and for
 *       changing the inode; however, if the inode is already dirty, there is
 *       no need to budget for it;
 *     o an existing clean page is changed - we have budget for it; if the page
 *       does not exist on the media (a hole), we have to budget for a new
 *       page; otherwise, we may budget for changing an existing page; the
 *       difference between these cases is that changing an existing page does
 *       not introduce anything new to the FS indexing information, so it does
 *       not grow, and smaller budget is acquired in this case;
 *     o an existing dirty page is changed - no need to budget at all, because
 *       the page budget has been acquired by earlier, when the page has been
 *       marked dirty.
 *
 * UBIFS budgeting sub-system may force write-back if it thinks there is no
 * space to reserve. This imposes some locking restrictions and makes it
 * impossible to take into account the above cases, and makes it impossible to
 * optimize budgeting.
 *
 * The solution for this is that the fast path of 'ubifs_write_begin()' assumes
 * there is a plenty of flash space and the budget will be acquired quickly,
 * without forcing write-back. The slow path does not make this assumption.
 */
static int ubifs_write_begin(struct file *file, struct address_space *mapping,
			     loff_t pos, unsigned len, unsigned flags,
			     struct page **pagep, void **fsdata)
{
	struct inode *inode = mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	struct ubifs_inode *ui = ubifs_inode(inode);
428
	pgoff_t index = pos >> PAGE_SHIFT;
429
	int err, appending = !!(pos + len > inode->i_size);
430
	int skipped_read = 0;
431 432
	struct page *page;

433 434
	ubifs_assert(c, ubifs_inode(inode)->ui_size == inode->i_size);
	ubifs_assert(c, !c->ro_media && !c->ro_mount);
435

436
	if (unlikely(c->ro_error))
437 438 439
		return -EROFS;

	/* Try out the fast-path part first */
440
	page = grab_cache_page_write_begin(mapping, index, flags);
441 442 443 444 445
	if (unlikely(!page))
		return -ENOMEM;

	if (!PageUptodate(page)) {
		/* The page is not loaded from the flash */
446
		if (!(pos & ~PAGE_MASK) && len == PAGE_SIZE) {
447 448
			/*
			 * We change whole page so no need to load it. But we
449 450 451 452 453 454
			 * do not know whether this page exists on the media or
			 * not, so we assume the latter because it requires
			 * larger budget. The assumption is that it is better
			 * to budget a bit more than to read the page from the
			 * media. Thus, we are setting the @PG_checked flag
			 * here.
455 456
			 */
			SetPageChecked(page);
457 458
			skipped_read = 1;
		} else {
459 460 461
			err = do_readpage(page);
			if (err) {
				unlock_page(page);
462
				put_page(page);
463 464 465 466 467 468 469 470 471 472
				return err;
			}
		}

		SetPageUptodate(page);
		ClearPageError(page);
	}

	err = allocate_budget(c, page, ui, appending);
	if (unlikely(err)) {
473
		ubifs_assert(c, err == -ENOSPC);
474 475 476 477 478 479 480 481
		/*
		 * If we skipped reading the page because we were going to
		 * write all of it, then it is not up to date.
		 */
		if (skipped_read) {
			ClearPageChecked(page);
			ClearPageUptodate(page);
		}
482 483 484 485 486 487 488 489
		/*
		 * Budgeting failed which means it would have to force
		 * write-back but didn't, because we set the @fast flag in the
		 * request. Write-back cannot be done now, while we have the
		 * page locked, because it would deadlock. Unlock and free
		 * everything and fall-back to slow-path.
		 */
		if (appending) {
490
			ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
491 492 493
			mutex_unlock(&ui->ui_mutex);
		}
		unlock_page(page);
494
		put_page(page);
495

496
		return write_begin_slow(mapping, pos, len, pagep, flags);
497 498 499
	}

	/*
A
Artem Bityutskiy 已提交
500 501
	 * Whee, we acquired budgeting quickly - without involving
	 * garbage-collection, committing or forcing write-back. We return
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
	 * with @ui->ui_mutex locked if we are appending pages, and unlocked
	 * otherwise. This is an optimization (slightly hacky though).
	 */
	*pagep = page;
	return 0;

}

/**
 * cancel_budget - cancel budget.
 * @c: UBIFS file-system description object
 * @page: page to cancel budget for
 * @ui: UBIFS inode object the page belongs to
 * @appending: non-zero if the page is appended
 *
 * This is a helper function for a page write operation. It unlocks the
 * @ui->ui_mutex in case of appending.
 */
static void cancel_budget(struct ubifs_info *c, struct page *page,
			  struct ubifs_inode *ui, int appending)
{
	if (appending) {
		if (!ui->dirty)
			ubifs_release_dirty_inode_budget(c, ui);
		mutex_unlock(&ui->ui_mutex);
	}
	if (!PagePrivate(page)) {
		if (PageChecked(page))
			release_new_page_budget(c);
		else
			release_existing_page_budget(c);
	}
}

static int ubifs_write_end(struct file *file, struct address_space *mapping,
			   loff_t pos, unsigned len, unsigned copied,
			   struct page *page, void *fsdata)
{
	struct inode *inode = mapping->host;
	struct ubifs_inode *ui = ubifs_inode(inode);
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	loff_t end_pos = pos + len;
	int appending = !!(end_pos > inode->i_size);

	dbg_gen("ino %lu, pos %llu, pg %lu, len %u, copied %d, i_size %lld",
		inode->i_ino, pos, page->index, len, copied, inode->i_size);

549
	if (unlikely(copied < len && len == PAGE_SIZE)) {
550 551 552 553
		/*
		 * VFS copied less data to the page that it intended and
		 * declared in its '->write_begin()' call via the @len
		 * argument. If the page was not up-to-date, and @len was
554
		 * @PAGE_SIZE, the 'ubifs_write_begin()' function did
555 556 557 558 559 560 561
		 * not load it from the media (for optimization reasons). This
		 * means that part of the page contains garbage. So read the
		 * page now.
		 */
		dbg_gen("copied %d instead of %d, read page and repeat",
			copied, len);
		cancel_budget(c, page, ui, appending);
562
		ClearPageChecked(page);
563 564 565

		/*
		 * Return 0 to force VFS to repeat the whole operation, or the
A
Artem Bityutskiy 已提交
566
		 * error code if 'do_readpage()' fails.
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
		 */
		copied = do_readpage(page);
		goto out;
	}

	if (!PagePrivate(page)) {
		SetPagePrivate(page);
		atomic_long_inc(&c->dirty_pg_cnt);
		__set_page_dirty_nobuffers(page);
	}

	if (appending) {
		i_size_write(inode, end_pos);
		ui->ui_size = end_pos;
		/*
		 * Note, we do not set @I_DIRTY_PAGES (which means that the
		 * inode has dirty pages), this has been done in
		 * '__set_page_dirty_nobuffers()'.
		 */
		__mark_inode_dirty(inode, I_DIRTY_DATASYNC);
587
		ubifs_assert(c, mutex_is_locked(&ui->ui_mutex));
588 589 590 591 592
		mutex_unlock(&ui->ui_mutex);
	}

out:
	unlock_page(page);
593
	put_page(page);
594 595 596
	return copied;
}

A
Adrian Hunter 已提交
597 598 599 600 601 602 603 604 605 606 607 608
/**
 * populate_page - copy data nodes into a page for bulk-read.
 * @c: UBIFS file-system description object
 * @page: page
 * @bu: bulk-read information
 * @n: next zbranch slot
 *
 * This function returns %0 on success and a negative error code on failure.
 */
static int populate_page(struct ubifs_info *c, struct page *page,
			 struct bu_info *bu, int *n)
{
609
	int i = 0, nn = *n, offs = bu->zbranch[0].offs, hole = 0, read = 0;
A
Adrian Hunter 已提交
610 611 612 613 614 615 616 617 618 619 620
	struct inode *inode = page->mapping->host;
	loff_t i_size = i_size_read(inode);
	unsigned int page_block;
	void *addr, *zaddr;
	pgoff_t end_index;

	dbg_gen("ino %lu, pg %lu, i_size %lld, flags %#lx",
		inode->i_ino, page->index, i_size, page->flags);

	addr = zaddr = kmap(page);

621
	end_index = (i_size - 1) >> PAGE_SHIFT;
A
Adrian Hunter 已提交
622
	if (!i_size || page->index > end_index) {
623
		hole = 1;
624
		memset(addr, 0, PAGE_SIZE);
A
Adrian Hunter 已提交
625 626 627 628 629 630 631
		goto out_hole;
	}

	page_block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
	while (1) {
		int err, len, out_len, dlen;

632 633
		if (nn >= bu->cnt) {
			hole = 1;
A
Adrian Hunter 已提交
634
			memset(addr, 0, UBIFS_BLOCK_SIZE);
635
		} else if (key_block(c, &bu->zbranch[nn].key) == page_block) {
A
Adrian Hunter 已提交
636 637 638 639
			struct ubifs_data_node *dn;

			dn = bu->buf + (bu->zbranch[nn].offs - offs);

640
			ubifs_assert(c, le64_to_cpu(dn->ch.sqnum) >
A
Adrian Hunter 已提交
641 642 643 644 645 646 647 648
				     ubifs_inode(inode)->creat_sqnum);

			len = le32_to_cpu(dn->size);
			if (len <= 0 || len > UBIFS_BLOCK_SIZE)
				goto out_err;

			dlen = le32_to_cpu(dn->ch.len) - UBIFS_DATA_NODE_SZ;
			out_len = UBIFS_BLOCK_SIZE;
649

650
			if (IS_ENCRYPTED(inode)) {
651 652 653 654 655
				err = ubifs_decrypt(inode, dn, &dlen, page_block);
				if (err)
					goto out_err;
			}

656
			err = ubifs_decompress(c, &dn->data, dlen, addr, &out_len,
A
Adrian Hunter 已提交
657 658 659 660 661 662 663 664 665
					       le16_to_cpu(dn->compr_type));
			if (err || len != out_len)
				goto out_err;

			if (len < UBIFS_BLOCK_SIZE)
				memset(addr + len, 0, UBIFS_BLOCK_SIZE - len);

			nn += 1;
			read = (i << UBIFS_BLOCK_SHIFT) + len;
666 667 668 669 670 671
		} else if (key_block(c, &bu->zbranch[nn].key) < page_block) {
			nn += 1;
			continue;
		} else {
			hole = 1;
			memset(addr, 0, UBIFS_BLOCK_SIZE);
A
Adrian Hunter 已提交
672 673 674 675 676 677 678 679
		}
		if (++i >= UBIFS_BLOCKS_PER_PAGE)
			break;
		addr += UBIFS_BLOCK_SIZE;
		page_block += 1;
	}

	if (end_index == page->index) {
680
		int len = i_size & (PAGE_SIZE - 1);
A
Adrian Hunter 已提交
681

682
		if (len && len < read)
A
Adrian Hunter 已提交
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
			memset(zaddr + len, 0, read - len);
	}

out_hole:
	if (hole) {
		SetPageChecked(page);
		dbg_gen("hole");
	}

	SetPageUptodate(page);
	ClearPageError(page);
	flush_dcache_page(page);
	kunmap(page);
	*n = nn;
	return 0;

out_err:
	ClearPageUptodate(page);
	SetPageError(page);
	flush_dcache_page(page);
	kunmap(page);
704
	ubifs_err(c, "bad data node (block %u, inode %lu)",
A
Adrian Hunter 已提交
705 706 707 708 709 710 711
		  page_block, inode->i_ino);
	return -EINVAL;
}

/**
 * ubifs_do_bulk_read - do bulk-read.
 * @c: UBIFS file-system description object
A
Artem Bityutskiy 已提交
712 713
 * @bu: bulk-read information
 * @page1: first page to read
A
Adrian Hunter 已提交
714 715 716
 *
 * This function returns %1 if the bulk-read is done, otherwise %0 is returned.
 */
A
Artem Bityutskiy 已提交
717 718
static int ubifs_do_bulk_read(struct ubifs_info *c, struct bu_info *bu,
			      struct page *page1)
A
Adrian Hunter 已提交
719 720 721 722 723 724
{
	pgoff_t offset = page1->index, end_index;
	struct address_space *mapping = page1->mapping;
	struct inode *inode = mapping->host;
	struct ubifs_inode *ui = ubifs_inode(inode);
	int err, page_idx, page_cnt, ret = 0, n = 0;
A
Artem Bityutskiy 已提交
725
	int allocate = bu->buf ? 0 : 1;
A
Adrian Hunter 已提交
726
	loff_t isize;
727
	gfp_t ra_gfp_mask = readahead_gfp_mask(mapping) & ~__GFP_FS;
A
Adrian Hunter 已提交
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746

	err = ubifs_tnc_get_bu_keys(c, bu);
	if (err)
		goto out_warn;

	if (bu->eof) {
		/* Turn off bulk-read at the end of the file */
		ui->read_in_a_row = 1;
		ui->bulk_read = 0;
	}

	page_cnt = bu->blk_cnt >> UBIFS_BLOCKS_PER_PAGE_SHIFT;
	if (!page_cnt) {
		/*
		 * This happens when there are multiple blocks per page and the
		 * blocks for the first page we are looking for, are not
		 * together. If all the pages were like this, bulk-read would
		 * reduce performance, so we turn it off for a while.
		 */
A
Artem Bityutskiy 已提交
747
		goto out_bu_off;
A
Adrian Hunter 已提交
748 749 750
	}

	if (bu->cnt) {
A
Artem Bityutskiy 已提交
751 752 753 754 755 756 757 758
		if (allocate) {
			/*
			 * Allocate bulk-read buffer depending on how many data
			 * nodes we are going to read.
			 */
			bu->buf_len = bu->zbranch[bu->cnt - 1].offs +
				      bu->zbranch[bu->cnt - 1].len -
				      bu->zbranch[0].offs;
759 760
			ubifs_assert(c, bu->buf_len > 0);
			ubifs_assert(c, bu->buf_len <= c->leb_size);
A
Artem Bityutskiy 已提交
761 762 763 764 765
			bu->buf = kmalloc(bu->buf_len, GFP_NOFS | __GFP_NOWARN);
			if (!bu->buf)
				goto out_bu_off;
		}

A
Adrian Hunter 已提交
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
		err = ubifs_tnc_bulk_read(c, bu);
		if (err)
			goto out_warn;
	}

	err = populate_page(c, page1, bu, &n);
	if (err)
		goto out_warn;

	unlock_page(page1);
	ret = 1;

	isize = i_size_read(inode);
	if (isize == 0)
		goto out_free;
781
	end_index = ((isize - 1) >> PAGE_SHIFT);
A
Adrian Hunter 已提交
782 783 784 785 786 787 788

	for (page_idx = 1; page_idx < page_cnt; page_idx++) {
		pgoff_t page_offset = offset + page_idx;
		struct page *page;

		if (page_offset > end_index)
			break;
789 790 791
		page = pagecache_get_page(mapping, page_offset,
				 FGP_LOCK|FGP_ACCESSED|FGP_CREAT|FGP_NOWAIT,
				 ra_gfp_mask);
A
Adrian Hunter 已提交
792 793 794 795 796
		if (!page)
			break;
		if (!PageUptodate(page))
			err = populate_page(c, page, bu, &n);
		unlock_page(page);
797
		put_page(page);
A
Adrian Hunter 已提交
798 799 800 801 802 803 804
		if (err)
			break;
	}

	ui->last_page_read = offset + page_idx - 1;

out_free:
A
Artem Bityutskiy 已提交
805 806
	if (allocate)
		kfree(bu->buf);
A
Adrian Hunter 已提交
807 808 809
	return ret;

out_warn:
810
	ubifs_warn(c, "ignoring error %d and skipping bulk-read", err);
A
Adrian Hunter 已提交
811
	goto out_free;
A
Artem Bityutskiy 已提交
812 813 814 815

out_bu_off:
	ui->read_in_a_row = ui->bulk_read = 0;
	goto out_free;
A
Adrian Hunter 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
}

/**
 * ubifs_bulk_read - determine whether to bulk-read and, if so, do it.
 * @page: page from which to start bulk-read.
 *
 * Some flash media are capable of reading sequentially at faster rates. UBIFS
 * bulk-read facility is designed to take advantage of that, by reading in one
 * go consecutive data nodes that are also located consecutively in the same
 * LEB. This function returns %1 if a bulk-read is done and %0 otherwise.
 */
static int ubifs_bulk_read(struct page *page)
{
	struct inode *inode = page->mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	struct ubifs_inode *ui = ubifs_inode(inode);
	pgoff_t index = page->index, last_page_read = ui->last_page_read;
A
Artem Bityutskiy 已提交
833
	struct bu_info *bu;
834
	int err = 0, allocated = 0;
A
Adrian Hunter 已提交
835 836 837 838

	ui->last_page_read = index;
	if (!c->bulk_read)
		return 0;
A
Artem Bityutskiy 已提交
839

A
Adrian Hunter 已提交
840
	/*
841 842
	 * Bulk-read is protected by @ui->ui_mutex, but it is an optimization,
	 * so don't bother if we cannot lock the mutex.
A
Adrian Hunter 已提交
843 844 845
	 */
	if (!mutex_trylock(&ui->ui_mutex))
		return 0;
A
Artem Bityutskiy 已提交
846

A
Adrian Hunter 已提交
847 848 849 850 851 852 853
	if (index != last_page_read + 1) {
		/* Turn off bulk-read if we stop reading sequentially */
		ui->read_in_a_row = 1;
		if (ui->bulk_read)
			ui->bulk_read = 0;
		goto out_unlock;
	}
A
Artem Bityutskiy 已提交
854

A
Adrian Hunter 已提交
855 856 857 858 859 860 861
	if (!ui->bulk_read) {
		ui->read_in_a_row += 1;
		if (ui->read_in_a_row < 3)
			goto out_unlock;
		/* Three reads in a row, so switch on bulk-read */
		ui->bulk_read = 1;
	}
A
Artem Bityutskiy 已提交
862

863 864 865 866 867 868 869 870 871 872 873 874 875 876
	/*
	 * If possible, try to use pre-allocated bulk-read information, which
	 * is protected by @c->bu_mutex.
	 */
	if (mutex_trylock(&c->bu_mutex))
		bu = &c->bu;
	else {
		bu = kmalloc(sizeof(struct bu_info), GFP_NOFS | __GFP_NOWARN);
		if (!bu)
			goto out_unlock;

		bu->buf = NULL;
		allocated = 1;
	}
A
Artem Bityutskiy 已提交
877 878 879 880 881

	bu->buf_len = c->max_bu_buf_len;
	data_key_init(c, &bu->key, inode->i_ino,
		      page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT);
	err = ubifs_do_bulk_read(c, bu, page);
882 883 884 885 886

	if (!allocated)
		mutex_unlock(&c->bu_mutex);
	else
		kfree(bu);
A
Artem Bityutskiy 已提交
887

A
Adrian Hunter 已提交
888 889
out_unlock:
	mutex_unlock(&ui->ui_mutex);
A
Artem Bityutskiy 已提交
890
	return err;
A
Adrian Hunter 已提交
891 892
}

893 894
static int ubifs_readpage(struct file *file, struct page *page)
{
A
Adrian Hunter 已提交
895 896
	if (ubifs_bulk_read(page))
		return 0;
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
	do_readpage(page);
	unlock_page(page);
	return 0;
}

static int do_writepage(struct page *page, int len)
{
	int err = 0, i, blen;
	unsigned int block;
	void *addr;
	union ubifs_key key;
	struct inode *inode = page->mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;

#ifdef UBIFS_DEBUG
912
	struct ubifs_inode *ui = ubifs_inode(inode);
913
	spin_lock(&ui->ui_lock);
914
	ubifs_assert(c, page->index <= ui->synced_i_size >> PAGE_SHIFT);
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
	spin_unlock(&ui->ui_lock);
#endif

	/* Update radix tree tags */
	set_page_writeback(page);

	addr = kmap(page);
	block = page->index << UBIFS_BLOCKS_PER_PAGE_SHIFT;
	i = 0;
	while (len) {
		blen = min_t(int, len, UBIFS_BLOCK_SIZE);
		data_key_init(c, &key, inode->i_ino, block);
		err = ubifs_jnl_write_data(c, inode, &key, addr, blen);
		if (err)
			break;
		if (++i >= UBIFS_BLOCKS_PER_PAGE)
			break;
		block += 1;
		addr += blen;
		len -= blen;
	}
	if (err) {
		SetPageError(page);
938
		ubifs_err(c, "cannot write page %lu of inode %lu, error %d",
939 940 941 942
			  page->index, inode->i_ino, err);
		ubifs_ro_mode(c, err);
	}

943
	ubifs_assert(c, PagePrivate(page));
944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
	if (PageChecked(page))
		release_new_page_budget(c);
	else
		release_existing_page_budget(c);

	atomic_long_dec(&c->dirty_pg_cnt);
	ClearPagePrivate(page);
	ClearPageChecked(page);

	kunmap(page);
	unlock_page(page);
	end_page_writeback(page);
	return err;
}

/*
 * When writing-back dirty inodes, VFS first writes-back pages belonging to the
 * inode, then the inode itself. For UBIFS this may cause a problem. Consider a
 * situation when a we have an inode with size 0, then a megabyte of data is
 * appended to the inode, then write-back starts and flushes some amount of the
 * dirty pages, the journal becomes full, commit happens and finishes, and then
 * an unclean reboot happens. When the file system is mounted next time, the
 * inode size would still be 0, but there would be many pages which are beyond
 * the inode size, they would be indexed and consume flash space. Because the
 * journal has been committed, the replay would not be able to detect this
 * situation and correct the inode size. This means UBIFS would have to scan
 * whole index and correct all inode sizes, which is long an unacceptable.
 *
 * To prevent situations like this, UBIFS writes pages back only if they are
A
Artem Bityutskiy 已提交
973
 * within the last synchronized inode size, i.e. the size which has been
974 975 976 977 978 979 980 981
 * written to the flash media last time. Otherwise, UBIFS forces inode
 * write-back, thus making sure the on-flash inode contains current inode size,
 * and then keeps writing pages back.
 *
 * Some locking issues explanation. 'ubifs_writepage()' first is called with
 * the page locked, and it locks @ui_mutex. However, write-back does take inode
 * @i_mutex, which means other VFS operations may be run on this inode at the
 * same time. And the problematic one is truncation to smaller size, from where
982 983 984 985 986
 * we have to call 'truncate_setsize()', which first changes @inode->i_size,
 * then drops the truncated pages. And while dropping the pages, it takes the
 * page lock. This means that 'do_truncation()' cannot call 'truncate_setsize()'
 * with @ui_mutex locked, because it would deadlock with 'ubifs_writepage()'.
 * This means that @inode->i_size is changed while @ui_mutex is unlocked.
987
 *
988 989 990
 * XXX(truncate): with the new truncate sequence this is not true anymore,
 * and the calls to truncate_setsize can be move around freely.  They should
 * be moved to the very end of the truncate sequence.
991
 *
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
 * But in 'ubifs_writepage()' we have to guarantee that we do not write beyond
 * inode size. How do we do this if @inode->i_size may became smaller while we
 * are in the middle of 'ubifs_writepage()'? The UBIFS solution is the
 * @ui->ui_isize "shadow" field which UBIFS uses instead of @inode->i_size
 * internally and updates it under @ui_mutex.
 *
 * Q: why we do not worry that if we race with truncation, we may end up with a
 * situation when the inode is truncated while we are in the middle of
 * 'do_writepage()', so we do write beyond inode size?
 * A: If we are in the middle of 'do_writepage()', truncation would be locked
 * on the page lock and it would not write the truncated inode node to the
 * journal before we have finished.
 */
static int ubifs_writepage(struct page *page, struct writeback_control *wbc)
{
	struct inode *inode = page->mapping->host;
1008
	struct ubifs_info *c = inode->i_sb->s_fs_info;
1009 1010
	struct ubifs_inode *ui = ubifs_inode(inode);
	loff_t i_size =  i_size_read(inode), synced_i_size;
1011 1012
	pgoff_t end_index = i_size >> PAGE_SHIFT;
	int err, len = i_size & (PAGE_SIZE - 1);
1013 1014 1015 1016
	void *kaddr;

	dbg_gen("ino %lu, pg %lu, pg flags %#lx",
		inode->i_ino, page->index, page->flags);
1017
	ubifs_assert(c, PagePrivate(page));
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030

	/* Is the page fully outside @i_size? (truncate in progress) */
	if (page->index > end_index || (page->index == end_index && !len)) {
		err = 0;
		goto out_unlock;
	}

	spin_lock(&ui->ui_lock);
	synced_i_size = ui->synced_i_size;
	spin_unlock(&ui->ui_lock);

	/* Is the page fully inside @i_size? */
	if (page->index < end_index) {
1031
		if (page->index >= synced_i_size >> PAGE_SHIFT) {
1032
			err = inode->i_sb->s_op->write_inode(inode, NULL);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
			if (err)
				goto out_unlock;
			/*
			 * The inode has been written, but the write-buffer has
			 * not been synchronized, so in case of an unclean
			 * reboot we may end up with some pages beyond inode
			 * size, but they would be in the journal (because
			 * commit flushes write buffers) and recovery would deal
			 * with this.
			 */
		}
1044
		return do_writepage(page, PAGE_SIZE);
1045 1046 1047 1048 1049 1050 1051 1052 1053
	}

	/*
	 * The page straddles @i_size. It must be zeroed out on each and every
	 * writepage invocation because it may be mmapped. "A file is mapped
	 * in multiples of the page size. For a file that is not a multiple of
	 * the page size, the remaining memory is zeroed when mapped, and
	 * writes to that region are not written out to the file."
	 */
1054
	kaddr = kmap_atomic(page);
1055
	memset(kaddr + len, 0, PAGE_SIZE - len);
1056
	flush_dcache_page(page);
1057
	kunmap_atomic(kaddr);
1058 1059

	if (i_size > synced_i_size) {
1060
		err = inode->i_sb->s_op->write_inode(inode, NULL);
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
		if (err)
			goto out_unlock;
	}

	return do_writepage(page, len);

out_unlock:
	unlock_page(page);
	return err;
}

/**
 * do_attr_changes - change inode attributes.
 * @inode: inode to change attributes for
 * @attr: describes attributes to change
 */
static void do_attr_changes(struct inode *inode, const struct iattr *attr)
{
	if (attr->ia_valid & ATTR_UID)
		inode->i_uid = attr->ia_uid;
	if (attr->ia_valid & ATTR_GID)
		inode->i_gid = attr->ia_gid;
1083 1084 1085 1086 1087 1088
	if (attr->ia_valid & ATTR_ATIME)
		inode->i_atime = attr->ia_atime;
	if (attr->ia_valid & ATTR_MTIME)
		inode->i_mtime = attr->ia_mtime;
	if (attr->ia_valid & ATTR_CTIME)
		inode->i_ctime = attr->ia_ctime;
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
	if (attr->ia_valid & ATTR_MODE) {
		umode_t mode = attr->ia_mode;

		if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
			mode &= ~S_ISGID;
		inode->i_mode = mode;
	}
}

/**
 * do_truncation - truncate an inode.
 * @c: UBIFS file-system description object
 * @inode: inode to truncate
 * @attr: inode attribute changes description
 *
 * This function implements VFS '->setattr()' call when the inode is truncated
 * to a smaller size. Returns zero in case of success and a negative error code
 * in case of failure.
 */
static int do_truncation(struct ubifs_info *c, struct inode *inode,
			 const struct iattr *attr)
{
	int err;
	struct ubifs_budget_req req;
	loff_t old_size = inode->i_size, new_size = attr->ia_size;
1114
	int offset = new_size & (UBIFS_BLOCK_SIZE - 1), budgeted = 1;
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
	struct ubifs_inode *ui = ubifs_inode(inode);

	dbg_gen("ino %lu, size %lld -> %lld", inode->i_ino, old_size, new_size);
	memset(&req, 0, sizeof(struct ubifs_budget_req));

	/*
	 * If this is truncation to a smaller size, and we do not truncate on a
	 * block boundary, budget for changing one data block, because the last
	 * block will be re-written.
	 */
	if (new_size & (UBIFS_BLOCK_SIZE - 1))
		req.dirtied_page = 1;

	req.dirtied_ino = 1;
	/* A funny way to budget for truncation node */
	req.dirtied_ino_d = UBIFS_TRUN_NODE_SZ;
	err = ubifs_budget_space(c, &req);
1132 1133 1134 1135 1136 1137 1138 1139 1140
	if (err) {
		/*
		 * Treat truncations to zero as deletion and always allow them,
		 * just like we do for '->unlink()'.
		 */
		if (new_size || err != -ENOSPC)
			return err;
		budgeted = 0;
	}
1141

1142
	truncate_setsize(inode, new_size);
1143 1144

	if (offset) {
1145
		pgoff_t index = new_size >> PAGE_SHIFT;
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
		struct page *page;

		page = find_lock_page(inode->i_mapping, index);
		if (page) {
			if (PageDirty(page)) {
				/*
				 * 'ubifs_jnl_truncate()' will try to truncate
				 * the last data node, but it contains
				 * out-of-date data because the page is dirty.
				 * Write the page now, so that
				 * 'ubifs_jnl_truncate()' will see an already
				 * truncated (and up to date) data node.
				 */
1159
				ubifs_assert(c, PagePrivate(page));
1160 1161 1162 1163

				clear_page_dirty_for_io(page);
				if (UBIFS_BLOCKS_PER_PAGE_SHIFT)
					offset = new_size &
1164
						 (PAGE_SIZE - 1);
1165
				err = do_writepage(page, offset);
1166
				put_page(page);
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
				if (err)
					goto out_budg;
				/*
				 * We could now tell 'ubifs_jnl_truncate()' not
				 * to read the last block.
				 */
			} else {
				/*
				 * We could 'kmap()' the page and pass the data
				 * to 'ubifs_jnl_truncate()' to save it from
				 * having to read it.
				 */
				unlock_page(page);
1180
				put_page(page);
1181 1182 1183 1184 1185 1186 1187
			}
		}
	}

	mutex_lock(&ui->ui_mutex);
	ui->ui_size = inode->i_size;
	/* Truncation changes inode [mc]time */
1188
	inode->i_mtime = inode->i_ctime = current_time(inode);
A
Artem Bityutskiy 已提交
1189
	/* Other attributes may be changed at the same time as well */
1190 1191 1192
	do_attr_changes(inode, attr);
	err = ubifs_jnl_truncate(c, inode, old_size, new_size);
	mutex_unlock(&ui->ui_mutex);
A
Artem Bityutskiy 已提交
1193

1194
out_budg:
1195 1196 1197
	if (budgeted)
		ubifs_release_budget(c, &req);
	else {
1198
		c->bi.nospace = c->bi.nospace_rp = 0;
1199 1200
		smp_wmb();
	}
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
	return err;
}

/**
 * do_setattr - change inode attributes.
 * @c: UBIFS file-system description object
 * @inode: inode to change attributes for
 * @attr: inode attribute changes description
 *
 * This function implements VFS '->setattr()' call for all cases except
 * truncations to smaller size. Returns zero in case of success and a negative
 * error code in case of failure.
 */
static int do_setattr(struct ubifs_info *c, struct inode *inode,
		      const struct iattr *attr)
{
	int err, release;
	loff_t new_size = attr->ia_size;
	struct ubifs_inode *ui = ubifs_inode(inode);
	struct ubifs_budget_req req = { .dirtied_ino = 1,
1221
				.dirtied_ino_d = ALIGN(ui->data_len, 8) };
1222 1223 1224 1225 1226 1227 1228

	err = ubifs_budget_space(c, &req);
	if (err)
		return err;

	if (attr->ia_valid & ATTR_SIZE) {
		dbg_gen("size %lld -> %lld", inode->i_size, new_size);
1229
		truncate_setsize(inode, new_size);
1230 1231 1232 1233 1234
	}

	mutex_lock(&ui->ui_mutex);
	if (attr->ia_valid & ATTR_SIZE) {
		/* Truncation changes inode [mc]time */
1235
		inode->i_mtime = inode->i_ctime = current_time(inode);
1236
		/* 'truncate_setsize()' changed @i_size, update @ui_size */
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
		ui->ui_size = inode->i_size;
	}

	do_attr_changes(inode, attr);

	release = ui->dirty;
	if (attr->ia_valid & ATTR_SIZE)
		/*
		 * Inode length changed, so we have to make sure
		 * @I_DIRTY_DATASYNC is set.
		 */
1248
		 __mark_inode_dirty(inode, I_DIRTY_DATASYNC);
1249 1250 1251 1252 1253 1254 1255
	else
		mark_inode_dirty_sync(inode);
	mutex_unlock(&ui->ui_mutex);

	if (release)
		ubifs_release_budget(c, &req);
	if (IS_SYNC(inode))
1256
		err = inode->i_sb->s_op->write_inode(inode, NULL);
1257 1258 1259
	return err;
}

1260 1261
int ubifs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
		  struct iattr *attr)
1262 1263
{
	int err;
1264
	struct inode *inode = d_inode(dentry);
1265 1266
	struct ubifs_info *c = inode->i_sb->s_fs_info;

A
Artem Bityutskiy 已提交
1267 1268
	dbg_gen("ino %lu, mode %#x, ia_valid %#x",
		inode->i_ino, inode->i_mode, attr->ia_valid);
C
Christian Brauner 已提交
1269
	err = setattr_prepare(&init_user_ns, dentry, attr);
1270 1271 1272
	if (err)
		return err;

1273
	err = dbg_check_synced_i_size(c, inode);
1274 1275 1276
	if (err)
		return err;

1277 1278 1279
	err = fscrypt_prepare_setattr(dentry, attr);
	if (err)
		return err;
1280

1281 1282 1283 1284 1285 1286 1287 1288 1289
	if ((attr->ia_valid & ATTR_SIZE) && attr->ia_size < inode->i_size)
		/* Truncation to a smaller size */
		err = do_truncation(c, inode, attr);
	else
		err = do_setattr(c, inode, attr);

	return err;
}

1290 1291
static void ubifs_invalidatepage(struct page *page, unsigned int offset,
				 unsigned int length)
1292 1293 1294 1295
{
	struct inode *inode = page->mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;

1296
	ubifs_assert(c, PagePrivate(page));
1297
	if (offset || length < PAGE_SIZE)
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
		/* Partial page remains dirty */
		return;

	if (PageChecked(page))
		release_new_page_budget(c);
	else
		release_existing_page_budget(c);

	atomic_long_dec(&c->dirty_pg_cnt);
	ClearPagePrivate(page);
	ClearPageChecked(page);
}

1311
int ubifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
1312
{
1313
	struct inode *inode = file->f_mapping->host;
1314 1315 1316 1317 1318
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	int err;

	dbg_gen("syncing inode %lu", inode->i_ino);

1319 1320 1321 1322 1323
	if (c->ro_mount)
		/*
		 * For some really strange reasons VFS does not filter out
		 * 'fsync()' for R/O mounted file-systems as per 2.6.39.
		 */
1324 1325
		return 0;

1326
	err = file_write_and_wait_range(file, start, end);
1327 1328
	if (err)
		return err;
A
Al Viro 已提交
1329
	inode_lock(inode);
1330 1331

	/* Synchronize the inode unless this is a 'datasync()' call. */
1332
	if (!datasync || (inode->i_state & I_DIRTY_DATASYNC)) {
1333
		err = inode->i_sb->s_op->write_inode(inode, NULL);
1334
		if (err)
1335
			goto out;
1336 1337 1338 1339 1340 1341 1342
	}

	/*
	 * Nodes related to this inode may still sit in a write-buffer. Flush
	 * them.
	 */
	err = ubifs_sync_wbufs_by_inode(c, inode);
1343
out:
A
Al Viro 已提交
1344
	inode_unlock(inode);
1345
	return err;
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
}

/**
 * mctime_update_needed - check if mtime or ctime update is needed.
 * @inode: the inode to do the check for
 * @now: current time
 *
 * This helper function checks if the inode mtime/ctime should be updated or
 * not. If current values of the time-stamps are within the UBIFS inode time
 * granularity, they are not updated. This is an optimization.
 */
static inline int mctime_update_needed(const struct inode *inode,
1358
				       const struct timespec64 *now)
1359
{
1360 1361
	if (!timespec64_equal(&inode->i_mtime, now) ||
	    !timespec64_equal(&inode->i_ctime, now))
1362 1363 1364 1365
		return 1;
	return 0;
}

1366 1367 1368 1369 1370 1371
/**
 * ubifs_update_time - update time of inode.
 * @inode: inode to update
 *
 * This function updates time of the inode.
 */
1372
int ubifs_update_time(struct inode *inode, struct timespec64 *time,
1373 1374 1375 1376 1377 1378 1379 1380
			     int flags)
{
	struct ubifs_inode *ui = ubifs_inode(inode);
	struct ubifs_info *c = inode->i_sb->s_fs_info;
	struct ubifs_budget_req req = { .dirtied_ino = 1,
			.dirtied_ino_d = ALIGN(ui->data_len, 8) };
	int err, release;

1381 1382 1383
	if (!IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
		return generic_update_time(inode, time, flags);

1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
	err = ubifs_budget_space(c, &req);
	if (err)
		return err;

	mutex_lock(&ui->ui_mutex);
	if (flags & S_ATIME)
		inode->i_atime = *time;
	if (flags & S_CTIME)
		inode->i_ctime = *time;
	if (flags & S_MTIME)
		inode->i_mtime = *time;

	release = ui->dirty;
1397
	__mark_inode_dirty(inode, I_DIRTY_SYNC);
1398 1399 1400 1401 1402 1403
	mutex_unlock(&ui->ui_mutex);
	if (release)
		ubifs_release_budget(c, &req);
	return 0;
}

1404
/**
1405
 * update_mctime - update mtime and ctime of an inode.
1406 1407 1408 1409 1410 1411
 * @inode: inode to update
 *
 * This function updates mtime and ctime of the inode if it is not equivalent to
 * current time. Returns zero in case of success and a negative error code in
 * case of failure.
 */
A
Al Viro 已提交
1412
static int update_mctime(struct inode *inode)
1413
{
1414
	struct timespec64 now = current_time(inode);
1415
	struct ubifs_inode *ui = ubifs_inode(inode);
A
Al Viro 已提交
1416
	struct ubifs_info *c = inode->i_sb->s_fs_info;
1417 1418 1419 1420

	if (mctime_update_needed(inode, &now)) {
		int err, release;
		struct ubifs_budget_req req = { .dirtied_ino = 1,
1421
				.dirtied_ino_d = ALIGN(ui->data_len, 8) };
1422 1423 1424 1425 1426 1427

		err = ubifs_budget_space(c, &req);
		if (err)
			return err;

		mutex_lock(&ui->ui_mutex);
1428
		inode->i_mtime = inode->i_ctime = current_time(inode);
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
		release = ui->dirty;
		mark_inode_dirty_sync(inode);
		mutex_unlock(&ui->ui_mutex);
		if (release)
			ubifs_release_budget(c, &req);
	}

	return 0;
}

A
Al Viro 已提交
1439
static ssize_t ubifs_write_iter(struct kiocb *iocb, struct iov_iter *from)
1440
{
A
Al Viro 已提交
1441
	int err = update_mctime(file_inode(iocb->ki_filp));
1442 1443 1444
	if (err)
		return err;

A
Al Viro 已提交
1445
	return generic_file_write_iter(iocb, from);
1446 1447 1448 1449 1450
}

static int ubifs_set_page_dirty(struct page *page)
{
	int ret;
1451 1452
	struct inode *inode = page->mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;
1453 1454 1455 1456 1457 1458

	ret = __set_page_dirty_nobuffers(page);
	/*
	 * An attempt to dirty a page without budgeting for it - should not
	 * happen.
	 */
1459
	ubifs_assert(c, ret == 0);
1460 1461 1462
	return ret;
}

1463 1464 1465 1466 1467 1468
#ifdef CONFIG_MIGRATION
static int ubifs_migrate_page(struct address_space *mapping,
		struct page *newpage, struct page *page, enum migrate_mode mode)
{
	int rc;

1469
	rc = migrate_page_move_mapping(mapping, newpage, page, 0);
1470 1471 1472 1473 1474 1475 1476 1477
	if (rc != MIGRATEPAGE_SUCCESS)
		return rc;

	if (PagePrivate(page)) {
		ClearPagePrivate(page);
		SetPagePrivate(newpage);
	}

1478 1479 1480 1481
	if (mode != MIGRATE_SYNC_NO_COPY)
		migrate_page_copy(newpage, page);
	else
		migrate_page_states(newpage, page);
1482 1483 1484 1485
	return MIGRATEPAGE_SUCCESS;
}
#endif

1486 1487
static int ubifs_releasepage(struct page *page, gfp_t unused_gfp_flags)
{
1488 1489 1490
	struct inode *inode = page->mapping->host;
	struct ubifs_info *c = inode->i_sb->s_fs_info;

1491 1492 1493 1494 1495 1496
	/*
	 * An attempt to release a dirty page without budgeting for it - should
	 * not happen.
	 */
	if (PageWriteback(page))
		return 0;
1497 1498
	ubifs_assert(c, PagePrivate(page));
	ubifs_assert(c, 0);
1499 1500 1501 1502 1503 1504
	ClearPagePrivate(page);
	ClearPageChecked(page);
	return 1;
}

/*
1505 1506
 * mmap()d file has taken write protection fault and is being made writable.
 * UBIFS must ensure page is budgeted for.
1507
 */
1508
static vm_fault_t ubifs_vm_page_mkwrite(struct vm_fault *vmf)
1509
{
1510
	struct page *page = vmf->page;
1511
	struct inode *inode = file_inode(vmf->vma->vm_file);
1512
	struct ubifs_info *c = inode->i_sb->s_fs_info;
1513
	struct timespec64 now = current_time(inode);
1514 1515 1516 1517 1518
	struct ubifs_budget_req req = { .new_page = 1 };
	int err, update_time;

	dbg_gen("ino %lu, pg %lu, i_size %lld",	inode->i_ino, page->index,
		i_size_read(inode));
1519
	ubifs_assert(c, !c->ro_media && !c->ro_mount);
1520

1521
	if (unlikely(c->ro_error))
1522
		return VM_FAULT_SIGBUS; /* -EROFS */
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552

	/*
	 * We have not locked @page so far so we may budget for changing the
	 * page. Note, we cannot do this after we locked the page, because
	 * budgeting may cause write-back which would cause deadlock.
	 *
	 * At the moment we do not know whether the page is dirty or not, so we
	 * assume that it is not and budget for a new page. We could look at
	 * the @PG_private flag and figure this out, but we may race with write
	 * back and the page state may change by the time we lock it, so this
	 * would need additional care. We do not bother with this at the
	 * moment, although it might be good idea to do. Instead, we allocate
	 * budget for a new page and amend it later on if the page was in fact
	 * dirty.
	 *
	 * The budgeting-related logic of this function is similar to what we
	 * do in 'ubifs_write_begin()' and 'ubifs_write_end()'. Glance there
	 * for more comments.
	 */
	update_time = mctime_update_needed(inode, &now);
	if (update_time)
		/*
		 * We have to change inode time stamp which requires extra
		 * budgeting.
		 */
		req.dirtied_ino = 1;

	err = ubifs_budget_space(c, &req);
	if (unlikely(err)) {
		if (err == -ENOSPC)
1553
			ubifs_warn(c, "out of space for mmapped file (inode number %lu)",
1554
				   inode->i_ino);
1555
		return VM_FAULT_SIGBUS;
1556 1557 1558 1559 1560 1561
	}

	lock_page(page);
	if (unlikely(page->mapping != inode->i_mapping ||
		     page_offset(page) > i_size_read(inode))) {
		/* Page got truncated out from underneath us */
1562
		goto sigbus;
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
	}

	if (PagePrivate(page))
		release_new_page_budget(c);
	else {
		if (!PageChecked(page))
			ubifs_convert_page_budget(c);
		SetPagePrivate(page);
		atomic_long_inc(&c->dirty_pg_cnt);
		__set_page_dirty_nobuffers(page);
	}

	if (update_time) {
		int release;
		struct ubifs_inode *ui = ubifs_inode(inode);

		mutex_lock(&ui->ui_mutex);
1580
		inode->i_mtime = inode->i_ctime = current_time(inode);
1581 1582 1583 1584 1585 1586 1587
		release = ui->dirty;
		mark_inode_dirty_sync(inode);
		mutex_unlock(&ui->ui_mutex);
		if (release)
			ubifs_release_dirty_inode_budget(c, ui);
	}

1588
	wait_for_stable_page(page);
1589
	return VM_FAULT_LOCKED;
1590

1591
sigbus:
1592 1593
	unlock_page(page);
	ubifs_release_budget(c, &req);
1594
	return VM_FAULT_SIGBUS;
1595 1596
}

1597
static const struct vm_operations_struct ubifs_file_vm_ops = {
1598
	.fault        = filemap_fault,
1599
	.map_pages = filemap_map_pages,
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
	.page_mkwrite = ubifs_vm_page_mkwrite,
};

static int ubifs_file_mmap(struct file *file, struct vm_area_struct *vma)
{
	int err;

	err = generic_file_mmap(file, vma);
	if (err)
		return err;
	vma->vm_ops = &ubifs_file_vm_ops;
1611 1612 1613 1614

	if (IS_ENABLED(CONFIG_UBIFS_ATIME_SUPPORT))
		file_accessed(file);

1615 1616 1617
	return 0;
}

1618 1619 1620 1621 1622 1623
static const char *ubifs_get_link(struct dentry *dentry,
					    struct inode *inode,
					    struct delayed_call *done)
{
	struct ubifs_inode *ui = ubifs_inode(inode);

1624
	if (!IS_ENCRYPTED(inode))
1625 1626 1627 1628 1629
		return ui->data;

	if (!dentry)
		return ERR_PTR(-ECHILD);

1630
	return fscrypt_get_symlink(inode, ui->data, ui->data_len, done);
1631 1632
}

1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
static int ubifs_symlink_getattr(struct user_namespace *mnt_userns,
				 const struct path *path, struct kstat *stat,
				 u32 request_mask, unsigned int query_flags)
{
	ubifs_getattr(mnt_userns, path, stat, request_mask, query_flags);

	if (IS_ENCRYPTED(d_inode(path->dentry)))
		return fscrypt_symlink_getattr(path, stat);
	return 0;
}

A
Artem Bityutskiy 已提交
1644
const struct address_space_operations ubifs_file_address_operations = {
1645 1646 1647 1648 1649 1650
	.readpage       = ubifs_readpage,
	.writepage      = ubifs_writepage,
	.write_begin    = ubifs_write_begin,
	.write_end      = ubifs_write_end,
	.invalidatepage = ubifs_invalidatepage,
	.set_page_dirty = ubifs_set_page_dirty,
1651 1652 1653
#ifdef CONFIG_MIGRATION
	.migratepage	= ubifs_migrate_page,
#endif
1654 1655 1656
	.releasepage    = ubifs_releasepage,
};

A
Artem Bityutskiy 已提交
1657
const struct inode_operations ubifs_file_inode_operations = {
1658 1659 1660
	.setattr     = ubifs_setattr,
	.getattr     = ubifs_getattr,
	.listxattr   = ubifs_listxattr,
1661
	.update_time = ubifs_update_time,
M
Miklos Szeredi 已提交
1662 1663
	.fileattr_get = ubifs_fileattr_get,
	.fileattr_set = ubifs_fileattr_set,
1664 1665
};

A
Artem Bityutskiy 已提交
1666
const struct inode_operations ubifs_symlink_inode_operations = {
1667
	.get_link    = ubifs_get_link,
1668
	.setattr     = ubifs_setattr,
1669
	.getattr     = ubifs_symlink_getattr,
1670
	.listxattr   = ubifs_listxattr,
1671
	.update_time = ubifs_update_time,
1672 1673
};

A
Artem Bityutskiy 已提交
1674
const struct file_operations ubifs_file_operations = {
1675
	.llseek         = generic_file_llseek,
1676
	.read_iter      = generic_file_read_iter,
A
Al Viro 已提交
1677
	.write_iter     = ubifs_write_iter,
1678 1679 1680 1681
	.mmap           = ubifs_file_mmap,
	.fsync          = ubifs_fsync,
	.unlocked_ioctl = ubifs_ioctl,
	.splice_read	= generic_file_splice_read,
A
Al Viro 已提交
1682
	.splice_write	= iter_file_splice_write,
1683
	.open		= fscrypt_file_open,
1684 1685 1686 1687
#ifdef CONFIG_COMPAT
	.compat_ioctl   = ubifs_compat_ioctl,
#endif
};