Linux Audio

Check our new training course

Loading...
   1/*
   2 * fs/f2fs/file.c
   3 *
   4 * Copyright (c) 2012 Samsung Electronics Co., Ltd.
   5 *             http://www.samsung.com/
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License version 2 as
   9 * published by the Free Software Foundation.
  10 */
  11#include <linux/fs.h>
  12#include <linux/f2fs_fs.h>
  13#include <linux/stat.h>
  14#include <linux/buffer_head.h>
  15#include <linux/writeback.h>
  16#include <linux/blkdev.h>
  17#include <linux/falloc.h>
  18#include <linux/types.h>
  19#include <linux/compat.h>
  20#include <linux/uaccess.h>
  21#include <linux/mount.h>
  22#include <linux/pagevec.h>
  23#include <linux/random.h>
  24
  25#include "f2fs.h"
  26#include "node.h"
  27#include "segment.h"
  28#include "xattr.h"
  29#include "acl.h"
  30#include "gc.h"
  31#include "trace.h"
  32#include <trace/events/f2fs.h>
  33
  34static int f2fs_vm_page_mkwrite(struct vm_area_struct *vma,
  35						struct vm_fault *vmf)
  36{
  37	struct page *page = vmf->page;
  38	struct inode *inode = file_inode(vma->vm_file);
  39	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
  40	struct dnode_of_data dn;
  41	int err;
  42
  43	sb_start_pagefault(inode->i_sb);
  44
  45	f2fs_bug_on(sbi, f2fs_has_inline_data(inode));
  46
  47	/* block allocation */
  48	f2fs_lock_op(sbi);
  49	set_new_dnode(&dn, inode, NULL, NULL, 0);
  50	err = f2fs_reserve_block(&dn, page->index);
  51	if (err) {
  52		f2fs_unlock_op(sbi);
  53		goto out;
  54	}
  55	f2fs_put_dnode(&dn);
  56	f2fs_unlock_op(sbi);
  57
  58	f2fs_balance_fs(sbi, dn.node_changed);
  59
  60	file_update_time(vma->vm_file);
  61	lock_page(page);
  62	if (unlikely(page->mapping != inode->i_mapping ||
  63			page_offset(page) > i_size_read(inode) ||
  64			!PageUptodate(page))) {
  65		unlock_page(page);
  66		err = -EFAULT;
  67		goto out;
  68	}
  69
  70	/*
  71	 * check to see if the page is mapped already (no holes)
  72	 */
  73	if (PageMappedToDisk(page))
  74		goto mapped;
  75
  76	/* page is wholly or partially inside EOF */
  77	if (((loff_t)(page->index + 1) << PAGE_SHIFT) >
  78						i_size_read(inode)) {
  79		unsigned offset;
  80		offset = i_size_read(inode) & ~PAGE_MASK;
  81		zero_user_segment(page, offset, PAGE_SIZE);
  82	}
  83	set_page_dirty(page);
  84	SetPageUptodate(page);
  85
  86	trace_f2fs_vm_page_mkwrite(page, DATA);
  87mapped:
  88	/* fill the page */
  89	f2fs_wait_on_page_writeback(page, DATA, false);
  90
  91	/* wait for GCed encrypted page writeback */
  92	if (f2fs_encrypted_inode(inode) && S_ISREG(inode->i_mode))
  93		f2fs_wait_on_encrypted_page_writeback(sbi, dn.data_blkaddr);
  94
  95	/* if gced page is attached, don't write to cold segment */
  96	clear_cold_data(page);
  97out:
  98	sb_end_pagefault(inode->i_sb);
  99	f2fs_update_time(sbi, REQ_TIME);
 100	return block_page_mkwrite_return(err);
 101}
 102
 103static const struct vm_operations_struct f2fs_file_vm_ops = {
 104	.fault		= filemap_fault,
 105	.map_pages	= filemap_map_pages,
 106	.page_mkwrite	= f2fs_vm_page_mkwrite,
 107};
 108
 109static int get_parent_ino(struct inode *inode, nid_t *pino)
 110{
 111	struct dentry *dentry;
 112
 113	inode = igrab(inode);
 114	dentry = d_find_any_alias(inode);
 115	iput(inode);
 116	if (!dentry)
 117		return 0;
 118
 119	if (update_dent_inode(inode, inode, &dentry->d_name)) {
 120		dput(dentry);
 121		return 0;
 122	}
 123
 124	*pino = parent_ino(dentry);
 125	dput(dentry);
 126	return 1;
 127}
 128
 129static inline bool need_do_checkpoint(struct inode *inode)
 130{
 131	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 132	bool need_cp = false;
 133
 134	if (!S_ISREG(inode->i_mode) || inode->i_nlink != 1)
 135		need_cp = true;
 136	else if (file_enc_name(inode) && need_dentry_mark(sbi, inode->i_ino))
 137		need_cp = true;
 138	else if (file_wrong_pino(inode))
 139		need_cp = true;
 140	else if (!space_for_roll_forward(sbi))
 141		need_cp = true;
 142	else if (!is_checkpointed_node(sbi, F2FS_I(inode)->i_pino))
 143		need_cp = true;
 144	else if (F2FS_I(inode)->xattr_ver == cur_cp_version(F2FS_CKPT(sbi)))
 145		need_cp = true;
 146	else if (test_opt(sbi, FASTBOOT))
 147		need_cp = true;
 148	else if (sbi->active_logs == 2)
 149		need_cp = true;
 150
 151	return need_cp;
 152}
 153
 154static bool need_inode_page_update(struct f2fs_sb_info *sbi, nid_t ino)
 155{
 156	struct page *i = find_get_page(NODE_MAPPING(sbi), ino);
 157	bool ret = false;
 158	/* But we need to avoid that there are some inode updates */
 159	if ((i && PageDirty(i)) || need_inode_block_update(sbi, ino))
 160		ret = true;
 161	f2fs_put_page(i, 0);
 162	return ret;
 163}
 164
 165static void try_to_fix_pino(struct inode *inode)
 166{
 167	struct f2fs_inode_info *fi = F2FS_I(inode);
 168	nid_t pino;
 169
 170	down_write(&fi->i_sem);
 171	fi->xattr_ver = 0;
 172	if (file_wrong_pino(inode) && inode->i_nlink == 1 &&
 173			get_parent_ino(inode, &pino)) {
 174		fi->i_pino = pino;
 175		file_got_pino(inode);
 176		up_write(&fi->i_sem);
 177
 178		mark_inode_dirty_sync(inode);
 179		f2fs_write_inode(inode, NULL);
 180	} else {
 181		up_write(&fi->i_sem);
 182	}
 183}
 184
 185int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
 186{
 187	struct inode *inode = file->f_mapping->host;
 188	struct f2fs_inode_info *fi = F2FS_I(inode);
 189	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 190	nid_t ino = inode->i_ino;
 191	int ret = 0;
 192	bool need_cp = false;
 193	struct writeback_control wbc = {
 194		.sync_mode = WB_SYNC_ALL,
 195		.nr_to_write = LONG_MAX,
 196		.for_reclaim = 0,
 197	};
 198
 199	if (unlikely(f2fs_readonly(inode->i_sb)))
 200		return 0;
 201
 202	trace_f2fs_sync_file_enter(inode);
 203
 204	/* if fdatasync is triggered, let's do in-place-update */
 205	if (datasync || get_dirty_pages(inode) <= SM_I(sbi)->min_fsync_blocks)
 206		set_inode_flag(fi, FI_NEED_IPU);
 207	ret = filemap_write_and_wait_range(inode->i_mapping, start, end);
 208	clear_inode_flag(fi, FI_NEED_IPU);
 209
 210	if (ret) {
 211		trace_f2fs_sync_file_exit(inode, need_cp, datasync, ret);
 212		return ret;
 213	}
 214
 215	/* if the inode is dirty, let's recover all the time */
 216	if (!datasync) {
 217		f2fs_write_inode(inode, NULL);
 218		goto go_write;
 219	}
 220
 221	/*
 222	 * if there is no written data, don't waste time to write recovery info.
 223	 */
 224	if (!is_inode_flag_set(fi, FI_APPEND_WRITE) &&
 225			!exist_written_data(sbi, ino, APPEND_INO)) {
 226
 227		/* it may call write_inode just prior to fsync */
 228		if (need_inode_page_update(sbi, ino))
 229			goto go_write;
 230
 231		if (is_inode_flag_set(fi, FI_UPDATE_WRITE) ||
 232				exist_written_data(sbi, ino, UPDATE_INO))
 233			goto flush_out;
 234		goto out;
 235	}
 236go_write:
 237	/*
 238	 * Both of fdatasync() and fsync() are able to be recovered from
 239	 * sudden-power-off.
 240	 */
 241	down_read(&fi->i_sem);
 242	need_cp = need_do_checkpoint(inode);
 243	up_read(&fi->i_sem);
 244
 245	if (need_cp) {
 246		/* all the dirty node pages should be flushed for POR */
 247		ret = f2fs_sync_fs(inode->i_sb, 1);
 248
 249		/*
 250		 * We've secured consistency through sync_fs. Following pino
 251		 * will be used only for fsynced inodes after checkpoint.
 252		 */
 253		try_to_fix_pino(inode);
 254		clear_inode_flag(fi, FI_APPEND_WRITE);
 255		clear_inode_flag(fi, FI_UPDATE_WRITE);
 256		goto out;
 257	}
 258sync_nodes:
 259	sync_node_pages(sbi, ino, &wbc);
 260
 261	/* if cp_error was enabled, we should avoid infinite loop */
 262	if (unlikely(f2fs_cp_error(sbi))) {
 263		ret = -EIO;
 264		goto out;
 265	}
 266
 267	if (need_inode_block_update(sbi, ino)) {
 268		mark_inode_dirty_sync(inode);
 269		f2fs_write_inode(inode, NULL);
 270		goto sync_nodes;
 271	}
 272
 273	ret = wait_on_node_pages_writeback(sbi, ino);
 274	if (ret)
 275		goto out;
 276
 277	/* once recovery info is written, don't need to tack this */
 278	remove_ino_entry(sbi, ino, APPEND_INO);
 279	clear_inode_flag(fi, FI_APPEND_WRITE);
 280flush_out:
 281	remove_ino_entry(sbi, ino, UPDATE_INO);
 282	clear_inode_flag(fi, FI_UPDATE_WRITE);
 283	ret = f2fs_issue_flush(sbi);
 284	f2fs_update_time(sbi, REQ_TIME);
 285out:
 286	trace_f2fs_sync_file_exit(inode, need_cp, datasync, ret);
 287	f2fs_trace_ios(NULL, 1);
 288	return ret;
 289}
 290
 291static pgoff_t __get_first_dirty_index(struct address_space *mapping,
 292						pgoff_t pgofs, int whence)
 293{
 294	struct pagevec pvec;
 295	int nr_pages;
 296
 297	if (whence != SEEK_DATA)
 298		return 0;
 299
 300	/* find first dirty page index */
 301	pagevec_init(&pvec, 0);
 302	nr_pages = pagevec_lookup_tag(&pvec, mapping, &pgofs,
 303					PAGECACHE_TAG_DIRTY, 1);
 304	pgofs = nr_pages ? pvec.pages[0]->index : ULONG_MAX;
 305	pagevec_release(&pvec);
 306	return pgofs;
 307}
 308
 309static bool __found_offset(block_t blkaddr, pgoff_t dirty, pgoff_t pgofs,
 310							int whence)
 311{
 312	switch (whence) {
 313	case SEEK_DATA:
 314		if ((blkaddr == NEW_ADDR && dirty == pgofs) ||
 315			(blkaddr != NEW_ADDR && blkaddr != NULL_ADDR))
 316			return true;
 317		break;
 318	case SEEK_HOLE:
 319		if (blkaddr == NULL_ADDR)
 320			return true;
 321		break;
 322	}
 323	return false;
 324}
 325
 326static loff_t f2fs_seek_block(struct file *file, loff_t offset, int whence)
 327{
 328	struct inode *inode = file->f_mapping->host;
 329	loff_t maxbytes = inode->i_sb->s_maxbytes;
 330	struct dnode_of_data dn;
 331	pgoff_t pgofs, end_offset, dirty;
 332	loff_t data_ofs = offset;
 333	loff_t isize;
 334	int err = 0;
 335
 336	inode_lock(inode);
 337
 338	isize = i_size_read(inode);
 339	if (offset >= isize)
 340		goto fail;
 341
 342	/* handle inline data case */
 343	if (f2fs_has_inline_data(inode) || f2fs_has_inline_dentry(inode)) {
 344		if (whence == SEEK_HOLE)
 345			data_ofs = isize;
 346		goto found;
 347	}
 348
 349	pgofs = (pgoff_t)(offset >> PAGE_SHIFT);
 350
 351	dirty = __get_first_dirty_index(inode->i_mapping, pgofs, whence);
 352
 353	for (; data_ofs < isize; data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
 354		set_new_dnode(&dn, inode, NULL, NULL, 0);
 355		err = get_dnode_of_data(&dn, pgofs, LOOKUP_NODE_RA);
 356		if (err && err != -ENOENT) {
 357			goto fail;
 358		} else if (err == -ENOENT) {
 359			/* direct node does not exists */
 360			if (whence == SEEK_DATA) {
 361				pgofs = get_next_page_offset(&dn, pgofs);
 362				continue;
 363			} else {
 364				goto found;
 365			}
 366		}
 367
 368		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
 369
 370		/* find data/hole in dnode block */
 371		for (; dn.ofs_in_node < end_offset;
 372				dn.ofs_in_node++, pgofs++,
 373				data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
 374			block_t blkaddr;
 375			blkaddr = datablock_addr(dn.node_page, dn.ofs_in_node);
 376
 377			if (__found_offset(blkaddr, dirty, pgofs, whence)) {
 378				f2fs_put_dnode(&dn);
 379				goto found;
 380			}
 381		}
 382		f2fs_put_dnode(&dn);
 383	}
 384
 385	if (whence == SEEK_DATA)
 386		goto fail;
 387found:
 388	if (whence == SEEK_HOLE && data_ofs > isize)
 389		data_ofs = isize;
 390	inode_unlock(inode);
 391	return vfs_setpos(file, data_ofs, maxbytes);
 392fail:
 393	inode_unlock(inode);
 394	return -ENXIO;
 395}
 396
 397static loff_t f2fs_llseek(struct file *file, loff_t offset, int whence)
 398{
 399	struct inode *inode = file->f_mapping->host;
 400	loff_t maxbytes = inode->i_sb->s_maxbytes;
 401
 402	switch (whence) {
 403	case SEEK_SET:
 404	case SEEK_CUR:
 405	case SEEK_END:
 406		return generic_file_llseek_size(file, offset, whence,
 407						maxbytes, i_size_read(inode));
 408	case SEEK_DATA:
 409	case SEEK_HOLE:
 410		if (offset < 0)
 411			return -ENXIO;
 412		return f2fs_seek_block(file, offset, whence);
 413	}
 414
 415	return -EINVAL;
 416}
 417
 418static int f2fs_file_mmap(struct file *file, struct vm_area_struct *vma)
 419{
 420	struct inode *inode = file_inode(file);
 421	int err;
 422
 423	if (f2fs_encrypted_inode(inode)) {
 424		err = fscrypt_get_encryption_info(inode);
 425		if (err)
 426			return 0;
 427		if (!f2fs_encrypted_inode(inode))
 428			return -ENOKEY;
 429	}
 430
 431	/* we don't need to use inline_data strictly */
 432	err = f2fs_convert_inline_inode(inode);
 433	if (err)
 434		return err;
 435
 436	file_accessed(file);
 437	vma->vm_ops = &f2fs_file_vm_ops;
 438	return 0;
 439}
 440
 441static int f2fs_file_open(struct inode *inode, struct file *filp)
 442{
 443	int ret = generic_file_open(inode, filp);
 444	struct dentry *dir;
 445
 446	if (!ret && f2fs_encrypted_inode(inode)) {
 447		ret = fscrypt_get_encryption_info(inode);
 448		if (ret)
 449			return -EACCES;
 450		if (!fscrypt_has_encryption_key(inode))
 451			return -ENOKEY;
 452	}
 453	dir = dget_parent(file_dentry(filp));
 454	if (f2fs_encrypted_inode(d_inode(dir)) &&
 455			!fscrypt_has_permitted_context(d_inode(dir), inode)) {
 456		dput(dir);
 457		return -EPERM;
 458	}
 459	dput(dir);
 460	return ret;
 461}
 462
 463int truncate_data_blocks_range(struct dnode_of_data *dn, int count)
 464{
 465	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
 466	struct f2fs_node *raw_node;
 467	int nr_free = 0, ofs = dn->ofs_in_node, len = count;
 468	__le32 *addr;
 469
 470	raw_node = F2FS_NODE(dn->node_page);
 471	addr = blkaddr_in_node(raw_node) + ofs;
 472
 473	for (; count > 0; count--, addr++, dn->ofs_in_node++) {
 474		block_t blkaddr = le32_to_cpu(*addr);
 475		if (blkaddr == NULL_ADDR)
 476			continue;
 477
 478		dn->data_blkaddr = NULL_ADDR;
 479		set_data_blkaddr(dn);
 480		invalidate_blocks(sbi, blkaddr);
 481		if (dn->ofs_in_node == 0 && IS_INODE(dn->node_page))
 482			clear_inode_flag(F2FS_I(dn->inode),
 483						FI_FIRST_BLOCK_WRITTEN);
 484		nr_free++;
 485	}
 486
 487	if (nr_free) {
 488		pgoff_t fofs;
 489		/*
 490		 * once we invalidate valid blkaddr in range [ofs, ofs + count],
 491		 * we will invalidate all blkaddr in the whole range.
 492		 */
 493		fofs = start_bidx_of_node(ofs_of_node(dn->node_page),
 494							dn->inode) + ofs;
 495		f2fs_update_extent_cache_range(dn, fofs, 0, len);
 496		dec_valid_block_count(sbi, dn->inode, nr_free);
 497		sync_inode_page(dn);
 498	}
 499	dn->ofs_in_node = ofs;
 500
 501	f2fs_update_time(sbi, REQ_TIME);
 502	trace_f2fs_truncate_data_blocks_range(dn->inode, dn->nid,
 503					 dn->ofs_in_node, nr_free);
 504	return nr_free;
 505}
 506
 507void truncate_data_blocks(struct dnode_of_data *dn)
 508{
 509	truncate_data_blocks_range(dn, ADDRS_PER_BLOCK);
 510}
 511
 512static int truncate_partial_data_page(struct inode *inode, u64 from,
 513								bool cache_only)
 514{
 515	unsigned offset = from & (PAGE_SIZE - 1);
 516	pgoff_t index = from >> PAGE_SHIFT;
 517	struct address_space *mapping = inode->i_mapping;
 518	struct page *page;
 519
 520	if (!offset && !cache_only)
 521		return 0;
 522
 523	if (cache_only) {
 524		page = f2fs_grab_cache_page(mapping, index, false);
 525		if (page && PageUptodate(page))
 526			goto truncate_out;
 527		f2fs_put_page(page, 1);
 528		return 0;
 529	}
 530
 531	page = get_lock_data_page(inode, index, true);
 532	if (IS_ERR(page))
 533		return 0;
 534truncate_out:
 535	f2fs_wait_on_page_writeback(page, DATA, true);
 536	zero_user(page, offset, PAGE_SIZE - offset);
 537	if (!cache_only || !f2fs_encrypted_inode(inode) ||
 538					!S_ISREG(inode->i_mode))
 539		set_page_dirty(page);
 540	f2fs_put_page(page, 1);
 541	return 0;
 542}
 543
 544int truncate_blocks(struct inode *inode, u64 from, bool lock)
 545{
 546	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 547	unsigned int blocksize = inode->i_sb->s_blocksize;
 548	struct dnode_of_data dn;
 549	pgoff_t free_from;
 550	int count = 0, err = 0;
 551	struct page *ipage;
 552	bool truncate_page = false;
 553
 554	trace_f2fs_truncate_blocks_enter(inode, from);
 555
 556	free_from = (pgoff_t)F2FS_BYTES_TO_BLK(from + blocksize - 1);
 557
 558	if (lock)
 559		f2fs_lock_op(sbi);
 560
 561	ipage = get_node_page(sbi, inode->i_ino);
 562	if (IS_ERR(ipage)) {
 563		err = PTR_ERR(ipage);
 564		goto out;
 565	}
 566
 567	if (f2fs_has_inline_data(inode)) {
 568		if (truncate_inline_inode(ipage, from))
 569			set_page_dirty(ipage);
 570		f2fs_put_page(ipage, 1);
 571		truncate_page = true;
 572		goto out;
 573	}
 574
 575	set_new_dnode(&dn, inode, ipage, NULL, 0);
 576	err = get_dnode_of_data(&dn, free_from, LOOKUP_NODE);
 577	if (err) {
 578		if (err == -ENOENT)
 579			goto free_next;
 580		goto out;
 581	}
 582
 583	count = ADDRS_PER_PAGE(dn.node_page, inode);
 584
 585	count -= dn.ofs_in_node;
 586	f2fs_bug_on(sbi, count < 0);
 587
 588	if (dn.ofs_in_node || IS_INODE(dn.node_page)) {
 589		truncate_data_blocks_range(&dn, count);
 590		free_from += count;
 591	}
 592
 593	f2fs_put_dnode(&dn);
 594free_next:
 595	err = truncate_inode_blocks(inode, free_from);
 596out:
 597	if (lock)
 598		f2fs_unlock_op(sbi);
 599
 600	/* lastly zero out the first data page */
 601	if (!err)
 602		err = truncate_partial_data_page(inode, from, truncate_page);
 603
 604	trace_f2fs_truncate_blocks_exit(inode, err);
 605	return err;
 606}
 607
 608int f2fs_truncate(struct inode *inode, bool lock)
 609{
 610	int err;
 611
 612	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
 613				S_ISLNK(inode->i_mode)))
 614		return 0;
 615
 616	trace_f2fs_truncate(inode);
 617
 618	/* we should check inline_data size */
 619	if (!f2fs_may_inline_data(inode)) {
 620		err = f2fs_convert_inline_inode(inode);
 621		if (err)
 622			return err;
 623	}
 624
 625	err = truncate_blocks(inode, i_size_read(inode), lock);
 626	if (err)
 627		return err;
 628
 629	inode->i_mtime = inode->i_ctime = CURRENT_TIME;
 630	mark_inode_dirty(inode);
 631	return 0;
 632}
 633
 634int f2fs_getattr(struct vfsmount *mnt,
 635			 struct dentry *dentry, struct kstat *stat)
 636{
 637	struct inode *inode = d_inode(dentry);
 638	generic_fillattr(inode, stat);
 639	stat->blocks <<= 3;
 640	return 0;
 641}
 642
 643#ifdef CONFIG_F2FS_FS_POSIX_ACL
 644static void __setattr_copy(struct inode *inode, const struct iattr *attr)
 645{
 646	struct f2fs_inode_info *fi = F2FS_I(inode);
 647	unsigned int ia_valid = attr->ia_valid;
 648
 649	if (ia_valid & ATTR_UID)
 650		inode->i_uid = attr->ia_uid;
 651	if (ia_valid & ATTR_GID)
 652		inode->i_gid = attr->ia_gid;
 653	if (ia_valid & ATTR_ATIME)
 654		inode->i_atime = timespec_trunc(attr->ia_atime,
 655						inode->i_sb->s_time_gran);
 656	if (ia_valid & ATTR_MTIME)
 657		inode->i_mtime = timespec_trunc(attr->ia_mtime,
 658						inode->i_sb->s_time_gran);
 659	if (ia_valid & ATTR_CTIME)
 660		inode->i_ctime = timespec_trunc(attr->ia_ctime,
 661						inode->i_sb->s_time_gran);
 662	if (ia_valid & ATTR_MODE) {
 663		umode_t mode = attr->ia_mode;
 664
 665		if (!in_group_p(inode->i_gid) && !capable(CAP_FSETID))
 666			mode &= ~S_ISGID;
 667		set_acl_inode(fi, mode);
 668	}
 669}
 670#else
 671#define __setattr_copy setattr_copy
 672#endif
 673
 674int f2fs_setattr(struct dentry *dentry, struct iattr *attr)
 675{
 676	struct inode *inode = d_inode(dentry);
 677	struct f2fs_inode_info *fi = F2FS_I(inode);
 678	int err;
 679
 680	err = inode_change_ok(inode, attr);
 681	if (err)
 682		return err;
 683
 684	if (attr->ia_valid & ATTR_SIZE) {
 685		if (f2fs_encrypted_inode(inode) &&
 686				fscrypt_get_encryption_info(inode))
 687			return -EACCES;
 688
 689		if (attr->ia_size <= i_size_read(inode)) {
 690			truncate_setsize(inode, attr->ia_size);
 691			err = f2fs_truncate(inode, true);
 692			if (err)
 693				return err;
 694			f2fs_balance_fs(F2FS_I_SB(inode), true);
 695		} else {
 696			/*
 697			 * do not trim all blocks after i_size if target size is
 698			 * larger than i_size.
 699			 */
 700			truncate_setsize(inode, attr->ia_size);
 701
 702			/* should convert inline inode here */
 703			if (!f2fs_may_inline_data(inode)) {
 704				err = f2fs_convert_inline_inode(inode);
 705				if (err)
 706					return err;
 707			}
 708			inode->i_mtime = inode->i_ctime = CURRENT_TIME;
 709		}
 710	}
 711
 712	__setattr_copy(inode, attr);
 713
 714	if (attr->ia_valid & ATTR_MODE) {
 715		err = posix_acl_chmod(inode, get_inode_mode(inode));
 716		if (err || is_inode_flag_set(fi, FI_ACL_MODE)) {
 717			inode->i_mode = fi->i_acl_mode;
 718			clear_inode_flag(fi, FI_ACL_MODE);
 719		}
 720	}
 721
 722	mark_inode_dirty(inode);
 723	return err;
 724}
 725
 726const struct inode_operations f2fs_file_inode_operations = {
 727	.getattr	= f2fs_getattr,
 728	.setattr	= f2fs_setattr,
 729	.get_acl	= f2fs_get_acl,
 730	.set_acl	= f2fs_set_acl,
 731#ifdef CONFIG_F2FS_FS_XATTR
 732	.setxattr	= generic_setxattr,
 733	.getxattr	= generic_getxattr,
 734	.listxattr	= f2fs_listxattr,
 735	.removexattr	= generic_removexattr,
 736#endif
 737	.fiemap		= f2fs_fiemap,
 738};
 739
 740static int fill_zero(struct inode *inode, pgoff_t index,
 741					loff_t start, loff_t len)
 742{
 743	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 744	struct page *page;
 745
 746	if (!len)
 747		return 0;
 748
 749	f2fs_balance_fs(sbi, true);
 750
 751	f2fs_lock_op(sbi);
 752	page = get_new_data_page(inode, NULL, index, false);
 753	f2fs_unlock_op(sbi);
 754
 755	if (IS_ERR(page))
 756		return PTR_ERR(page);
 757
 758	f2fs_wait_on_page_writeback(page, DATA, true);
 759	zero_user(page, start, len);
 760	set_page_dirty(page);
 761	f2fs_put_page(page, 1);
 762	return 0;
 763}
 764
 765int truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end)
 766{
 767	int err;
 768
 769	while (pg_start < pg_end) {
 770		struct dnode_of_data dn;
 771		pgoff_t end_offset, count;
 772
 773		set_new_dnode(&dn, inode, NULL, NULL, 0);
 774		err = get_dnode_of_data(&dn, pg_start, LOOKUP_NODE);
 775		if (err) {
 776			if (err == -ENOENT) {
 777				pg_start++;
 778				continue;
 779			}
 780			return err;
 781		}
 782
 783		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
 784		count = min(end_offset - dn.ofs_in_node, pg_end - pg_start);
 785
 786		f2fs_bug_on(F2FS_I_SB(inode), count == 0 || count > end_offset);
 787
 788		truncate_data_blocks_range(&dn, count);
 789		f2fs_put_dnode(&dn);
 790
 791		pg_start += count;
 792	}
 793	return 0;
 794}
 795
 796static int punch_hole(struct inode *inode, loff_t offset, loff_t len)
 797{
 798	pgoff_t pg_start, pg_end;
 799	loff_t off_start, off_end;
 800	int ret;
 801
 802	ret = f2fs_convert_inline_inode(inode);
 803	if (ret)
 804		return ret;
 805
 806	pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
 807	pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
 808
 809	off_start = offset & (PAGE_SIZE - 1);
 810	off_end = (offset + len) & (PAGE_SIZE - 1);
 811
 812	if (pg_start == pg_end) {
 813		ret = fill_zero(inode, pg_start, off_start,
 814						off_end - off_start);
 815		if (ret)
 816			return ret;
 817	} else {
 818		if (off_start) {
 819			ret = fill_zero(inode, pg_start++, off_start,
 820						PAGE_SIZE - off_start);
 821			if (ret)
 822				return ret;
 823		}
 824		if (off_end) {
 825			ret = fill_zero(inode, pg_end, 0, off_end);
 826			if (ret)
 827				return ret;
 828		}
 829
 830		if (pg_start < pg_end) {
 831			struct address_space *mapping = inode->i_mapping;
 832			loff_t blk_start, blk_end;
 833			struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 834
 835			f2fs_balance_fs(sbi, true);
 836
 837			blk_start = (loff_t)pg_start << PAGE_SHIFT;
 838			blk_end = (loff_t)pg_end << PAGE_SHIFT;
 839			truncate_inode_pages_range(mapping, blk_start,
 840					blk_end - 1);
 841
 842			f2fs_lock_op(sbi);
 843			ret = truncate_hole(inode, pg_start, pg_end);
 844			f2fs_unlock_op(sbi);
 845		}
 846	}
 847
 848	return ret;
 849}
 850
 851static int __exchange_data_block(struct inode *inode, pgoff_t src,
 852					pgoff_t dst, bool full)
 853{
 854	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 855	struct dnode_of_data dn;
 856	block_t new_addr;
 857	bool do_replace = false;
 858	int ret;
 859
 860	set_new_dnode(&dn, inode, NULL, NULL, 0);
 861	ret = get_dnode_of_data(&dn, src, LOOKUP_NODE_RA);
 862	if (ret && ret != -ENOENT) {
 863		return ret;
 864	} else if (ret == -ENOENT) {
 865		new_addr = NULL_ADDR;
 866	} else {
 867		new_addr = dn.data_blkaddr;
 868		if (!is_checkpointed_data(sbi, new_addr)) {
 869			/* do not invalidate this block address */
 870			f2fs_update_data_blkaddr(&dn, NULL_ADDR);
 871			do_replace = true;
 872		}
 873		f2fs_put_dnode(&dn);
 874	}
 875
 876	if (new_addr == NULL_ADDR)
 877		return full ? truncate_hole(inode, dst, dst + 1) : 0;
 878
 879	if (do_replace) {
 880		struct page *ipage = get_node_page(sbi, inode->i_ino);
 881		struct node_info ni;
 882
 883		if (IS_ERR(ipage)) {
 884			ret = PTR_ERR(ipage);
 885			goto err_out;
 886		}
 887
 888		set_new_dnode(&dn, inode, ipage, NULL, 0);
 889		ret = f2fs_reserve_block(&dn, dst);
 890		if (ret)
 891			goto err_out;
 892
 893		truncate_data_blocks_range(&dn, 1);
 894
 895		get_node_info(sbi, dn.nid, &ni);
 896		f2fs_replace_block(sbi, &dn, dn.data_blkaddr, new_addr,
 897				ni.version, true, false);
 898		f2fs_put_dnode(&dn);
 899	} else {
 900		struct page *psrc, *pdst;
 901
 902		psrc = get_lock_data_page(inode, src, true);
 903		if (IS_ERR(psrc))
 904			return PTR_ERR(psrc);
 905		pdst = get_new_data_page(inode, NULL, dst, true);
 906		if (IS_ERR(pdst)) {
 907			f2fs_put_page(psrc, 1);
 908			return PTR_ERR(pdst);
 909		}
 910		f2fs_copy_page(psrc, pdst);
 911		set_page_dirty(pdst);
 912		f2fs_put_page(pdst, 1);
 913		f2fs_put_page(psrc, 1);
 914
 915		return truncate_hole(inode, src, src + 1);
 916	}
 917	return 0;
 918
 919err_out:
 920	if (!get_dnode_of_data(&dn, src, LOOKUP_NODE)) {
 921		f2fs_update_data_blkaddr(&dn, new_addr);
 922		f2fs_put_dnode(&dn);
 923	}
 924	return ret;
 925}
 926
 927static int f2fs_do_collapse(struct inode *inode, pgoff_t start, pgoff_t end)
 928{
 929	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 930	pgoff_t nrpages = (i_size_read(inode) + PAGE_SIZE - 1) / PAGE_SIZE;
 931	int ret = 0;
 932
 933	for (; end < nrpages; start++, end++) {
 934		f2fs_balance_fs(sbi, true);
 935		f2fs_lock_op(sbi);
 936		ret = __exchange_data_block(inode, end, start, true);
 937		f2fs_unlock_op(sbi);
 938		if (ret)
 939			break;
 940	}
 941	return ret;
 942}
 943
 944static int f2fs_collapse_range(struct inode *inode, loff_t offset, loff_t len)
 945{
 946	pgoff_t pg_start, pg_end;
 947	loff_t new_size;
 948	int ret;
 949
 950	if (offset + len >= i_size_read(inode))
 951		return -EINVAL;
 952
 953	/* collapse range should be aligned to block size of f2fs. */
 954	if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
 955		return -EINVAL;
 956
 957	ret = f2fs_convert_inline_inode(inode);
 958	if (ret)
 959		return ret;
 960
 961	pg_start = offset >> PAGE_SHIFT;
 962	pg_end = (offset + len) >> PAGE_SHIFT;
 963
 964	/* write out all dirty pages from offset */
 965	ret = filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
 966	if (ret)
 967		return ret;
 968
 969	truncate_pagecache(inode, offset);
 970
 971	ret = f2fs_do_collapse(inode, pg_start, pg_end);
 972	if (ret)
 973		return ret;
 974
 975	/* write out all moved pages, if possible */
 976	filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
 977	truncate_pagecache(inode, offset);
 978
 979	new_size = i_size_read(inode) - len;
 980	truncate_pagecache(inode, new_size);
 981
 982	ret = truncate_blocks(inode, new_size, true);
 983	if (!ret)
 984		i_size_write(inode, new_size);
 985
 986	return ret;
 987}
 988
 989static int f2fs_zero_range(struct inode *inode, loff_t offset, loff_t len,
 990								int mode)
 991{
 992	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 993	struct address_space *mapping = inode->i_mapping;
 994	pgoff_t index, pg_start, pg_end;
 995	loff_t new_size = i_size_read(inode);
 996	loff_t off_start, off_end;
 997	int ret = 0;
 998
 999	ret = inode_newsize_ok(inode, (len + offset));
1000	if (ret)
1001		return ret;
1002
1003	ret = f2fs_convert_inline_inode(inode);
1004	if (ret)
1005		return ret;
1006
1007	ret = filemap_write_and_wait_range(mapping, offset, offset + len - 1);
1008	if (ret)
1009		return ret;
1010
1011	truncate_pagecache_range(inode, offset, offset + len - 1);
1012
1013	pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1014	pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1015
1016	off_start = offset & (PAGE_SIZE - 1);
1017	off_end = (offset + len) & (PAGE_SIZE - 1);
1018
1019	if (pg_start == pg_end) {
1020		ret = fill_zero(inode, pg_start, off_start,
1021						off_end - off_start);
1022		if (ret)
1023			return ret;
1024
1025		if (offset + len > new_size)
1026			new_size = offset + len;
1027		new_size = max_t(loff_t, new_size, offset + len);
1028	} else {
1029		if (off_start) {
1030			ret = fill_zero(inode, pg_start++, off_start,
1031						PAGE_SIZE - off_start);
1032			if (ret)
1033				return ret;
1034
1035			new_size = max_t(loff_t, new_size,
1036					(loff_t)pg_start << PAGE_SHIFT);
1037		}
1038
1039		for (index = pg_start; index < pg_end; index++) {
1040			struct dnode_of_data dn;
1041			struct page *ipage;
1042
1043			f2fs_lock_op(sbi);
1044
1045			ipage = get_node_page(sbi, inode->i_ino);
1046			if (IS_ERR(ipage)) {
1047				ret = PTR_ERR(ipage);
1048				f2fs_unlock_op(sbi);
1049				goto out;
1050			}
1051
1052			set_new_dnode(&dn, inode, ipage, NULL, 0);
1053			ret = f2fs_reserve_block(&dn, index);
1054			if (ret) {
1055				f2fs_unlock_op(sbi);
1056				goto out;
1057			}
1058
1059			if (dn.data_blkaddr != NEW_ADDR) {
1060				invalidate_blocks(sbi, dn.data_blkaddr);
1061				f2fs_update_data_blkaddr(&dn, NEW_ADDR);
1062			}
1063			f2fs_put_dnode(&dn);
1064			f2fs_unlock_op(sbi);
1065
1066			new_size = max_t(loff_t, new_size,
1067				(loff_t)(index + 1) << PAGE_SHIFT);
1068		}
1069
1070		if (off_end) {
1071			ret = fill_zero(inode, pg_end, 0, off_end);
1072			if (ret)
1073				goto out;
1074
1075			new_size = max_t(loff_t, new_size, offset + len);
1076		}
1077	}
1078
1079out:
1080	if (!(mode & FALLOC_FL_KEEP_SIZE) && i_size_read(inode) < new_size) {
1081		i_size_write(inode, new_size);
1082		mark_inode_dirty(inode);
1083		update_inode_page(inode);
1084	}
1085
1086	return ret;
1087}
1088
1089static int f2fs_insert_range(struct inode *inode, loff_t offset, loff_t len)
1090{
1091	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1092	pgoff_t pg_start, pg_end, delta, nrpages, idx;
1093	loff_t new_size;
1094	int ret = 0;
1095
1096	new_size = i_size_read(inode) + len;
1097	if (new_size > inode->i_sb->s_maxbytes)
1098		return -EFBIG;
1099
1100	if (offset >= i_size_read(inode))
1101		return -EINVAL;
1102
1103	/* insert range should be aligned to block size of f2fs. */
1104	if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
1105		return -EINVAL;
1106
1107	ret = f2fs_convert_inline_inode(inode);
1108	if (ret)
1109		return ret;
1110
1111	f2fs_balance_fs(sbi, true);
1112
1113	ret = truncate_blocks(inode, i_size_read(inode), true);
1114	if (ret)
1115		return ret;
1116
1117	/* write out all dirty pages from offset */
1118	ret = filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1119	if (ret)
1120		return ret;
1121
1122	truncate_pagecache(inode, offset);
1123
1124	pg_start = offset >> PAGE_SHIFT;
1125	pg_end = (offset + len) >> PAGE_SHIFT;
1126	delta = pg_end - pg_start;
1127	nrpages = (i_size_read(inode) + PAGE_SIZE - 1) / PAGE_SIZE;
1128
1129	for (idx = nrpages - 1; idx >= pg_start && idx != -1; idx--) {
1130		f2fs_lock_op(sbi);
1131		ret = __exchange_data_block(inode, idx, idx + delta, false);
1132		f2fs_unlock_op(sbi);
1133		if (ret)
1134			break;
1135	}
1136
1137	/* write out all moved pages, if possible */
1138	filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1139	truncate_pagecache(inode, offset);
1140
1141	if (!ret)
1142		i_size_write(inode, new_size);
1143	return ret;
1144}
1145
1146static int expand_inode_data(struct inode *inode, loff_t offset,
1147					loff_t len, int mode)
1148{
1149	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1150	pgoff_t index, pg_start, pg_end;
1151	loff_t new_size = i_size_read(inode);
1152	loff_t off_start, off_end;
1153	int ret = 0;
1154
1155	ret = inode_newsize_ok(inode, (len + offset));
1156	if (ret)
1157		return ret;
1158
1159	ret = f2fs_convert_inline_inode(inode);
1160	if (ret)
1161		return ret;
1162
1163	f2fs_balance_fs(sbi, true);
1164
1165	pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1166	pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1167
1168	off_start = offset & (PAGE_SIZE - 1);
1169	off_end = (offset + len) & (PAGE_SIZE - 1);
1170
1171	f2fs_lock_op(sbi);
1172
1173	for (index = pg_start; index <= pg_end; index++) {
1174		struct dnode_of_data dn;
1175
1176		if (index == pg_end && !off_end)
1177			goto noalloc;
1178
1179		set_new_dnode(&dn, inode, NULL, NULL, 0);
1180		ret = f2fs_reserve_block(&dn, index);
1181		if (ret)
1182			break;
1183noalloc:
1184		if (pg_start == pg_end)
1185			new_size = offset + len;
1186		else if (index == pg_start && off_start)
1187			new_size = (loff_t)(index + 1) << PAGE_SHIFT;
1188		else if (index == pg_end)
1189			new_size = ((loff_t)index << PAGE_SHIFT) +
1190								off_end;
1191		else
1192			new_size += PAGE_SIZE;
1193	}
1194
1195	if (!(mode & FALLOC_FL_KEEP_SIZE) &&
1196		i_size_read(inode) < new_size) {
1197		i_size_write(inode, new_size);
1198		mark_inode_dirty(inode);
1199		update_inode_page(inode);
1200	}
1201	f2fs_unlock_op(sbi);
1202
1203	return ret;
1204}
1205
1206static long f2fs_fallocate(struct file *file, int mode,
1207				loff_t offset, loff_t len)
1208{
1209	struct inode *inode = file_inode(file);
1210	long ret = 0;
1211
1212	/* f2fs only support ->fallocate for regular file */
1213	if (!S_ISREG(inode->i_mode))
1214		return -EINVAL;
1215
1216	if (f2fs_encrypted_inode(inode) &&
1217		(mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
1218		return -EOPNOTSUPP;
1219
1220	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
1221			FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
1222			FALLOC_FL_INSERT_RANGE))
1223		return -EOPNOTSUPP;
1224
1225	inode_lock(inode);
1226
1227	if (mode & FALLOC_FL_PUNCH_HOLE) {
1228		if (offset >= inode->i_size)
1229			goto out;
1230
1231		ret = punch_hole(inode, offset, len);
1232	} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
1233		ret = f2fs_collapse_range(inode, offset, len);
1234	} else if (mode & FALLOC_FL_ZERO_RANGE) {
1235		ret = f2fs_zero_range(inode, offset, len, mode);
1236	} else if (mode & FALLOC_FL_INSERT_RANGE) {
1237		ret = f2fs_insert_range(inode, offset, len);
1238	} else {
1239		ret = expand_inode_data(inode, offset, len, mode);
1240	}
1241
1242	if (!ret) {
1243		inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1244		mark_inode_dirty(inode);
1245		f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1246	}
1247
1248out:
1249	inode_unlock(inode);
1250
1251	trace_f2fs_fallocate(inode, mode, offset, len, ret);
1252	return ret;
1253}
1254
1255static int f2fs_release_file(struct inode *inode, struct file *filp)
1256{
1257	/* some remained atomic pages should discarded */
1258	if (f2fs_is_atomic_file(inode))
1259		drop_inmem_pages(inode);
1260	if (f2fs_is_volatile_file(inode)) {
1261		set_inode_flag(F2FS_I(inode), FI_DROP_CACHE);
1262		filemap_fdatawrite(inode->i_mapping);
1263		clear_inode_flag(F2FS_I(inode), FI_DROP_CACHE);
1264	}
1265	return 0;
1266}
1267
1268#define F2FS_REG_FLMASK		(~(FS_DIRSYNC_FL | FS_TOPDIR_FL))
1269#define F2FS_OTHER_FLMASK	(FS_NODUMP_FL | FS_NOATIME_FL)
1270
1271static inline __u32 f2fs_mask_flags(umode_t mode, __u32 flags)
1272{
1273	if (S_ISDIR(mode))
1274		return flags;
1275	else if (S_ISREG(mode))
1276		return flags & F2FS_REG_FLMASK;
1277	else
1278		return flags & F2FS_OTHER_FLMASK;
1279}
1280
1281static int f2fs_ioc_getflags(struct file *filp, unsigned long arg)
1282{
1283	struct inode *inode = file_inode(filp);
1284	struct f2fs_inode_info *fi = F2FS_I(inode);
1285	unsigned int flags = fi->i_flags & FS_FL_USER_VISIBLE;
1286	return put_user(flags, (int __user *)arg);
1287}
1288
1289static int f2fs_ioc_setflags(struct file *filp, unsigned long arg)
1290{
1291	struct inode *inode = file_inode(filp);
1292	struct f2fs_inode_info *fi = F2FS_I(inode);
1293	unsigned int flags = fi->i_flags & FS_FL_USER_VISIBLE;
1294	unsigned int oldflags;
1295	int ret;
1296
1297	ret = mnt_want_write_file(filp);
1298	if (ret)
1299		return ret;
1300
1301	if (!inode_owner_or_capable(inode)) {
1302		ret = -EACCES;
1303		goto out;
1304	}
1305
1306	if (get_user(flags, (int __user *)arg)) {
1307		ret = -EFAULT;
1308		goto out;
1309	}
1310
1311	flags = f2fs_mask_flags(inode->i_mode, flags);
1312
1313	inode_lock(inode);
1314
1315	oldflags = fi->i_flags;
1316
1317	if ((flags ^ oldflags) & (FS_APPEND_FL | FS_IMMUTABLE_FL)) {
1318		if (!capable(CAP_LINUX_IMMUTABLE)) {
1319			inode_unlock(inode);
1320			ret = -EPERM;
1321			goto out;
1322		}
1323	}
1324
1325	flags = flags & FS_FL_USER_MODIFIABLE;
1326	flags |= oldflags & ~FS_FL_USER_MODIFIABLE;
1327	fi->i_flags = flags;
1328	inode_unlock(inode);
1329
1330	f2fs_set_inode_flags(inode);
1331	inode->i_ctime = CURRENT_TIME;
1332	mark_inode_dirty(inode);
1333out:
1334	mnt_drop_write_file(filp);
1335	return ret;
1336}
1337
1338static int f2fs_ioc_getversion(struct file *filp, unsigned long arg)
1339{
1340	struct inode *inode = file_inode(filp);
1341
1342	return put_user(inode->i_generation, (int __user *)arg);
1343}
1344
1345static int f2fs_ioc_start_atomic_write(struct file *filp)
1346{
1347	struct inode *inode = file_inode(filp);
1348	int ret;
1349
1350	if (!inode_owner_or_capable(inode))
1351		return -EACCES;
1352
1353	if (f2fs_is_atomic_file(inode))
1354		return 0;
1355
1356	ret = f2fs_convert_inline_inode(inode);
1357	if (ret)
1358		return ret;
1359
1360	set_inode_flag(F2FS_I(inode), FI_ATOMIC_FILE);
1361	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1362
1363	return 0;
1364}
1365
1366static int f2fs_ioc_commit_atomic_write(struct file *filp)
1367{
1368	struct inode *inode = file_inode(filp);
1369	int ret;
1370
1371	if (!inode_owner_or_capable(inode))
1372		return -EACCES;
1373
1374	if (f2fs_is_volatile_file(inode))
1375		return 0;
1376
1377	ret = mnt_want_write_file(filp);
1378	if (ret)
1379		return ret;
1380
1381	if (f2fs_is_atomic_file(inode)) {
1382		clear_inode_flag(F2FS_I(inode), FI_ATOMIC_FILE);
1383		ret = commit_inmem_pages(inode);
1384		if (ret) {
1385			set_inode_flag(F2FS_I(inode), FI_ATOMIC_FILE);
1386			goto err_out;
1387		}
1388	}
1389
1390	ret = f2fs_sync_file(filp, 0, LLONG_MAX, 0);
1391err_out:
1392	mnt_drop_write_file(filp);
1393	return ret;
1394}
1395
1396static int f2fs_ioc_start_volatile_write(struct file *filp)
1397{
1398	struct inode *inode = file_inode(filp);
1399	int ret;
1400
1401	if (!inode_owner_or_capable(inode))
1402		return -EACCES;
1403
1404	if (f2fs_is_volatile_file(inode))
1405		return 0;
1406
1407	ret = f2fs_convert_inline_inode(inode);
1408	if (ret)
1409		return ret;
1410
1411	set_inode_flag(F2FS_I(inode), FI_VOLATILE_FILE);
1412	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1413	return 0;
1414}
1415
1416static int f2fs_ioc_release_volatile_write(struct file *filp)
1417{
1418	struct inode *inode = file_inode(filp);
1419
1420	if (!inode_owner_or_capable(inode))
1421		return -EACCES;
1422
1423	if (!f2fs_is_volatile_file(inode))
1424		return 0;
1425
1426	if (!f2fs_is_first_block_written(inode))
1427		return truncate_partial_data_page(inode, 0, true);
1428
1429	return punch_hole(inode, 0, F2FS_BLKSIZE);
1430}
1431
1432static int f2fs_ioc_abort_volatile_write(struct file *filp)
1433{
1434	struct inode *inode = file_inode(filp);
1435	int ret;
1436
1437	if (!inode_owner_or_capable(inode))
1438		return -EACCES;
1439
1440	ret = mnt_want_write_file(filp);
1441	if (ret)
1442		return ret;
1443
1444	if (f2fs_is_atomic_file(inode)) {
1445		clear_inode_flag(F2FS_I(inode), FI_ATOMIC_FILE);
1446		drop_inmem_pages(inode);
1447	}
1448	if (f2fs_is_volatile_file(inode)) {
1449		clear_inode_flag(F2FS_I(inode), FI_VOLATILE_FILE);
1450		ret = f2fs_sync_file(filp, 0, LLONG_MAX, 0);
1451	}
1452
1453	mnt_drop_write_file(filp);
1454	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1455	return ret;
1456}
1457
1458static int f2fs_ioc_shutdown(struct file *filp, unsigned long arg)
1459{
1460	struct inode *inode = file_inode(filp);
1461	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1462	struct super_block *sb = sbi->sb;
1463	__u32 in;
1464
1465	if (!capable(CAP_SYS_ADMIN))
1466		return -EPERM;
1467
1468	if (get_user(in, (__u32 __user *)arg))
1469		return -EFAULT;
1470
1471	switch (in) {
1472	case F2FS_GOING_DOWN_FULLSYNC:
1473		sb = freeze_bdev(sb->s_bdev);
1474		if (sb && !IS_ERR(sb)) {
1475			f2fs_stop_checkpoint(sbi);
1476			thaw_bdev(sb->s_bdev, sb);
1477		}
1478		break;
1479	case F2FS_GOING_DOWN_METASYNC:
1480		/* do checkpoint only */
1481		f2fs_sync_fs(sb, 1);
1482		f2fs_stop_checkpoint(sbi);
1483		break;
1484	case F2FS_GOING_DOWN_NOSYNC:
1485		f2fs_stop_checkpoint(sbi);
1486		break;
1487	case F2FS_GOING_DOWN_METAFLUSH:
1488		sync_meta_pages(sbi, META, LONG_MAX);
1489		f2fs_stop_checkpoint(sbi);
1490		break;
1491	default:
1492		return -EINVAL;
1493	}
1494	f2fs_update_time(sbi, REQ_TIME);
1495	return 0;
1496}
1497
1498static int f2fs_ioc_fitrim(struct file *filp, unsigned long arg)
1499{
1500	struct inode *inode = file_inode(filp);
1501	struct super_block *sb = inode->i_sb;
1502	struct request_queue *q = bdev_get_queue(sb->s_bdev);
1503	struct fstrim_range range;
1504	int ret;
1505
1506	if (!capable(CAP_SYS_ADMIN))
1507		return -EPERM;
1508
1509	if (!blk_queue_discard(q))
1510		return -EOPNOTSUPP;
1511
1512	if (copy_from_user(&range, (struct fstrim_range __user *)arg,
1513				sizeof(range)))
1514		return -EFAULT;
1515
1516	range.minlen = max((unsigned int)range.minlen,
1517				q->limits.discard_granularity);
1518	ret = f2fs_trim_fs(F2FS_SB(sb), &range);
1519	if (ret < 0)
1520		return ret;
1521
1522	if (copy_to_user((struct fstrim_range __user *)arg, &range,
1523				sizeof(range)))
1524		return -EFAULT;
1525	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1526	return 0;
1527}
1528
1529static bool uuid_is_nonzero(__u8 u[16])
1530{
1531	int i;
1532
1533	for (i = 0; i < 16; i++)
1534		if (u[i])
1535			return true;
1536	return false;
1537}
1538
1539static int f2fs_ioc_set_encryption_policy(struct file *filp, unsigned long arg)
1540{
1541	struct fscrypt_policy policy;
1542	struct inode *inode = file_inode(filp);
1543
1544	if (copy_from_user(&policy, (struct fscrypt_policy __user *)arg,
1545							sizeof(policy)))
1546		return -EFAULT;
1547
1548	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1549	return fscrypt_process_policy(inode, &policy);
1550}
1551
1552static int f2fs_ioc_get_encryption_policy(struct file *filp, unsigned long arg)
1553{
1554	struct fscrypt_policy policy;
1555	struct inode *inode = file_inode(filp);
1556	int err;
1557
1558	err = fscrypt_get_policy(inode, &policy);
1559	if (err)
1560		return err;
1561
1562	if (copy_to_user((struct fscrypt_policy __user *)arg, &policy, sizeof(policy)))
1563		return -EFAULT;
1564	return 0;
1565}
1566
1567static int f2fs_ioc_get_encryption_pwsalt(struct file *filp, unsigned long arg)
1568{
1569	struct inode *inode = file_inode(filp);
1570	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1571	int err;
1572
1573	if (!f2fs_sb_has_crypto(inode->i_sb))
1574		return -EOPNOTSUPP;
1575
1576	if (uuid_is_nonzero(sbi->raw_super->encrypt_pw_salt))
1577		goto got_it;
1578
1579	err = mnt_want_write_file(filp);
1580	if (err)
1581		return err;
1582
1583	/* update superblock with uuid */
1584	generate_random_uuid(sbi->raw_super->encrypt_pw_salt);
1585
1586	err = f2fs_commit_super(sbi, false);
1587	if (err) {
1588		/* undo new data */
1589		memset(sbi->raw_super->encrypt_pw_salt, 0, 16);
1590		mnt_drop_write_file(filp);
1591		return err;
1592	}
1593	mnt_drop_write_file(filp);
1594got_it:
1595	if (copy_to_user((__u8 __user *)arg, sbi->raw_super->encrypt_pw_salt,
1596									16))
1597		return -EFAULT;
1598	return 0;
1599}
1600
1601static int f2fs_ioc_gc(struct file *filp, unsigned long arg)
1602{
1603	struct inode *inode = file_inode(filp);
1604	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1605	__u32 sync;
1606
1607	if (!capable(CAP_SYS_ADMIN))
1608		return -EPERM;
1609
1610	if (get_user(sync, (__u32 __user *)arg))
1611		return -EFAULT;
1612
1613	if (f2fs_readonly(sbi->sb))
1614		return -EROFS;
1615
1616	if (!sync) {
1617		if (!mutex_trylock(&sbi->gc_mutex))
1618			return -EBUSY;
1619	} else {
1620		mutex_lock(&sbi->gc_mutex);
1621	}
1622
1623	return f2fs_gc(sbi, sync);
1624}
1625
1626static int f2fs_ioc_write_checkpoint(struct file *filp, unsigned long arg)
1627{
1628	struct inode *inode = file_inode(filp);
1629	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1630
1631	if (!capable(CAP_SYS_ADMIN))
1632		return -EPERM;
1633
1634	if (f2fs_readonly(sbi->sb))
1635		return -EROFS;
1636
1637	return f2fs_sync_fs(sbi->sb, 1);
1638}
1639
1640static int f2fs_defragment_range(struct f2fs_sb_info *sbi,
1641					struct file *filp,
1642					struct f2fs_defragment *range)
1643{
1644	struct inode *inode = file_inode(filp);
1645	struct f2fs_map_blocks map = { .m_next_pgofs = NULL };
1646	struct extent_info ei;
1647	pgoff_t pg_start, pg_end;
1648	unsigned int blk_per_seg = sbi->blocks_per_seg;
1649	unsigned int total = 0, sec_num;
1650	unsigned int pages_per_sec = sbi->segs_per_sec * blk_per_seg;
1651	block_t blk_end = 0;
1652	bool fragmented = false;
1653	int err;
1654
1655	/* if in-place-update policy is enabled, don't waste time here */
1656	if (need_inplace_update(inode))
1657		return -EINVAL;
1658
1659	pg_start = range->start >> PAGE_SHIFT;
1660	pg_end = (range->start + range->len) >> PAGE_SHIFT;
1661
1662	f2fs_balance_fs(sbi, true);
1663
1664	inode_lock(inode);
1665
1666	/* writeback all dirty pages in the range */
1667	err = filemap_write_and_wait_range(inode->i_mapping, range->start,
1668						range->start + range->len - 1);
1669	if (err)
1670		goto out;
1671
1672	/*
1673	 * lookup mapping info in extent cache, skip defragmenting if physical
1674	 * block addresses are continuous.
1675	 */
1676	if (f2fs_lookup_extent_cache(inode, pg_start, &ei)) {
1677		if (ei.fofs + ei.len >= pg_end)
1678			goto out;
1679	}
1680
1681	map.m_lblk = pg_start;
1682
1683	/*
1684	 * lookup mapping info in dnode page cache, skip defragmenting if all
1685	 * physical block addresses are continuous even if there are hole(s)
1686	 * in logical blocks.
1687	 */
1688	while (map.m_lblk < pg_end) {
1689		map.m_len = pg_end - map.m_lblk;
1690		err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_READ);
1691		if (err)
1692			goto out;
1693
1694		if (!(map.m_flags & F2FS_MAP_FLAGS)) {
1695			map.m_lblk++;
1696			continue;
1697		}
1698
1699		if (blk_end && blk_end != map.m_pblk) {
1700			fragmented = true;
1701			break;
1702		}
1703		blk_end = map.m_pblk + map.m_len;
1704
1705		map.m_lblk += map.m_len;
1706	}
1707
1708	if (!fragmented)
1709		goto out;
1710
1711	map.m_lblk = pg_start;
1712	map.m_len = pg_end - pg_start;
1713
1714	sec_num = (map.m_len + pages_per_sec - 1) / pages_per_sec;
1715
1716	/*
1717	 * make sure there are enough free section for LFS allocation, this can
1718	 * avoid defragment running in SSR mode when free section are allocated
1719	 * intensively
1720	 */
1721	if (has_not_enough_free_secs(sbi, sec_num)) {
1722		err = -EAGAIN;
1723		goto out;
1724	}
1725
1726	while (map.m_lblk < pg_end) {
1727		pgoff_t idx;
1728		int cnt = 0;
1729
1730do_map:
1731		map.m_len = pg_end - map.m_lblk;
1732		err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_READ);
1733		if (err)
1734			goto clear_out;
1735
1736		if (!(map.m_flags & F2FS_MAP_FLAGS)) {
1737			map.m_lblk++;
1738			continue;
1739		}
1740
1741		set_inode_flag(F2FS_I(inode), FI_DO_DEFRAG);
1742
1743		idx = map.m_lblk;
1744		while (idx < map.m_lblk + map.m_len && cnt < blk_per_seg) {
1745			struct page *page;
1746
1747			page = get_lock_data_page(inode, idx, true);
1748			if (IS_ERR(page)) {
1749				err = PTR_ERR(page);
1750				goto clear_out;
1751			}
1752
1753			set_page_dirty(page);
1754			f2fs_put_page(page, 1);
1755
1756			idx++;
1757			cnt++;
1758			total++;
1759		}
1760
1761		map.m_lblk = idx;
1762
1763		if (idx < pg_end && cnt < blk_per_seg)
1764			goto do_map;
1765
1766		clear_inode_flag(F2FS_I(inode), FI_DO_DEFRAG);
1767
1768		err = filemap_fdatawrite(inode->i_mapping);
1769		if (err)
1770			goto out;
1771	}
1772clear_out:
1773	clear_inode_flag(F2FS_I(inode), FI_DO_DEFRAG);
1774out:
1775	inode_unlock(inode);
1776	if (!err)
1777		range->len = (u64)total << PAGE_SHIFT;
1778	return err;
1779}
1780
1781static int f2fs_ioc_defragment(struct file *filp, unsigned long arg)
1782{
1783	struct inode *inode = file_inode(filp);
1784	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1785	struct f2fs_defragment range;
1786	int err;
1787
1788	if (!capable(CAP_SYS_ADMIN))
1789		return -EPERM;
1790
1791	if (!S_ISREG(inode->i_mode))
1792		return -EINVAL;
1793
1794	err = mnt_want_write_file(filp);
1795	if (err)
1796		return err;
1797
1798	if (f2fs_readonly(sbi->sb)) {
1799		err = -EROFS;
1800		goto out;
1801	}
1802
1803	if (copy_from_user(&range, (struct f2fs_defragment __user *)arg,
1804							sizeof(range))) {
1805		err = -EFAULT;
1806		goto out;
1807	}
1808
1809	/* verify alignment of offset & size */
1810	if (range.start & (F2FS_BLKSIZE - 1) ||
1811		range.len & (F2FS_BLKSIZE - 1)) {
1812		err = -EINVAL;
1813		goto out;
1814	}
1815
1816	err = f2fs_defragment_range(sbi, filp, &range);
1817	f2fs_update_time(sbi, REQ_TIME);
1818	if (err < 0)
1819		goto out;
1820
1821	if (copy_to_user((struct f2fs_defragment __user *)arg, &range,
1822							sizeof(range)))
1823		err = -EFAULT;
1824out:
1825	mnt_drop_write_file(filp);
1826	return err;
1827}
1828
1829long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1830{
1831	switch (cmd) {
1832	case F2FS_IOC_GETFLAGS:
1833		return f2fs_ioc_getflags(filp, arg);
1834	case F2FS_IOC_SETFLAGS:
1835		return f2fs_ioc_setflags(filp, arg);
1836	case F2FS_IOC_GETVERSION:
1837		return f2fs_ioc_getversion(filp, arg);
1838	case F2FS_IOC_START_ATOMIC_WRITE:
1839		return f2fs_ioc_start_atomic_write(filp);
1840	case F2FS_IOC_COMMIT_ATOMIC_WRITE:
1841		return f2fs_ioc_commit_atomic_write(filp);
1842	case F2FS_IOC_START_VOLATILE_WRITE:
1843		return f2fs_ioc_start_volatile_write(filp);
1844	case F2FS_IOC_RELEASE_VOLATILE_WRITE:
1845		return f2fs_ioc_release_volatile_write(filp);
1846	case F2FS_IOC_ABORT_VOLATILE_WRITE:
1847		return f2fs_ioc_abort_volatile_write(filp);
1848	case F2FS_IOC_SHUTDOWN:
1849		return f2fs_ioc_shutdown(filp, arg);
1850	case FITRIM:
1851		return f2fs_ioc_fitrim(filp, arg);
1852	case F2FS_IOC_SET_ENCRYPTION_POLICY:
1853		return f2fs_ioc_set_encryption_policy(filp, arg);
1854	case F2FS_IOC_GET_ENCRYPTION_POLICY:
1855		return f2fs_ioc_get_encryption_policy(filp, arg);
1856	case F2FS_IOC_GET_ENCRYPTION_PWSALT:
1857		return f2fs_ioc_get_encryption_pwsalt(filp, arg);
1858	case F2FS_IOC_GARBAGE_COLLECT:
1859		return f2fs_ioc_gc(filp, arg);
1860	case F2FS_IOC_WRITE_CHECKPOINT:
1861		return f2fs_ioc_write_checkpoint(filp, arg);
1862	case F2FS_IOC_DEFRAGMENT:
1863		return f2fs_ioc_defragment(filp, arg);
1864	default:
1865		return -ENOTTY;
1866	}
1867}
1868
1869static ssize_t f2fs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1870{
1871	struct file *file = iocb->ki_filp;
1872	struct inode *inode = file_inode(file);
1873	ssize_t ret;
1874
1875	if (f2fs_encrypted_inode(inode) &&
1876				!fscrypt_has_encryption_key(inode) &&
1877				fscrypt_get_encryption_info(inode))
1878		return -EACCES;
1879
1880	inode_lock(inode);
1881	ret = generic_write_checks(iocb, from);
1882	if (ret > 0) {
1883		ret = f2fs_preallocate_blocks(iocb, from);
1884		if (!ret)
1885			ret = __generic_file_write_iter(iocb, from);
1886	}
1887	inode_unlock(inode);
1888
1889	if (ret > 0) {
1890		ssize_t err;
1891
1892		err = generic_write_sync(file, iocb->ki_pos - ret, ret);
1893		if (err < 0)
1894			ret = err;
1895	}
1896	return ret;
1897}
1898
1899#ifdef CONFIG_COMPAT
1900long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
1901{
1902	switch (cmd) {
1903	case F2FS_IOC32_GETFLAGS:
1904		cmd = F2FS_IOC_GETFLAGS;
1905		break;
1906	case F2FS_IOC32_SETFLAGS:
1907		cmd = F2FS_IOC_SETFLAGS;
1908		break;
1909	case F2FS_IOC32_GETVERSION:
1910		cmd = F2FS_IOC_GETVERSION;
1911		break;
1912	case F2FS_IOC_START_ATOMIC_WRITE:
1913	case F2FS_IOC_COMMIT_ATOMIC_WRITE:
1914	case F2FS_IOC_START_VOLATILE_WRITE:
1915	case F2FS_IOC_RELEASE_VOLATILE_WRITE:
1916	case F2FS_IOC_ABORT_VOLATILE_WRITE:
1917	case F2FS_IOC_SHUTDOWN:
1918	case F2FS_IOC_SET_ENCRYPTION_POLICY:
1919	case F2FS_IOC_GET_ENCRYPTION_PWSALT:
1920	case F2FS_IOC_GET_ENCRYPTION_POLICY:
1921	case F2FS_IOC_GARBAGE_COLLECT:
1922	case F2FS_IOC_WRITE_CHECKPOINT:
1923	case F2FS_IOC_DEFRAGMENT:
1924		break;
1925	default:
1926		return -ENOIOCTLCMD;
1927	}
1928	return f2fs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
1929}
1930#endif
1931
1932const struct file_operations f2fs_file_operations = {
1933	.llseek		= f2fs_llseek,
1934	.read_iter	= generic_file_read_iter,
1935	.write_iter	= f2fs_file_write_iter,
1936	.open		= f2fs_file_open,
1937	.release	= f2fs_release_file,
1938	.mmap		= f2fs_file_mmap,
1939	.fsync		= f2fs_sync_file,
1940	.fallocate	= f2fs_fallocate,
1941	.unlocked_ioctl	= f2fs_ioctl,
1942#ifdef CONFIG_COMPAT
1943	.compat_ioctl	= f2fs_compat_ioctl,
1944#endif
1945	.splice_read	= generic_file_splice_read,
1946	.splice_write	= iter_file_splice_write,
1947};
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * fs/f2fs/file.c
   4 *
   5 * Copyright (c) 2012 Samsung Electronics Co., Ltd.
   6 *             http://www.samsung.com/
   7 */
   8#include <linux/fs.h>
   9#include <linux/f2fs_fs.h>
  10#include <linux/stat.h>
  11#include <linux/buffer_head.h>
  12#include <linux/writeback.h>
  13#include <linux/blkdev.h>
  14#include <linux/falloc.h>
  15#include <linux/types.h>
  16#include <linux/compat.h>
  17#include <linux/uaccess.h>
  18#include <linux/mount.h>
  19#include <linux/pagevec.h>
  20#include <linux/uio.h>
  21#include <linux/uuid.h>
  22#include <linux/file.h>
  23#include <linux/nls.h>
  24#include <linux/sched/signal.h>
  25#include <linux/fileattr.h>
  26#include <linux/fadvise.h>
  27#include <linux/iomap.h>
  28
  29#include "f2fs.h"
  30#include "node.h"
  31#include "segment.h"
  32#include "xattr.h"
  33#include "acl.h"
  34#include "gc.h"
  35#include "iostat.h"
  36#include <trace/events/f2fs.h>
  37#include <uapi/linux/f2fs.h>
  38
  39static vm_fault_t f2fs_filemap_fault(struct vm_fault *vmf)
  40{
  41	struct inode *inode = file_inode(vmf->vma->vm_file);
  42	vm_fault_t ret;
  43
  44	ret = filemap_fault(vmf);
  45	if (!ret)
  46		f2fs_update_iostat(F2FS_I_SB(inode), inode,
  47					APP_MAPPED_READ_IO, F2FS_BLKSIZE);
  48
  49	trace_f2fs_filemap_fault(inode, vmf->pgoff, (unsigned long)ret);
  50
  51	return ret;
  52}
  53
  54static vm_fault_t f2fs_vm_page_mkwrite(struct vm_fault *vmf)
  55{
  56	struct page *page = vmf->page;
  57	struct inode *inode = file_inode(vmf->vma->vm_file);
  58	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
  59	struct dnode_of_data dn;
  60	bool need_alloc = true;
  61	int err = 0;
  62
  63	if (unlikely(IS_IMMUTABLE(inode)))
  64		return VM_FAULT_SIGBUS;
  65
  66	if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
  67		return VM_FAULT_SIGBUS;
  68
  69	if (unlikely(f2fs_cp_error(sbi))) {
  70		err = -EIO;
  71		goto err;
  72	}
  73
  74	if (!f2fs_is_checkpoint_ready(sbi)) {
  75		err = -ENOSPC;
  76		goto err;
  77	}
  78
  79	err = f2fs_convert_inline_inode(inode);
  80	if (err)
  81		goto err;
  82
  83#ifdef CONFIG_F2FS_FS_COMPRESSION
  84	if (f2fs_compressed_file(inode)) {
  85		int ret = f2fs_is_compressed_cluster(inode, page->index);
  86
  87		if (ret < 0) {
  88			err = ret;
  89			goto err;
  90		} else if (ret) {
  91			need_alloc = false;
  92		}
  93	}
  94#endif
  95	/* should do out of any locked page */
  96	if (need_alloc)
  97		f2fs_balance_fs(sbi, true);
  98
  99	sb_start_pagefault(inode->i_sb);
 100
 101	f2fs_bug_on(sbi, f2fs_has_inline_data(inode));
 102
 103	file_update_time(vmf->vma->vm_file);
 104	filemap_invalidate_lock_shared(inode->i_mapping);
 105	lock_page(page);
 106	if (unlikely(page->mapping != inode->i_mapping ||
 107			page_offset(page) > i_size_read(inode) ||
 108			!PageUptodate(page))) {
 109		unlock_page(page);
 110		err = -EFAULT;
 111		goto out_sem;
 112	}
 113
 114	if (need_alloc) {
 115		/* block allocation */
 116		f2fs_do_map_lock(sbi, F2FS_GET_BLOCK_PRE_AIO, true);
 117		set_new_dnode(&dn, inode, NULL, NULL, 0);
 118		err = f2fs_get_block(&dn, page->index);
 119		f2fs_do_map_lock(sbi, F2FS_GET_BLOCK_PRE_AIO, false);
 120	}
 121
 122#ifdef CONFIG_F2FS_FS_COMPRESSION
 123	if (!need_alloc) {
 124		set_new_dnode(&dn, inode, NULL, NULL, 0);
 125		err = f2fs_get_dnode_of_data(&dn, page->index, LOOKUP_NODE);
 126		f2fs_put_dnode(&dn);
 127	}
 128#endif
 129	if (err) {
 130		unlock_page(page);
 131		goto out_sem;
 132	}
 133
 134	f2fs_wait_on_page_writeback(page, DATA, false, true);
 135
 136	/* wait for GCed page writeback via META_MAPPING */
 137	f2fs_wait_on_block_writeback(inode, dn.data_blkaddr);
 138
 139	/*
 140	 * check to see if the page is mapped already (no holes)
 141	 */
 142	if (PageMappedToDisk(page))
 143		goto out_sem;
 144
 145	/* page is wholly or partially inside EOF */
 146	if (((loff_t)(page->index + 1) << PAGE_SHIFT) >
 147						i_size_read(inode)) {
 148		loff_t offset;
 149
 150		offset = i_size_read(inode) & ~PAGE_MASK;
 151		zero_user_segment(page, offset, PAGE_SIZE);
 152	}
 153	set_page_dirty(page);
 154	if (!PageUptodate(page))
 155		SetPageUptodate(page);
 156
 157	f2fs_update_iostat(sbi, inode, APP_MAPPED_IO, F2FS_BLKSIZE);
 158	f2fs_update_time(sbi, REQ_TIME);
 159
 160	trace_f2fs_vm_page_mkwrite(page, DATA);
 161out_sem:
 162	filemap_invalidate_unlock_shared(inode->i_mapping);
 163
 164	sb_end_pagefault(inode->i_sb);
 165err:
 166	return block_page_mkwrite_return(err);
 167}
 168
 169static const struct vm_operations_struct f2fs_file_vm_ops = {
 170	.fault		= f2fs_filemap_fault,
 171	.map_pages	= filemap_map_pages,
 172	.page_mkwrite	= f2fs_vm_page_mkwrite,
 173};
 174
 175static int get_parent_ino(struct inode *inode, nid_t *pino)
 176{
 177	struct dentry *dentry;
 178
 179	/*
 180	 * Make sure to get the non-deleted alias.  The alias associated with
 181	 * the open file descriptor being fsync()'ed may be deleted already.
 182	 */
 183	dentry = d_find_alias(inode);
 184	if (!dentry)
 185		return 0;
 186
 187	*pino = parent_ino(dentry);
 188	dput(dentry);
 189	return 1;
 190}
 191
 192static inline enum cp_reason_type need_do_checkpoint(struct inode *inode)
 193{
 194	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 195	enum cp_reason_type cp_reason = CP_NO_NEEDED;
 196
 197	if (!S_ISREG(inode->i_mode))
 198		cp_reason = CP_NON_REGULAR;
 199	else if (f2fs_compressed_file(inode))
 200		cp_reason = CP_COMPRESSED;
 201	else if (inode->i_nlink != 1)
 202		cp_reason = CP_HARDLINK;
 203	else if (is_sbi_flag_set(sbi, SBI_NEED_CP))
 204		cp_reason = CP_SB_NEED_CP;
 205	else if (file_wrong_pino(inode))
 206		cp_reason = CP_WRONG_PINO;
 207	else if (!f2fs_space_for_roll_forward(sbi))
 208		cp_reason = CP_NO_SPC_ROLL;
 209	else if (!f2fs_is_checkpointed_node(sbi, F2FS_I(inode)->i_pino))
 210		cp_reason = CP_NODE_NEED_CP;
 211	else if (test_opt(sbi, FASTBOOT))
 212		cp_reason = CP_FASTBOOT_MODE;
 213	else if (F2FS_OPTION(sbi).active_logs == 2)
 214		cp_reason = CP_SPEC_LOG_NUM;
 215	else if (F2FS_OPTION(sbi).fsync_mode == FSYNC_MODE_STRICT &&
 216		f2fs_need_dentry_mark(sbi, inode->i_ino) &&
 217		f2fs_exist_written_data(sbi, F2FS_I(inode)->i_pino,
 218							TRANS_DIR_INO))
 219		cp_reason = CP_RECOVER_DIR;
 220
 221	return cp_reason;
 222}
 223
 224static bool need_inode_page_update(struct f2fs_sb_info *sbi, nid_t ino)
 225{
 226	struct page *i = find_get_page(NODE_MAPPING(sbi), ino);
 227	bool ret = false;
 228	/* But we need to avoid that there are some inode updates */
 229	if ((i && PageDirty(i)) || f2fs_need_inode_block_update(sbi, ino))
 230		ret = true;
 231	f2fs_put_page(i, 0);
 232	return ret;
 233}
 234
 235static void try_to_fix_pino(struct inode *inode)
 236{
 237	struct f2fs_inode_info *fi = F2FS_I(inode);
 238	nid_t pino;
 239
 240	f2fs_down_write(&fi->i_sem);
 241	if (file_wrong_pino(inode) && inode->i_nlink == 1 &&
 242			get_parent_ino(inode, &pino)) {
 243		f2fs_i_pino_write(inode, pino);
 244		file_got_pino(inode);
 245	}
 246	f2fs_up_write(&fi->i_sem);
 247}
 248
 249static int f2fs_do_sync_file(struct file *file, loff_t start, loff_t end,
 250						int datasync, bool atomic)
 251{
 252	struct inode *inode = file->f_mapping->host;
 253	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 254	nid_t ino = inode->i_ino;
 255	int ret = 0;
 256	enum cp_reason_type cp_reason = 0;
 257	struct writeback_control wbc = {
 258		.sync_mode = WB_SYNC_ALL,
 259		.nr_to_write = LONG_MAX,
 260		.for_reclaim = 0,
 261	};
 262	unsigned int seq_id = 0;
 263
 264	if (unlikely(f2fs_readonly(inode->i_sb)))
 265		return 0;
 266
 267	trace_f2fs_sync_file_enter(inode);
 268
 269	if (S_ISDIR(inode->i_mode))
 270		goto go_write;
 271
 272	/* if fdatasync is triggered, let's do in-place-update */
 273	if (datasync || get_dirty_pages(inode) <= SM_I(sbi)->min_fsync_blocks)
 274		set_inode_flag(inode, FI_NEED_IPU);
 275	ret = file_write_and_wait_range(file, start, end);
 276	clear_inode_flag(inode, FI_NEED_IPU);
 277
 278	if (ret || is_sbi_flag_set(sbi, SBI_CP_DISABLED)) {
 279		trace_f2fs_sync_file_exit(inode, cp_reason, datasync, ret);
 280		return ret;
 281	}
 282
 283	/* if the inode is dirty, let's recover all the time */
 284	if (!f2fs_skip_inode_update(inode, datasync)) {
 285		f2fs_write_inode(inode, NULL);
 286		goto go_write;
 287	}
 288
 289	/*
 290	 * if there is no written data, don't waste time to write recovery info.
 291	 */
 292	if (!is_inode_flag_set(inode, FI_APPEND_WRITE) &&
 293			!f2fs_exist_written_data(sbi, ino, APPEND_INO)) {
 294
 295		/* it may call write_inode just prior to fsync */
 296		if (need_inode_page_update(sbi, ino))
 297			goto go_write;
 298
 299		if (is_inode_flag_set(inode, FI_UPDATE_WRITE) ||
 300				f2fs_exist_written_data(sbi, ino, UPDATE_INO))
 301			goto flush_out;
 302		goto out;
 303	} else {
 304		/*
 305		 * for OPU case, during fsync(), node can be persisted before
 306		 * data when lower device doesn't support write barrier, result
 307		 * in data corruption after SPO.
 308		 * So for strict fsync mode, force to use atomic write sematics
 309		 * to keep write order in between data/node and last node to
 310		 * avoid potential data corruption.
 311		 */
 312		if (F2FS_OPTION(sbi).fsync_mode ==
 313				FSYNC_MODE_STRICT && !atomic)
 314			atomic = true;
 315	}
 316go_write:
 317	/*
 318	 * Both of fdatasync() and fsync() are able to be recovered from
 319	 * sudden-power-off.
 320	 */
 321	f2fs_down_read(&F2FS_I(inode)->i_sem);
 322	cp_reason = need_do_checkpoint(inode);
 323	f2fs_up_read(&F2FS_I(inode)->i_sem);
 324
 325	if (cp_reason) {
 326		/* all the dirty node pages should be flushed for POR */
 327		ret = f2fs_sync_fs(inode->i_sb, 1);
 328
 329		/*
 330		 * We've secured consistency through sync_fs. Following pino
 331		 * will be used only for fsynced inodes after checkpoint.
 332		 */
 333		try_to_fix_pino(inode);
 334		clear_inode_flag(inode, FI_APPEND_WRITE);
 335		clear_inode_flag(inode, FI_UPDATE_WRITE);
 336		goto out;
 337	}
 338sync_nodes:
 339	atomic_inc(&sbi->wb_sync_req[NODE]);
 340	ret = f2fs_fsync_node_pages(sbi, inode, &wbc, atomic, &seq_id);
 341	atomic_dec(&sbi->wb_sync_req[NODE]);
 342	if (ret)
 343		goto out;
 344
 345	/* if cp_error was enabled, we should avoid infinite loop */
 346	if (unlikely(f2fs_cp_error(sbi))) {
 347		ret = -EIO;
 348		goto out;
 349	}
 350
 351	if (f2fs_need_inode_block_update(sbi, ino)) {
 352		f2fs_mark_inode_dirty_sync(inode, true);
 353		f2fs_write_inode(inode, NULL);
 354		goto sync_nodes;
 355	}
 356
 357	/*
 358	 * If it's atomic_write, it's just fine to keep write ordering. So
 359	 * here we don't need to wait for node write completion, since we use
 360	 * node chain which serializes node blocks. If one of node writes are
 361	 * reordered, we can see simply broken chain, resulting in stopping
 362	 * roll-forward recovery. It means we'll recover all or none node blocks
 363	 * given fsync mark.
 364	 */
 365	if (!atomic) {
 366		ret = f2fs_wait_on_node_pages_writeback(sbi, seq_id);
 367		if (ret)
 368			goto out;
 369	}
 370
 371	/* once recovery info is written, don't need to tack this */
 372	f2fs_remove_ino_entry(sbi, ino, APPEND_INO);
 373	clear_inode_flag(inode, FI_APPEND_WRITE);
 374flush_out:
 375	if ((!atomic && F2FS_OPTION(sbi).fsync_mode != FSYNC_MODE_NOBARRIER) ||
 376	    (atomic && !test_opt(sbi, NOBARRIER) && f2fs_sb_has_blkzoned(sbi)))
 377		ret = f2fs_issue_flush(sbi, inode->i_ino);
 378	if (!ret) {
 379		f2fs_remove_ino_entry(sbi, ino, UPDATE_INO);
 380		clear_inode_flag(inode, FI_UPDATE_WRITE);
 381		f2fs_remove_ino_entry(sbi, ino, FLUSH_INO);
 382	}
 383	f2fs_update_time(sbi, REQ_TIME);
 384out:
 385	trace_f2fs_sync_file_exit(inode, cp_reason, datasync, ret);
 386	return ret;
 387}
 388
 389int f2fs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
 390{
 391	if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(file)))))
 392		return -EIO;
 393	return f2fs_do_sync_file(file, start, end, datasync, false);
 394}
 395
 396static bool __found_offset(struct address_space *mapping, block_t blkaddr,
 397				pgoff_t index, int whence)
 398{
 399	switch (whence) {
 400	case SEEK_DATA:
 401		if (__is_valid_data_blkaddr(blkaddr))
 402			return true;
 403		if (blkaddr == NEW_ADDR &&
 404		    xa_get_mark(&mapping->i_pages, index, PAGECACHE_TAG_DIRTY))
 405			return true;
 406		break;
 407	case SEEK_HOLE:
 408		if (blkaddr == NULL_ADDR)
 409			return true;
 410		break;
 411	}
 412	return false;
 413}
 414
 415static loff_t f2fs_seek_block(struct file *file, loff_t offset, int whence)
 416{
 417	struct inode *inode = file->f_mapping->host;
 418	loff_t maxbytes = inode->i_sb->s_maxbytes;
 419	struct dnode_of_data dn;
 420	pgoff_t pgofs, end_offset;
 421	loff_t data_ofs = offset;
 422	loff_t isize;
 423	int err = 0;
 424
 425	inode_lock(inode);
 426
 427	isize = i_size_read(inode);
 428	if (offset >= isize)
 429		goto fail;
 430
 431	/* handle inline data case */
 432	if (f2fs_has_inline_data(inode)) {
 433		if (whence == SEEK_HOLE) {
 434			data_ofs = isize;
 435			goto found;
 436		} else if (whence == SEEK_DATA) {
 437			data_ofs = offset;
 438			goto found;
 439		}
 440	}
 441
 442	pgofs = (pgoff_t)(offset >> PAGE_SHIFT);
 443
 444	for (; data_ofs < isize; data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
 445		set_new_dnode(&dn, inode, NULL, NULL, 0);
 446		err = f2fs_get_dnode_of_data(&dn, pgofs, LOOKUP_NODE);
 447		if (err && err != -ENOENT) {
 448			goto fail;
 449		} else if (err == -ENOENT) {
 450			/* direct node does not exists */
 451			if (whence == SEEK_DATA) {
 452				pgofs = f2fs_get_next_page_offset(&dn, pgofs);
 453				continue;
 454			} else {
 455				goto found;
 456			}
 457		}
 458
 459		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
 460
 461		/* find data/hole in dnode block */
 462		for (; dn.ofs_in_node < end_offset;
 463				dn.ofs_in_node++, pgofs++,
 464				data_ofs = (loff_t)pgofs << PAGE_SHIFT) {
 465			block_t blkaddr;
 466
 467			blkaddr = f2fs_data_blkaddr(&dn);
 468
 469			if (__is_valid_data_blkaddr(blkaddr) &&
 470				!f2fs_is_valid_blkaddr(F2FS_I_SB(inode),
 471					blkaddr, DATA_GENERIC_ENHANCE)) {
 472				f2fs_put_dnode(&dn);
 473				goto fail;
 474			}
 475
 476			if (__found_offset(file->f_mapping, blkaddr,
 477							pgofs, whence)) {
 478				f2fs_put_dnode(&dn);
 479				goto found;
 480			}
 481		}
 482		f2fs_put_dnode(&dn);
 483	}
 484
 485	if (whence == SEEK_DATA)
 486		goto fail;
 487found:
 488	if (whence == SEEK_HOLE && data_ofs > isize)
 489		data_ofs = isize;
 490	inode_unlock(inode);
 491	return vfs_setpos(file, data_ofs, maxbytes);
 492fail:
 493	inode_unlock(inode);
 494	return -ENXIO;
 495}
 496
 497static loff_t f2fs_llseek(struct file *file, loff_t offset, int whence)
 498{
 499	struct inode *inode = file->f_mapping->host;
 500	loff_t maxbytes = inode->i_sb->s_maxbytes;
 501
 502	if (f2fs_compressed_file(inode))
 503		maxbytes = max_file_blocks(inode) << F2FS_BLKSIZE_BITS;
 504
 505	switch (whence) {
 506	case SEEK_SET:
 507	case SEEK_CUR:
 508	case SEEK_END:
 509		return generic_file_llseek_size(file, offset, whence,
 510						maxbytes, i_size_read(inode));
 511	case SEEK_DATA:
 512	case SEEK_HOLE:
 513		if (offset < 0)
 514			return -ENXIO;
 515		return f2fs_seek_block(file, offset, whence);
 516	}
 517
 518	return -EINVAL;
 519}
 520
 521static int f2fs_file_mmap(struct file *file, struct vm_area_struct *vma)
 522{
 523	struct inode *inode = file_inode(file);
 524
 525	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
 526		return -EIO;
 527
 528	if (!f2fs_is_compress_backend_ready(inode))
 529		return -EOPNOTSUPP;
 530
 531	file_accessed(file);
 532	vma->vm_ops = &f2fs_file_vm_ops;
 533	set_inode_flag(inode, FI_MMAP_FILE);
 534	return 0;
 535}
 536
 537static int f2fs_file_open(struct inode *inode, struct file *filp)
 538{
 539	int err = fscrypt_file_open(inode, filp);
 540
 541	if (err)
 542		return err;
 543
 544	if (!f2fs_is_compress_backend_ready(inode))
 545		return -EOPNOTSUPP;
 546
 547	err = fsverity_file_open(inode, filp);
 548	if (err)
 549		return err;
 550
 551	filp->f_mode |= FMODE_NOWAIT;
 552
 553	return dquot_file_open(inode, filp);
 554}
 555
 556void f2fs_truncate_data_blocks_range(struct dnode_of_data *dn, int count)
 557{
 558	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
 559	struct f2fs_node *raw_node;
 560	int nr_free = 0, ofs = dn->ofs_in_node, len = count;
 561	__le32 *addr;
 562	int base = 0;
 563	bool compressed_cluster = false;
 564	int cluster_index = 0, valid_blocks = 0;
 565	int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
 566	bool released = !atomic_read(&F2FS_I(dn->inode)->i_compr_blocks);
 567
 568	if (IS_INODE(dn->node_page) && f2fs_has_extra_attr(dn->inode))
 569		base = get_extra_isize(dn->inode);
 570
 571	raw_node = F2FS_NODE(dn->node_page);
 572	addr = blkaddr_in_node(raw_node) + base + ofs;
 573
 574	/* Assumption: truncation starts with cluster */
 575	for (; count > 0; count--, addr++, dn->ofs_in_node++, cluster_index++) {
 576		block_t blkaddr = le32_to_cpu(*addr);
 577
 578		if (f2fs_compressed_file(dn->inode) &&
 579					!(cluster_index & (cluster_size - 1))) {
 580			if (compressed_cluster)
 581				f2fs_i_compr_blocks_update(dn->inode,
 582							valid_blocks, false);
 583			compressed_cluster = (blkaddr == COMPRESS_ADDR);
 584			valid_blocks = 0;
 585		}
 586
 587		if (blkaddr == NULL_ADDR)
 588			continue;
 589
 590		dn->data_blkaddr = NULL_ADDR;
 591		f2fs_set_data_blkaddr(dn);
 592
 593		if (__is_valid_data_blkaddr(blkaddr)) {
 594			if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
 595					DATA_GENERIC_ENHANCE))
 596				continue;
 597			if (compressed_cluster)
 598				valid_blocks++;
 599		}
 600
 601		if (dn->ofs_in_node == 0 && IS_INODE(dn->node_page))
 602			clear_inode_flag(dn->inode, FI_FIRST_BLOCK_WRITTEN);
 603
 604		f2fs_invalidate_blocks(sbi, blkaddr);
 605
 606		if (!released || blkaddr != COMPRESS_ADDR)
 607			nr_free++;
 608	}
 609
 610	if (compressed_cluster)
 611		f2fs_i_compr_blocks_update(dn->inode, valid_blocks, false);
 612
 613	if (nr_free) {
 614		pgoff_t fofs;
 615		/*
 616		 * once we invalidate valid blkaddr in range [ofs, ofs + count],
 617		 * we will invalidate all blkaddr in the whole range.
 618		 */
 619		fofs = f2fs_start_bidx_of_node(ofs_of_node(dn->node_page),
 620							dn->inode) + ofs;
 621		f2fs_update_read_extent_cache_range(dn, fofs, 0, len);
 622		f2fs_update_age_extent_cache_range(dn, fofs, nr_free);
 623		dec_valid_block_count(sbi, dn->inode, nr_free);
 624	}
 625	dn->ofs_in_node = ofs;
 626
 627	f2fs_update_time(sbi, REQ_TIME);
 628	trace_f2fs_truncate_data_blocks_range(dn->inode, dn->nid,
 629					 dn->ofs_in_node, nr_free);
 630}
 631
 632void f2fs_truncate_data_blocks(struct dnode_of_data *dn)
 633{
 634	f2fs_truncate_data_blocks_range(dn, ADDRS_PER_BLOCK(dn->inode));
 635}
 636
 637static int truncate_partial_data_page(struct inode *inode, u64 from,
 638								bool cache_only)
 639{
 640	loff_t offset = from & (PAGE_SIZE - 1);
 641	pgoff_t index = from >> PAGE_SHIFT;
 642	struct address_space *mapping = inode->i_mapping;
 643	struct page *page;
 644
 645	if (!offset && !cache_only)
 646		return 0;
 647
 648	if (cache_only) {
 649		page = find_lock_page(mapping, index);
 650		if (page && PageUptodate(page))
 651			goto truncate_out;
 652		f2fs_put_page(page, 1);
 653		return 0;
 654	}
 655
 656	page = f2fs_get_lock_data_page(inode, index, true);
 657	if (IS_ERR(page))
 658		return PTR_ERR(page) == -ENOENT ? 0 : PTR_ERR(page);
 659truncate_out:
 660	f2fs_wait_on_page_writeback(page, DATA, true, true);
 661	zero_user(page, offset, PAGE_SIZE - offset);
 662
 663	/* An encrypted inode should have a key and truncate the last page. */
 664	f2fs_bug_on(F2FS_I_SB(inode), cache_only && IS_ENCRYPTED(inode));
 665	if (!cache_only)
 666		set_page_dirty(page);
 667	f2fs_put_page(page, 1);
 668	return 0;
 669}
 670
 671int f2fs_do_truncate_blocks(struct inode *inode, u64 from, bool lock)
 672{
 673	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 674	struct dnode_of_data dn;
 675	pgoff_t free_from;
 676	int count = 0, err = 0;
 677	struct page *ipage;
 678	bool truncate_page = false;
 679
 680	trace_f2fs_truncate_blocks_enter(inode, from);
 681
 682	free_from = (pgoff_t)F2FS_BLK_ALIGN(from);
 683
 684	if (free_from >= max_file_blocks(inode))
 685		goto free_partial;
 686
 687	if (lock)
 688		f2fs_lock_op(sbi);
 689
 690	ipage = f2fs_get_node_page(sbi, inode->i_ino);
 691	if (IS_ERR(ipage)) {
 692		err = PTR_ERR(ipage);
 693		goto out;
 694	}
 695
 696	if (f2fs_has_inline_data(inode)) {
 697		f2fs_truncate_inline_inode(inode, ipage, from);
 698		f2fs_put_page(ipage, 1);
 699		truncate_page = true;
 700		goto out;
 701	}
 702
 703	set_new_dnode(&dn, inode, ipage, NULL, 0);
 704	err = f2fs_get_dnode_of_data(&dn, free_from, LOOKUP_NODE_RA);
 705	if (err) {
 706		if (err == -ENOENT)
 707			goto free_next;
 708		goto out;
 709	}
 710
 711	count = ADDRS_PER_PAGE(dn.node_page, inode);
 712
 713	count -= dn.ofs_in_node;
 714	f2fs_bug_on(sbi, count < 0);
 715
 716	if (dn.ofs_in_node || IS_INODE(dn.node_page)) {
 717		f2fs_truncate_data_blocks_range(&dn, count);
 718		free_from += count;
 719	}
 720
 721	f2fs_put_dnode(&dn);
 722free_next:
 723	err = f2fs_truncate_inode_blocks(inode, free_from);
 724out:
 725	if (lock)
 726		f2fs_unlock_op(sbi);
 727free_partial:
 728	/* lastly zero out the first data page */
 729	if (!err)
 730		err = truncate_partial_data_page(inode, from, truncate_page);
 731
 732	trace_f2fs_truncate_blocks_exit(inode, err);
 733	return err;
 734}
 735
 736int f2fs_truncate_blocks(struct inode *inode, u64 from, bool lock)
 737{
 738	u64 free_from = from;
 739	int err;
 740
 741#ifdef CONFIG_F2FS_FS_COMPRESSION
 742	/*
 743	 * for compressed file, only support cluster size
 744	 * aligned truncation.
 745	 */
 746	if (f2fs_compressed_file(inode))
 747		free_from = round_up(from,
 748				F2FS_I(inode)->i_cluster_size << PAGE_SHIFT);
 749#endif
 750
 751	err = f2fs_do_truncate_blocks(inode, free_from, lock);
 752	if (err)
 753		return err;
 754
 755#ifdef CONFIG_F2FS_FS_COMPRESSION
 756	/*
 757	 * For compressed file, after release compress blocks, don't allow write
 758	 * direct, but we should allow write direct after truncate to zero.
 759	 */
 760	if (f2fs_compressed_file(inode) && !free_from
 761			&& is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
 762		clear_inode_flag(inode, FI_COMPRESS_RELEASED);
 763
 764	if (from != free_from) {
 765		err = f2fs_truncate_partial_cluster(inode, from, lock);
 766		if (err)
 767			return err;
 768	}
 769#endif
 770
 771	return 0;
 772}
 773
 774int f2fs_truncate(struct inode *inode)
 775{
 776	int err;
 777
 778	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
 779		return -EIO;
 780
 781	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
 782				S_ISLNK(inode->i_mode)))
 783		return 0;
 784
 785	trace_f2fs_truncate(inode);
 786
 787	if (time_to_inject(F2FS_I_SB(inode), FAULT_TRUNCATE)) {
 788		f2fs_show_injection_info(F2FS_I_SB(inode), FAULT_TRUNCATE);
 789		return -EIO;
 790	}
 791
 792	err = f2fs_dquot_initialize(inode);
 793	if (err)
 794		return err;
 795
 796	/* we should check inline_data size */
 797	if (!f2fs_may_inline_data(inode)) {
 798		err = f2fs_convert_inline_inode(inode);
 799		if (err)
 800			return err;
 801	}
 802
 803	err = f2fs_truncate_blocks(inode, i_size_read(inode), true);
 804	if (err)
 805		return err;
 806
 807	inode->i_mtime = inode->i_ctime = current_time(inode);
 808	f2fs_mark_inode_dirty_sync(inode, false);
 809	return 0;
 810}
 811
 812static bool f2fs_force_buffered_io(struct inode *inode, int rw)
 813{
 814	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
 815
 816	if (!fscrypt_dio_supported(inode))
 817		return true;
 818	if (fsverity_active(inode))
 819		return true;
 820	if (f2fs_compressed_file(inode))
 821		return true;
 822
 823	/* disallow direct IO if any of devices has unaligned blksize */
 824	if (f2fs_is_multi_device(sbi) && !sbi->aligned_blksize)
 825		return true;
 826	/*
 827	 * for blkzoned device, fallback direct IO to buffered IO, so
 828	 * all IOs can be serialized by log-structured write.
 829	 */
 830	if (f2fs_sb_has_blkzoned(sbi) && (rw == WRITE))
 831		return true;
 832	if (f2fs_lfs_mode(sbi) && rw == WRITE && F2FS_IO_ALIGNED(sbi))
 833		return true;
 834	if (is_sbi_flag_set(sbi, SBI_CP_DISABLED))
 835		return true;
 836
 837	return false;
 838}
 839
 840int f2fs_getattr(struct user_namespace *mnt_userns, const struct path *path,
 841		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
 842{
 843	struct inode *inode = d_inode(path->dentry);
 844	struct f2fs_inode_info *fi = F2FS_I(inode);
 845	struct f2fs_inode *ri = NULL;
 846	unsigned int flags;
 847
 848	if (f2fs_has_extra_attr(inode) &&
 849			f2fs_sb_has_inode_crtime(F2FS_I_SB(inode)) &&
 850			F2FS_FITS_IN_INODE(ri, fi->i_extra_isize, i_crtime)) {
 851		stat->result_mask |= STATX_BTIME;
 852		stat->btime.tv_sec = fi->i_crtime.tv_sec;
 853		stat->btime.tv_nsec = fi->i_crtime.tv_nsec;
 854	}
 855
 856	/*
 857	 * Return the DIO alignment restrictions if requested.  We only return
 858	 * this information when requested, since on encrypted files it might
 859	 * take a fair bit of work to get if the file wasn't opened recently.
 860	 *
 861	 * f2fs sometimes supports DIO reads but not DIO writes.  STATX_DIOALIGN
 862	 * cannot represent that, so in that case we report no DIO support.
 863	 */
 864	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
 865		unsigned int bsize = i_blocksize(inode);
 866
 867		stat->result_mask |= STATX_DIOALIGN;
 868		if (!f2fs_force_buffered_io(inode, WRITE)) {
 869			stat->dio_mem_align = bsize;
 870			stat->dio_offset_align = bsize;
 871		}
 872	}
 873
 874	flags = fi->i_flags;
 875	if (flags & F2FS_COMPR_FL)
 876		stat->attributes |= STATX_ATTR_COMPRESSED;
 877	if (flags & F2FS_APPEND_FL)
 878		stat->attributes |= STATX_ATTR_APPEND;
 879	if (IS_ENCRYPTED(inode))
 880		stat->attributes |= STATX_ATTR_ENCRYPTED;
 881	if (flags & F2FS_IMMUTABLE_FL)
 882		stat->attributes |= STATX_ATTR_IMMUTABLE;
 883	if (flags & F2FS_NODUMP_FL)
 884		stat->attributes |= STATX_ATTR_NODUMP;
 885	if (IS_VERITY(inode))
 886		stat->attributes |= STATX_ATTR_VERITY;
 887
 888	stat->attributes_mask |= (STATX_ATTR_COMPRESSED |
 889				  STATX_ATTR_APPEND |
 890				  STATX_ATTR_ENCRYPTED |
 891				  STATX_ATTR_IMMUTABLE |
 892				  STATX_ATTR_NODUMP |
 893				  STATX_ATTR_VERITY);
 894
 895	generic_fillattr(mnt_userns, inode, stat);
 896
 897	/* we need to show initial sectors used for inline_data/dentries */
 898	if ((S_ISREG(inode->i_mode) && f2fs_has_inline_data(inode)) ||
 899					f2fs_has_inline_dentry(inode))
 900		stat->blocks += (stat->size + 511) >> 9;
 901
 902	return 0;
 903}
 904
 905#ifdef CONFIG_F2FS_FS_POSIX_ACL
 906static void __setattr_copy(struct user_namespace *mnt_userns,
 907			   struct inode *inode, const struct iattr *attr)
 908{
 909	unsigned int ia_valid = attr->ia_valid;
 910
 911	i_uid_update(mnt_userns, attr, inode);
 912	i_gid_update(mnt_userns, attr, inode);
 913	if (ia_valid & ATTR_ATIME)
 914		inode->i_atime = attr->ia_atime;
 915	if (ia_valid & ATTR_MTIME)
 916		inode->i_mtime = attr->ia_mtime;
 917	if (ia_valid & ATTR_CTIME)
 918		inode->i_ctime = attr->ia_ctime;
 919	if (ia_valid & ATTR_MODE) {
 920		umode_t mode = attr->ia_mode;
 921		vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
 922
 923		if (!vfsgid_in_group_p(vfsgid) &&
 924		    !capable_wrt_inode_uidgid(mnt_userns, inode, CAP_FSETID))
 925			mode &= ~S_ISGID;
 926		set_acl_inode(inode, mode);
 927	}
 928}
 929#else
 930#define __setattr_copy setattr_copy
 931#endif
 932
 933int f2fs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
 934		 struct iattr *attr)
 935{
 936	struct inode *inode = d_inode(dentry);
 937	int err;
 938
 939	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
 940		return -EIO;
 941
 942	if (unlikely(IS_IMMUTABLE(inode)))
 943		return -EPERM;
 944
 945	if (unlikely(IS_APPEND(inode) &&
 946			(attr->ia_valid & (ATTR_MODE | ATTR_UID |
 947				  ATTR_GID | ATTR_TIMES_SET))))
 948		return -EPERM;
 949
 950	if ((attr->ia_valid & ATTR_SIZE) &&
 951		!f2fs_is_compress_backend_ready(inode))
 952		return -EOPNOTSUPP;
 953
 954	err = setattr_prepare(mnt_userns, dentry, attr);
 955	if (err)
 956		return err;
 957
 958	err = fscrypt_prepare_setattr(dentry, attr);
 959	if (err)
 960		return err;
 961
 962	err = fsverity_prepare_setattr(dentry, attr);
 963	if (err)
 964		return err;
 965
 966	if (is_quota_modification(mnt_userns, inode, attr)) {
 967		err = f2fs_dquot_initialize(inode);
 968		if (err)
 969			return err;
 970	}
 971	if (i_uid_needs_update(mnt_userns, attr, inode) ||
 972	    i_gid_needs_update(mnt_userns, attr, inode)) {
 973		f2fs_lock_op(F2FS_I_SB(inode));
 974		err = dquot_transfer(mnt_userns, inode, attr);
 975		if (err) {
 976			set_sbi_flag(F2FS_I_SB(inode),
 977					SBI_QUOTA_NEED_REPAIR);
 978			f2fs_unlock_op(F2FS_I_SB(inode));
 979			return err;
 980		}
 981		/*
 982		 * update uid/gid under lock_op(), so that dquot and inode can
 983		 * be updated atomically.
 984		 */
 985		i_uid_update(mnt_userns, attr, inode);
 986		i_gid_update(mnt_userns, attr, inode);
 987		f2fs_mark_inode_dirty_sync(inode, true);
 988		f2fs_unlock_op(F2FS_I_SB(inode));
 989	}
 990
 991	if (attr->ia_valid & ATTR_SIZE) {
 992		loff_t old_size = i_size_read(inode);
 993
 994		if (attr->ia_size > MAX_INLINE_DATA(inode)) {
 995			/*
 996			 * should convert inline inode before i_size_write to
 997			 * keep smaller than inline_data size with inline flag.
 998			 */
 999			err = f2fs_convert_inline_inode(inode);
1000			if (err)
1001				return err;
1002		}
1003
1004		f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1005		filemap_invalidate_lock(inode->i_mapping);
1006
1007		truncate_setsize(inode, attr->ia_size);
1008
1009		if (attr->ia_size <= old_size)
1010			err = f2fs_truncate(inode);
1011		/*
1012		 * do not trim all blocks after i_size if target size is
1013		 * larger than i_size.
1014		 */
1015		filemap_invalidate_unlock(inode->i_mapping);
1016		f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1017		if (err)
1018			return err;
1019
1020		spin_lock(&F2FS_I(inode)->i_size_lock);
1021		inode->i_mtime = inode->i_ctime = current_time(inode);
1022		F2FS_I(inode)->last_disk_size = i_size_read(inode);
1023		spin_unlock(&F2FS_I(inode)->i_size_lock);
1024	}
1025
1026	__setattr_copy(mnt_userns, inode, attr);
1027
1028	if (attr->ia_valid & ATTR_MODE) {
1029		err = posix_acl_chmod(mnt_userns, dentry, f2fs_get_inode_mode(inode));
1030
1031		if (is_inode_flag_set(inode, FI_ACL_MODE)) {
1032			if (!err)
1033				inode->i_mode = F2FS_I(inode)->i_acl_mode;
1034			clear_inode_flag(inode, FI_ACL_MODE);
1035		}
1036	}
1037
1038	/* file size may changed here */
1039	f2fs_mark_inode_dirty_sync(inode, true);
1040
1041	/* inode change will produce dirty node pages flushed by checkpoint */
1042	f2fs_balance_fs(F2FS_I_SB(inode), true);
1043
1044	return err;
1045}
1046
1047const struct inode_operations f2fs_file_inode_operations = {
1048	.getattr	= f2fs_getattr,
1049	.setattr	= f2fs_setattr,
1050	.get_inode_acl	= f2fs_get_acl,
1051	.set_acl	= f2fs_set_acl,
1052	.listxattr	= f2fs_listxattr,
1053	.fiemap		= f2fs_fiemap,
1054	.fileattr_get	= f2fs_fileattr_get,
1055	.fileattr_set	= f2fs_fileattr_set,
1056};
1057
1058static int fill_zero(struct inode *inode, pgoff_t index,
1059					loff_t start, loff_t len)
1060{
1061	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1062	struct page *page;
1063
1064	if (!len)
1065		return 0;
1066
1067	f2fs_balance_fs(sbi, true);
1068
1069	f2fs_lock_op(sbi);
1070	page = f2fs_get_new_data_page(inode, NULL, index, false);
1071	f2fs_unlock_op(sbi);
1072
1073	if (IS_ERR(page))
1074		return PTR_ERR(page);
1075
1076	f2fs_wait_on_page_writeback(page, DATA, true, true);
1077	zero_user(page, start, len);
1078	set_page_dirty(page);
1079	f2fs_put_page(page, 1);
1080	return 0;
1081}
1082
1083int f2fs_truncate_hole(struct inode *inode, pgoff_t pg_start, pgoff_t pg_end)
1084{
1085	int err;
1086
1087	while (pg_start < pg_end) {
1088		struct dnode_of_data dn;
1089		pgoff_t end_offset, count;
1090
1091		set_new_dnode(&dn, inode, NULL, NULL, 0);
1092		err = f2fs_get_dnode_of_data(&dn, pg_start, LOOKUP_NODE);
1093		if (err) {
1094			if (err == -ENOENT) {
1095				pg_start = f2fs_get_next_page_offset(&dn,
1096								pg_start);
1097				continue;
1098			}
1099			return err;
1100		}
1101
1102		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
1103		count = min(end_offset - dn.ofs_in_node, pg_end - pg_start);
1104
1105		f2fs_bug_on(F2FS_I_SB(inode), count == 0 || count > end_offset);
1106
1107		f2fs_truncate_data_blocks_range(&dn, count);
1108		f2fs_put_dnode(&dn);
1109
1110		pg_start += count;
1111	}
1112	return 0;
1113}
1114
1115static int punch_hole(struct inode *inode, loff_t offset, loff_t len)
1116{
1117	pgoff_t pg_start, pg_end;
1118	loff_t off_start, off_end;
1119	int ret;
1120
1121	ret = f2fs_convert_inline_inode(inode);
1122	if (ret)
1123		return ret;
1124
1125	pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1126	pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1127
1128	off_start = offset & (PAGE_SIZE - 1);
1129	off_end = (offset + len) & (PAGE_SIZE - 1);
1130
1131	if (pg_start == pg_end) {
1132		ret = fill_zero(inode, pg_start, off_start,
1133						off_end - off_start);
1134		if (ret)
1135			return ret;
1136	} else {
1137		if (off_start) {
1138			ret = fill_zero(inode, pg_start++, off_start,
1139						PAGE_SIZE - off_start);
1140			if (ret)
1141				return ret;
1142		}
1143		if (off_end) {
1144			ret = fill_zero(inode, pg_end, 0, off_end);
1145			if (ret)
1146				return ret;
1147		}
1148
1149		if (pg_start < pg_end) {
1150			loff_t blk_start, blk_end;
1151			struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1152
1153			f2fs_balance_fs(sbi, true);
1154
1155			blk_start = (loff_t)pg_start << PAGE_SHIFT;
1156			blk_end = (loff_t)pg_end << PAGE_SHIFT;
1157
1158			f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1159			filemap_invalidate_lock(inode->i_mapping);
1160
1161			truncate_pagecache_range(inode, blk_start, blk_end - 1);
1162
1163			f2fs_lock_op(sbi);
1164			ret = f2fs_truncate_hole(inode, pg_start, pg_end);
1165			f2fs_unlock_op(sbi);
1166
1167			filemap_invalidate_unlock(inode->i_mapping);
1168			f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1169		}
1170	}
1171
1172	return ret;
1173}
1174
1175static int __read_out_blkaddrs(struct inode *inode, block_t *blkaddr,
1176				int *do_replace, pgoff_t off, pgoff_t len)
1177{
1178	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1179	struct dnode_of_data dn;
1180	int ret, done, i;
1181
1182next_dnode:
1183	set_new_dnode(&dn, inode, NULL, NULL, 0);
1184	ret = f2fs_get_dnode_of_data(&dn, off, LOOKUP_NODE_RA);
1185	if (ret && ret != -ENOENT) {
1186		return ret;
1187	} else if (ret == -ENOENT) {
1188		if (dn.max_level == 0)
1189			return -ENOENT;
1190		done = min((pgoff_t)ADDRS_PER_BLOCK(inode) -
1191						dn.ofs_in_node, len);
1192		blkaddr += done;
1193		do_replace += done;
1194		goto next;
1195	}
1196
1197	done = min((pgoff_t)ADDRS_PER_PAGE(dn.node_page, inode) -
1198							dn.ofs_in_node, len);
1199	for (i = 0; i < done; i++, blkaddr++, do_replace++, dn.ofs_in_node++) {
1200		*blkaddr = f2fs_data_blkaddr(&dn);
1201
1202		if (__is_valid_data_blkaddr(*blkaddr) &&
1203			!f2fs_is_valid_blkaddr(sbi, *blkaddr,
1204					DATA_GENERIC_ENHANCE)) {
1205			f2fs_put_dnode(&dn);
1206			f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
1207			return -EFSCORRUPTED;
1208		}
1209
1210		if (!f2fs_is_checkpointed_data(sbi, *blkaddr)) {
1211
1212			if (f2fs_lfs_mode(sbi)) {
1213				f2fs_put_dnode(&dn);
1214				return -EOPNOTSUPP;
1215			}
1216
1217			/* do not invalidate this block address */
1218			f2fs_update_data_blkaddr(&dn, NULL_ADDR);
1219			*do_replace = 1;
1220		}
1221	}
1222	f2fs_put_dnode(&dn);
1223next:
1224	len -= done;
1225	off += done;
1226	if (len)
1227		goto next_dnode;
1228	return 0;
1229}
1230
1231static int __roll_back_blkaddrs(struct inode *inode, block_t *blkaddr,
1232				int *do_replace, pgoff_t off, int len)
1233{
1234	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1235	struct dnode_of_data dn;
1236	int ret, i;
1237
1238	for (i = 0; i < len; i++, do_replace++, blkaddr++) {
1239		if (*do_replace == 0)
1240			continue;
1241
1242		set_new_dnode(&dn, inode, NULL, NULL, 0);
1243		ret = f2fs_get_dnode_of_data(&dn, off + i, LOOKUP_NODE_RA);
1244		if (ret) {
1245			dec_valid_block_count(sbi, inode, 1);
1246			f2fs_invalidate_blocks(sbi, *blkaddr);
1247		} else {
1248			f2fs_update_data_blkaddr(&dn, *blkaddr);
1249		}
1250		f2fs_put_dnode(&dn);
1251	}
1252	return 0;
1253}
1254
1255static int __clone_blkaddrs(struct inode *src_inode, struct inode *dst_inode,
1256			block_t *blkaddr, int *do_replace,
1257			pgoff_t src, pgoff_t dst, pgoff_t len, bool full)
1258{
1259	struct f2fs_sb_info *sbi = F2FS_I_SB(src_inode);
1260	pgoff_t i = 0;
1261	int ret;
1262
1263	while (i < len) {
1264		if (blkaddr[i] == NULL_ADDR && !full) {
1265			i++;
1266			continue;
1267		}
1268
1269		if (do_replace[i] || blkaddr[i] == NULL_ADDR) {
1270			struct dnode_of_data dn;
1271			struct node_info ni;
1272			size_t new_size;
1273			pgoff_t ilen;
1274
1275			set_new_dnode(&dn, dst_inode, NULL, NULL, 0);
1276			ret = f2fs_get_dnode_of_data(&dn, dst + i, ALLOC_NODE);
1277			if (ret)
1278				return ret;
1279
1280			ret = f2fs_get_node_info(sbi, dn.nid, &ni, false);
1281			if (ret) {
1282				f2fs_put_dnode(&dn);
1283				return ret;
1284			}
1285
1286			ilen = min((pgoff_t)
1287				ADDRS_PER_PAGE(dn.node_page, dst_inode) -
1288						dn.ofs_in_node, len - i);
1289			do {
1290				dn.data_blkaddr = f2fs_data_blkaddr(&dn);
1291				f2fs_truncate_data_blocks_range(&dn, 1);
1292
1293				if (do_replace[i]) {
1294					f2fs_i_blocks_write(src_inode,
1295							1, false, false);
1296					f2fs_i_blocks_write(dst_inode,
1297							1, true, false);
1298					f2fs_replace_block(sbi, &dn, dn.data_blkaddr,
1299					blkaddr[i], ni.version, true, false);
1300
1301					do_replace[i] = 0;
1302				}
1303				dn.ofs_in_node++;
1304				i++;
1305				new_size = (loff_t)(dst + i) << PAGE_SHIFT;
1306				if (dst_inode->i_size < new_size)
1307					f2fs_i_size_write(dst_inode, new_size);
1308			} while (--ilen && (do_replace[i] || blkaddr[i] == NULL_ADDR));
1309
1310			f2fs_put_dnode(&dn);
1311		} else {
1312			struct page *psrc, *pdst;
1313
1314			psrc = f2fs_get_lock_data_page(src_inode,
1315							src + i, true);
1316			if (IS_ERR(psrc))
1317				return PTR_ERR(psrc);
1318			pdst = f2fs_get_new_data_page(dst_inode, NULL, dst + i,
1319								true);
1320			if (IS_ERR(pdst)) {
1321				f2fs_put_page(psrc, 1);
1322				return PTR_ERR(pdst);
1323			}
1324			memcpy_page(pdst, 0, psrc, 0, PAGE_SIZE);
1325			set_page_dirty(pdst);
1326			f2fs_put_page(pdst, 1);
1327			f2fs_put_page(psrc, 1);
1328
1329			ret = f2fs_truncate_hole(src_inode,
1330						src + i, src + i + 1);
1331			if (ret)
1332				return ret;
1333			i++;
1334		}
1335	}
1336	return 0;
1337}
1338
1339static int __exchange_data_block(struct inode *src_inode,
1340			struct inode *dst_inode, pgoff_t src, pgoff_t dst,
1341			pgoff_t len, bool full)
1342{
1343	block_t *src_blkaddr;
1344	int *do_replace;
1345	pgoff_t olen;
1346	int ret;
1347
1348	while (len) {
1349		olen = min((pgoff_t)4 * ADDRS_PER_BLOCK(src_inode), len);
1350
1351		src_blkaddr = f2fs_kvzalloc(F2FS_I_SB(src_inode),
1352					array_size(olen, sizeof(block_t)),
1353					GFP_NOFS);
1354		if (!src_blkaddr)
1355			return -ENOMEM;
1356
1357		do_replace = f2fs_kvzalloc(F2FS_I_SB(src_inode),
1358					array_size(olen, sizeof(int)),
1359					GFP_NOFS);
1360		if (!do_replace) {
1361			kvfree(src_blkaddr);
1362			return -ENOMEM;
1363		}
1364
1365		ret = __read_out_blkaddrs(src_inode, src_blkaddr,
1366					do_replace, src, olen);
1367		if (ret)
1368			goto roll_back;
1369
1370		ret = __clone_blkaddrs(src_inode, dst_inode, src_blkaddr,
1371					do_replace, src, dst, olen, full);
1372		if (ret)
1373			goto roll_back;
1374
1375		src += olen;
1376		dst += olen;
1377		len -= olen;
1378
1379		kvfree(src_blkaddr);
1380		kvfree(do_replace);
1381	}
1382	return 0;
1383
1384roll_back:
1385	__roll_back_blkaddrs(src_inode, src_blkaddr, do_replace, src, olen);
1386	kvfree(src_blkaddr);
1387	kvfree(do_replace);
1388	return ret;
1389}
1390
1391static int f2fs_do_collapse(struct inode *inode, loff_t offset, loff_t len)
1392{
1393	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1394	pgoff_t nrpages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
1395	pgoff_t start = offset >> PAGE_SHIFT;
1396	pgoff_t end = (offset + len) >> PAGE_SHIFT;
1397	int ret;
1398
1399	f2fs_balance_fs(sbi, true);
1400
1401	/* avoid gc operation during block exchange */
1402	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1403	filemap_invalidate_lock(inode->i_mapping);
1404
1405	f2fs_lock_op(sbi);
1406	f2fs_drop_extent_tree(inode);
1407	truncate_pagecache(inode, offset);
1408	ret = __exchange_data_block(inode, inode, end, start, nrpages - end, true);
1409	f2fs_unlock_op(sbi);
1410
1411	filemap_invalidate_unlock(inode->i_mapping);
1412	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1413	return ret;
1414}
1415
1416static int f2fs_collapse_range(struct inode *inode, loff_t offset, loff_t len)
1417{
1418	loff_t new_size;
1419	int ret;
1420
1421	if (offset + len >= i_size_read(inode))
1422		return -EINVAL;
1423
1424	/* collapse range should be aligned to block size of f2fs. */
1425	if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
1426		return -EINVAL;
1427
1428	ret = f2fs_convert_inline_inode(inode);
1429	if (ret)
1430		return ret;
1431
1432	/* write out all dirty pages from offset */
1433	ret = filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1434	if (ret)
1435		return ret;
1436
1437	ret = f2fs_do_collapse(inode, offset, len);
1438	if (ret)
1439		return ret;
1440
1441	/* write out all moved pages, if possible */
1442	filemap_invalidate_lock(inode->i_mapping);
1443	filemap_write_and_wait_range(inode->i_mapping, offset, LLONG_MAX);
1444	truncate_pagecache(inode, offset);
1445
1446	new_size = i_size_read(inode) - len;
1447	ret = f2fs_truncate_blocks(inode, new_size, true);
1448	filemap_invalidate_unlock(inode->i_mapping);
1449	if (!ret)
1450		f2fs_i_size_write(inode, new_size);
1451	return ret;
1452}
1453
1454static int f2fs_do_zero_range(struct dnode_of_data *dn, pgoff_t start,
1455								pgoff_t end)
1456{
1457	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
1458	pgoff_t index = start;
1459	unsigned int ofs_in_node = dn->ofs_in_node;
1460	blkcnt_t count = 0;
1461	int ret;
1462
1463	for (; index < end; index++, dn->ofs_in_node++) {
1464		if (f2fs_data_blkaddr(dn) == NULL_ADDR)
1465			count++;
1466	}
1467
1468	dn->ofs_in_node = ofs_in_node;
1469	ret = f2fs_reserve_new_blocks(dn, count);
1470	if (ret)
1471		return ret;
1472
1473	dn->ofs_in_node = ofs_in_node;
1474	for (index = start; index < end; index++, dn->ofs_in_node++) {
1475		dn->data_blkaddr = f2fs_data_blkaddr(dn);
1476		/*
1477		 * f2fs_reserve_new_blocks will not guarantee entire block
1478		 * allocation.
1479		 */
1480		if (dn->data_blkaddr == NULL_ADDR) {
1481			ret = -ENOSPC;
1482			break;
1483		}
1484
1485		if (dn->data_blkaddr == NEW_ADDR)
1486			continue;
1487
1488		if (!f2fs_is_valid_blkaddr(sbi, dn->data_blkaddr,
1489					DATA_GENERIC_ENHANCE)) {
1490			ret = -EFSCORRUPTED;
1491			f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
1492			break;
1493		}
1494
1495		f2fs_invalidate_blocks(sbi, dn->data_blkaddr);
1496		dn->data_blkaddr = NEW_ADDR;
1497		f2fs_set_data_blkaddr(dn);
1498	}
1499
1500	f2fs_update_read_extent_cache_range(dn, start, 0, index - start);
1501
1502	return ret;
1503}
1504
1505static int f2fs_zero_range(struct inode *inode, loff_t offset, loff_t len,
1506								int mode)
1507{
1508	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1509	struct address_space *mapping = inode->i_mapping;
1510	pgoff_t index, pg_start, pg_end;
1511	loff_t new_size = i_size_read(inode);
1512	loff_t off_start, off_end;
1513	int ret = 0;
1514
1515	ret = inode_newsize_ok(inode, (len + offset));
1516	if (ret)
1517		return ret;
1518
1519	ret = f2fs_convert_inline_inode(inode);
1520	if (ret)
1521		return ret;
1522
1523	ret = filemap_write_and_wait_range(mapping, offset, offset + len - 1);
1524	if (ret)
1525		return ret;
1526
1527	pg_start = ((unsigned long long) offset) >> PAGE_SHIFT;
1528	pg_end = ((unsigned long long) offset + len) >> PAGE_SHIFT;
1529
1530	off_start = offset & (PAGE_SIZE - 1);
1531	off_end = (offset + len) & (PAGE_SIZE - 1);
1532
1533	if (pg_start == pg_end) {
1534		ret = fill_zero(inode, pg_start, off_start,
1535						off_end - off_start);
1536		if (ret)
1537			return ret;
1538
1539		new_size = max_t(loff_t, new_size, offset + len);
1540	} else {
1541		if (off_start) {
1542			ret = fill_zero(inode, pg_start++, off_start,
1543						PAGE_SIZE - off_start);
1544			if (ret)
1545				return ret;
1546
1547			new_size = max_t(loff_t, new_size,
1548					(loff_t)pg_start << PAGE_SHIFT);
1549		}
1550
1551		for (index = pg_start; index < pg_end;) {
1552			struct dnode_of_data dn;
1553			unsigned int end_offset;
1554			pgoff_t end;
1555
1556			f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1557			filemap_invalidate_lock(mapping);
1558
1559			truncate_pagecache_range(inode,
1560				(loff_t)index << PAGE_SHIFT,
1561				((loff_t)pg_end << PAGE_SHIFT) - 1);
1562
1563			f2fs_lock_op(sbi);
1564
1565			set_new_dnode(&dn, inode, NULL, NULL, 0);
1566			ret = f2fs_get_dnode_of_data(&dn, index, ALLOC_NODE);
1567			if (ret) {
1568				f2fs_unlock_op(sbi);
1569				filemap_invalidate_unlock(mapping);
1570				f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1571				goto out;
1572			}
1573
1574			end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
1575			end = min(pg_end, end_offset - dn.ofs_in_node + index);
1576
1577			ret = f2fs_do_zero_range(&dn, index, end);
1578			f2fs_put_dnode(&dn);
1579
1580			f2fs_unlock_op(sbi);
1581			filemap_invalidate_unlock(mapping);
1582			f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1583
1584			f2fs_balance_fs(sbi, dn.node_changed);
1585
1586			if (ret)
1587				goto out;
1588
1589			index = end;
1590			new_size = max_t(loff_t, new_size,
1591					(loff_t)index << PAGE_SHIFT);
1592		}
1593
1594		if (off_end) {
1595			ret = fill_zero(inode, pg_end, 0, off_end);
1596			if (ret)
1597				goto out;
1598
1599			new_size = max_t(loff_t, new_size, offset + len);
1600		}
1601	}
1602
1603out:
1604	if (new_size > i_size_read(inode)) {
1605		if (mode & FALLOC_FL_KEEP_SIZE)
1606			file_set_keep_isize(inode);
1607		else
1608			f2fs_i_size_write(inode, new_size);
1609	}
1610	return ret;
1611}
1612
1613static int f2fs_insert_range(struct inode *inode, loff_t offset, loff_t len)
1614{
1615	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1616	struct address_space *mapping = inode->i_mapping;
1617	pgoff_t nr, pg_start, pg_end, delta, idx;
1618	loff_t new_size;
1619	int ret = 0;
1620
1621	new_size = i_size_read(inode) + len;
1622	ret = inode_newsize_ok(inode, new_size);
1623	if (ret)
1624		return ret;
1625
1626	if (offset >= i_size_read(inode))
1627		return -EINVAL;
1628
1629	/* insert range should be aligned to block size of f2fs. */
1630	if (offset & (F2FS_BLKSIZE - 1) || len & (F2FS_BLKSIZE - 1))
1631		return -EINVAL;
1632
1633	ret = f2fs_convert_inline_inode(inode);
1634	if (ret)
1635		return ret;
1636
1637	f2fs_balance_fs(sbi, true);
1638
1639	filemap_invalidate_lock(mapping);
1640	ret = f2fs_truncate_blocks(inode, i_size_read(inode), true);
1641	filemap_invalidate_unlock(mapping);
1642	if (ret)
1643		return ret;
1644
1645	/* write out all dirty pages from offset */
1646	ret = filemap_write_and_wait_range(mapping, offset, LLONG_MAX);
1647	if (ret)
1648		return ret;
1649
1650	pg_start = offset >> PAGE_SHIFT;
1651	pg_end = (offset + len) >> PAGE_SHIFT;
1652	delta = pg_end - pg_start;
1653	idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
1654
1655	/* avoid gc operation during block exchange */
1656	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1657	filemap_invalidate_lock(mapping);
1658	truncate_pagecache(inode, offset);
1659
1660	while (!ret && idx > pg_start) {
1661		nr = idx - pg_start;
1662		if (nr > delta)
1663			nr = delta;
1664		idx -= nr;
1665
1666		f2fs_lock_op(sbi);
1667		f2fs_drop_extent_tree(inode);
1668
1669		ret = __exchange_data_block(inode, inode, idx,
1670					idx + delta, nr, false);
1671		f2fs_unlock_op(sbi);
1672	}
1673	filemap_invalidate_unlock(mapping);
1674	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
1675
1676	/* write out all moved pages, if possible */
1677	filemap_invalidate_lock(mapping);
1678	filemap_write_and_wait_range(mapping, offset, LLONG_MAX);
1679	truncate_pagecache(inode, offset);
1680	filemap_invalidate_unlock(mapping);
1681
1682	if (!ret)
1683		f2fs_i_size_write(inode, new_size);
1684	return ret;
1685}
1686
1687static int expand_inode_data(struct inode *inode, loff_t offset,
1688					loff_t len, int mode)
1689{
1690	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
1691	struct f2fs_map_blocks map = { .m_next_pgofs = NULL,
1692			.m_next_extent = NULL, .m_seg_type = NO_CHECK_TYPE,
1693			.m_may_create = true };
1694	struct f2fs_gc_control gc_control = { .victim_segno = NULL_SEGNO,
1695			.init_gc_type = FG_GC,
1696			.should_migrate_blocks = false,
1697			.err_gc_skipped = true,
1698			.nr_free_secs = 0 };
1699	pgoff_t pg_start, pg_end;
1700	loff_t new_size = i_size_read(inode);
1701	loff_t off_end;
1702	block_t expanded = 0;
1703	int err;
1704
1705	err = inode_newsize_ok(inode, (len + offset));
1706	if (err)
1707		return err;
1708
1709	err = f2fs_convert_inline_inode(inode);
1710	if (err)
1711		return err;
1712
1713	f2fs_balance_fs(sbi, true);
1714
1715	pg_start = ((unsigned long long)offset) >> PAGE_SHIFT;
1716	pg_end = ((unsigned long long)offset + len) >> PAGE_SHIFT;
1717	off_end = (offset + len) & (PAGE_SIZE - 1);
1718
1719	map.m_lblk = pg_start;
1720	map.m_len = pg_end - pg_start;
1721	if (off_end)
1722		map.m_len++;
1723
1724	if (!map.m_len)
1725		return 0;
1726
1727	if (f2fs_is_pinned_file(inode)) {
1728		block_t sec_blks = CAP_BLKS_PER_SEC(sbi);
1729		block_t sec_len = roundup(map.m_len, sec_blks);
1730
1731		map.m_len = sec_blks;
1732next_alloc:
1733		if (has_not_enough_free_secs(sbi, 0,
1734			GET_SEC_FROM_SEG(sbi, overprovision_segments(sbi)))) {
1735			f2fs_down_write(&sbi->gc_lock);
1736			err = f2fs_gc(sbi, &gc_control);
1737			if (err && err != -ENODATA)
1738				goto out_err;
1739		}
1740
1741		f2fs_down_write(&sbi->pin_sem);
1742
1743		f2fs_lock_op(sbi);
1744		f2fs_allocate_new_section(sbi, CURSEG_COLD_DATA_PINNED, false);
1745		f2fs_unlock_op(sbi);
1746
1747		map.m_seg_type = CURSEG_COLD_DATA_PINNED;
1748		err = f2fs_map_blocks(inode, &map, 1, F2FS_GET_BLOCK_PRE_DIO);
1749		file_dont_truncate(inode);
1750
1751		f2fs_up_write(&sbi->pin_sem);
1752
1753		expanded += map.m_len;
1754		sec_len -= map.m_len;
1755		map.m_lblk += map.m_len;
1756		if (!err && sec_len)
1757			goto next_alloc;
1758
1759		map.m_len = expanded;
1760	} else {
1761		err = f2fs_map_blocks(inode, &map, 1, F2FS_GET_BLOCK_PRE_AIO);
1762		expanded = map.m_len;
1763	}
1764out_err:
1765	if (err) {
1766		pgoff_t last_off;
1767
1768		if (!expanded)
1769			return err;
1770
1771		last_off = pg_start + expanded - 1;
1772
1773		/* update new size to the failed position */
1774		new_size = (last_off == pg_end) ? offset + len :
1775					(loff_t)(last_off + 1) << PAGE_SHIFT;
1776	} else {
1777		new_size = ((loff_t)pg_end << PAGE_SHIFT) + off_end;
1778	}
1779
1780	if (new_size > i_size_read(inode)) {
1781		if (mode & FALLOC_FL_KEEP_SIZE)
1782			file_set_keep_isize(inode);
1783		else
1784			f2fs_i_size_write(inode, new_size);
1785	}
1786
1787	return err;
1788}
1789
1790static long f2fs_fallocate(struct file *file, int mode,
1791				loff_t offset, loff_t len)
1792{
1793	struct inode *inode = file_inode(file);
1794	long ret = 0;
1795
1796	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
1797		return -EIO;
1798	if (!f2fs_is_checkpoint_ready(F2FS_I_SB(inode)))
1799		return -ENOSPC;
1800	if (!f2fs_is_compress_backend_ready(inode))
1801		return -EOPNOTSUPP;
1802
1803	/* f2fs only support ->fallocate for regular file */
1804	if (!S_ISREG(inode->i_mode))
1805		return -EINVAL;
1806
1807	if (IS_ENCRYPTED(inode) &&
1808		(mode & (FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_INSERT_RANGE)))
1809		return -EOPNOTSUPP;
1810
1811	/*
1812	 * Pinned file should not support partial trucation since the block
1813	 * can be used by applications.
1814	 */
1815	if ((f2fs_compressed_file(inode) || f2fs_is_pinned_file(inode)) &&
1816		(mode & (FALLOC_FL_PUNCH_HOLE | FALLOC_FL_COLLAPSE_RANGE |
1817			FALLOC_FL_ZERO_RANGE | FALLOC_FL_INSERT_RANGE)))
1818		return -EOPNOTSUPP;
1819
1820	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
1821			FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |
1822			FALLOC_FL_INSERT_RANGE))
1823		return -EOPNOTSUPP;
1824
1825	inode_lock(inode);
1826
1827	ret = file_modified(file);
1828	if (ret)
1829		goto out;
1830
1831	if (mode & FALLOC_FL_PUNCH_HOLE) {
1832		if (offset >= inode->i_size)
1833			goto out;
1834
1835		ret = punch_hole(inode, offset, len);
1836	} else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
1837		ret = f2fs_collapse_range(inode, offset, len);
1838	} else if (mode & FALLOC_FL_ZERO_RANGE) {
1839		ret = f2fs_zero_range(inode, offset, len, mode);
1840	} else if (mode & FALLOC_FL_INSERT_RANGE) {
1841		ret = f2fs_insert_range(inode, offset, len);
1842	} else {
1843		ret = expand_inode_data(inode, offset, len, mode);
1844	}
1845
1846	if (!ret) {
1847		inode->i_mtime = inode->i_ctime = current_time(inode);
1848		f2fs_mark_inode_dirty_sync(inode, false);
1849		f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
1850	}
1851
1852out:
1853	inode_unlock(inode);
1854
1855	trace_f2fs_fallocate(inode, mode, offset, len, ret);
1856	return ret;
1857}
1858
1859static int f2fs_release_file(struct inode *inode, struct file *filp)
1860{
1861	/*
1862	 * f2fs_relase_file is called at every close calls. So we should
1863	 * not drop any inmemory pages by close called by other process.
1864	 */
1865	if (!(filp->f_mode & FMODE_WRITE) ||
1866			atomic_read(&inode->i_writecount) != 1)
1867		return 0;
1868
1869	f2fs_abort_atomic_write(inode, true);
1870	return 0;
1871}
1872
1873static int f2fs_file_flush(struct file *file, fl_owner_t id)
1874{
1875	struct inode *inode = file_inode(file);
1876
1877	/*
1878	 * If the process doing a transaction is crashed, we should do
1879	 * roll-back. Otherwise, other reader/write can see corrupted database
1880	 * until all the writers close its file. Since this should be done
1881	 * before dropping file lock, it needs to do in ->flush.
1882	 */
1883	if (F2FS_I(inode)->atomic_write_task == current)
1884		f2fs_abort_atomic_write(inode, true);
1885	return 0;
1886}
1887
1888static int f2fs_setflags_common(struct inode *inode, u32 iflags, u32 mask)
1889{
1890	struct f2fs_inode_info *fi = F2FS_I(inode);
1891	u32 masked_flags = fi->i_flags & mask;
1892
1893	/* mask can be shrunk by flags_valid selector */
1894	iflags &= mask;
1895
1896	/* Is it quota file? Do not allow user to mess with it */
1897	if (IS_NOQUOTA(inode))
1898		return -EPERM;
1899
1900	if ((iflags ^ masked_flags) & F2FS_CASEFOLD_FL) {
1901		if (!f2fs_sb_has_casefold(F2FS_I_SB(inode)))
1902			return -EOPNOTSUPP;
1903		if (!f2fs_empty_dir(inode))
1904			return -ENOTEMPTY;
1905	}
1906
1907	if (iflags & (F2FS_COMPR_FL | F2FS_NOCOMP_FL)) {
1908		if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
1909			return -EOPNOTSUPP;
1910		if ((iflags & F2FS_COMPR_FL) && (iflags & F2FS_NOCOMP_FL))
1911			return -EINVAL;
1912	}
1913
1914	if ((iflags ^ masked_flags) & F2FS_COMPR_FL) {
1915		if (masked_flags & F2FS_COMPR_FL) {
1916			if (!f2fs_disable_compressed_file(inode))
1917				return -EINVAL;
1918		} else {
1919			/* try to convert inline_data to support compression */
1920			int err = f2fs_convert_inline_inode(inode);
1921			if (err)
1922				return err;
1923			if (!f2fs_may_compress(inode))
1924				return -EINVAL;
1925			if (S_ISREG(inode->i_mode) && F2FS_HAS_BLOCKS(inode))
1926				return -EINVAL;
1927			if (set_compress_context(inode))
1928				return -EOPNOTSUPP;
1929		}
1930	}
1931
1932	fi->i_flags = iflags | (fi->i_flags & ~mask);
1933	f2fs_bug_on(F2FS_I_SB(inode), (fi->i_flags & F2FS_COMPR_FL) &&
1934					(fi->i_flags & F2FS_NOCOMP_FL));
1935
1936	if (fi->i_flags & F2FS_PROJINHERIT_FL)
1937		set_inode_flag(inode, FI_PROJ_INHERIT);
1938	else
1939		clear_inode_flag(inode, FI_PROJ_INHERIT);
1940
1941	inode->i_ctime = current_time(inode);
1942	f2fs_set_inode_flags(inode);
1943	f2fs_mark_inode_dirty_sync(inode, true);
1944	return 0;
1945}
1946
1947/* FS_IOC_[GS]ETFLAGS and FS_IOC_FS[GS]ETXATTR support */
1948
1949/*
1950 * To make a new on-disk f2fs i_flag gettable via FS_IOC_GETFLAGS, add an entry
1951 * for it to f2fs_fsflags_map[], and add its FS_*_FL equivalent to
1952 * F2FS_GETTABLE_FS_FL.  To also make it settable via FS_IOC_SETFLAGS, also add
1953 * its FS_*_FL equivalent to F2FS_SETTABLE_FS_FL.
1954 *
1955 * Translating flags to fsx_flags value used by FS_IOC_FSGETXATTR and
1956 * FS_IOC_FSSETXATTR is done by the VFS.
1957 */
1958
1959static const struct {
1960	u32 iflag;
1961	u32 fsflag;
1962} f2fs_fsflags_map[] = {
1963	{ F2FS_COMPR_FL,	FS_COMPR_FL },
1964	{ F2FS_SYNC_FL,		FS_SYNC_FL },
1965	{ F2FS_IMMUTABLE_FL,	FS_IMMUTABLE_FL },
1966	{ F2FS_APPEND_FL,	FS_APPEND_FL },
1967	{ F2FS_NODUMP_FL,	FS_NODUMP_FL },
1968	{ F2FS_NOATIME_FL,	FS_NOATIME_FL },
1969	{ F2FS_NOCOMP_FL,	FS_NOCOMP_FL },
1970	{ F2FS_INDEX_FL,	FS_INDEX_FL },
1971	{ F2FS_DIRSYNC_FL,	FS_DIRSYNC_FL },
1972	{ F2FS_PROJINHERIT_FL,	FS_PROJINHERIT_FL },
1973	{ F2FS_CASEFOLD_FL,	FS_CASEFOLD_FL },
1974};
1975
1976#define F2FS_GETTABLE_FS_FL (		\
1977		FS_COMPR_FL |		\
1978		FS_SYNC_FL |		\
1979		FS_IMMUTABLE_FL |	\
1980		FS_APPEND_FL |		\
1981		FS_NODUMP_FL |		\
1982		FS_NOATIME_FL |		\
1983		FS_NOCOMP_FL |		\
1984		FS_INDEX_FL |		\
1985		FS_DIRSYNC_FL |		\
1986		FS_PROJINHERIT_FL |	\
1987		FS_ENCRYPT_FL |		\
1988		FS_INLINE_DATA_FL |	\
1989		FS_NOCOW_FL |		\
1990		FS_VERITY_FL |		\
1991		FS_CASEFOLD_FL)
1992
1993#define F2FS_SETTABLE_FS_FL (		\
1994		FS_COMPR_FL |		\
1995		FS_SYNC_FL |		\
1996		FS_IMMUTABLE_FL |	\
1997		FS_APPEND_FL |		\
1998		FS_NODUMP_FL |		\
1999		FS_NOATIME_FL |		\
2000		FS_NOCOMP_FL |		\
2001		FS_DIRSYNC_FL |		\
2002		FS_PROJINHERIT_FL |	\
2003		FS_CASEFOLD_FL)
2004
2005/* Convert f2fs on-disk i_flags to FS_IOC_{GET,SET}FLAGS flags */
2006static inline u32 f2fs_iflags_to_fsflags(u32 iflags)
2007{
2008	u32 fsflags = 0;
2009	int i;
2010
2011	for (i = 0; i < ARRAY_SIZE(f2fs_fsflags_map); i++)
2012		if (iflags & f2fs_fsflags_map[i].iflag)
2013			fsflags |= f2fs_fsflags_map[i].fsflag;
2014
2015	return fsflags;
2016}
2017
2018/* Convert FS_IOC_{GET,SET}FLAGS flags to f2fs on-disk i_flags */
2019static inline u32 f2fs_fsflags_to_iflags(u32 fsflags)
2020{
2021	u32 iflags = 0;
2022	int i;
2023
2024	for (i = 0; i < ARRAY_SIZE(f2fs_fsflags_map); i++)
2025		if (fsflags & f2fs_fsflags_map[i].fsflag)
2026			iflags |= f2fs_fsflags_map[i].iflag;
2027
2028	return iflags;
2029}
2030
2031static int f2fs_ioc_getversion(struct file *filp, unsigned long arg)
2032{
2033	struct inode *inode = file_inode(filp);
2034
2035	return put_user(inode->i_generation, (int __user *)arg);
2036}
2037
2038static int f2fs_ioc_start_atomic_write(struct file *filp, bool truncate)
2039{
2040	struct inode *inode = file_inode(filp);
2041	struct user_namespace *mnt_userns = file_mnt_user_ns(filp);
2042	struct f2fs_inode_info *fi = F2FS_I(inode);
2043	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2044	struct inode *pinode;
2045	loff_t isize;
2046	int ret;
2047
2048	if (!inode_owner_or_capable(mnt_userns, inode))
2049		return -EACCES;
2050
2051	if (!S_ISREG(inode->i_mode))
2052		return -EINVAL;
2053
2054	if (filp->f_flags & O_DIRECT)
2055		return -EINVAL;
2056
2057	ret = mnt_want_write_file(filp);
2058	if (ret)
2059		return ret;
2060
2061	inode_lock(inode);
2062
2063	if (!f2fs_disable_compressed_file(inode)) {
2064		ret = -EINVAL;
2065		goto out;
2066	}
2067
2068	if (f2fs_is_atomic_file(inode))
2069		goto out;
2070
2071	ret = f2fs_convert_inline_inode(inode);
2072	if (ret)
2073		goto out;
2074
2075	f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
2076
2077	/*
2078	 * Should wait end_io to count F2FS_WB_CP_DATA correctly by
2079	 * f2fs_is_atomic_file.
2080	 */
2081	if (get_dirty_pages(inode))
2082		f2fs_warn(sbi, "Unexpected flush for atomic writes: ino=%lu, npages=%u",
2083			  inode->i_ino, get_dirty_pages(inode));
2084	ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
2085	if (ret) {
2086		f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2087		goto out;
2088	}
2089
2090	/* Create a COW inode for atomic write */
2091	pinode = f2fs_iget(inode->i_sb, fi->i_pino);
2092	if (IS_ERR(pinode)) {
2093		f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2094		ret = PTR_ERR(pinode);
2095		goto out;
2096	}
2097
2098	ret = f2fs_get_tmpfile(mnt_userns, pinode, &fi->cow_inode);
2099	iput(pinode);
2100	if (ret) {
2101		f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2102		goto out;
2103	}
2104
2105	f2fs_write_inode(inode, NULL);
2106
2107	stat_inc_atomic_inode(inode);
2108
2109	set_inode_flag(inode, FI_ATOMIC_FILE);
2110	set_inode_flag(fi->cow_inode, FI_COW_FILE);
2111	clear_inode_flag(fi->cow_inode, FI_INLINE_DATA);
2112
2113	isize = i_size_read(inode);
2114	fi->original_i_size = isize;
2115	if (truncate) {
2116		set_inode_flag(inode, FI_ATOMIC_REPLACE);
2117		truncate_inode_pages_final(inode->i_mapping);
2118		f2fs_i_size_write(inode, 0);
2119		isize = 0;
2120	}
2121	f2fs_i_size_write(fi->cow_inode, isize);
2122
2123	f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
2124
2125	f2fs_update_time(sbi, REQ_TIME);
2126	fi->atomic_write_task = current;
2127	stat_update_max_atomic_write(inode);
2128	fi->atomic_write_cnt = 0;
2129out:
2130	inode_unlock(inode);
2131	mnt_drop_write_file(filp);
2132	return ret;
2133}
2134
2135static int f2fs_ioc_commit_atomic_write(struct file *filp)
2136{
2137	struct inode *inode = file_inode(filp);
2138	struct user_namespace *mnt_userns = file_mnt_user_ns(filp);
2139	int ret;
2140
2141	if (!inode_owner_or_capable(mnt_userns, inode))
2142		return -EACCES;
2143
2144	ret = mnt_want_write_file(filp);
2145	if (ret)
2146		return ret;
2147
2148	f2fs_balance_fs(F2FS_I_SB(inode), true);
2149
2150	inode_lock(inode);
2151
2152	if (f2fs_is_atomic_file(inode)) {
2153		ret = f2fs_commit_atomic_write(inode);
2154		if (!ret)
2155			ret = f2fs_do_sync_file(filp, 0, LLONG_MAX, 0, true);
2156
2157		f2fs_abort_atomic_write(inode, ret);
2158	} else {
2159		ret = f2fs_do_sync_file(filp, 0, LLONG_MAX, 1, false);
2160	}
2161
2162	inode_unlock(inode);
2163	mnt_drop_write_file(filp);
2164	return ret;
2165}
2166
2167static int f2fs_ioc_abort_atomic_write(struct file *filp)
2168{
2169	struct inode *inode = file_inode(filp);
2170	struct user_namespace *mnt_userns = file_mnt_user_ns(filp);
2171	int ret;
2172
2173	if (!inode_owner_or_capable(mnt_userns, inode))
2174		return -EACCES;
2175
2176	ret = mnt_want_write_file(filp);
2177	if (ret)
2178		return ret;
2179
2180	inode_lock(inode);
2181
2182	f2fs_abort_atomic_write(inode, true);
2183
2184	inode_unlock(inode);
2185
2186	mnt_drop_write_file(filp);
2187	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2188	return ret;
2189}
2190
2191static int f2fs_ioc_shutdown(struct file *filp, unsigned long arg)
2192{
2193	struct inode *inode = file_inode(filp);
2194	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2195	struct super_block *sb = sbi->sb;
2196	__u32 in;
2197	int ret = 0;
2198
2199	if (!capable(CAP_SYS_ADMIN))
2200		return -EPERM;
2201
2202	if (get_user(in, (__u32 __user *)arg))
2203		return -EFAULT;
2204
2205	if (in != F2FS_GOING_DOWN_FULLSYNC) {
2206		ret = mnt_want_write_file(filp);
2207		if (ret) {
2208			if (ret == -EROFS) {
2209				ret = 0;
2210				f2fs_stop_checkpoint(sbi, false,
2211						STOP_CP_REASON_SHUTDOWN);
2212				set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
2213				trace_f2fs_shutdown(sbi, in, ret);
2214			}
2215			return ret;
2216		}
2217	}
2218
2219	switch (in) {
2220	case F2FS_GOING_DOWN_FULLSYNC:
2221		ret = freeze_bdev(sb->s_bdev);
2222		if (ret)
2223			goto out;
2224		f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2225		set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
2226		thaw_bdev(sb->s_bdev);
2227		break;
2228	case F2FS_GOING_DOWN_METASYNC:
2229		/* do checkpoint only */
2230		ret = f2fs_sync_fs(sb, 1);
2231		if (ret)
2232			goto out;
2233		f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2234		set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
2235		break;
2236	case F2FS_GOING_DOWN_NOSYNC:
2237		f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2238		set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
2239		break;
2240	case F2FS_GOING_DOWN_METAFLUSH:
2241		f2fs_sync_meta_pages(sbi, META, LONG_MAX, FS_META_IO);
2242		f2fs_stop_checkpoint(sbi, false, STOP_CP_REASON_SHUTDOWN);
2243		set_sbi_flag(sbi, SBI_IS_SHUTDOWN);
2244		break;
2245	case F2FS_GOING_DOWN_NEED_FSCK:
2246		set_sbi_flag(sbi, SBI_NEED_FSCK);
2247		set_sbi_flag(sbi, SBI_CP_DISABLED_QUICK);
2248		set_sbi_flag(sbi, SBI_IS_DIRTY);
2249		/* do checkpoint only */
2250		ret = f2fs_sync_fs(sb, 1);
2251		goto out;
2252	default:
2253		ret = -EINVAL;
2254		goto out;
2255	}
2256
2257	f2fs_stop_gc_thread(sbi);
2258	f2fs_stop_discard_thread(sbi);
2259
2260	f2fs_drop_discard_cmd(sbi);
2261	clear_opt(sbi, DISCARD);
2262
2263	f2fs_update_time(sbi, REQ_TIME);
2264out:
2265	if (in != F2FS_GOING_DOWN_FULLSYNC)
2266		mnt_drop_write_file(filp);
2267
2268	trace_f2fs_shutdown(sbi, in, ret);
2269
2270	return ret;
2271}
2272
2273static int f2fs_ioc_fitrim(struct file *filp, unsigned long arg)
2274{
2275	struct inode *inode = file_inode(filp);
2276	struct super_block *sb = inode->i_sb;
2277	struct fstrim_range range;
2278	int ret;
2279
2280	if (!capable(CAP_SYS_ADMIN))
2281		return -EPERM;
2282
2283	if (!f2fs_hw_support_discard(F2FS_SB(sb)))
2284		return -EOPNOTSUPP;
2285
2286	if (copy_from_user(&range, (struct fstrim_range __user *)arg,
2287				sizeof(range)))
2288		return -EFAULT;
2289
2290	ret = mnt_want_write_file(filp);
2291	if (ret)
2292		return ret;
2293
2294	range.minlen = max((unsigned int)range.minlen,
2295			   bdev_discard_granularity(sb->s_bdev));
2296	ret = f2fs_trim_fs(F2FS_SB(sb), &range);
2297	mnt_drop_write_file(filp);
2298	if (ret < 0)
2299		return ret;
2300
2301	if (copy_to_user((struct fstrim_range __user *)arg, &range,
2302				sizeof(range)))
2303		return -EFAULT;
2304	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2305	return 0;
2306}
2307
2308static bool uuid_is_nonzero(__u8 u[16])
2309{
2310	int i;
2311
2312	for (i = 0; i < 16; i++)
2313		if (u[i])
2314			return true;
2315	return false;
2316}
2317
2318static int f2fs_ioc_set_encryption_policy(struct file *filp, unsigned long arg)
2319{
2320	struct inode *inode = file_inode(filp);
2321
2322	if (!f2fs_sb_has_encrypt(F2FS_I_SB(inode)))
2323		return -EOPNOTSUPP;
2324
2325	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
2326
2327	return fscrypt_ioctl_set_policy(filp, (const void __user *)arg);
2328}
2329
2330static int f2fs_ioc_get_encryption_policy(struct file *filp, unsigned long arg)
2331{
2332	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2333		return -EOPNOTSUPP;
2334	return fscrypt_ioctl_get_policy(filp, (void __user *)arg);
2335}
2336
2337static int f2fs_ioc_get_encryption_pwsalt(struct file *filp, unsigned long arg)
2338{
2339	struct inode *inode = file_inode(filp);
2340	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2341	int err;
2342
2343	if (!f2fs_sb_has_encrypt(sbi))
2344		return -EOPNOTSUPP;
2345
2346	err = mnt_want_write_file(filp);
2347	if (err)
2348		return err;
2349
2350	f2fs_down_write(&sbi->sb_lock);
2351
2352	if (uuid_is_nonzero(sbi->raw_super->encrypt_pw_salt))
2353		goto got_it;
2354
2355	/* update superblock with uuid */
2356	generate_random_uuid(sbi->raw_super->encrypt_pw_salt);
2357
2358	err = f2fs_commit_super(sbi, false);
2359	if (err) {
2360		/* undo new data */
2361		memset(sbi->raw_super->encrypt_pw_salt, 0, 16);
2362		goto out_err;
2363	}
2364got_it:
2365	if (copy_to_user((__u8 __user *)arg, sbi->raw_super->encrypt_pw_salt,
2366									16))
2367		err = -EFAULT;
2368out_err:
2369	f2fs_up_write(&sbi->sb_lock);
2370	mnt_drop_write_file(filp);
2371	return err;
2372}
2373
2374static int f2fs_ioc_get_encryption_policy_ex(struct file *filp,
2375					     unsigned long arg)
2376{
2377	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2378		return -EOPNOTSUPP;
2379
2380	return fscrypt_ioctl_get_policy_ex(filp, (void __user *)arg);
2381}
2382
2383static int f2fs_ioc_add_encryption_key(struct file *filp, unsigned long arg)
2384{
2385	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2386		return -EOPNOTSUPP;
2387
2388	return fscrypt_ioctl_add_key(filp, (void __user *)arg);
2389}
2390
2391static int f2fs_ioc_remove_encryption_key(struct file *filp, unsigned long arg)
2392{
2393	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2394		return -EOPNOTSUPP;
2395
2396	return fscrypt_ioctl_remove_key(filp, (void __user *)arg);
2397}
2398
2399static int f2fs_ioc_remove_encryption_key_all_users(struct file *filp,
2400						    unsigned long arg)
2401{
2402	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2403		return -EOPNOTSUPP;
2404
2405	return fscrypt_ioctl_remove_key_all_users(filp, (void __user *)arg);
2406}
2407
2408static int f2fs_ioc_get_encryption_key_status(struct file *filp,
2409					      unsigned long arg)
2410{
2411	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2412		return -EOPNOTSUPP;
2413
2414	return fscrypt_ioctl_get_key_status(filp, (void __user *)arg);
2415}
2416
2417static int f2fs_ioc_get_encryption_nonce(struct file *filp, unsigned long arg)
2418{
2419	if (!f2fs_sb_has_encrypt(F2FS_I_SB(file_inode(filp))))
2420		return -EOPNOTSUPP;
2421
2422	return fscrypt_ioctl_get_nonce(filp, (void __user *)arg);
2423}
2424
2425static int f2fs_ioc_gc(struct file *filp, unsigned long arg)
2426{
2427	struct inode *inode = file_inode(filp);
2428	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2429	struct f2fs_gc_control gc_control = { .victim_segno = NULL_SEGNO,
2430			.no_bg_gc = false,
2431			.should_migrate_blocks = false,
2432			.nr_free_secs = 0 };
2433	__u32 sync;
2434	int ret;
2435
2436	if (!capable(CAP_SYS_ADMIN))
2437		return -EPERM;
2438
2439	if (get_user(sync, (__u32 __user *)arg))
2440		return -EFAULT;
2441
2442	if (f2fs_readonly(sbi->sb))
2443		return -EROFS;
2444
2445	ret = mnt_want_write_file(filp);
2446	if (ret)
2447		return ret;
2448
2449	if (!sync) {
2450		if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2451			ret = -EBUSY;
2452			goto out;
2453		}
2454	} else {
2455		f2fs_down_write(&sbi->gc_lock);
2456	}
2457
2458	gc_control.init_gc_type = sync ? FG_GC : BG_GC;
2459	gc_control.err_gc_skipped = sync;
2460	ret = f2fs_gc(sbi, &gc_control);
2461out:
2462	mnt_drop_write_file(filp);
2463	return ret;
2464}
2465
2466static int __f2fs_ioc_gc_range(struct file *filp, struct f2fs_gc_range *range)
2467{
2468	struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(filp));
2469	struct f2fs_gc_control gc_control = {
2470			.init_gc_type = range->sync ? FG_GC : BG_GC,
2471			.no_bg_gc = false,
2472			.should_migrate_blocks = false,
2473			.err_gc_skipped = range->sync,
2474			.nr_free_secs = 0 };
2475	u64 end;
2476	int ret;
2477
2478	if (!capable(CAP_SYS_ADMIN))
2479		return -EPERM;
2480	if (f2fs_readonly(sbi->sb))
2481		return -EROFS;
2482
2483	end = range->start + range->len;
2484	if (end < range->start || range->start < MAIN_BLKADDR(sbi) ||
2485					end >= MAX_BLKADDR(sbi))
2486		return -EINVAL;
2487
2488	ret = mnt_want_write_file(filp);
2489	if (ret)
2490		return ret;
2491
2492do_more:
2493	if (!range->sync) {
2494		if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2495			ret = -EBUSY;
2496			goto out;
2497		}
2498	} else {
2499		f2fs_down_write(&sbi->gc_lock);
2500	}
2501
2502	gc_control.victim_segno = GET_SEGNO(sbi, range->start);
2503	ret = f2fs_gc(sbi, &gc_control);
2504	if (ret) {
2505		if (ret == -EBUSY)
2506			ret = -EAGAIN;
2507		goto out;
2508	}
2509	range->start += CAP_BLKS_PER_SEC(sbi);
2510	if (range->start <= end)
2511		goto do_more;
2512out:
2513	mnt_drop_write_file(filp);
2514	return ret;
2515}
2516
2517static int f2fs_ioc_gc_range(struct file *filp, unsigned long arg)
2518{
2519	struct f2fs_gc_range range;
2520
2521	if (copy_from_user(&range, (struct f2fs_gc_range __user *)arg,
2522							sizeof(range)))
2523		return -EFAULT;
2524	return __f2fs_ioc_gc_range(filp, &range);
2525}
2526
2527static int f2fs_ioc_write_checkpoint(struct file *filp, unsigned long arg)
2528{
2529	struct inode *inode = file_inode(filp);
2530	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2531	int ret;
2532
2533	if (!capable(CAP_SYS_ADMIN))
2534		return -EPERM;
2535
2536	if (f2fs_readonly(sbi->sb))
2537		return -EROFS;
2538
2539	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED))) {
2540		f2fs_info(sbi, "Skipping Checkpoint. Checkpoints currently disabled.");
2541		return -EINVAL;
2542	}
2543
2544	ret = mnt_want_write_file(filp);
2545	if (ret)
2546		return ret;
2547
2548	ret = f2fs_sync_fs(sbi->sb, 1);
2549
2550	mnt_drop_write_file(filp);
2551	return ret;
2552}
2553
2554static int f2fs_defragment_range(struct f2fs_sb_info *sbi,
2555					struct file *filp,
2556					struct f2fs_defragment *range)
2557{
2558	struct inode *inode = file_inode(filp);
2559	struct f2fs_map_blocks map = { .m_next_extent = NULL,
2560					.m_seg_type = NO_CHECK_TYPE,
2561					.m_may_create = false };
2562	struct extent_info ei = {};
2563	pgoff_t pg_start, pg_end, next_pgofs;
2564	unsigned int blk_per_seg = sbi->blocks_per_seg;
2565	unsigned int total = 0, sec_num;
2566	block_t blk_end = 0;
2567	bool fragmented = false;
2568	int err;
2569
2570	pg_start = range->start >> PAGE_SHIFT;
2571	pg_end = (range->start + range->len) >> PAGE_SHIFT;
2572
2573	f2fs_balance_fs(sbi, true);
2574
2575	inode_lock(inode);
2576
2577	/* if in-place-update policy is enabled, don't waste time here */
2578	set_inode_flag(inode, FI_OPU_WRITE);
2579	if (f2fs_should_update_inplace(inode, NULL)) {
2580		err = -EINVAL;
2581		goto out;
2582	}
2583
2584	/* writeback all dirty pages in the range */
2585	err = filemap_write_and_wait_range(inode->i_mapping, range->start,
2586						range->start + range->len - 1);
2587	if (err)
2588		goto out;
2589
2590	/*
2591	 * lookup mapping info in extent cache, skip defragmenting if physical
2592	 * block addresses are continuous.
2593	 */
2594	if (f2fs_lookup_read_extent_cache(inode, pg_start, &ei)) {
2595		if (ei.fofs + ei.len >= pg_end)
2596			goto out;
2597	}
2598
2599	map.m_lblk = pg_start;
2600	map.m_next_pgofs = &next_pgofs;
2601
2602	/*
2603	 * lookup mapping info in dnode page cache, skip defragmenting if all
2604	 * physical block addresses are continuous even if there are hole(s)
2605	 * in logical blocks.
2606	 */
2607	while (map.m_lblk < pg_end) {
2608		map.m_len = pg_end - map.m_lblk;
2609		err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_DEFAULT);
2610		if (err)
2611			goto out;
2612
2613		if (!(map.m_flags & F2FS_MAP_FLAGS)) {
2614			map.m_lblk = next_pgofs;
2615			continue;
2616		}
2617
2618		if (blk_end && blk_end != map.m_pblk)
2619			fragmented = true;
2620
2621		/* record total count of block that we're going to move */
2622		total += map.m_len;
2623
2624		blk_end = map.m_pblk + map.m_len;
2625
2626		map.m_lblk += map.m_len;
2627	}
2628
2629	if (!fragmented) {
2630		total = 0;
2631		goto out;
2632	}
2633
2634	sec_num = DIV_ROUND_UP(total, CAP_BLKS_PER_SEC(sbi));
2635
2636	/*
2637	 * make sure there are enough free section for LFS allocation, this can
2638	 * avoid defragment running in SSR mode when free section are allocated
2639	 * intensively
2640	 */
2641	if (has_not_enough_free_secs(sbi, 0, sec_num)) {
2642		err = -EAGAIN;
2643		goto out;
2644	}
2645
2646	map.m_lblk = pg_start;
2647	map.m_len = pg_end - pg_start;
2648	total = 0;
2649
2650	while (map.m_lblk < pg_end) {
2651		pgoff_t idx;
2652		int cnt = 0;
2653
2654do_map:
2655		map.m_len = pg_end - map.m_lblk;
2656		err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_DEFAULT);
2657		if (err)
2658			goto clear_out;
2659
2660		if (!(map.m_flags & F2FS_MAP_FLAGS)) {
2661			map.m_lblk = next_pgofs;
2662			goto check;
2663		}
2664
2665		set_inode_flag(inode, FI_SKIP_WRITES);
2666
2667		idx = map.m_lblk;
2668		while (idx < map.m_lblk + map.m_len && cnt < blk_per_seg) {
2669			struct page *page;
2670
2671			page = f2fs_get_lock_data_page(inode, idx, true);
2672			if (IS_ERR(page)) {
2673				err = PTR_ERR(page);
2674				goto clear_out;
2675			}
2676
2677			set_page_dirty(page);
2678			set_page_private_gcing(page);
2679			f2fs_put_page(page, 1);
2680
2681			idx++;
2682			cnt++;
2683			total++;
2684		}
2685
2686		map.m_lblk = idx;
2687check:
2688		if (map.m_lblk < pg_end && cnt < blk_per_seg)
2689			goto do_map;
2690
2691		clear_inode_flag(inode, FI_SKIP_WRITES);
2692
2693		err = filemap_fdatawrite(inode->i_mapping);
2694		if (err)
2695			goto out;
2696	}
2697clear_out:
2698	clear_inode_flag(inode, FI_SKIP_WRITES);
2699out:
2700	clear_inode_flag(inode, FI_OPU_WRITE);
2701	inode_unlock(inode);
2702	if (!err)
2703		range->len = (u64)total << PAGE_SHIFT;
2704	return err;
2705}
2706
2707static int f2fs_ioc_defragment(struct file *filp, unsigned long arg)
2708{
2709	struct inode *inode = file_inode(filp);
2710	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2711	struct f2fs_defragment range;
2712	int err;
2713
2714	if (!capable(CAP_SYS_ADMIN))
2715		return -EPERM;
2716
2717	if (!S_ISREG(inode->i_mode) || f2fs_is_atomic_file(inode))
2718		return -EINVAL;
2719
2720	if (f2fs_readonly(sbi->sb))
2721		return -EROFS;
2722
2723	if (copy_from_user(&range, (struct f2fs_defragment __user *)arg,
2724							sizeof(range)))
2725		return -EFAULT;
2726
2727	/* verify alignment of offset & size */
2728	if (range.start & (F2FS_BLKSIZE - 1) || range.len & (F2FS_BLKSIZE - 1))
2729		return -EINVAL;
2730
2731	if (unlikely((range.start + range.len) >> PAGE_SHIFT >
2732					max_file_blocks(inode)))
2733		return -EINVAL;
2734
2735	err = mnt_want_write_file(filp);
2736	if (err)
2737		return err;
2738
2739	err = f2fs_defragment_range(sbi, filp, &range);
2740	mnt_drop_write_file(filp);
2741
2742	f2fs_update_time(sbi, REQ_TIME);
2743	if (err < 0)
2744		return err;
2745
2746	if (copy_to_user((struct f2fs_defragment __user *)arg, &range,
2747							sizeof(range)))
2748		return -EFAULT;
2749
2750	return 0;
2751}
2752
2753static int f2fs_move_file_range(struct file *file_in, loff_t pos_in,
2754			struct file *file_out, loff_t pos_out, size_t len)
2755{
2756	struct inode *src = file_inode(file_in);
2757	struct inode *dst = file_inode(file_out);
2758	struct f2fs_sb_info *sbi = F2FS_I_SB(src);
2759	size_t olen = len, dst_max_i_size = 0;
2760	size_t dst_osize;
2761	int ret;
2762
2763	if (file_in->f_path.mnt != file_out->f_path.mnt ||
2764				src->i_sb != dst->i_sb)
2765		return -EXDEV;
2766
2767	if (unlikely(f2fs_readonly(src->i_sb)))
2768		return -EROFS;
2769
2770	if (!S_ISREG(src->i_mode) || !S_ISREG(dst->i_mode))
2771		return -EINVAL;
2772
2773	if (IS_ENCRYPTED(src) || IS_ENCRYPTED(dst))
2774		return -EOPNOTSUPP;
2775
2776	if (pos_out < 0 || pos_in < 0)
2777		return -EINVAL;
2778
2779	if (src == dst) {
2780		if (pos_in == pos_out)
2781			return 0;
2782		if (pos_out > pos_in && pos_out < pos_in + len)
2783			return -EINVAL;
2784	}
2785
2786	inode_lock(src);
2787	if (src != dst) {
2788		ret = -EBUSY;
2789		if (!inode_trylock(dst))
2790			goto out;
2791	}
2792
2793	ret = -EINVAL;
2794	if (pos_in + len > src->i_size || pos_in + len < pos_in)
2795		goto out_unlock;
2796	if (len == 0)
2797		olen = len = src->i_size - pos_in;
2798	if (pos_in + len == src->i_size)
2799		len = ALIGN(src->i_size, F2FS_BLKSIZE) - pos_in;
2800	if (len == 0) {
2801		ret = 0;
2802		goto out_unlock;
2803	}
2804
2805	dst_osize = dst->i_size;
2806	if (pos_out + olen > dst->i_size)
2807		dst_max_i_size = pos_out + olen;
2808
2809	/* verify the end result is block aligned */
2810	if (!IS_ALIGNED(pos_in, F2FS_BLKSIZE) ||
2811			!IS_ALIGNED(pos_in + len, F2FS_BLKSIZE) ||
2812			!IS_ALIGNED(pos_out, F2FS_BLKSIZE))
2813		goto out_unlock;
2814
2815	ret = f2fs_convert_inline_inode(src);
2816	if (ret)
2817		goto out_unlock;
2818
2819	ret = f2fs_convert_inline_inode(dst);
2820	if (ret)
2821		goto out_unlock;
2822
2823	/* write out all dirty pages from offset */
2824	ret = filemap_write_and_wait_range(src->i_mapping,
2825					pos_in, pos_in + len);
2826	if (ret)
2827		goto out_unlock;
2828
2829	ret = filemap_write_and_wait_range(dst->i_mapping,
2830					pos_out, pos_out + len);
2831	if (ret)
2832		goto out_unlock;
2833
2834	f2fs_balance_fs(sbi, true);
2835
2836	f2fs_down_write(&F2FS_I(src)->i_gc_rwsem[WRITE]);
2837	if (src != dst) {
2838		ret = -EBUSY;
2839		if (!f2fs_down_write_trylock(&F2FS_I(dst)->i_gc_rwsem[WRITE]))
2840			goto out_src;
2841	}
2842
2843	f2fs_lock_op(sbi);
2844	ret = __exchange_data_block(src, dst, pos_in >> F2FS_BLKSIZE_BITS,
2845				pos_out >> F2FS_BLKSIZE_BITS,
2846				len >> F2FS_BLKSIZE_BITS, false);
2847
2848	if (!ret) {
2849		if (dst_max_i_size)
2850			f2fs_i_size_write(dst, dst_max_i_size);
2851		else if (dst_osize != dst->i_size)
2852			f2fs_i_size_write(dst, dst_osize);
2853	}
2854	f2fs_unlock_op(sbi);
2855
2856	if (src != dst)
2857		f2fs_up_write(&F2FS_I(dst)->i_gc_rwsem[WRITE]);
2858out_src:
2859	f2fs_up_write(&F2FS_I(src)->i_gc_rwsem[WRITE]);
2860out_unlock:
2861	if (src != dst)
2862		inode_unlock(dst);
2863out:
2864	inode_unlock(src);
2865	return ret;
2866}
2867
2868static int __f2fs_ioc_move_range(struct file *filp,
2869				struct f2fs_move_range *range)
2870{
2871	struct fd dst;
2872	int err;
2873
2874	if (!(filp->f_mode & FMODE_READ) ||
2875			!(filp->f_mode & FMODE_WRITE))
2876		return -EBADF;
2877
2878	dst = fdget(range->dst_fd);
2879	if (!dst.file)
2880		return -EBADF;
2881
2882	if (!(dst.file->f_mode & FMODE_WRITE)) {
2883		err = -EBADF;
2884		goto err_out;
2885	}
2886
2887	err = mnt_want_write_file(filp);
2888	if (err)
2889		goto err_out;
2890
2891	err = f2fs_move_file_range(filp, range->pos_in, dst.file,
2892					range->pos_out, range->len);
2893
2894	mnt_drop_write_file(filp);
2895err_out:
2896	fdput(dst);
2897	return err;
2898}
2899
2900static int f2fs_ioc_move_range(struct file *filp, unsigned long arg)
2901{
2902	struct f2fs_move_range range;
2903
2904	if (copy_from_user(&range, (struct f2fs_move_range __user *)arg,
2905							sizeof(range)))
2906		return -EFAULT;
2907	return __f2fs_ioc_move_range(filp, &range);
2908}
2909
2910static int f2fs_ioc_flush_device(struct file *filp, unsigned long arg)
2911{
2912	struct inode *inode = file_inode(filp);
2913	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2914	struct sit_info *sm = SIT_I(sbi);
2915	unsigned int start_segno = 0, end_segno = 0;
2916	unsigned int dev_start_segno = 0, dev_end_segno = 0;
2917	struct f2fs_flush_device range;
2918	struct f2fs_gc_control gc_control = {
2919			.init_gc_type = FG_GC,
2920			.should_migrate_blocks = true,
2921			.err_gc_skipped = true,
2922			.nr_free_secs = 0 };
2923	int ret;
2924
2925	if (!capable(CAP_SYS_ADMIN))
2926		return -EPERM;
2927
2928	if (f2fs_readonly(sbi->sb))
2929		return -EROFS;
2930
2931	if (unlikely(is_sbi_flag_set(sbi, SBI_CP_DISABLED)))
2932		return -EINVAL;
2933
2934	if (copy_from_user(&range, (struct f2fs_flush_device __user *)arg,
2935							sizeof(range)))
2936		return -EFAULT;
2937
2938	if (!f2fs_is_multi_device(sbi) || sbi->s_ndevs - 1 <= range.dev_num ||
2939			__is_large_section(sbi)) {
2940		f2fs_warn(sbi, "Can't flush %u in %d for segs_per_sec %u != 1",
2941			  range.dev_num, sbi->s_ndevs, sbi->segs_per_sec);
2942		return -EINVAL;
2943	}
2944
2945	ret = mnt_want_write_file(filp);
2946	if (ret)
2947		return ret;
2948
2949	if (range.dev_num != 0)
2950		dev_start_segno = GET_SEGNO(sbi, FDEV(range.dev_num).start_blk);
2951	dev_end_segno = GET_SEGNO(sbi, FDEV(range.dev_num).end_blk);
2952
2953	start_segno = sm->last_victim[FLUSH_DEVICE];
2954	if (start_segno < dev_start_segno || start_segno >= dev_end_segno)
2955		start_segno = dev_start_segno;
2956	end_segno = min(start_segno + range.segments, dev_end_segno);
2957
2958	while (start_segno < end_segno) {
2959		if (!f2fs_down_write_trylock(&sbi->gc_lock)) {
2960			ret = -EBUSY;
2961			goto out;
2962		}
2963		sm->last_victim[GC_CB] = end_segno + 1;
2964		sm->last_victim[GC_GREEDY] = end_segno + 1;
2965		sm->last_victim[ALLOC_NEXT] = end_segno + 1;
2966
2967		gc_control.victim_segno = start_segno;
2968		ret = f2fs_gc(sbi, &gc_control);
2969		if (ret == -EAGAIN)
2970			ret = 0;
2971		else if (ret < 0)
2972			break;
2973		start_segno++;
2974	}
2975out:
2976	mnt_drop_write_file(filp);
2977	return ret;
2978}
2979
2980static int f2fs_ioc_get_features(struct file *filp, unsigned long arg)
2981{
2982	struct inode *inode = file_inode(filp);
2983	u32 sb_feature = le32_to_cpu(F2FS_I_SB(inode)->raw_super->feature);
2984
2985	/* Must validate to set it with SQLite behavior in Android. */
2986	sb_feature |= F2FS_FEATURE_ATOMIC_WRITE;
2987
2988	return put_user(sb_feature, (u32 __user *)arg);
2989}
2990
2991#ifdef CONFIG_QUOTA
2992int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid)
2993{
2994	struct dquot *transfer_to[MAXQUOTAS] = {};
2995	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
2996	struct super_block *sb = sbi->sb;
2997	int err = 0;
2998
2999	transfer_to[PRJQUOTA] = dqget(sb, make_kqid_projid(kprojid));
3000	if (!IS_ERR(transfer_to[PRJQUOTA])) {
3001		err = __dquot_transfer(inode, transfer_to);
3002		if (err)
3003			set_sbi_flag(sbi, SBI_QUOTA_NEED_REPAIR);
3004		dqput(transfer_to[PRJQUOTA]);
3005	}
3006	return err;
3007}
3008
3009static int f2fs_ioc_setproject(struct inode *inode, __u32 projid)
3010{
3011	struct f2fs_inode_info *fi = F2FS_I(inode);
3012	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3013	struct f2fs_inode *ri = NULL;
3014	kprojid_t kprojid;
3015	int err;
3016
3017	if (!f2fs_sb_has_project_quota(sbi)) {
3018		if (projid != F2FS_DEF_PROJID)
3019			return -EOPNOTSUPP;
3020		else
3021			return 0;
3022	}
3023
3024	if (!f2fs_has_extra_attr(inode))
3025		return -EOPNOTSUPP;
3026
3027	kprojid = make_kprojid(&init_user_ns, (projid_t)projid);
3028
3029	if (projid_eq(kprojid, fi->i_projid))
3030		return 0;
3031
3032	err = -EPERM;
3033	/* Is it quota file? Do not allow user to mess with it */
3034	if (IS_NOQUOTA(inode))
3035		return err;
3036
3037	if (!F2FS_FITS_IN_INODE(ri, fi->i_extra_isize, i_projid))
3038		return -EOVERFLOW;
3039
3040	err = f2fs_dquot_initialize(inode);
3041	if (err)
3042		return err;
3043
3044	f2fs_lock_op(sbi);
3045	err = f2fs_transfer_project_quota(inode, kprojid);
3046	if (err)
3047		goto out_unlock;
3048
3049	fi->i_projid = kprojid;
3050	inode->i_ctime = current_time(inode);
3051	f2fs_mark_inode_dirty_sync(inode, true);
3052out_unlock:
3053	f2fs_unlock_op(sbi);
3054	return err;
3055}
3056#else
3057int f2fs_transfer_project_quota(struct inode *inode, kprojid_t kprojid)
3058{
3059	return 0;
3060}
3061
3062static int f2fs_ioc_setproject(struct inode *inode, __u32 projid)
3063{
3064	if (projid != F2FS_DEF_PROJID)
3065		return -EOPNOTSUPP;
3066	return 0;
3067}
3068#endif
3069
3070int f2fs_fileattr_get(struct dentry *dentry, struct fileattr *fa)
3071{
3072	struct inode *inode = d_inode(dentry);
3073	struct f2fs_inode_info *fi = F2FS_I(inode);
3074	u32 fsflags = f2fs_iflags_to_fsflags(fi->i_flags);
3075
3076	if (IS_ENCRYPTED(inode))
3077		fsflags |= FS_ENCRYPT_FL;
3078	if (IS_VERITY(inode))
3079		fsflags |= FS_VERITY_FL;
3080	if (f2fs_has_inline_data(inode) || f2fs_has_inline_dentry(inode))
3081		fsflags |= FS_INLINE_DATA_FL;
3082	if (is_inode_flag_set(inode, FI_PIN_FILE))
3083		fsflags |= FS_NOCOW_FL;
3084
3085	fileattr_fill_flags(fa, fsflags & F2FS_GETTABLE_FS_FL);
3086
3087	if (f2fs_sb_has_project_quota(F2FS_I_SB(inode)))
3088		fa->fsx_projid = from_kprojid(&init_user_ns, fi->i_projid);
3089
3090	return 0;
3091}
3092
3093int f2fs_fileattr_set(struct user_namespace *mnt_userns,
3094		      struct dentry *dentry, struct fileattr *fa)
3095{
3096	struct inode *inode = d_inode(dentry);
3097	u32 fsflags = fa->flags, mask = F2FS_SETTABLE_FS_FL;
3098	u32 iflags;
3099	int err;
3100
3101	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode))))
3102		return -EIO;
3103	if (!f2fs_is_checkpoint_ready(F2FS_I_SB(inode)))
3104		return -ENOSPC;
3105	if (fsflags & ~F2FS_GETTABLE_FS_FL)
3106		return -EOPNOTSUPP;
3107	fsflags &= F2FS_SETTABLE_FS_FL;
3108	if (!fa->flags_valid)
3109		mask &= FS_COMMON_FL;
3110
3111	iflags = f2fs_fsflags_to_iflags(fsflags);
3112	if (f2fs_mask_flags(inode->i_mode, iflags) != iflags)
3113		return -EOPNOTSUPP;
3114
3115	err = f2fs_setflags_common(inode, iflags, f2fs_fsflags_to_iflags(mask));
3116	if (!err)
3117		err = f2fs_ioc_setproject(inode, fa->fsx_projid);
3118
3119	return err;
3120}
3121
3122int f2fs_pin_file_control(struct inode *inode, bool inc)
3123{
3124	struct f2fs_inode_info *fi = F2FS_I(inode);
3125	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3126
3127	/* Use i_gc_failures for normal file as a risk signal. */
3128	if (inc)
3129		f2fs_i_gc_failures_write(inode,
3130				fi->i_gc_failures[GC_FAILURE_PIN] + 1);
3131
3132	if (fi->i_gc_failures[GC_FAILURE_PIN] > sbi->gc_pin_file_threshold) {
3133		f2fs_warn(sbi, "%s: Enable GC = ino %lx after %x GC trials",
3134			  __func__, inode->i_ino,
3135			  fi->i_gc_failures[GC_FAILURE_PIN]);
3136		clear_inode_flag(inode, FI_PIN_FILE);
3137		return -EAGAIN;
3138	}
3139	return 0;
3140}
3141
3142static int f2fs_ioc_set_pin_file(struct file *filp, unsigned long arg)
3143{
3144	struct inode *inode = file_inode(filp);
3145	__u32 pin;
3146	int ret = 0;
3147
3148	if (get_user(pin, (__u32 __user *)arg))
3149		return -EFAULT;
3150
3151	if (!S_ISREG(inode->i_mode))
3152		return -EINVAL;
3153
3154	if (f2fs_readonly(F2FS_I_SB(inode)->sb))
3155		return -EROFS;
3156
3157	ret = mnt_want_write_file(filp);
3158	if (ret)
3159		return ret;
3160
3161	inode_lock(inode);
3162
3163	if (!pin) {
3164		clear_inode_flag(inode, FI_PIN_FILE);
3165		f2fs_i_gc_failures_write(inode, 0);
3166		goto done;
3167	}
3168
3169	if (f2fs_should_update_outplace(inode, NULL)) {
3170		ret = -EINVAL;
3171		goto out;
3172	}
3173
3174	if (f2fs_pin_file_control(inode, false)) {
3175		ret = -EAGAIN;
3176		goto out;
3177	}
3178
3179	ret = f2fs_convert_inline_inode(inode);
3180	if (ret)
3181		goto out;
3182
3183	if (!f2fs_disable_compressed_file(inode)) {
3184		ret = -EOPNOTSUPP;
3185		goto out;
3186	}
3187
3188	set_inode_flag(inode, FI_PIN_FILE);
3189	ret = F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN];
3190done:
3191	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3192out:
3193	inode_unlock(inode);
3194	mnt_drop_write_file(filp);
3195	return ret;
3196}
3197
3198static int f2fs_ioc_get_pin_file(struct file *filp, unsigned long arg)
3199{
3200	struct inode *inode = file_inode(filp);
3201	__u32 pin = 0;
3202
3203	if (is_inode_flag_set(inode, FI_PIN_FILE))
3204		pin = F2FS_I(inode)->i_gc_failures[GC_FAILURE_PIN];
3205	return put_user(pin, (u32 __user *)arg);
3206}
3207
3208int f2fs_precache_extents(struct inode *inode)
3209{
3210	struct f2fs_inode_info *fi = F2FS_I(inode);
3211	struct f2fs_map_blocks map;
3212	pgoff_t m_next_extent;
3213	loff_t end;
3214	int err;
3215
3216	if (is_inode_flag_set(inode, FI_NO_EXTENT))
3217		return -EOPNOTSUPP;
3218
3219	map.m_lblk = 0;
3220	map.m_next_pgofs = NULL;
3221	map.m_next_extent = &m_next_extent;
3222	map.m_seg_type = NO_CHECK_TYPE;
3223	map.m_may_create = false;
3224	end = max_file_blocks(inode);
3225
3226	while (map.m_lblk < end) {
3227		map.m_len = end - map.m_lblk;
3228
3229		f2fs_down_write(&fi->i_gc_rwsem[WRITE]);
3230		err = f2fs_map_blocks(inode, &map, 0, F2FS_GET_BLOCK_PRECACHE);
3231		f2fs_up_write(&fi->i_gc_rwsem[WRITE]);
3232		if (err)
3233			return err;
3234
3235		map.m_lblk = m_next_extent;
3236	}
3237
3238	return 0;
3239}
3240
3241static int f2fs_ioc_precache_extents(struct file *filp, unsigned long arg)
3242{
3243	return f2fs_precache_extents(file_inode(filp));
3244}
3245
3246static int f2fs_ioc_resize_fs(struct file *filp, unsigned long arg)
3247{
3248	struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(filp));
3249	__u64 block_count;
3250
3251	if (!capable(CAP_SYS_ADMIN))
3252		return -EPERM;
3253
3254	if (f2fs_readonly(sbi->sb))
3255		return -EROFS;
3256
3257	if (copy_from_user(&block_count, (void __user *)arg,
3258			   sizeof(block_count)))
3259		return -EFAULT;
3260
3261	return f2fs_resize_fs(sbi, block_count);
3262}
3263
3264static int f2fs_ioc_enable_verity(struct file *filp, unsigned long arg)
3265{
3266	struct inode *inode = file_inode(filp);
3267
3268	f2fs_update_time(F2FS_I_SB(inode), REQ_TIME);
3269
3270	if (!f2fs_sb_has_verity(F2FS_I_SB(inode))) {
3271		f2fs_warn(F2FS_I_SB(inode),
3272			  "Can't enable fs-verity on inode %lu: the verity feature is not enabled on this filesystem",
3273			  inode->i_ino);
3274		return -EOPNOTSUPP;
3275	}
3276
3277	return fsverity_ioctl_enable(filp, (const void __user *)arg);
3278}
3279
3280static int f2fs_ioc_measure_verity(struct file *filp, unsigned long arg)
3281{
3282	if (!f2fs_sb_has_verity(F2FS_I_SB(file_inode(filp))))
3283		return -EOPNOTSUPP;
3284
3285	return fsverity_ioctl_measure(filp, (void __user *)arg);
3286}
3287
3288static int f2fs_ioc_read_verity_metadata(struct file *filp, unsigned long arg)
3289{
3290	if (!f2fs_sb_has_verity(F2FS_I_SB(file_inode(filp))))
3291		return -EOPNOTSUPP;
3292
3293	return fsverity_ioctl_read_metadata(filp, (const void __user *)arg);
3294}
3295
3296static int f2fs_ioc_getfslabel(struct file *filp, unsigned long arg)
3297{
3298	struct inode *inode = file_inode(filp);
3299	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3300	char *vbuf;
3301	int count;
3302	int err = 0;
3303
3304	vbuf = f2fs_kzalloc(sbi, MAX_VOLUME_NAME, GFP_KERNEL);
3305	if (!vbuf)
3306		return -ENOMEM;
3307
3308	f2fs_down_read(&sbi->sb_lock);
3309	count = utf16s_to_utf8s(sbi->raw_super->volume_name,
3310			ARRAY_SIZE(sbi->raw_super->volume_name),
3311			UTF16_LITTLE_ENDIAN, vbuf, MAX_VOLUME_NAME);
3312	f2fs_up_read(&sbi->sb_lock);
3313
3314	if (copy_to_user((char __user *)arg, vbuf,
3315				min(FSLABEL_MAX, count)))
3316		err = -EFAULT;
3317
3318	kfree(vbuf);
3319	return err;
3320}
3321
3322static int f2fs_ioc_setfslabel(struct file *filp, unsigned long arg)
3323{
3324	struct inode *inode = file_inode(filp);
3325	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3326	char *vbuf;
3327	int err = 0;
3328
3329	if (!capable(CAP_SYS_ADMIN))
3330		return -EPERM;
3331
3332	vbuf = strndup_user((const char __user *)arg, FSLABEL_MAX);
3333	if (IS_ERR(vbuf))
3334		return PTR_ERR(vbuf);
3335
3336	err = mnt_want_write_file(filp);
3337	if (err)
3338		goto out;
3339
3340	f2fs_down_write(&sbi->sb_lock);
3341
3342	memset(sbi->raw_super->volume_name, 0,
3343			sizeof(sbi->raw_super->volume_name));
3344	utf8s_to_utf16s(vbuf, strlen(vbuf), UTF16_LITTLE_ENDIAN,
3345			sbi->raw_super->volume_name,
3346			ARRAY_SIZE(sbi->raw_super->volume_name));
3347
3348	err = f2fs_commit_super(sbi, false);
3349
3350	f2fs_up_write(&sbi->sb_lock);
3351
3352	mnt_drop_write_file(filp);
3353out:
3354	kfree(vbuf);
3355	return err;
3356}
3357
3358static int f2fs_get_compress_blocks(struct file *filp, unsigned long arg)
3359{
3360	struct inode *inode = file_inode(filp);
3361	__u64 blocks;
3362
3363	if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3364		return -EOPNOTSUPP;
3365
3366	if (!f2fs_compressed_file(inode))
3367		return -EINVAL;
3368
3369	blocks = atomic_read(&F2FS_I(inode)->i_compr_blocks);
3370	return put_user(blocks, (u64 __user *)arg);
3371}
3372
3373static int release_compress_blocks(struct dnode_of_data *dn, pgoff_t count)
3374{
3375	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
3376	unsigned int released_blocks = 0;
3377	int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
3378	block_t blkaddr;
3379	int i;
3380
3381	for (i = 0; i < count; i++) {
3382		blkaddr = data_blkaddr(dn->inode, dn->node_page,
3383						dn->ofs_in_node + i);
3384
3385		if (!__is_valid_data_blkaddr(blkaddr))
3386			continue;
3387		if (unlikely(!f2fs_is_valid_blkaddr(sbi, blkaddr,
3388					DATA_GENERIC_ENHANCE))) {
3389			f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
3390			return -EFSCORRUPTED;
3391		}
3392	}
3393
3394	while (count) {
3395		int compr_blocks = 0;
3396
3397		for (i = 0; i < cluster_size; i++, dn->ofs_in_node++) {
3398			blkaddr = f2fs_data_blkaddr(dn);
3399
3400			if (i == 0) {
3401				if (blkaddr == COMPRESS_ADDR)
3402					continue;
3403				dn->ofs_in_node += cluster_size;
3404				goto next;
3405			}
3406
3407			if (__is_valid_data_blkaddr(blkaddr))
3408				compr_blocks++;
3409
3410			if (blkaddr != NEW_ADDR)
3411				continue;
3412
3413			dn->data_blkaddr = NULL_ADDR;
3414			f2fs_set_data_blkaddr(dn);
3415		}
3416
3417		f2fs_i_compr_blocks_update(dn->inode, compr_blocks, false);
3418		dec_valid_block_count(sbi, dn->inode,
3419					cluster_size - compr_blocks);
3420
3421		released_blocks += cluster_size - compr_blocks;
3422next:
3423		count -= cluster_size;
3424	}
3425
3426	return released_blocks;
3427}
3428
3429static int f2fs_release_compress_blocks(struct file *filp, unsigned long arg)
3430{
3431	struct inode *inode = file_inode(filp);
3432	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3433	pgoff_t page_idx = 0, last_idx;
3434	unsigned int released_blocks = 0;
3435	int ret;
3436	int writecount;
3437
3438	if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3439		return -EOPNOTSUPP;
3440
3441	if (!f2fs_compressed_file(inode))
3442		return -EINVAL;
3443
3444	if (f2fs_readonly(sbi->sb))
3445		return -EROFS;
3446
3447	ret = mnt_want_write_file(filp);
3448	if (ret)
3449		return ret;
3450
3451	f2fs_balance_fs(F2FS_I_SB(inode), true);
3452
3453	inode_lock(inode);
3454
3455	writecount = atomic_read(&inode->i_writecount);
3456	if ((filp->f_mode & FMODE_WRITE && writecount != 1) ||
3457			(!(filp->f_mode & FMODE_WRITE) && writecount)) {
3458		ret = -EBUSY;
3459		goto out;
3460	}
3461
3462	if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
3463		ret = -EINVAL;
3464		goto out;
3465	}
3466
3467	ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
3468	if (ret)
3469		goto out;
3470
3471	set_inode_flag(inode, FI_COMPRESS_RELEASED);
3472	inode->i_ctime = current_time(inode);
3473	f2fs_mark_inode_dirty_sync(inode, true);
3474
3475	if (!atomic_read(&F2FS_I(inode)->i_compr_blocks))
3476		goto out;
3477
3478	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3479	filemap_invalidate_lock(inode->i_mapping);
3480
3481	last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3482
3483	while (page_idx < last_idx) {
3484		struct dnode_of_data dn;
3485		pgoff_t end_offset, count;
3486
3487		set_new_dnode(&dn, inode, NULL, NULL, 0);
3488		ret = f2fs_get_dnode_of_data(&dn, page_idx, LOOKUP_NODE);
3489		if (ret) {
3490			if (ret == -ENOENT) {
3491				page_idx = f2fs_get_next_page_offset(&dn,
3492								page_idx);
3493				ret = 0;
3494				continue;
3495			}
3496			break;
3497		}
3498
3499		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3500		count = min(end_offset - dn.ofs_in_node, last_idx - page_idx);
3501		count = round_up(count, F2FS_I(inode)->i_cluster_size);
3502
3503		ret = release_compress_blocks(&dn, count);
3504
3505		f2fs_put_dnode(&dn);
3506
3507		if (ret < 0)
3508			break;
3509
3510		page_idx += count;
3511		released_blocks += ret;
3512	}
3513
3514	filemap_invalidate_unlock(inode->i_mapping);
3515	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3516out:
3517	inode_unlock(inode);
3518
3519	mnt_drop_write_file(filp);
3520
3521	if (ret >= 0) {
3522		ret = put_user(released_blocks, (u64 __user *)arg);
3523	} else if (released_blocks &&
3524			atomic_read(&F2FS_I(inode)->i_compr_blocks)) {
3525		set_sbi_flag(sbi, SBI_NEED_FSCK);
3526		f2fs_warn(sbi, "%s: partial blocks were released i_ino=%lx "
3527			"iblocks=%llu, released=%u, compr_blocks=%u, "
3528			"run fsck to fix.",
3529			__func__, inode->i_ino, inode->i_blocks,
3530			released_blocks,
3531			atomic_read(&F2FS_I(inode)->i_compr_blocks));
3532	}
3533
3534	return ret;
3535}
3536
3537static int reserve_compress_blocks(struct dnode_of_data *dn, pgoff_t count)
3538{
3539	struct f2fs_sb_info *sbi = F2FS_I_SB(dn->inode);
3540	unsigned int reserved_blocks = 0;
3541	int cluster_size = F2FS_I(dn->inode)->i_cluster_size;
3542	block_t blkaddr;
3543	int i;
3544
3545	for (i = 0; i < count; i++) {
3546		blkaddr = data_blkaddr(dn->inode, dn->node_page,
3547						dn->ofs_in_node + i);
3548
3549		if (!__is_valid_data_blkaddr(blkaddr))
3550			continue;
3551		if (unlikely(!f2fs_is_valid_blkaddr(sbi, blkaddr,
3552					DATA_GENERIC_ENHANCE))) {
3553			f2fs_handle_error(sbi, ERROR_INVALID_BLKADDR);
3554			return -EFSCORRUPTED;
3555		}
3556	}
3557
3558	while (count) {
3559		int compr_blocks = 0;
3560		blkcnt_t reserved;
3561		int ret;
3562
3563		for (i = 0; i < cluster_size; i++, dn->ofs_in_node++) {
3564			blkaddr = f2fs_data_blkaddr(dn);
3565
3566			if (i == 0) {
3567				if (blkaddr == COMPRESS_ADDR)
3568					continue;
3569				dn->ofs_in_node += cluster_size;
3570				goto next;
3571			}
3572
3573			if (__is_valid_data_blkaddr(blkaddr)) {
3574				compr_blocks++;
3575				continue;
3576			}
3577
3578			dn->data_blkaddr = NEW_ADDR;
3579			f2fs_set_data_blkaddr(dn);
3580		}
3581
3582		reserved = cluster_size - compr_blocks;
3583		ret = inc_valid_block_count(sbi, dn->inode, &reserved);
3584		if (ret)
3585			return ret;
3586
3587		if (reserved != cluster_size - compr_blocks)
3588			return -ENOSPC;
3589
3590		f2fs_i_compr_blocks_update(dn->inode, compr_blocks, true);
3591
3592		reserved_blocks += reserved;
3593next:
3594		count -= cluster_size;
3595	}
3596
3597	return reserved_blocks;
3598}
3599
3600static int f2fs_reserve_compress_blocks(struct file *filp, unsigned long arg)
3601{
3602	struct inode *inode = file_inode(filp);
3603	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3604	pgoff_t page_idx = 0, last_idx;
3605	unsigned int reserved_blocks = 0;
3606	int ret;
3607
3608	if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3609		return -EOPNOTSUPP;
3610
3611	if (!f2fs_compressed_file(inode))
3612		return -EINVAL;
3613
3614	if (f2fs_readonly(sbi->sb))
3615		return -EROFS;
3616
3617	ret = mnt_want_write_file(filp);
3618	if (ret)
3619		return ret;
3620
3621	if (atomic_read(&F2FS_I(inode)->i_compr_blocks))
3622		goto out;
3623
3624	f2fs_balance_fs(F2FS_I_SB(inode), true);
3625
3626	inode_lock(inode);
3627
3628	if (!is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
3629		ret = -EINVAL;
3630		goto unlock_inode;
3631	}
3632
3633	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3634	filemap_invalidate_lock(inode->i_mapping);
3635
3636	last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3637
3638	while (page_idx < last_idx) {
3639		struct dnode_of_data dn;
3640		pgoff_t end_offset, count;
3641
3642		set_new_dnode(&dn, inode, NULL, NULL, 0);
3643		ret = f2fs_get_dnode_of_data(&dn, page_idx, LOOKUP_NODE);
3644		if (ret) {
3645			if (ret == -ENOENT) {
3646				page_idx = f2fs_get_next_page_offset(&dn,
3647								page_idx);
3648				ret = 0;
3649				continue;
3650			}
3651			break;
3652		}
3653
3654		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3655		count = min(end_offset - dn.ofs_in_node, last_idx - page_idx);
3656		count = round_up(count, F2FS_I(inode)->i_cluster_size);
3657
3658		ret = reserve_compress_blocks(&dn, count);
3659
3660		f2fs_put_dnode(&dn);
3661
3662		if (ret < 0)
3663			break;
3664
3665		page_idx += count;
3666		reserved_blocks += ret;
3667	}
3668
3669	filemap_invalidate_unlock(inode->i_mapping);
3670	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3671
3672	if (ret >= 0) {
3673		clear_inode_flag(inode, FI_COMPRESS_RELEASED);
3674		inode->i_ctime = current_time(inode);
3675		f2fs_mark_inode_dirty_sync(inode, true);
3676	}
3677unlock_inode:
3678	inode_unlock(inode);
3679out:
3680	mnt_drop_write_file(filp);
3681
3682	if (ret >= 0) {
3683		ret = put_user(reserved_blocks, (u64 __user *)arg);
3684	} else if (reserved_blocks &&
3685			atomic_read(&F2FS_I(inode)->i_compr_blocks)) {
3686		set_sbi_flag(sbi, SBI_NEED_FSCK);
3687		f2fs_warn(sbi, "%s: partial blocks were released i_ino=%lx "
3688			"iblocks=%llu, reserved=%u, compr_blocks=%u, "
3689			"run fsck to fix.",
3690			__func__, inode->i_ino, inode->i_blocks,
3691			reserved_blocks,
3692			atomic_read(&F2FS_I(inode)->i_compr_blocks));
3693	}
3694
3695	return ret;
3696}
3697
3698static int f2fs_secure_erase(struct block_device *bdev, struct inode *inode,
3699		pgoff_t off, block_t block, block_t len, u32 flags)
3700{
3701	sector_t sector = SECTOR_FROM_BLOCK(block);
3702	sector_t nr_sects = SECTOR_FROM_BLOCK(len);
3703	int ret = 0;
3704
3705	if (flags & F2FS_TRIM_FILE_DISCARD) {
3706		if (bdev_max_secure_erase_sectors(bdev))
3707			ret = blkdev_issue_secure_erase(bdev, sector, nr_sects,
3708					GFP_NOFS);
3709		else
3710			ret = blkdev_issue_discard(bdev, sector, nr_sects,
3711					GFP_NOFS);
3712	}
3713
3714	if (!ret && (flags & F2FS_TRIM_FILE_ZEROOUT)) {
3715		if (IS_ENCRYPTED(inode))
3716			ret = fscrypt_zeroout_range(inode, off, block, len);
3717		else
3718			ret = blkdev_issue_zeroout(bdev, sector, nr_sects,
3719					GFP_NOFS, 0);
3720	}
3721
3722	return ret;
3723}
3724
3725static int f2fs_sec_trim_file(struct file *filp, unsigned long arg)
3726{
3727	struct inode *inode = file_inode(filp);
3728	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3729	struct address_space *mapping = inode->i_mapping;
3730	struct block_device *prev_bdev = NULL;
3731	struct f2fs_sectrim_range range;
3732	pgoff_t index, pg_end, prev_index = 0;
3733	block_t prev_block = 0, len = 0;
3734	loff_t end_addr;
3735	bool to_end = false;
3736	int ret = 0;
3737
3738	if (!(filp->f_mode & FMODE_WRITE))
3739		return -EBADF;
3740
3741	if (copy_from_user(&range, (struct f2fs_sectrim_range __user *)arg,
3742				sizeof(range)))
3743		return -EFAULT;
3744
3745	if (range.flags == 0 || (range.flags & ~F2FS_TRIM_FILE_MASK) ||
3746			!S_ISREG(inode->i_mode))
3747		return -EINVAL;
3748
3749	if (((range.flags & F2FS_TRIM_FILE_DISCARD) &&
3750			!f2fs_hw_support_discard(sbi)) ||
3751			((range.flags & F2FS_TRIM_FILE_ZEROOUT) &&
3752			 IS_ENCRYPTED(inode) && f2fs_is_multi_device(sbi)))
3753		return -EOPNOTSUPP;
3754
3755	file_start_write(filp);
3756	inode_lock(inode);
3757
3758	if (f2fs_is_atomic_file(inode) || f2fs_compressed_file(inode) ||
3759			range.start >= inode->i_size) {
3760		ret = -EINVAL;
3761		goto err;
3762	}
3763
3764	if (range.len == 0)
3765		goto err;
3766
3767	if (inode->i_size - range.start > range.len) {
3768		end_addr = range.start + range.len;
3769	} else {
3770		end_addr = range.len == (u64)-1 ?
3771			sbi->sb->s_maxbytes : inode->i_size;
3772		to_end = true;
3773	}
3774
3775	if (!IS_ALIGNED(range.start, F2FS_BLKSIZE) ||
3776			(!to_end && !IS_ALIGNED(end_addr, F2FS_BLKSIZE))) {
3777		ret = -EINVAL;
3778		goto err;
3779	}
3780
3781	index = F2FS_BYTES_TO_BLK(range.start);
3782	pg_end = DIV_ROUND_UP(end_addr, F2FS_BLKSIZE);
3783
3784	ret = f2fs_convert_inline_inode(inode);
3785	if (ret)
3786		goto err;
3787
3788	f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3789	filemap_invalidate_lock(mapping);
3790
3791	ret = filemap_write_and_wait_range(mapping, range.start,
3792			to_end ? LLONG_MAX : end_addr - 1);
3793	if (ret)
3794		goto out;
3795
3796	truncate_inode_pages_range(mapping, range.start,
3797			to_end ? -1 : end_addr - 1);
3798
3799	while (index < pg_end) {
3800		struct dnode_of_data dn;
3801		pgoff_t end_offset, count;
3802		int i;
3803
3804		set_new_dnode(&dn, inode, NULL, NULL, 0);
3805		ret = f2fs_get_dnode_of_data(&dn, index, LOOKUP_NODE);
3806		if (ret) {
3807			if (ret == -ENOENT) {
3808				index = f2fs_get_next_page_offset(&dn, index);
3809				continue;
3810			}
3811			goto out;
3812		}
3813
3814		end_offset = ADDRS_PER_PAGE(dn.node_page, inode);
3815		count = min(end_offset - dn.ofs_in_node, pg_end - index);
3816		for (i = 0; i < count; i++, index++, dn.ofs_in_node++) {
3817			struct block_device *cur_bdev;
3818			block_t blkaddr = f2fs_data_blkaddr(&dn);
3819
3820			if (!__is_valid_data_blkaddr(blkaddr))
3821				continue;
3822
3823			if (!f2fs_is_valid_blkaddr(sbi, blkaddr,
3824						DATA_GENERIC_ENHANCE)) {
3825				ret = -EFSCORRUPTED;
3826				f2fs_put_dnode(&dn);
3827				f2fs_handle_error(sbi,
3828						ERROR_INVALID_BLKADDR);
3829				goto out;
3830			}
3831
3832			cur_bdev = f2fs_target_device(sbi, blkaddr, NULL);
3833			if (f2fs_is_multi_device(sbi)) {
3834				int di = f2fs_target_device_index(sbi, blkaddr);
3835
3836				blkaddr -= FDEV(di).start_blk;
3837			}
3838
3839			if (len) {
3840				if (prev_bdev == cur_bdev &&
3841						index == prev_index + len &&
3842						blkaddr == prev_block + len) {
3843					len++;
3844				} else {
3845					ret = f2fs_secure_erase(prev_bdev,
3846						inode, prev_index, prev_block,
3847						len, range.flags);
3848					if (ret) {
3849						f2fs_put_dnode(&dn);
3850						goto out;
3851					}
3852
3853					len = 0;
3854				}
3855			}
3856
3857			if (!len) {
3858				prev_bdev = cur_bdev;
3859				prev_index = index;
3860				prev_block = blkaddr;
3861				len = 1;
3862			}
3863		}
3864
3865		f2fs_put_dnode(&dn);
3866
3867		if (fatal_signal_pending(current)) {
3868			ret = -EINTR;
3869			goto out;
3870		}
3871		cond_resched();
3872	}
3873
3874	if (len)
3875		ret = f2fs_secure_erase(prev_bdev, inode, prev_index,
3876				prev_block, len, range.flags);
3877out:
3878	filemap_invalidate_unlock(mapping);
3879	f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
3880err:
3881	inode_unlock(inode);
3882	file_end_write(filp);
3883
3884	return ret;
3885}
3886
3887static int f2fs_ioc_get_compress_option(struct file *filp, unsigned long arg)
3888{
3889	struct inode *inode = file_inode(filp);
3890	struct f2fs_comp_option option;
3891
3892	if (!f2fs_sb_has_compression(F2FS_I_SB(inode)))
3893		return -EOPNOTSUPP;
3894
3895	inode_lock_shared(inode);
3896
3897	if (!f2fs_compressed_file(inode)) {
3898		inode_unlock_shared(inode);
3899		return -ENODATA;
3900	}
3901
3902	option.algorithm = F2FS_I(inode)->i_compress_algorithm;
3903	option.log_cluster_size = F2FS_I(inode)->i_log_cluster_size;
3904
3905	inode_unlock_shared(inode);
3906
3907	if (copy_to_user((struct f2fs_comp_option __user *)arg, &option,
3908				sizeof(option)))
3909		return -EFAULT;
3910
3911	return 0;
3912}
3913
3914static int f2fs_ioc_set_compress_option(struct file *filp, unsigned long arg)
3915{
3916	struct inode *inode = file_inode(filp);
3917	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
3918	struct f2fs_comp_option option;
3919	int ret = 0;
3920
3921	if (!f2fs_sb_has_compression(sbi))
3922		return -EOPNOTSUPP;
3923
3924	if (!(filp->f_mode & FMODE_WRITE))
3925		return -EBADF;
3926
3927	if (copy_from_user(&option, (struct f2fs_comp_option __user *)arg,
3928				sizeof(option)))
3929		return -EFAULT;
3930
3931	if (!f2fs_compressed_file(inode) ||
3932			option.log_cluster_size < MIN_COMPRESS_LOG_SIZE ||
3933			option.log_cluster_size > MAX_COMPRESS_LOG_SIZE ||
3934			option.algorithm >= COMPRESS_MAX)
3935		return -EINVAL;
3936
3937	file_start_write(filp);
3938	inode_lock(inode);
3939
3940	if (f2fs_is_mmap_file(inode) || get_dirty_pages(inode)) {
3941		ret = -EBUSY;
3942		goto out;
3943	}
3944
3945	if (inode->i_size != 0) {
3946		ret = -EFBIG;
3947		goto out;
3948	}
3949
3950	F2FS_I(inode)->i_compress_algorithm = option.algorithm;
3951	F2FS_I(inode)->i_log_cluster_size = option.log_cluster_size;
3952	F2FS_I(inode)->i_cluster_size = 1 << option.log_cluster_size;
3953	f2fs_mark_inode_dirty_sync(inode, true);
3954
3955	if (!f2fs_is_compress_backend_ready(inode))
3956		f2fs_warn(sbi, "compression algorithm is successfully set, "
3957			"but current kernel doesn't support this algorithm.");
3958out:
3959	inode_unlock(inode);
3960	file_end_write(filp);
3961
3962	return ret;
3963}
3964
3965static int redirty_blocks(struct inode *inode, pgoff_t page_idx, int len)
3966{
3967	DEFINE_READAHEAD(ractl, NULL, NULL, inode->i_mapping, page_idx);
3968	struct address_space *mapping = inode->i_mapping;
3969	struct page *page;
3970	pgoff_t redirty_idx = page_idx;
3971	int i, page_len = 0, ret = 0;
3972
3973	page_cache_ra_unbounded(&ractl, len, 0);
3974
3975	for (i = 0; i < len; i++, page_idx++) {
3976		page = read_cache_page(mapping, page_idx, NULL, NULL);
3977		if (IS_ERR(page)) {
3978			ret = PTR_ERR(page);
3979			break;
3980		}
3981		page_len++;
3982	}
3983
3984	for (i = 0; i < page_len; i++, redirty_idx++) {
3985		page = find_lock_page(mapping, redirty_idx);
3986
3987		/* It will never fail, when page has pinned above */
3988		f2fs_bug_on(F2FS_I_SB(inode), !page);
3989
3990		set_page_dirty(page);
3991		f2fs_put_page(page, 1);
3992		f2fs_put_page(page, 0);
3993	}
3994
3995	return ret;
3996}
3997
3998static int f2fs_ioc_decompress_file(struct file *filp, unsigned long arg)
3999{
4000	struct inode *inode = file_inode(filp);
4001	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4002	struct f2fs_inode_info *fi = F2FS_I(inode);
4003	pgoff_t page_idx = 0, last_idx;
4004	unsigned int blk_per_seg = sbi->blocks_per_seg;
4005	int cluster_size = fi->i_cluster_size;
4006	int count, ret;
4007
4008	if (!f2fs_sb_has_compression(sbi) ||
4009			F2FS_OPTION(sbi).compress_mode != COMPR_MODE_USER)
4010		return -EOPNOTSUPP;
4011
4012	if (!(filp->f_mode & FMODE_WRITE))
4013		return -EBADF;
4014
4015	if (!f2fs_compressed_file(inode))
4016		return -EINVAL;
4017
4018	f2fs_balance_fs(F2FS_I_SB(inode), true);
4019
4020	file_start_write(filp);
4021	inode_lock(inode);
4022
4023	if (!f2fs_is_compress_backend_ready(inode)) {
4024		ret = -EOPNOTSUPP;
4025		goto out;
4026	}
4027
4028	if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
4029		ret = -EINVAL;
4030		goto out;
4031	}
4032
4033	ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
4034	if (ret)
4035		goto out;
4036
4037	if (!atomic_read(&fi->i_compr_blocks))
4038		goto out;
4039
4040	last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
4041
4042	count = last_idx - page_idx;
4043	while (count) {
4044		int len = min(cluster_size, count);
4045
4046		ret = redirty_blocks(inode, page_idx, len);
4047		if (ret < 0)
4048			break;
4049
4050		if (get_dirty_pages(inode) >= blk_per_seg)
4051			filemap_fdatawrite(inode->i_mapping);
4052
4053		count -= len;
4054		page_idx += len;
4055	}
4056
4057	if (!ret)
4058		ret = filemap_write_and_wait_range(inode->i_mapping, 0,
4059							LLONG_MAX);
4060
4061	if (ret)
4062		f2fs_warn(sbi, "%s: The file might be partially decompressed (errno=%d). Please delete the file.",
4063			  __func__, ret);
4064out:
4065	inode_unlock(inode);
4066	file_end_write(filp);
4067
4068	return ret;
4069}
4070
4071static int f2fs_ioc_compress_file(struct file *filp, unsigned long arg)
4072{
4073	struct inode *inode = file_inode(filp);
4074	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4075	pgoff_t page_idx = 0, last_idx;
4076	unsigned int blk_per_seg = sbi->blocks_per_seg;
4077	int cluster_size = F2FS_I(inode)->i_cluster_size;
4078	int count, ret;
4079
4080	if (!f2fs_sb_has_compression(sbi) ||
4081			F2FS_OPTION(sbi).compress_mode != COMPR_MODE_USER)
4082		return -EOPNOTSUPP;
4083
4084	if (!(filp->f_mode & FMODE_WRITE))
4085		return -EBADF;
4086
4087	if (!f2fs_compressed_file(inode))
4088		return -EINVAL;
4089
4090	f2fs_balance_fs(F2FS_I_SB(inode), true);
4091
4092	file_start_write(filp);
4093	inode_lock(inode);
4094
4095	if (!f2fs_is_compress_backend_ready(inode)) {
4096		ret = -EOPNOTSUPP;
4097		goto out;
4098	}
4099
4100	if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED)) {
4101		ret = -EINVAL;
4102		goto out;
4103	}
4104
4105	ret = filemap_write_and_wait_range(inode->i_mapping, 0, LLONG_MAX);
4106	if (ret)
4107		goto out;
4108
4109	set_inode_flag(inode, FI_ENABLE_COMPRESS);
4110
4111	last_idx = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
4112
4113	count = last_idx - page_idx;
4114	while (count) {
4115		int len = min(cluster_size, count);
4116
4117		ret = redirty_blocks(inode, page_idx, len);
4118		if (ret < 0)
4119			break;
4120
4121		if (get_dirty_pages(inode) >= blk_per_seg)
4122			filemap_fdatawrite(inode->i_mapping);
4123
4124		count -= len;
4125		page_idx += len;
4126	}
4127
4128	if (!ret)
4129		ret = filemap_write_and_wait_range(inode->i_mapping, 0,
4130							LLONG_MAX);
4131
4132	clear_inode_flag(inode, FI_ENABLE_COMPRESS);
4133
4134	if (ret)
4135		f2fs_warn(sbi, "%s: The file might be partially compressed (errno=%d). Please delete the file.",
4136			  __func__, ret);
4137out:
4138	inode_unlock(inode);
4139	file_end_write(filp);
4140
4141	return ret;
4142}
4143
4144static long __f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
4145{
4146	switch (cmd) {
4147	case FS_IOC_GETVERSION:
4148		return f2fs_ioc_getversion(filp, arg);
4149	case F2FS_IOC_START_ATOMIC_WRITE:
4150		return f2fs_ioc_start_atomic_write(filp, false);
4151	case F2FS_IOC_START_ATOMIC_REPLACE:
4152		return f2fs_ioc_start_atomic_write(filp, true);
4153	case F2FS_IOC_COMMIT_ATOMIC_WRITE:
4154		return f2fs_ioc_commit_atomic_write(filp);
4155	case F2FS_IOC_ABORT_ATOMIC_WRITE:
4156		return f2fs_ioc_abort_atomic_write(filp);
4157	case F2FS_IOC_START_VOLATILE_WRITE:
4158	case F2FS_IOC_RELEASE_VOLATILE_WRITE:
4159		return -EOPNOTSUPP;
4160	case F2FS_IOC_SHUTDOWN:
4161		return f2fs_ioc_shutdown(filp, arg);
4162	case FITRIM:
4163		return f2fs_ioc_fitrim(filp, arg);
4164	case FS_IOC_SET_ENCRYPTION_POLICY:
4165		return f2fs_ioc_set_encryption_policy(filp, arg);
4166	case FS_IOC_GET_ENCRYPTION_POLICY:
4167		return f2fs_ioc_get_encryption_policy(filp, arg);
4168	case FS_IOC_GET_ENCRYPTION_PWSALT:
4169		return f2fs_ioc_get_encryption_pwsalt(filp, arg);
4170	case FS_IOC_GET_ENCRYPTION_POLICY_EX:
4171		return f2fs_ioc_get_encryption_policy_ex(filp, arg);
4172	case FS_IOC_ADD_ENCRYPTION_KEY:
4173		return f2fs_ioc_add_encryption_key(filp, arg);
4174	case FS_IOC_REMOVE_ENCRYPTION_KEY:
4175		return f2fs_ioc_remove_encryption_key(filp, arg);
4176	case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
4177		return f2fs_ioc_remove_encryption_key_all_users(filp, arg);
4178	case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
4179		return f2fs_ioc_get_encryption_key_status(filp, arg);
4180	case FS_IOC_GET_ENCRYPTION_NONCE:
4181		return f2fs_ioc_get_encryption_nonce(filp, arg);
4182	case F2FS_IOC_GARBAGE_COLLECT:
4183		return f2fs_ioc_gc(filp, arg);
4184	case F2FS_IOC_GARBAGE_COLLECT_RANGE:
4185		return f2fs_ioc_gc_range(filp, arg);
4186	case F2FS_IOC_WRITE_CHECKPOINT:
4187		return f2fs_ioc_write_checkpoint(filp, arg);
4188	case F2FS_IOC_DEFRAGMENT:
4189		return f2fs_ioc_defragment(filp, arg);
4190	case F2FS_IOC_MOVE_RANGE:
4191		return f2fs_ioc_move_range(filp, arg);
4192	case F2FS_IOC_FLUSH_DEVICE:
4193		return f2fs_ioc_flush_device(filp, arg);
4194	case F2FS_IOC_GET_FEATURES:
4195		return f2fs_ioc_get_features(filp, arg);
4196	case F2FS_IOC_GET_PIN_FILE:
4197		return f2fs_ioc_get_pin_file(filp, arg);
4198	case F2FS_IOC_SET_PIN_FILE:
4199		return f2fs_ioc_set_pin_file(filp, arg);
4200	case F2FS_IOC_PRECACHE_EXTENTS:
4201		return f2fs_ioc_precache_extents(filp, arg);
4202	case F2FS_IOC_RESIZE_FS:
4203		return f2fs_ioc_resize_fs(filp, arg);
4204	case FS_IOC_ENABLE_VERITY:
4205		return f2fs_ioc_enable_verity(filp, arg);
4206	case FS_IOC_MEASURE_VERITY:
4207		return f2fs_ioc_measure_verity(filp, arg);
4208	case FS_IOC_READ_VERITY_METADATA:
4209		return f2fs_ioc_read_verity_metadata(filp, arg);
4210	case FS_IOC_GETFSLABEL:
4211		return f2fs_ioc_getfslabel(filp, arg);
4212	case FS_IOC_SETFSLABEL:
4213		return f2fs_ioc_setfslabel(filp, arg);
4214	case F2FS_IOC_GET_COMPRESS_BLOCKS:
4215		return f2fs_get_compress_blocks(filp, arg);
4216	case F2FS_IOC_RELEASE_COMPRESS_BLOCKS:
4217		return f2fs_release_compress_blocks(filp, arg);
4218	case F2FS_IOC_RESERVE_COMPRESS_BLOCKS:
4219		return f2fs_reserve_compress_blocks(filp, arg);
4220	case F2FS_IOC_SEC_TRIM_FILE:
4221		return f2fs_sec_trim_file(filp, arg);
4222	case F2FS_IOC_GET_COMPRESS_OPTION:
4223		return f2fs_ioc_get_compress_option(filp, arg);
4224	case F2FS_IOC_SET_COMPRESS_OPTION:
4225		return f2fs_ioc_set_compress_option(filp, arg);
4226	case F2FS_IOC_DECOMPRESS_FILE:
4227		return f2fs_ioc_decompress_file(filp, arg);
4228	case F2FS_IOC_COMPRESS_FILE:
4229		return f2fs_ioc_compress_file(filp, arg);
4230	default:
4231		return -ENOTTY;
4232	}
4233}
4234
4235long f2fs_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
4236{
4237	if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(filp)))))
4238		return -EIO;
4239	if (!f2fs_is_checkpoint_ready(F2FS_I_SB(file_inode(filp))))
4240		return -ENOSPC;
4241
4242	return __f2fs_ioctl(filp, cmd, arg);
4243}
4244
4245/*
4246 * Return %true if the given read or write request should use direct I/O, or
4247 * %false if it should use buffered I/O.
4248 */
4249static bool f2fs_should_use_dio(struct inode *inode, struct kiocb *iocb,
4250				struct iov_iter *iter)
4251{
4252	unsigned int align;
4253
4254	if (!(iocb->ki_flags & IOCB_DIRECT))
4255		return false;
4256
4257	if (f2fs_force_buffered_io(inode, iov_iter_rw(iter)))
4258		return false;
4259
4260	/*
4261	 * Direct I/O not aligned to the disk's logical_block_size will be
4262	 * attempted, but will fail with -EINVAL.
4263	 *
4264	 * f2fs additionally requires that direct I/O be aligned to the
4265	 * filesystem block size, which is often a stricter requirement.
4266	 * However, f2fs traditionally falls back to buffered I/O on requests
4267	 * that are logical_block_size-aligned but not fs-block aligned.
4268	 *
4269	 * The below logic implements this behavior.
4270	 */
4271	align = iocb->ki_pos | iov_iter_alignment(iter);
4272	if (!IS_ALIGNED(align, i_blocksize(inode)) &&
4273	    IS_ALIGNED(align, bdev_logical_block_size(inode->i_sb->s_bdev)))
4274		return false;
4275
4276	return true;
4277}
4278
4279static int f2fs_dio_read_end_io(struct kiocb *iocb, ssize_t size, int error,
4280				unsigned int flags)
4281{
4282	struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(iocb->ki_filp));
4283
4284	dec_page_count(sbi, F2FS_DIO_READ);
4285	if (error)
4286		return error;
4287	f2fs_update_iostat(sbi, NULL, APP_DIRECT_READ_IO, size);
4288	return 0;
4289}
4290
4291static const struct iomap_dio_ops f2fs_iomap_dio_read_ops = {
4292	.end_io = f2fs_dio_read_end_io,
4293};
4294
4295static ssize_t f2fs_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
4296{
4297	struct file *file = iocb->ki_filp;
4298	struct inode *inode = file_inode(file);
4299	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4300	struct f2fs_inode_info *fi = F2FS_I(inode);
4301	const loff_t pos = iocb->ki_pos;
4302	const size_t count = iov_iter_count(to);
4303	struct iomap_dio *dio;
4304	ssize_t ret;
4305
4306	if (count == 0)
4307		return 0; /* skip atime update */
4308
4309	trace_f2fs_direct_IO_enter(inode, iocb, count, READ);
4310
4311	if (iocb->ki_flags & IOCB_NOWAIT) {
4312		if (!f2fs_down_read_trylock(&fi->i_gc_rwsem[READ])) {
4313			ret = -EAGAIN;
4314			goto out;
4315		}
4316	} else {
4317		f2fs_down_read(&fi->i_gc_rwsem[READ]);
4318	}
4319
4320	/*
4321	 * We have to use __iomap_dio_rw() and iomap_dio_complete() instead of
4322	 * the higher-level function iomap_dio_rw() in order to ensure that the
4323	 * F2FS_DIO_READ counter will be decremented correctly in all cases.
4324	 */
4325	inc_page_count(sbi, F2FS_DIO_READ);
4326	dio = __iomap_dio_rw(iocb, to, &f2fs_iomap_ops,
4327			     &f2fs_iomap_dio_read_ops, 0, NULL, 0);
4328	if (IS_ERR_OR_NULL(dio)) {
4329		ret = PTR_ERR_OR_ZERO(dio);
4330		if (ret != -EIOCBQUEUED)
4331			dec_page_count(sbi, F2FS_DIO_READ);
4332	} else {
4333		ret = iomap_dio_complete(dio);
4334	}
4335
4336	f2fs_up_read(&fi->i_gc_rwsem[READ]);
4337
4338	file_accessed(file);
4339out:
4340	trace_f2fs_direct_IO_exit(inode, pos, count, READ, ret);
4341	return ret;
4342}
4343
4344static ssize_t f2fs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
4345{
4346	struct inode *inode = file_inode(iocb->ki_filp);
4347	const loff_t pos = iocb->ki_pos;
4348	ssize_t ret;
4349
4350	if (!f2fs_is_compress_backend_ready(inode))
4351		return -EOPNOTSUPP;
4352
4353	if (trace_f2fs_dataread_start_enabled()) {
4354		char *p = f2fs_kmalloc(F2FS_I_SB(inode), PATH_MAX, GFP_KERNEL);
4355		char *path;
4356
4357		if (!p)
4358			goto skip_read_trace;
4359
4360		path = dentry_path_raw(file_dentry(iocb->ki_filp), p, PATH_MAX);
4361		if (IS_ERR(path)) {
4362			kfree(p);
4363			goto skip_read_trace;
4364		}
4365
4366		trace_f2fs_dataread_start(inode, pos, iov_iter_count(to),
4367					current->pid, path, current->comm);
4368		kfree(p);
4369	}
4370skip_read_trace:
4371	if (f2fs_should_use_dio(inode, iocb, to)) {
4372		ret = f2fs_dio_read_iter(iocb, to);
4373	} else {
4374		ret = filemap_read(iocb, to, 0);
4375		if (ret > 0)
4376			f2fs_update_iostat(F2FS_I_SB(inode), inode,
4377						APP_BUFFERED_READ_IO, ret);
4378	}
4379	if (trace_f2fs_dataread_end_enabled())
4380		trace_f2fs_dataread_end(inode, pos, ret);
4381	return ret;
4382}
4383
4384static ssize_t f2fs_write_checks(struct kiocb *iocb, struct iov_iter *from)
4385{
4386	struct file *file = iocb->ki_filp;
4387	struct inode *inode = file_inode(file);
4388	ssize_t count;
4389	int err;
4390
4391	if (IS_IMMUTABLE(inode))
4392		return -EPERM;
4393
4394	if (is_inode_flag_set(inode, FI_COMPRESS_RELEASED))
4395		return -EPERM;
4396
4397	count = generic_write_checks(iocb, from);
4398	if (count <= 0)
4399		return count;
4400
4401	err = file_modified(file);
4402	if (err)
4403		return err;
4404	return count;
4405}
4406
4407/*
4408 * Preallocate blocks for a write request, if it is possible and helpful to do
4409 * so.  Returns a positive number if blocks may have been preallocated, 0 if no
4410 * blocks were preallocated, or a negative errno value if something went
4411 * seriously wrong.  Also sets FI_PREALLOCATED_ALL on the inode if *all* the
4412 * requested blocks (not just some of them) have been allocated.
4413 */
4414static int f2fs_preallocate_blocks(struct kiocb *iocb, struct iov_iter *iter,
4415				   bool dio)
4416{
4417	struct inode *inode = file_inode(iocb->ki_filp);
4418	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4419	const loff_t pos = iocb->ki_pos;
4420	const size_t count = iov_iter_count(iter);
4421	struct f2fs_map_blocks map = {};
4422	int flag;
4423	int ret;
4424
4425	/* If it will be an out-of-place direct write, don't bother. */
4426	if (dio && f2fs_lfs_mode(sbi))
4427		return 0;
4428	/*
4429	 * Don't preallocate holes aligned to DIO_SKIP_HOLES which turns into
4430	 * buffered IO, if DIO meets any holes.
4431	 */
4432	if (dio && i_size_read(inode) &&
4433		(F2FS_BYTES_TO_BLK(pos) < F2FS_BLK_ALIGN(i_size_read(inode))))
4434		return 0;
4435
4436	/* No-wait I/O can't allocate blocks. */
4437	if (iocb->ki_flags & IOCB_NOWAIT)
4438		return 0;
4439
4440	/* If it will be a short write, don't bother. */
4441	if (fault_in_iov_iter_readable(iter, count))
4442		return 0;
4443
4444	if (f2fs_has_inline_data(inode)) {
4445		/* If the data will fit inline, don't bother. */
4446		if (pos + count <= MAX_INLINE_DATA(inode))
4447			return 0;
4448		ret = f2fs_convert_inline_inode(inode);
4449		if (ret)
4450			return ret;
4451	}
4452
4453	/* Do not preallocate blocks that will be written partially in 4KB. */
4454	map.m_lblk = F2FS_BLK_ALIGN(pos);
4455	map.m_len = F2FS_BYTES_TO_BLK(pos + count);
4456	if (map.m_len > map.m_lblk)
4457		map.m_len -= map.m_lblk;
4458	else
4459		map.m_len = 0;
4460	map.m_may_create = true;
4461	if (dio) {
4462		map.m_seg_type = f2fs_rw_hint_to_seg_type(inode->i_write_hint);
4463		flag = F2FS_GET_BLOCK_PRE_DIO;
4464	} else {
4465		map.m_seg_type = NO_CHECK_TYPE;
4466		flag = F2FS_GET_BLOCK_PRE_AIO;
4467	}
4468
4469	ret = f2fs_map_blocks(inode, &map, 1, flag);
4470	/* -ENOSPC|-EDQUOT are fine to report the number of allocated blocks. */
4471	if (ret < 0 && !((ret == -ENOSPC || ret == -EDQUOT) && map.m_len > 0))
4472		return ret;
4473	if (ret == 0)
4474		set_inode_flag(inode, FI_PREALLOCATED_ALL);
4475	return map.m_len;
4476}
4477
4478static ssize_t f2fs_buffered_write_iter(struct kiocb *iocb,
4479					struct iov_iter *from)
4480{
4481	struct file *file = iocb->ki_filp;
4482	struct inode *inode = file_inode(file);
4483	ssize_t ret;
4484
4485	if (iocb->ki_flags & IOCB_NOWAIT)
4486		return -EOPNOTSUPP;
4487
4488	current->backing_dev_info = inode_to_bdi(inode);
4489	ret = generic_perform_write(iocb, from);
4490	current->backing_dev_info = NULL;
4491
4492	if (ret > 0) {
4493		iocb->ki_pos += ret;
4494		f2fs_update_iostat(F2FS_I_SB(inode), inode,
4495						APP_BUFFERED_IO, ret);
4496	}
4497	return ret;
4498}
4499
4500static int f2fs_dio_write_end_io(struct kiocb *iocb, ssize_t size, int error,
4501				 unsigned int flags)
4502{
4503	struct f2fs_sb_info *sbi = F2FS_I_SB(file_inode(iocb->ki_filp));
4504
4505	dec_page_count(sbi, F2FS_DIO_WRITE);
4506	if (error)
4507		return error;
4508	f2fs_update_iostat(sbi, NULL, APP_DIRECT_IO, size);
4509	return 0;
4510}
4511
4512static const struct iomap_dio_ops f2fs_iomap_dio_write_ops = {
4513	.end_io = f2fs_dio_write_end_io,
4514};
4515
4516static ssize_t f2fs_dio_write_iter(struct kiocb *iocb, struct iov_iter *from,
4517				   bool *may_need_sync)
4518{
4519	struct file *file = iocb->ki_filp;
4520	struct inode *inode = file_inode(file);
4521	struct f2fs_inode_info *fi = F2FS_I(inode);
4522	struct f2fs_sb_info *sbi = F2FS_I_SB(inode);
4523	const bool do_opu = f2fs_lfs_mode(sbi);
4524	const loff_t pos = iocb->ki_pos;
4525	const ssize_t count = iov_iter_count(from);
4526	unsigned int dio_flags;
4527	struct iomap_dio *dio;
4528	ssize_t ret;
4529
4530	trace_f2fs_direct_IO_enter(inode, iocb, count, WRITE);
4531
4532	if (iocb->ki_flags & IOCB_NOWAIT) {
4533		/* f2fs_convert_inline_inode() and block allocation can block */
4534		if (f2fs_has_inline_data(inode) ||
4535		    !f2fs_overwrite_io(inode, pos, count)) {
4536			ret = -EAGAIN;
4537			goto out;
4538		}
4539
4540		if (!f2fs_down_read_trylock(&fi->i_gc_rwsem[WRITE])) {
4541			ret = -EAGAIN;
4542			goto out;
4543		}
4544		if (do_opu && !f2fs_down_read_trylock(&fi->i_gc_rwsem[READ])) {
4545			f2fs_up_read(&fi->i_gc_rwsem[WRITE]);
4546			ret = -EAGAIN;
4547			goto out;
4548		}
4549	} else {
4550		ret = f2fs_convert_inline_inode(inode);
4551		if (ret)
4552			goto out;
4553
4554		f2fs_down_read(&fi->i_gc_rwsem[WRITE]);
4555		if (do_opu)
4556			f2fs_down_read(&fi->i_gc_rwsem[READ]);
4557	}
4558
4559	/*
4560	 * We have to use __iomap_dio_rw() and iomap_dio_complete() instead of
4561	 * the higher-level function iomap_dio_rw() in order to ensure that the
4562	 * F2FS_DIO_WRITE counter will be decremented correctly in all cases.
4563	 */
4564	inc_page_count(sbi, F2FS_DIO_WRITE);
4565	dio_flags = 0;
4566	if (pos + count > inode->i_size)
4567		dio_flags |= IOMAP_DIO_FORCE_WAIT;
4568	dio = __iomap_dio_rw(iocb, from, &f2fs_iomap_ops,
4569			     &f2fs_iomap_dio_write_ops, dio_flags, NULL, 0);
4570	if (IS_ERR_OR_NULL(dio)) {
4571		ret = PTR_ERR_OR_ZERO(dio);
4572		if (ret == -ENOTBLK)
4573			ret = 0;
4574		if (ret != -EIOCBQUEUED)
4575			dec_page_count(sbi, F2FS_DIO_WRITE);
4576	} else {
4577		ret = iomap_dio_complete(dio);
4578	}
4579
4580	if (do_opu)
4581		f2fs_up_read(&fi->i_gc_rwsem[READ]);
4582	f2fs_up_read(&fi->i_gc_rwsem[WRITE]);
4583
4584	if (ret < 0)
4585		goto out;
4586	if (pos + ret > inode->i_size)
4587		f2fs_i_size_write(inode, pos + ret);
4588	if (!do_opu)
4589		set_inode_flag(inode, FI_UPDATE_WRITE);
4590
4591	if (iov_iter_count(from)) {
4592		ssize_t ret2;
4593		loff_t bufio_start_pos = iocb->ki_pos;
4594
4595		/*
4596		 * The direct write was partial, so we need to fall back to a
4597		 * buffered write for the remainder.
4598		 */
4599
4600		ret2 = f2fs_buffered_write_iter(iocb, from);
4601		if (iov_iter_count(from))
4602			f2fs_write_failed(inode, iocb->ki_pos);
4603		if (ret2 < 0)
4604			goto out;
4605
4606		/*
4607		 * Ensure that the pagecache pages are written to disk and
4608		 * invalidated to preserve the expected O_DIRECT semantics.
4609		 */
4610		if (ret2 > 0) {
4611			loff_t bufio_end_pos = bufio_start_pos + ret2 - 1;
4612
4613			ret += ret2;
4614
4615			ret2 = filemap_write_and_wait_range(file->f_mapping,
4616							    bufio_start_pos,
4617							    bufio_end_pos);
4618			if (ret2 < 0)
4619				goto out;
4620			invalidate_mapping_pages(file->f_mapping,
4621						 bufio_start_pos >> PAGE_SHIFT,
4622						 bufio_end_pos >> PAGE_SHIFT);
4623		}
4624	} else {
4625		/* iomap_dio_rw() already handled the generic_write_sync(). */
4626		*may_need_sync = false;
4627	}
4628out:
4629	trace_f2fs_direct_IO_exit(inode, pos, count, WRITE, ret);
4630	return ret;
4631}
4632
4633static ssize_t f2fs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
4634{
4635	struct inode *inode = file_inode(iocb->ki_filp);
4636	const loff_t orig_pos = iocb->ki_pos;
4637	const size_t orig_count = iov_iter_count(from);
4638	loff_t target_size;
4639	bool dio;
4640	bool may_need_sync = true;
4641	int preallocated;
4642	ssize_t ret;
4643
4644	if (unlikely(f2fs_cp_error(F2FS_I_SB(inode)))) {
4645		ret = -EIO;
4646		goto out;
4647	}
4648
4649	if (!f2fs_is_compress_backend_ready(inode)) {
4650		ret = -EOPNOTSUPP;
4651		goto out;
4652	}
4653
4654	if (iocb->ki_flags & IOCB_NOWAIT) {
4655		if (!inode_trylock(inode)) {
4656			ret = -EAGAIN;
4657			goto out;
4658		}
4659	} else {
4660		inode_lock(inode);
4661	}
4662
4663	ret = f2fs_write_checks(iocb, from);
4664	if (ret <= 0)
4665		goto out_unlock;
4666
4667	/* Determine whether we will do a direct write or a buffered write. */
4668	dio = f2fs_should_use_dio(inode, iocb, from);
4669
4670	/* Possibly preallocate the blocks for the write. */
4671	target_size = iocb->ki_pos + iov_iter_count(from);
4672	preallocated = f2fs_preallocate_blocks(iocb, from, dio);
4673	if (preallocated < 0) {
4674		ret = preallocated;
4675	} else {
4676		if (trace_f2fs_datawrite_start_enabled()) {
4677			char *p = f2fs_kmalloc(F2FS_I_SB(inode),
4678						PATH_MAX, GFP_KERNEL);
4679			char *path;
4680
4681			if (!p)
4682				goto skip_write_trace;
4683			path = dentry_path_raw(file_dentry(iocb->ki_filp),
4684								p, PATH_MAX);
4685			if (IS_ERR(path)) {
4686				kfree(p);
4687				goto skip_write_trace;
4688			}
4689			trace_f2fs_datawrite_start(inode, orig_pos, orig_count,
4690					current->pid, path, current->comm);
4691			kfree(p);
4692		}
4693skip_write_trace:
4694		/* Do the actual write. */
4695		ret = dio ?
4696			f2fs_dio_write_iter(iocb, from, &may_need_sync) :
4697			f2fs_buffered_write_iter(iocb, from);
4698
4699		if (trace_f2fs_datawrite_end_enabled())
4700			trace_f2fs_datawrite_end(inode, orig_pos, ret);
4701	}
4702
4703	/* Don't leave any preallocated blocks around past i_size. */
4704	if (preallocated && i_size_read(inode) < target_size) {
4705		f2fs_down_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4706		filemap_invalidate_lock(inode->i_mapping);
4707		if (!f2fs_truncate(inode))
4708			file_dont_truncate(inode);
4709		filemap_invalidate_unlock(inode->i_mapping);
4710		f2fs_up_write(&F2FS_I(inode)->i_gc_rwsem[WRITE]);
4711	} else {
4712		file_dont_truncate(inode);
4713	}
4714
4715	clear_inode_flag(inode, FI_PREALLOCATED_ALL);
4716out_unlock:
4717	inode_unlock(inode);
4718out:
4719	trace_f2fs_file_write_iter(inode, orig_pos, orig_count, ret);
4720	if (ret > 0 && may_need_sync)
4721		ret = generic_write_sync(iocb, ret);
4722	return ret;
4723}
4724
4725static int f2fs_file_fadvise(struct file *filp, loff_t offset, loff_t len,
4726		int advice)
4727{
4728	struct address_space *mapping;
4729	struct backing_dev_info *bdi;
4730	struct inode *inode = file_inode(filp);
4731	int err;
4732
4733	if (advice == POSIX_FADV_SEQUENTIAL) {
4734		if (S_ISFIFO(inode->i_mode))
4735			return -ESPIPE;
4736
4737		mapping = filp->f_mapping;
4738		if (!mapping || len < 0)
4739			return -EINVAL;
4740
4741		bdi = inode_to_bdi(mapping->host);
4742		filp->f_ra.ra_pages = bdi->ra_pages *
4743			F2FS_I_SB(inode)->seq_file_ra_mul;
4744		spin_lock(&filp->f_lock);
4745		filp->f_mode &= ~FMODE_RANDOM;
4746		spin_unlock(&filp->f_lock);
4747		return 0;
4748	}
4749
4750	err = generic_fadvise(filp, offset, len, advice);
4751	if (!err && advice == POSIX_FADV_DONTNEED &&
4752		test_opt(F2FS_I_SB(inode), COMPRESS_CACHE) &&
4753		f2fs_compressed_file(inode))
4754		f2fs_invalidate_compress_pages(F2FS_I_SB(inode), inode->i_ino);
4755
4756	return err;
4757}
4758
4759#ifdef CONFIG_COMPAT
4760struct compat_f2fs_gc_range {
4761	u32 sync;
4762	compat_u64 start;
4763	compat_u64 len;
4764};
4765#define F2FS_IOC32_GARBAGE_COLLECT_RANGE	_IOW(F2FS_IOCTL_MAGIC, 11,\
4766						struct compat_f2fs_gc_range)
4767
4768static int f2fs_compat_ioc_gc_range(struct file *file, unsigned long arg)
4769{
4770	struct compat_f2fs_gc_range __user *urange;
4771	struct f2fs_gc_range range;
4772	int err;
4773
4774	urange = compat_ptr(arg);
4775	err = get_user(range.sync, &urange->sync);
4776	err |= get_user(range.start, &urange->start);
4777	err |= get_user(range.len, &urange->len);
4778	if (err)
4779		return -EFAULT;
4780
4781	return __f2fs_ioc_gc_range(file, &range);
4782}
4783
4784struct compat_f2fs_move_range {
4785	u32 dst_fd;
4786	compat_u64 pos_in;
4787	compat_u64 pos_out;
4788	compat_u64 len;
4789};
4790#define F2FS_IOC32_MOVE_RANGE		_IOWR(F2FS_IOCTL_MAGIC, 9,	\
4791					struct compat_f2fs_move_range)
4792
4793static int f2fs_compat_ioc_move_range(struct file *file, unsigned long arg)
4794{
4795	struct compat_f2fs_move_range __user *urange;
4796	struct f2fs_move_range range;
4797	int err;
4798
4799	urange = compat_ptr(arg);
4800	err = get_user(range.dst_fd, &urange->dst_fd);
4801	err |= get_user(range.pos_in, &urange->pos_in);
4802	err |= get_user(range.pos_out, &urange->pos_out);
4803	err |= get_user(range.len, &urange->len);
4804	if (err)
4805		return -EFAULT;
4806
4807	return __f2fs_ioc_move_range(file, &range);
4808}
4809
4810long f2fs_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4811{
4812	if (unlikely(f2fs_cp_error(F2FS_I_SB(file_inode(file)))))
4813		return -EIO;
4814	if (!f2fs_is_checkpoint_ready(F2FS_I_SB(file_inode(file))))
4815		return -ENOSPC;
4816
4817	switch (cmd) {
4818	case FS_IOC32_GETVERSION:
4819		cmd = FS_IOC_GETVERSION;
4820		break;
4821	case F2FS_IOC32_GARBAGE_COLLECT_RANGE:
4822		return f2fs_compat_ioc_gc_range(file, arg);
4823	case F2FS_IOC32_MOVE_RANGE:
4824		return f2fs_compat_ioc_move_range(file, arg);
4825	case F2FS_IOC_START_ATOMIC_WRITE:
4826	case F2FS_IOC_COMMIT_ATOMIC_WRITE:
4827	case F2FS_IOC_START_VOLATILE_WRITE:
4828	case F2FS_IOC_RELEASE_VOLATILE_WRITE:
4829	case F2FS_IOC_ABORT_ATOMIC_WRITE:
4830	case F2FS_IOC_SHUTDOWN:
4831	case FITRIM:
4832	case FS_IOC_SET_ENCRYPTION_POLICY:
4833	case FS_IOC_GET_ENCRYPTION_PWSALT:
4834	case FS_IOC_GET_ENCRYPTION_POLICY:
4835	case FS_IOC_GET_ENCRYPTION_POLICY_EX:
4836	case FS_IOC_ADD_ENCRYPTION_KEY:
4837	case FS_IOC_REMOVE_ENCRYPTION_KEY:
4838	case FS_IOC_REMOVE_ENCRYPTION_KEY_ALL_USERS:
4839	case FS_IOC_GET_ENCRYPTION_KEY_STATUS:
4840	case FS_IOC_GET_ENCRYPTION_NONCE:
4841	case F2FS_IOC_GARBAGE_COLLECT:
4842	case F2FS_IOC_WRITE_CHECKPOINT:
4843	case F2FS_IOC_DEFRAGMENT:
4844	case F2FS_IOC_FLUSH_DEVICE:
4845	case F2FS_IOC_GET_FEATURES:
4846	case F2FS_IOC_GET_PIN_FILE:
4847	case F2FS_IOC_SET_PIN_FILE:
4848	case F2FS_IOC_PRECACHE_EXTENTS:
4849	case F2FS_IOC_RESIZE_FS:
4850	case FS_IOC_ENABLE_VERITY:
4851	case FS_IOC_MEASURE_VERITY:
4852	case FS_IOC_READ_VERITY_METADATA:
4853	case FS_IOC_GETFSLABEL:
4854	case FS_IOC_SETFSLABEL:
4855	case F2FS_IOC_GET_COMPRESS_BLOCKS:
4856	case F2FS_IOC_RELEASE_COMPRESS_BLOCKS:
4857	case F2FS_IOC_RESERVE_COMPRESS_BLOCKS:
4858	case F2FS_IOC_SEC_TRIM_FILE:
4859	case F2FS_IOC_GET_COMPRESS_OPTION:
4860	case F2FS_IOC_SET_COMPRESS_OPTION:
4861	case F2FS_IOC_DECOMPRESS_FILE:
4862	case F2FS_IOC_COMPRESS_FILE:
4863		break;
4864	default:
4865		return -ENOIOCTLCMD;
4866	}
4867	return __f2fs_ioctl(file, cmd, (unsigned long) compat_ptr(arg));
4868}
4869#endif
4870
4871const struct file_operations f2fs_file_operations = {
4872	.llseek		= f2fs_llseek,
4873	.read_iter	= f2fs_file_read_iter,
4874	.write_iter	= f2fs_file_write_iter,
4875	.open		= f2fs_file_open,
4876	.release	= f2fs_release_file,
4877	.mmap		= f2fs_file_mmap,
4878	.flush		= f2fs_file_flush,
4879	.fsync		= f2fs_sync_file,
4880	.fallocate	= f2fs_fallocate,
4881	.unlocked_ioctl	= f2fs_ioctl,
4882#ifdef CONFIG_COMPAT
4883	.compat_ioctl	= f2fs_compat_ioctl,
4884#endif
4885	.splice_read	= generic_file_splice_read,
4886	.splice_write	= iter_file_splice_write,
4887	.fadvise	= f2fs_file_fadvise,
4888};