inode.c 178 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0
2
/*
3
 *  linux/fs/ext4/inode.c
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * Copyright (C) 1992, 1993, 1994, 1995
 * Remy Card (card@masi.ibp.fr)
 * Laboratoire MASI - Institut Blaise Pascal
 * Universite Pierre et Marie Curie (Paris VI)
 *
 *  from
 *
 *  linux/fs/minix/inode.c
 *
 *  Copyright (C) 1991, 1992  Linus Torvalds
 *
 *  64-bit file support on 64-bit platforms by Jakub Jelinek
 *	(jj@sunsite.ms.mff.cuni.cz)
 *
19
 *  Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
20 21 22
 */

#include <linux/fs.h>
23
#include <linux/mount.h>
24 25 26
#include <linux/time.h>
#include <linux/highuid.h>
#include <linux/pagemap.h>
27
#include <linux/dax.h>
28 29 30 31
#include <linux/quotaops.h>
#include <linux/string.h>
#include <linux/buffer_head.h>
#include <linux/writeback.h>
32
#include <linux/pagevec.h>
33
#include <linux/mpage.h>
34
#include <linux/namei.h>
35 36
#include <linux/uio.h>
#include <linux/bio.h>
37
#include <linux/workqueue.h>
38
#include <linux/kernel.h>
39
#include <linux/printk.h>
40
#include <linux/slab.h>
41
#include <linux/bitops.h>
42
#include <linux/iomap.h>
43
#include <linux/iversion.h>
44

45
#include "ext4_jbd2.h"
46 47
#include "xattr.h"
#include "acl.h"
48
#include "truncate.h"
49

50 51
#include <trace/events/ext4.h>

52 53 54 55 56
static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw,
			      struct ext4_inode_info *ei)
{
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
	__u32 csum;
57 58 59
	__u16 dummy_csum = 0;
	int offset = offsetof(struct ext4_inode, i_checksum_lo);
	unsigned int csum_size = sizeof(dummy_csum);
60

61 62 63 64 65
	csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, offset);
	csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum, csum_size);
	offset += csum_size;
	csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
			   EXT4_GOOD_OLD_INODE_SIZE - offset);
66

67 68 69 70 71 72 73 74 75 76
	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
		offset = offsetof(struct ext4_inode, i_checksum_hi);
		csum = ext4_chksum(sbi, csum, (__u8 *)raw +
				   EXT4_GOOD_OLD_INODE_SIZE,
				   offset - EXT4_GOOD_OLD_INODE_SIZE);
		if (EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) {
			csum = ext4_chksum(sbi, csum, (__u8 *)&dummy_csum,
					   csum_size);
			offset += csum_size;
		}
77 78
		csum = ext4_chksum(sbi, csum, (__u8 *)raw + offset,
				   EXT4_INODE_SIZE(inode->i_sb) - offset);
79 80 81 82 83 84 85 86 87 88 89 90
	}

	return csum;
}

static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw,
				  struct ext4_inode_info *ei)
{
	__u32 provided, calculated;

	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
	    cpu_to_le32(EXT4_OS_LINUX) ||
91
	    !ext4_has_metadata_csum(inode->i_sb))
92 93 94 95 96 97 98 99 100 101 102 103 104
		return 1;

	provided = le16_to_cpu(raw->i_checksum_lo);
	calculated = ext4_inode_csum(inode, raw, ei);
	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
		provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16;
	else
		calculated &= 0xFFFF;

	return provided == calculated;
}

105 106
void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw,
			 struct ext4_inode_info *ei)
107 108 109 110 111
{
	__u32 csum;

	if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
	    cpu_to_le32(EXT4_OS_LINUX) ||
112
	    !ext4_has_metadata_csum(inode->i_sb))
113 114 115 116 117 118 119 120 121
		return;

	csum = ext4_inode_csum(inode, raw, ei);
	raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF);
	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
	    EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi))
		raw->i_checksum_hi = cpu_to_le16(csum >> 16);
}

122 123 124
static inline int ext4_begin_ordered_truncate(struct inode *inode,
					      loff_t new_size)
{
125
	trace_ext4_begin_ordered_truncate(inode, new_size);
126 127 128 129 130 131 132 133 134 135 136
	/*
	 * If jinode is zero, then we never opened the file for
	 * writing, so there's no need to call
	 * jbd2_journal_begin_ordered_truncate() since there's no
	 * outstanding writes we need to flush.
	 */
	if (!EXT4_I(inode)->jinode)
		return 0;
	return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
						   EXT4_I(inode)->jinode,
						   new_size);
137 138
}

139 140
static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
				  int pextents);
141

142 143
/*
 * Test whether an inode is a fast symlink.
144
 * A fast symlink has its symlink data stored in ext4_inode_info->i_data.
145
 */
146
int ext4_inode_is_fast_symlink(struct inode *inode)
147
{
148 149 150 151 152 153 154 155 156
	if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)) {
		int ea_blocks = EXT4_I(inode)->i_file_acl ?
				EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0;

		if (ext4_has_inline_data(inode))
			return 0;

		return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
	}
157 158
	return S_ISLNK(inode->i_mode) && inode->i_size &&
	       (inode->i_size < EXT4_N_BLOCKS * 4);
159 160 161 162 163
}

/*
 * Called at the last iput() if i_nlink is zero.
 */
Al Viro's avatar
Al Viro committed
164
void ext4_evict_inode(struct inode *inode)
165 166
{
	handle_t *handle;
167
	int err;
168 169 170 171 172 173
	/*
	 * Credits for final inode cleanup and freeing:
	 * sb + inode (ext4_orphan_del()), block bitmap, group descriptor
	 * (xattr block freeing), bitmap, group descriptor (inode freeing)
	 */
	int extra_credits = 6;
174
	struct ext4_xattr_inode_array *ea_inode_array = NULL;
175
	bool freeze_protected = false;
176

177
	trace_ext4_evict_inode(inode);
178

179 180
	if (EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL)
		ext4_evict_ea_inode(inode);
Al Viro's avatar
Al Viro committed
181
	if (inode->i_nlink) {
182
		truncate_inode_pages_final(&inode->i_data);
Jan Kara's avatar
Jan Kara committed
183

Al Viro's avatar
Al Viro committed
184 185 186
		goto no_delete;
	}

187 188 189
	if (is_bad_inode(inode))
		goto no_delete;
	dquot_initialize(inode);
190

191 192
	if (ext4_should_order_data(inode))
		ext4_begin_ordered_truncate(inode, 0);
193
	truncate_inode_pages_final(&inode->i_data);
194

195 196
	/*
	 * For inodes with journalled data, transaction commit could have
197 198 199 200
	 * dirtied the inode. And for inodes with dioread_nolock, unwritten
	 * extents converting worker could merge extents and also have dirtied
	 * the inode. Flush worker is ignoring it because of I_FREEING flag but
	 * we still need to remove the inode from the writeback lists.
201
	 */
202
	if (!list_empty_careful(&inode->i_io_list))
203 204
		inode_io_list_del(inode);

205 206
	/*
	 * Protect us against freezing - iput() caller didn't have to have any
207 208 209
	 * protection against it. When we are in a running transaction though,
	 * we are already protected against freezing and we cannot grab further
	 * protection due to lock ordering constraints.
210
	 */
211 212 213 214
	if (!ext4_journal_current_handle()) {
		sb_start_intwrite(inode->i_sb);
		freeze_protected = true;
	}
Andreas Dilger's avatar
Andreas Dilger committed
215

216 217 218
	if (!IS_NOQUOTA(inode))
		extra_credits += EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb);

219 220 221 222
	/*
	 * Block bitmap, group descriptor, and inode are accounted in both
	 * ext4_blocks_for_truncate() and extra_credits. So subtract 3.
	 */
223
	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE,
224
			 ext4_blocks_for_truncate(inode) + extra_credits - 3);
225
	if (IS_ERR(handle)) {
226
		ext4_std_error(inode->i_sb, PTR_ERR(handle));
227 228 229 230 231
		/*
		 * If we're going to skip the normal cleanup, we still need to
		 * make sure that the in-core orphan linked list is properly
		 * cleaned up.
		 */
232
		ext4_orphan_del(NULL, inode);
233 234
		if (freeze_protected)
			sb_end_intwrite(inode->i_sb);
235 236
		goto no_delete;
	}
237

238
	if (IS_SYNC(inode))
239
		ext4_handle_sync(handle);
240 241 242 243 244 245 246 247 248 249

	/*
	 * Set inode->i_size to 0 before calling ext4_truncate(). We need
	 * special handling of symlinks here because i_size is used to
	 * determine whether ext4_inode_info->i_data contains symlink data or
	 * block mappings. Setting i_size to 0 will remove its fast symlink
	 * status. Erase i_data so that it becomes a valid empty block map.
	 */
	if (ext4_inode_is_fast_symlink(inode))
		memset(EXT4_I(inode)->i_data, 0, sizeof(EXT4_I(inode)->i_data));
250
	inode->i_size = 0;
251 252
	err = ext4_mark_inode_dirty(handle, inode);
	if (err) {
253
		ext4_warning(inode->i_sb,
254 255 256
			     "couldn't mark inode dirty (err %d)", err);
		goto stop_handle;
	}
257 258 259
	if (inode->i_blocks) {
		err = ext4_truncate(inode);
		if (err) {
260 261 262
			ext4_error_err(inode->i_sb, -err,
				       "couldn't truncate inode %lu (err %d)",
				       inode->i_ino, err);
263 264 265
			goto stop_handle;
		}
	}
266

267 268 269 270 271 272 273 274
	/* Remove xattr references. */
	err = ext4_xattr_delete_inode(handle, inode, &ea_inode_array,
				      extra_credits);
	if (err) {
		ext4_warning(inode->i_sb, "xattr delete (err %d)", err);
stop_handle:
		ext4_journal_stop(handle);
		ext4_orphan_del(NULL, inode);
275 276
		if (freeze_protected)
			sb_end_intwrite(inode->i_sb);
277 278
		ext4_xattr_inode_array_free(ea_inode_array);
		goto no_delete;
279 280
	}

281
	/*
282
	 * Kill off the orphan record which ext4_truncate created.
283
	 * AKPM: I think this can be inside the above `if'.
284
	 * Note that ext4_orphan_del() has to be able to cope with the
285
	 * deletion of a non-existent orphan - this is because we don't
286
	 * know if ext4_truncate() actually created an orphan record.
287 288
	 * (Well, we could do this if we need to, but heck - it works)
	 */
289
	ext4_orphan_del(handle, inode);
290
	EXT4_I(inode)->i_dtime	= (__u32)ktime_get_real_seconds();
291 292 293 294 295 296 297 298

	/*
	 * One subtle ordering requirement: if anything has gone wrong
	 * (transaction abort, IO errors, whatever), then we can still
	 * do these next steps (the fs will already have been marked as
	 * having errors), but we can't free the inode if the mark_dirty
	 * fails.
	 */
299
	if (ext4_mark_inode_dirty(handle, inode))
300
		/* If that failed, just do the required in-core inode clear. */
Al Viro's avatar
Al Viro committed
301
		ext4_clear_inode(inode);
302
	else
303 304
		ext4_free_inode(handle, inode);
	ext4_journal_stop(handle);
305 306
	if (freeze_protected)
		sb_end_intwrite(inode->i_sb);
307
	ext4_xattr_inode_array_free(ea_inode_array);
308 309
	return;
no_delete:
310 311 312 313 314 315
	/*
	 * Check out some where else accidentally dirty the evicting inode,
	 * which may probably cause inode use-after-free issues later.
	 */
	WARN_ON_ONCE(!list_empty_careful(&inode->i_io_list));

316
	if (!list_empty(&EXT4_I(inode)->i_fc_list))
317
		ext4_fc_mark_ineligible(inode->i_sb, EXT4_FC_REASON_NOMEM, NULL);
Al Viro's avatar
Al Viro committed
318
	ext4_clear_inode(inode);	/* We must guarantee clearing of inode... */
319 320
}

321 322
#ifdef CONFIG_QUOTA
qsize_t *ext4_get_reserved_space(struct inode *inode)
323
{
324
	return &EXT4_I(inode)->i_reserved_quota;
325
}
326
#endif
327

328 329 330 331
/*
 * Called with i_data_sem down, which is important since we can call
 * ext4_discard_preallocations() from here.
 */
332 333
void ext4_da_update_reserve_space(struct inode *inode,
					int used, int quota_claim)
334 335
{
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
336 337 338
	struct ext4_inode_info *ei = EXT4_I(inode);

	spin_lock(&ei->i_block_reservation_lock);
339
	trace_ext4_da_update_reserve_space(inode, used, quota_claim);
340
	if (unlikely(used > ei->i_reserved_data_blocks)) {
341
		ext4_warning(inode->i_sb, "%s: ino %lu, used %d "
342
			 "with only %d reserved data blocks",
343 344 345 346 347
			 __func__, inode->i_ino, used,
			 ei->i_reserved_data_blocks);
		WARN_ON(1);
		used = ei->i_reserved_data_blocks;
	}
348

349 350
	/* Update per-inode reservations */
	ei->i_reserved_data_blocks -= used;
351
	percpu_counter_sub(&sbi->s_dirtyclusters_counter, used);
352

353
	spin_unlock(&ei->i_block_reservation_lock);
354

355 356
	/* Update quota subsystem for data blocks */
	if (quota_claim)
357
		dquot_claim_block(inode, EXT4_C2B(sbi, used));
358
	else {
359 360 361
		/*
		 * We did fallocate with an offset that is already delayed
		 * allocated. So on delayed allocated writeback we should
362
		 * not re-claim the quota for fallocated blocks.
363
		 */
364
		dquot_release_reservation_block(inode, EXT4_C2B(sbi, used));
365
	}
366 367 368 369 370 371

	/*
	 * If we have done all the pending block allocations and if
	 * there aren't any writers on the inode, we can discard the
	 * inode's preallocations.
	 */
372
	if ((ei->i_reserved_data_blocks == 0) &&
373
	    !inode_is_open_for_write(inode))
374
		ext4_discard_preallocations(inode, 0);
375 376
}

377
static int __check_block_validity(struct inode *inode, const char *func,
378 379
				unsigned int line,
				struct ext4_map_blocks *map)
380
{
381 382 383 384
	if (ext4_has_feature_journal(inode->i_sb) &&
	    (inode->i_ino ==
	     le32_to_cpu(EXT4_SB(inode->i_sb)->s_es->s_journal_inum)))
		return 0;
385
	if (!ext4_inode_block_valid(inode, map->m_pblk, map->m_len)) {
386
		ext4_error_inode(inode, func, line, map->m_pblk,
387
				 "lblock %lu mapped to illegal pblock %llu "
388
				 "(length %d)", (unsigned long) map->m_lblk,
389
				 map->m_pblk, map->m_len);
390
		return -EFSCORRUPTED;
391 392 393 394
	}
	return 0;
}

Jan Kara's avatar
Jan Kara committed
395 396 397 398 399
int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk,
		       ext4_lblk_t len)
{
	int ret;

400
	if (IS_ENCRYPTED(inode) && S_ISREG(inode->i_mode))
401
		return fscrypt_zeroout_range(inode, lblk, pblk, len);
Jan Kara's avatar
Jan Kara committed
402 403 404 405 406 407 408 409

	ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS);
	if (ret > 0)
		ret = 0;

	return ret;
}

410
#define check_block_validity(inode, map)	\
411
	__check_block_validity((inode), __func__, __LINE__, (map))
412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
#ifdef ES_AGGRESSIVE_TEST
static void ext4_map_blocks_es_recheck(handle_t *handle,
				       struct inode *inode,
				       struct ext4_map_blocks *es_map,
				       struct ext4_map_blocks *map,
				       int flags)
{
	int retval;

	map->m_flags = 0;
	/*
	 * There is a race window that the result is not the same.
	 * e.g. xfstests #223 when dioread_nolock enables.  The reason
	 * is that we lookup a block mapping in extent status tree with
	 * out taking i_data_sem.  So at the time the unwritten extent
	 * could be converted.
	 */
430
	down_read(&EXT4_I(inode)->i_data_sem);
431
	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
432
		retval = ext4_ext_map_blocks(handle, inode, map, 0);
433
	} else {
434
		retval = ext4_ind_map_blocks(handle, inode, map, 0);
435
	}
436
	up_read((&EXT4_I(inode)->i_data_sem));
437 438 439 440 441 442 443 444

	/*
	 * We don't check m_len because extent will be collpased in status
	 * tree.  So the m_len might not equal.
	 */
	if (es_map->m_lblk != map->m_lblk ||
	    es_map->m_flags != map->m_flags ||
	    es_map->m_pblk != map->m_pblk) {
445
		printk("ES cache assertion failed for inode: %lu "
446 447 448 449 450 451 452 453 454 455
		       "es_cached ex [%d/%d/%llu/%x] != "
		       "found ex [%d/%d/%llu/%x] retval %d flags %x\n",
		       inode->i_ino, es_map->m_lblk, es_map->m_len,
		       es_map->m_pblk, es_map->m_flags, map->m_lblk,
		       map->m_len, map->m_pblk, map->m_flags,
		       retval, flags);
	}
}
#endif /* ES_AGGRESSIVE_TEST */

456
/*
457
 * The ext4_map_blocks() function tries to look up the requested blocks,
458
 * and returns if the blocks are already mapped.
459 460 461 462 463
 *
 * Otherwise it takes the write lock of the i_data_sem and allocate blocks
 * and store the allocated blocks in the result buffer head and mark it
 * mapped.
 *
464 465
 * If file type is extents based, it will call ext4_ext_map_blocks(),
 * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
466 467
 * based files
 *
468 469 470
 * On success, it returns the number of blocks being mapped or allocated.  if
 * create==0 and the blocks are pre-allocated and unwritten, the resulting @map
 * is marked as unwritten. If the create == 1, it will mark @map as mapped.
471 472
 *
 * It returns 0 if plain look up failed (blocks have not been allocated), in
473 474
 * that case, @map is returned as unmapped but we still do fill map->m_len to
 * indicate the length of a hole starting at map->m_lblk.
475 476 477
 *
 * It returns the error in case of allocation failure.
 */
478 479
int ext4_map_blocks(handle_t *handle, struct inode *inode,
		    struct ext4_map_blocks *map, int flags)
480
{
481
	struct extent_status es;
482
	int retval;
483
	int ret = 0;
484 485 486 487 488
#ifdef ES_AGGRESSIVE_TEST
	struct ext4_map_blocks orig_map;

	memcpy(&orig_map, map, sizeof(*map));
#endif
489

490
	map->m_flags = 0;
491 492
	ext_debug(inode, "flag 0x%x, max_blocks %u, logical block %lu\n",
		  flags, map->m_len, (unsigned long) map->m_lblk);
493

494 495 496 497 498 499
	/*
	 * ext4_map_blocks returns an int, and m_len is an unsigned int
	 */
	if (unlikely(map->m_len > INT_MAX))
		map->m_len = INT_MAX;

500 501
	/* We can handle the block number less than EXT_MAX_BLOCKS */
	if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS))
502
		return -EFSCORRUPTED;
503

504
	/* Lookup extent status tree firstly */
505 506
	if (!(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY) &&
	    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
507 508 509 510 511 512 513 514 515 516
		if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) {
			map->m_pblk = ext4_es_pblock(&es) +
					map->m_lblk - es.es_lblk;
			map->m_flags |= ext4_es_is_written(&es) ?
					EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN;
			retval = es.es_len - (map->m_lblk - es.es_lblk);
			if (retval > map->m_len)
				retval = map->m_len;
			map->m_len = retval;
		} else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) {
517 518 519 520 521
			map->m_pblk = 0;
			retval = es.es_len - (map->m_lblk - es.es_lblk);
			if (retval > map->m_len)
				retval = map->m_len;
			map->m_len = retval;
522 523
			retval = 0;
		} else {
524
			BUG();
525
		}
526 527 528

		if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
			return retval;
529 530 531 532
#ifdef ES_AGGRESSIVE_TEST
		ext4_map_blocks_es_recheck(handle, inode, map,
					   &orig_map, flags);
#endif
533 534
		goto found;
	}
535 536 537 538 539 540
	/*
	 * In the query cache no-wait mode, nothing we can do more if we
	 * cannot find extent in the cache.
	 */
	if (flags & EXT4_GET_BLOCKS_CACHED_NOWAIT)
		return 0;
541

542
	/*
543 544
	 * Try to see if we can get the block without requesting a new
	 * file system block.
545
	 */
546
	down_read(&EXT4_I(inode)->i_data_sem);
547
	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
548
		retval = ext4_ext_map_blocks(handle, inode, map, 0);
549
	} else {
550
		retval = ext4_ind_map_blocks(handle, inode, map, 0);
551
	}
552
	if (retval > 0) {
553
		unsigned int status;
554

555 556 557 558 559 560
		if (unlikely(retval != map->m_len)) {
			ext4_warning(inode->i_sb,
				     "ES len assertion failed for inode "
				     "%lu: retval %d != map->m_len %d",
				     inode->i_ino, retval, map->m_len);
			WARN_ON(1);
561 562
		}

563 564 565
		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
566
		    !(status & EXTENT_STATUS_WRITTEN) &&
567 568
		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
				       map->m_lblk + map->m_len - 1))
569
			status |= EXTENT_STATUS_DELAYED;
570 571
		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
				      map->m_pblk, status);
572
	}
573
	up_read((&EXT4_I(inode)->i_data_sem));
574

575
found:
576
	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
577
		ret = check_block_validity(inode, map);
578 579 580 581
		if (ret != 0)
			return ret;
	}

582
	/* If it is only a block(s) look up */
583
	if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
584 585 586 587 588 589
		return retval;

	/*
	 * Returns if the blocks have already allocated
	 *
	 * Note that if blocks have been preallocated
590
	 * ext4_ext_get_block() returns the create = 0
591 592
	 * with buffer head unmapped.
	 */
593
	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
594 595 596 597 598 599 600
		/*
		 * If we need to convert extent to unwritten
		 * we continue and do the actual work in
		 * ext4_ext_map_blocks()
		 */
		if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN))
			return retval;
601

602
	/*
603 604
	 * Here we clear m_flags because after allocating an new extent,
	 * it will be set again.
605
	 */
606
	map->m_flags &= ~EXT4_MAP_FLAGS;
607

608
	/*
609
	 * New blocks allocate and/or writing to unwritten extent
610
	 * will possibly result in updating i_data, so we take
611
	 * the write lock of i_data_sem, and call get_block()
612
	 * with create == 1 flag.
613
	 */
614
	down_write(&EXT4_I(inode)->i_data_sem);
615

616 617 618 619
	/*
	 * We need to check for EXT4 here because migrate
	 * could have changed the inode type in between
	 */
620
	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
621
		retval = ext4_ext_map_blocks(handle, inode, map, flags);
622
	} else {
623
		retval = ext4_ind_map_blocks(handle, inode, map, flags);
624

625
		if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
626 627 628 629 630
			/*
			 * We allocated new blocks which will result in
			 * i_data's format changing.  Force the migrate
			 * to fail by clearing migrate flags
			 */
631
			ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
632
		}
633
	}
634

635
	if (retval > 0) {
636
		unsigned int status;
637

638 639 640 641 642 643
		if (unlikely(retval != map->m_len)) {
			ext4_warning(inode->i_sb,
				     "ES len assertion failed for inode "
				     "%lu: retval %d != map->m_len %d",
				     inode->i_ino, retval, map->m_len);
			WARN_ON(1);
644 645
		}

646 647 648
		/*
		 * We have to zeroout blocks before inserting them into extent
		 * status tree. Otherwise someone could look them up there and
649 650 651
		 * use them before they are really zeroed. We also have to
		 * unmap metadata before zeroing as otherwise writeback can
		 * overwrite zeros with stale data from block device.
652 653 654 655 656 657 658 659 660 661 662 663
		 */
		if (flags & EXT4_GET_BLOCKS_ZERO &&
		    map->m_flags & EXT4_MAP_MAPPED &&
		    map->m_flags & EXT4_MAP_NEW) {
			ret = ext4_issue_zeroout(inode, map->m_lblk,
						 map->m_pblk, map->m_len);
			if (ret) {
				retval = ret;
				goto out_sem;
			}
		}

664 665 666 667 668
		/*
		 * If the extent has been zeroed out, we don't need to update
		 * extent status tree.
		 */
		if ((flags & EXT4_GET_BLOCKS_PRE_IO) &&
669
		    ext4_es_lookup_extent(inode, map->m_lblk, NULL, &es)) {
670
			if (ext4_es_is_written(&es))
671
				goto out_sem;
672
		}
673 674 675
		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
		if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) &&
676
		    !(status & EXTENT_STATUS_WRITTEN) &&
677 678
		    ext4_es_scan_range(inode, &ext4_es_is_delayed, map->m_lblk,
				       map->m_lblk + map->m_len - 1))
679
			status |= EXTENT_STATUS_DELAYED;
680 681
		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
				      map->m_pblk, status);
682 683
	}

684
out_sem:
685
	up_write((&EXT4_I(inode)->i_data_sem));
686
	if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
687
		ret = check_block_validity(inode, map);
688 689
		if (ret != 0)
			return ret;
690 691 692 693 694 695 696 697 698

		/*
		 * Inodes with freshly allocated blocks where contents will be
		 * visible after transaction commit must be on transaction's
		 * ordered data list.
		 */
		if (map->m_flags & EXT4_MAP_NEW &&
		    !(map->m_flags & EXT4_MAP_UNWRITTEN) &&
		    !(flags & EXT4_GET_BLOCKS_ZERO) &&
699
		    !ext4_is_quota_file(inode) &&
700
		    ext4_should_order_data(inode)) {
701 702 703 704
			loff_t start_byte =
				(loff_t)map->m_lblk << inode->i_blkbits;
			loff_t length = (loff_t)map->m_len << inode->i_blkbits;

705
			if (flags & EXT4_GET_BLOCKS_IO_SUBMIT)
706 707
				ret = ext4_jbd2_inode_add_wait(handle, inode,
						start_byte, length);
708
			else
709 710
				ret = ext4_jbd2_inode_add_write(handle, inode,
						start_byte, length);
711 712 713
			if (ret)
				return ret;
		}
714
	}
715 716 717 718
	if (retval > 0 && (map->m_flags & EXT4_MAP_UNWRITTEN ||
				map->m_flags & EXT4_MAP_MAPPED))
		ext4_fc_track_range(handle, inode, map->m_lblk,
					map->m_lblk + map->m_len - 1);
719
	if (retval < 0)
720
		ext_debug(inode, "failed with err %d\n", retval);
721 722 723
	return retval;
}

Jan Kara's avatar
Jan Kara committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
/*
 * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages
 * we have to be careful as someone else may be manipulating b_state as well.
 */
static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags)
{
	unsigned long old_state;
	unsigned long new_state;

	flags &= EXT4_MAP_FLAGS;

	/* Dummy buffer_head? Set non-atomically. */
	if (!bh->b_page) {
		bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags;
		return;
	}
	/*
	 * Someone else may be modifying b_state. Be careful! This is ugly but
	 * once we get rid of using bh as a container for mapping information
	 * to pass to / from get_block functions, this can go away.
	 */
745
	old_state = READ_ONCE(bh->b_state);
Jan Kara's avatar
Jan Kara committed
746 747
	do {
		new_state = (old_state & ~EXT4_MAP_FLAGS) | flags;
748
	} while (unlikely(!try_cmpxchg(&bh->b_state, &old_state, new_state)));
Jan Kara's avatar
Jan Kara committed
749 750
}

751 752
static int _ext4_get_block(struct inode *inode, sector_t iblock,
			   struct buffer_head *bh, int flags)
753
{
754
	struct ext4_map_blocks map;
755
	int ret = 0;
756

757 758 759
	if (ext4_has_inline_data(inode))
		return -ERANGE;

760 761 762
	map.m_lblk = iblock;
	map.m_len = bh->b_size >> inode->i_blkbits;

763 764
	ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map,
			      flags);
Jan Kara's avatar
Jan Kara committed
765
	if (ret > 0) {
766
		map_bh(bh, inode->i_sb, map.m_pblk);
Jan Kara's avatar
Jan Kara committed
767
		ext4_update_bh_state(bh, map.m_flags);
768
		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
Jan Kara's avatar
Jan Kara committed
769
		ret = 0;
770 771 772
	} else if (ret == 0) {
		/* hole case, need to fill in bh->b_size */
		bh->b_size = inode->i_sb->s_blocksize * map.m_len;
773 774 775 776
	}
	return ret;
}

777 778 779 780 781 782 783
int ext4_get_block(struct inode *inode, sector_t iblock,
		   struct buffer_head *bh, int create)
{
	return _ext4_get_block(inode, iblock, bh,
			       create ? EXT4_GET_BLOCKS_CREATE : 0);
}

784 785 786 787 788 789 790 791
/*
 * Get block function used when preparing for buffered write if we require
 * creating an unwritten extent if blocks haven't been allocated.  The extent
 * will be converted to written after the IO is complete.
 */
int ext4_get_block_unwritten(struct inode *inode, sector_t iblock,
			     struct buffer_head *bh_result, int create)
{
792 793
	int ret = 0;

794 795
	ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n",
		   inode->i_ino, create);
796
	ret = _ext4_get_block(inode, iblock, bh_result,
797
			       EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT);
798 799 800 801 802 803 804 805 806 807

	/*
	 * If the buffer is marked unwritten, mark it as new to make sure it is
	 * zeroed out correctly in case of partial writes. Otherwise, there is
	 * a chance of stale data getting exposed.
	 */
	if (ret == 0 && buffer_unwritten(bh_result))
		set_buffer_new(bh_result);

	return ret;
808 809
}

810 811 812
/* Maximum number of blocks we map for direct IO at once. */
#define DIO_MAX_BLOCKS 4096

813 814 815
/*
 * `handle' can be NULL if create is zero
 */
816
struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
817
				ext4_lblk_t block, int map_flags)
818
{
819 820
	struct ext4_map_blocks map;
	struct buffer_head *bh;
821
	int create = map_flags & EXT4_GET_BLOCKS_CREATE;
822
	bool nowait = map_flags & EXT4_GET_BLOCKS_CACHED_NOWAIT;
823
	int err;
824

825 826
	ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
		    || handle != NULL || create == 0);
827
	ASSERT(create == 0 || !nowait);
828

829 830
	map.m_lblk = block;
	map.m_len = 1;
831
	err = ext4_map_blocks(handle, inode, &map, map_flags);
832

833 834
	if (err == 0)
		return create ? ERR_PTR(-ENOSPC) : NULL;
835
	if (err < 0)
836
		return ERR_PTR(err);
837

838 839 840
	if (nowait)
		return sb_find_get_block(inode->i_sb, map.m_pblk);

841
	bh = sb_getblk(inode->i_sb, map.m_pblk);
842 843
	if (unlikely(!bh))
		return ERR_PTR(-ENOMEM);
844
	if (map.m_flags & EXT4_MAP_NEW) {
845 846 847
		ASSERT(create != 0);
		ASSERT((EXT4_SB(inode->i_sb)->s_mount_state & EXT4_FC_REPLAY)
			    || (handle != NULL));
848

849 850 851 852 853 854 855 856 857
		/*
		 * Now that we do not always journal data, we should
		 * keep in mind whether this should always journal the
		 * new buffer as metadata.  For now, regular file
		 * writes use ext4_get_block instead, so it's not a
		 * problem.
		 */
		lock_buffer(bh);
		BUFFER_TRACE(bh, "call get_create_access");
858 859
		err = ext4_journal_get_create_access(handle, inode->i_sb, bh,
						     EXT4_JTR_NONE);
860 861 862 863 864
		if (unlikely(err)) {
			unlock_buffer(bh);
			goto errout;
		}
		if (!buffer_uptodate(bh)) {
865 866
			memset(bh->b_data, 0, inode->i_sb->s_blocksize);
			set_buffer_uptodate(bh);
867
		}
868 869 870
		unlock_buffer(bh);
		BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
		err = ext4_handle_dirty_metadata(handle, inode, bh);
871 872 873
		if (unlikely(err))
			goto errout;
	} else
874 875
		BUFFER_TRACE(bh, "not a new buffer");
	return bh;
876 877 878
errout:
	brelse(bh);
	return ERR_PTR(err);
879 880
}

881
struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
882
			       ext4_lblk_t block, int map_flags)
883
{
884
	struct buffer_head *bh;
885
	int ret;
886

887
	bh = ext4_getblk(handle, inode, block, map_flags);
888
	if (IS_ERR(bh))
889
		return bh;
890
	if (!bh || ext4_buffer_uptodate(bh))
891
		return bh;
892 893 894 895 896 897 898

	ret = ext4_read_bh_lock(bh, REQ_META | REQ_PRIO, true);
	if (ret) {
		put_bh(bh);
		return ERR_PTR(ret);
	}
	return bh;
899 900
}

901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
/* Read a contiguous batch of blocks. */
int ext4_bread_batch(struct inode *inode, ext4_lblk_t block, int bh_count,
		     bool wait, struct buffer_head **bhs)
{
	int i, err;

	for (i = 0; i < bh_count; i++) {
		bhs[i] = ext4_getblk(NULL, inode, block + i, 0 /* map_flags */);
		if (IS_ERR(bhs[i])) {
			err = PTR_ERR(bhs[i]);
			bh_count = i;
			goto out_brelse;
		}
	}

	for (i = 0; i < bh_count; i++)
		/* Note that NULL bhs[i] is valid because of holes. */
918 919
		if (bhs[i] && !ext4_buffer_uptodate(bhs[i]))
			ext4_read_bh_lock(bhs[i], REQ_META | REQ_PRIO, false);
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943

	if (!wait)
		return 0;

	for (i = 0; i < bh_count; i++)
		if (bhs[i])
			wait_on_buffer(bhs[i]);

	for (i = 0; i < bh_count; i++) {
		if (bhs[i] && !buffer_uptodate(bhs[i])) {
			err = -EIO;
			goto out_brelse;
		}
	}
	return 0;

out_brelse:
	for (i = 0; i < bh_count; i++) {
		brelse(bhs[i]);
		bhs[i] = NULL;
	}
	return err;
}

944
int ext4_walk_page_buffers(handle_t *handle, struct inode *inode,
945 946 947 948
			   struct buffer_head *head,
			   unsigned from,
			   unsigned to,
			   int *partial,
949
			   int (*fn)(handle_t *handle, struct inode *inode,
950
				     struct buffer_head *bh))
951 952 953 954 955 956 957
{
	struct buffer_head *bh;
	unsigned block_start, block_end;
	unsigned blocksize = head->b_size;
	int err, ret = 0;
	struct buffer_head *next;

958 959
	for (bh = head, block_start = 0;
	     ret == 0 && (bh != head || !block_start);
960
	     block_start = block_end, bh = next) {
961 962 963 964 965 966 967
		next = bh->b_this_page;
		block_end = block_start + blocksize;
		if (block_end <= from || block_start >= to) {
			if (partial && !buffer_uptodate(bh))
				*partial = 1;
			continue;
		}
968
		err = (*fn)(handle, inode, bh);
969 970 971 972 973 974
		if (!ret)
			ret = err;
	}
	return ret;
}

975 976 977 978 979 980 981 982 983 984 985 986
/*
 * Helper for handling dirtying of journalled data. We also mark the folio as
 * dirty so that writeback code knows about this page (and inode) contains
 * dirty data. ext4_writepages() then commits appropriate transaction to
 * make data stable.
 */
static int ext4_dirty_journalled_data(handle_t *handle, struct buffer_head *bh)
{
	folio_mark_dirty(bh->b_folio);
	return ext4_handle_dirty_metadata(handle, NULL, bh);
}

987
int do_journal_get_write_access(handle_t *handle, struct inode *inode,
988
				struct buffer_head *bh)
989
{
990 991 992
	int dirty = buffer_dirty(bh);
	int ret;

993 994
	if (!buffer_mapped(bh) || buffer_freed(bh))
		return 0;
995
	/*
996
	 * __block_write_begin() could have dirtied some buffers. Clean
997 998
	 * the dirty bit as jbd2_journal_get_write_access() could complain
	 * otherwise about fs integrity issues. Setting of the dirty bit
999
	 * by __block_write_begin() isn't a real problem here as we clear
1000 1001 1002 1003 1004
	 * the bit before releasing a page lock and thus writeback cannot
	 * ever write the buffer.
	 */
	if (dirty)
		clear_buffer_dirty(bh);
1005
	BUFFER_TRACE(bh, "get write access");
1006 1007
	ret = ext4_journal_get_write_access(handle, inode->i_sb, bh,
					    EXT4_JTR_NONE);
1008
	if (!ret && dirty)
1009
		ret = ext4_dirty_journalled_data(handle, bh);
1010
	return ret;
1011 1012
}

1013
#ifdef CONFIG_FS_ENCRYPTION
1014
static int ext4_block_write_begin(struct folio *folio, loff_t pos, unsigned len,
1015 1016
				  get_block_t *get_block)
{
1017
	unsigned from = pos & (PAGE_SIZE - 1);
1018
	unsigned to = from + len;
1019
	struct inode *inode = folio->mapping->host;
1020 1021 1022 1023 1024
	unsigned block_start, block_end;
	sector_t block;
	int err = 0;
	unsigned blocksize = inode->i_sb->s_blocksize;
	unsigned bbits;
1025 1026 1027
	struct buffer_head *bh, *head, *wait[2];
	int nr_wait = 0;
	int i;
1028

1029
	BUG_ON(!folio_test_locked(folio));
1030 1031
	BUG_ON(from > PAGE_SIZE);
	BUG_ON(to > PAGE_SIZE);
1032 1033
	BUG_ON(from > to);

1034
	head = folio_buffers(folio);
1035
	if (!head)
1036
		head = create_empty_buffers(folio, blocksize, 0);
1037
	bbits = ilog2(blocksize);
1038
	block = (sector_t)folio->index << (PAGE_SHIFT - bbits);
1039 1040 1041 1042 1043

	for (bh = head, block_start = 0; bh != head || !block_start;
	    block++, block_start = block_end, bh = bh->b_this_page) {
		block_end = block_start + blocksize;
		if (block_end <= from || block_start >= to) {
1044
			if (folio_test_uptodate(folio)) {
1045
				set_buffer_uptodate(bh);
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
			}
			continue;
		}
		if (buffer_new(bh))
			clear_buffer_new(bh);
		if (!buffer_mapped(bh)) {
			WARN_ON(bh->b_size != blocksize);
			err = get_block(inode, block, bh, 1);
			if (err)
				break;
			if (buffer_new(bh)) {
1057
				if (folio_test_uptodate(folio)) {
1058 1059 1060 1061 1062 1063
					clear_buffer_new(bh);
					set_buffer_uptodate(bh);
					mark_buffer_dirty(bh);
					continue;
				}
				if (block_end > to || block_start < from)
1064 1065 1066
					folio_zero_segments(folio, to,
							    block_end,
							    block_start, from);
1067 1068 1069
				continue;
			}
		}
1070
		if (folio_test_uptodate(folio)) {
1071
			set_buffer_uptodate(bh);
1072 1073 1074 1075 1076
			continue;
		}
		if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
		    !buffer_unwritten(bh) &&
		    (block_start < from || block_end > to)) {
1077
			ext4_read_bh_lock(bh, 0, false);
1078
			wait[nr_wait++] = bh;
1079 1080 1081 1082 1083
		}
	}
	/*
	 * If we issued read requests, let them complete.
	 */
1084 1085 1086
	for (i = 0; i < nr_wait; i++) {
		wait_on_buffer(wait[i]);
		if (!buffer_uptodate(wait[i]))
1087 1088
			err = -EIO;
	}
1089
	if (unlikely(err)) {
1090
		folio_zero_new_buffers(folio, from, to);
1091
	} else if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
1092 1093 1094
		for (i = 0; i < nr_wait; i++) {
			int err2;

1095 1096
			err2 = fscrypt_decrypt_pagecache_blocks(folio,
						blocksize, bh_offset(wait[i]));
1097 1098 1099 1100 1101
			if (err2) {
				clear_buffer_uptodate(wait[i]);
				err = err2;
			}
		}
1102 1103
	}

1104 1105 1106 1107
	return err;
}
#endif

1108 1109 1110 1111 1112 1113 1114
/*
 * To preserve ordering, it is essential that the hole instantiation and
 * the data write be encapsulated in a single transaction.  We cannot
 * close off a transaction and start a new one between the ext4_get_block()
 * and the ext4_write_end().  So doing the jbd2_journal_start at the start of
 * ext4_write_begin() is the right place.
 */
Nick Piggin's avatar
Nick Piggin committed
1115
static int ext4_write_begin(struct file *file, struct address_space *mapping,
1116
			    loff_t pos, unsigned len,
1117
			    struct page **pagep, void **fsdata)
1118
{
1119
	struct inode *inode = mapping->host;
1120
	int ret, needed_blocks;
1121 1122
	handle_t *handle;
	int retries = 0;
1123
	struct folio *folio;
1124
	pgoff_t index;
1125
	unsigned from, to;
Nick Piggin's avatar
Nick Piggin committed
1126

1127
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
1128 1129
		return -EIO;

1130
	trace_ext4_write_begin(inode, pos, len);
1131 1132 1133 1134 1135
	/*
	 * Reserve one block more for addition to orphan list in case
	 * we allocate blocks but write fails for some reason
	 */
	needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
1136 1137
	index = pos >> PAGE_SHIFT;
	from = pos & (PAGE_SIZE - 1);
1138
	to = from + len;
1139

1140 1141
	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
		ret = ext4_try_to_write_inline_data(mapping, inode, pos, len,
1142
						    pagep);
1143
		if (ret < 0)
1144 1145 1146
			return ret;
		if (ret == 1)
			return 0;
1147 1148
	}

1149
	/*
1150 1151
	 * __filemap_get_folio() can take a long time if the
	 * system is thrashing due to memory pressure, or if the folio
1152 1153
	 * is being written back.  So grab it first before we start
	 * the transaction handle.  This also allows us to allocate
1154
	 * the folio (if needed) without using GFP_NOFS.
1155 1156
	 */
retry_grab:
1157 1158
	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
					mapping_gfp_mask(mapping));
1159 1160
	if (IS_ERR(folio))
		return PTR_ERR(folio);
1161 1162 1163 1164
	/*
	 * The same as page allocation, we prealloc buffer heads before
	 * starting the handle.
	 */
1165
	if (!folio_buffers(folio))
1166
		create_empty_buffers(folio, inode->i_sb->s_blocksize, 0);
1167

1168
	folio_unlock(folio);
1169 1170

retry_journal:
1171
	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks);
1172
	if (IS_ERR(handle)) {
1173
		folio_put(folio);
1174
		return PTR_ERR(handle);
1175
	}
1176

1177 1178 1179 1180 1181
	folio_lock(folio);
	if (folio->mapping != mapping) {
		/* The folio got truncated from under us */
		folio_unlock(folio);
		folio_put(folio);
1182
		ext4_journal_stop(handle);
1183
		goto retry_grab;
1184
	}
1185 1186
	/* In case writeback began while the folio was unlocked */
	folio_wait_stable(folio);
1187

1188
#ifdef CONFIG_FS_ENCRYPTION
1189
	if (ext4_should_dioread_nolock(inode))
1190
		ret = ext4_block_write_begin(folio, pos, len,
1191
					     ext4_get_block_unwritten);
1192
	else
1193
		ret = ext4_block_write_begin(folio, pos, len, ext4_get_block);
1194
#else
1195
	if (ext4_should_dioread_nolock(inode))
1196
		ret = __block_write_begin(&folio->page, pos, len,
1197
					  ext4_get_block_unwritten);
1198
	else
1199
		ret = __block_write_begin(&folio->page, pos, len, ext4_get_block);
1200
#endif
Nick Piggin's avatar
Nick Piggin committed
1201
	if (!ret && ext4_should_journal_data(inode)) {
1202
		ret = ext4_walk_page_buffers(handle, inode,
1203 1204
					     folio_buffers(folio), from, to,
					     NULL, do_journal_get_write_access);
1205
	}
Nick Piggin's avatar
Nick Piggin committed
1206 1207

	if (ret) {
1208 1209 1210
		bool extended = (pos + len > inode->i_size) &&
				!ext4_verity_in_progress(inode);

1211
		folio_unlock(folio);
1212
		/*
1213
		 * __block_write_begin may have instantiated a few blocks
1214
		 * outside i_size.  Trim these off again. Don't need
1215
		 * i_size_read because we hold i_rwsem.
1216 1217 1218
		 *
		 * Add inode to orphan list in case we crash before
		 * truncate finishes
1219
		 */
1220
		if (extended && ext4_can_truncate(inode))
1221 1222 1223
			ext4_orphan_add(handle, inode);

		ext4_journal_stop(handle);
1224
		if (extended) {
1225
			ext4_truncate_failed_write(inode);
1226
			/*
1227
			 * If truncate failed early the inode might
1228 1229 1230 1231 1232 1233 1234
			 * still be on the orphan list; we need to
			 * make sure the inode is removed from the
			 * orphan list in that case.
			 */
			if (inode->i_nlink)
				ext4_orphan_del(NULL, inode);
		}
Nick Piggin's avatar
Nick Piggin committed
1235

1236 1237 1238
		if (ret == -ENOSPC &&
		    ext4_should_retry_alloc(inode->i_sb, &retries))
			goto retry_journal;
1239
		folio_put(folio);
1240 1241
		return ret;
	}
1242
	*pagep = &folio->page;
1243 1244 1245
	return ret;
}

Nick Piggin's avatar
Nick Piggin committed
1246
/* For write_end() in data=journal mode */
1247 1248
static int write_end_fn(handle_t *handle, struct inode *inode,
			struct buffer_head *bh)
1249
{
1250
	int ret;
1251 1252 1253
	if (!buffer_mapped(bh) || buffer_freed(bh))
		return 0;
	set_buffer_uptodate(bh);
1254
	ret = ext4_dirty_journalled_data(handle, bh);
1255 1256 1257
	clear_buffer_meta(bh);
	clear_buffer_prio(bh);
	return ret;
1258 1259
}

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
/*
 * We need to pick up the new inode size which generic_commit_write gave us
 * `file' can be NULL - eg, when called from page_symlink().
 *
 * ext4 never places buffers on inode->i_mapping->private_list.  metadata
 * buffers are managed internally.
 */
static int ext4_write_end(struct file *file,
			  struct address_space *mapping,
			  loff_t pos, unsigned len, unsigned copied,
			  struct page *page, void *fsdata)
1271
{
1272
	struct folio *folio = page_folio(page);
1273
	handle_t *handle = ext4_journal_current_handle();
1274
	struct inode *inode = mapping->host;
1275
	loff_t old_size = inode->i_size;
1276 1277
	int ret = 0, ret2;
	int i_size_changed = 0;
1278
	bool verity = ext4_verity_in_progress(inode);
1279 1280

	trace_ext4_write_end(inode, pos, len, copied);
1281

1282 1283
	if (ext4_has_inline_data(inode) &&
	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA))
1284 1285
		return ext4_write_inline_data_end(inode, pos, len, copied,
						  folio);
1286 1287

	copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
1288
	/*
1289
	 * it's important to update i_size while still holding folio lock:
1290
	 * page writeout could otherwise come in and zero beyond i_size.
1291 1292 1293
	 *
	 * If FS_IOC_ENABLE_VERITY is running on this inode, then Merkle tree
	 * blocks are being written past EOF, so skip the i_size update.
1294
	 */
1295 1296
	if (!verity)
		i_size_changed = ext4_update_inode_size(inode, pos + copied);
1297 1298
	folio_unlock(folio);
	folio_put(folio);
1299

1300
	if (old_size < pos && !verity)
1301
		pagecache_isize_extended(inode, old_size, pos);
1302
	/*
1303 1304 1305
	 * Don't mark the inode dirty under folio lock. First, it unnecessarily
	 * makes the holding time of folio lock longer. Second, it forces lock
	 * ordering of folio lock and transaction start for journaling
1306 1307
	 * filesystems.
	 */
1308
	if (i_size_changed)
1309
		ret = ext4_mark_inode_dirty(handle, inode);
1310

1311
	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1312 1313 1314 1315 1316
		/* if we have allocated more blocks and copied
		 * less. We will have blocks allocated outside
		 * inode->i_size. So truncate them
		 */
		ext4_orphan_add(handle, inode);
1317

1318
	ret2 = ext4_journal_stop(handle);
1319 1320
	if (!ret)
		ret = ret2;
Nick Piggin's avatar
Nick Piggin committed
1321

1322
	if (pos + len > inode->i_size && !verity) {
1323
		ext4_truncate_failed_write(inode);
1324
		/*
1325
		 * If truncate failed early the inode might still be
1326 1327 1328 1329 1330 1331 1332
		 * on the orphan list; we need to make sure the inode
		 * is removed from the orphan list in that case.
		 */
		if (inode->i_nlink)
			ext4_orphan_del(NULL, inode);
	}

Nick Piggin's avatar
Nick Piggin committed
1333
	return ret ? ret : copied;
1334 1335
}

1336
/*
1337
 * This is a private version of folio_zero_new_buffers() which doesn't
1338
 * set the buffer to be dirty, since in data=journalled mode we need
1339
 * to call ext4_dirty_journalled_data() instead.
1340
 */
1341
static void ext4_journalled_zero_new_buffers(handle_t *handle,
1342
					    struct inode *inode,
1343
					    struct folio *folio,
1344
					    unsigned from, unsigned to)
1345 1346 1347 1348
{
	unsigned int block_start = 0, block_end;
	struct buffer_head *head, *bh;

1349
	bh = head = folio_buffers(folio);
1350 1351 1352 1353
	do {
		block_end = block_start + bh->b_size;
		if (buffer_new(bh)) {
			if (block_end > from && block_start < to) {
1354
				if (!folio_test_uptodate(folio)) {
1355 1356 1357 1358 1359
					unsigned start, size;

					start = max(from, block_start);
					size = min(to, block_end) - start;

1360
					folio_zero_range(folio, start, size);
1361
					write_end_fn(handle, inode, bh);
1362 1363 1364 1365 1366 1367 1368 1369 1370
				}
				clear_buffer_new(bh);
			}
		}
		block_start = block_end;
		bh = bh->b_this_page;
	} while (bh != head);
}

Nick Piggin's avatar
Nick Piggin committed
1371
static int ext4_journalled_write_end(struct file *file,
1372 1373 1374
				     struct address_space *mapping,
				     loff_t pos, unsigned len, unsigned copied,
				     struct page *page, void *fsdata)
1375
{
1376
	struct folio *folio = page_folio(page);
1377
	handle_t *handle = ext4_journal_current_handle();
Nick Piggin's avatar
Nick Piggin committed
1378
	struct inode *inode = mapping->host;
1379
	loff_t old_size = inode->i_size;
1380 1381
	int ret = 0, ret2;
	int partial = 0;
Nick Piggin's avatar
Nick Piggin committed
1382
	unsigned from, to;
1383
	int size_changed = 0;
1384
	bool verity = ext4_verity_in_progress(inode);
1385

1386
	trace_ext4_journalled_write_end(inode, pos, len, copied);
1387
	from = pos & (PAGE_SIZE - 1);
Nick Piggin's avatar
Nick Piggin committed
1388 1389
	to = from + len;

1390 1391
	BUG_ON(!ext4_handle_valid(handle));

1392
	if (ext4_has_inline_data(inode))
1393 1394
		return ext4_write_inline_data_end(inode, pos, len, copied,
						  folio);
1395

1396
	if (unlikely(copied < len) && !folio_test_uptodate(folio)) {
1397
		copied = 0;
1398 1399
		ext4_journalled_zero_new_buffers(handle, inode, folio,
						 from, to);
1400 1401
	} else {
		if (unlikely(copied < len))
1402
			ext4_journalled_zero_new_buffers(handle, inode, folio,
1403
							 from + copied, to);
1404 1405
		ret = ext4_walk_page_buffers(handle, inode,
					     folio_buffers(folio),
1406
					     from, from + copied, &partial,
1407
					     write_end_fn);
1408
		if (!partial)
1409
			folio_mark_uptodate(folio);
1410
	}
1411 1412
	if (!verity)
		size_changed = ext4_update_inode_size(inode, pos + copied);
1413
	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
1414 1415
	folio_unlock(folio);
	folio_put(folio);
1416

1417
	if (old_size < pos && !verity)
1418 1419
		pagecache_isize_extended(inode, old_size, pos);

1420
	if (size_changed) {
1421
		ret2 = ext4_mark_inode_dirty(handle, inode);
1422 1423 1424
		if (!ret)
			ret = ret2;
	}
Nick Piggin's avatar
Nick Piggin committed
1425

1426
	if (pos + len > inode->i_size && !verity && ext4_can_truncate(inode))
1427 1428 1429 1430 1431 1432
		/* if we have allocated more blocks and copied
		 * less. We will have blocks allocated outside
		 * inode->i_size. So truncate them
		 */
		ext4_orphan_add(handle, inode);

1433
	ret2 = ext4_journal_stop(handle);
1434 1435
	if (!ret)
		ret = ret2;
1436
	if (pos + len > inode->i_size && !verity) {
1437
		ext4_truncate_failed_write(inode);
1438
		/*
1439
		 * If truncate failed early the inode might still be
1440 1441 1442 1443 1444 1445
		 * on the orphan list; we need to make sure the inode
		 * is removed from the orphan list in that case.
		 */
		if (inode->i_nlink)
			ext4_orphan_del(NULL, inode);
	}
Nick Piggin's avatar
Nick Piggin committed
1446 1447

	return ret ? ret : copied;
1448
}
1449

1450
/*
1451
 * Reserve space for a single cluster
1452
 */
1453
static int ext4_da_reserve_space(struct inode *inode)
1454
{
1455
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1456
	struct ext4_inode_info *ei = EXT4_I(inode);
1457
	int ret;
1458 1459 1460 1461 1462 1463 1464 1465 1466

	/*
	 * We will charge metadata quota at writeout time; this saves
	 * us from metadata over-estimation, though we may go over by
	 * a small amount in the end.  Here we just reserve for data.
	 */
	ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1));
	if (ret)
		return ret;
1467

1468
	spin_lock(&ei->i_block_reservation_lock);
1469
	if (ext4_claim_free_clusters(sbi, 1, 0)) {
1470 1471
		spin_unlock(&ei->i_block_reservation_lock);
		dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1));
1472 1473
		return -ENOSPC;
	}
1474
	ei->i_reserved_data_blocks++;
1475
	trace_ext4_da_reserve_space(inode);
1476
	spin_unlock(&ei->i_block_reservation_lock);
1477

1478 1479 1480
	return 0;       /* success */
}

1481
void ext4_da_release_space(struct inode *inode, int to_free)
1482 1483
{
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1484
	struct ext4_inode_info *ei = EXT4_I(inode);
1485

1486 1487 1488
	if (!to_free)
		return;		/* Nothing to release, exit */

1489
	spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
1490

Li Zefan's avatar
Li Zefan committed
1491
	trace_ext4_da_release_space(inode, to_free);
1492
	if (unlikely(to_free > ei->i_reserved_data_blocks)) {
1493
		/*
1494 1495 1496 1497
		 * if there aren't enough reserved blocks, then the
		 * counter is messed up somewhere.  Since this
		 * function is called from invalidate page, it's
		 * harmless to return without any action.
1498
		 */
1499
		ext4_warning(inode->i_sb, "ext4_da_release_space: "
1500
			 "ino %lu, to_free %d with only %d reserved "
1501
			 "data blocks", inode->i_ino, to_free,
1502 1503 1504
			 ei->i_reserved_data_blocks);
		WARN_ON(1);
		to_free = ei->i_reserved_data_blocks;
1505
	}
1506
	ei->i_reserved_data_blocks -= to_free;
1507

1508
	/* update fs dirty data blocks counter */
1509
	percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free);
1510 1511

	spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
1512

1513
	dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free));
1514 1515
}

1516 1517 1518 1519
/*
 * Delayed allocation stuff
 */

Jan Kara's avatar
Jan Kara committed
1520
struct mpage_da_data {
Jan Kara's avatar
Jan Kara committed
1521
	/* These are input fields for ext4_do_writepages() */
Jan Kara's avatar
Jan Kara committed
1522 1523
	struct inode *inode;
	struct writeback_control *wbc;
Jan Kara's avatar
Jan Kara committed
1524
	unsigned int can_map:1;	/* Can writepages call map blocks? */
1525

Jan Kara's avatar
Jan Kara committed
1526
	/* These are internal state of ext4_do_writepages() */
Jan Kara's avatar
Jan Kara committed
1527 1528 1529
	pgoff_t first_page;	/* The first page to write */
	pgoff_t next_page;	/* Current page to examine */
	pgoff_t last_page;	/* Last page to examine */
1530
	/*
Jan Kara's avatar
Jan Kara committed
1531 1532 1533
	 * Extent to map - this can be after first_page because that can be
	 * fully mapped. We somewhat abuse m_flags to store whether the extent
	 * is delalloc or unwritten.
1534
	 */
Jan Kara's avatar
Jan Kara committed
1535 1536
	struct ext4_map_blocks map;
	struct ext4_io_submit io_submit;	/* IO submission data */
1537
	unsigned int do_map:1;
1538
	unsigned int scanned_until_end:1;
1539
	unsigned int journalled_more_data:1;
Jan Kara's avatar
Jan Kara committed
1540
};
1541

Jan Kara's avatar
Jan Kara committed
1542 1543
static void mpage_release_unused_pages(struct mpage_da_data *mpd,
				       bool invalidate)
1544
{
1545
	unsigned nr, i;
1546
	pgoff_t index, end;
1547
	struct folio_batch fbatch;
1548 1549
	struct inode *inode = mpd->inode;
	struct address_space *mapping = inode->i_mapping;
Jan Kara's avatar
Jan Kara committed
1550 1551 1552 1553

	/* This is necessary when next_page == 0. */
	if (mpd->first_page >= mpd->next_page)
		return;
1554

1555
	mpd->scanned_until_end = 0;
1556 1557
	index = mpd->first_page;
	end   = mpd->next_page - 1;
Jan Kara's avatar
Jan Kara committed
1558 1559
	if (invalidate) {
		ext4_lblk_t start, last;
1560 1561
		start = index << (PAGE_SHIFT - inode->i_blkbits);
		last = end << (PAGE_SHIFT - inode->i_blkbits);
1562 1563 1564 1565 1566 1567

		/*
		 * avoid racing with extent status tree scans made by
		 * ext4_insert_delayed_block()
		 */
		down_write(&EXT4_I(inode)->i_data_sem);
Jan Kara's avatar
Jan Kara committed
1568
		ext4_es_remove_extent(inode, start, last - start + 1);
1569
		up_write(&EXT4_I(inode)->i_data_sem);
Jan Kara's avatar
Jan Kara committed
1570
	}
1571

1572
	folio_batch_init(&fbatch);
1573
	while (index <= end) {
1574 1575
		nr = filemap_get_folios(mapping, &index, end, &fbatch);
		if (nr == 0)
1576
			break;
1577 1578
		for (i = 0; i < nr; i++) {
			struct folio *folio = fbatch.folios[i];
1579

1580 1581
			if (folio->index < mpd->first_page)
				continue;
1582
			if (folio_next_index(folio) - 1 > end)
1583
				continue;
1584 1585
			BUG_ON(!folio_test_locked(folio));
			BUG_ON(folio_test_writeback(folio));
Jan Kara's avatar
Jan Kara committed
1586
			if (invalidate) {
1587 1588 1589 1590 1591
				if (folio_mapped(folio))
					folio_clear_dirty_for_io(folio);
				block_invalidate_folio(folio, 0,
						folio_size(folio));
				folio_clear_uptodate(folio);
Jan Kara's avatar
Jan Kara committed
1592
			}
1593
			folio_unlock(folio);
1594
		}
1595
		folio_batch_release(&fbatch);
1596 1597 1598
	}
}

1599 1600 1601
static void ext4_print_free_blocks(struct inode *inode)
{
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
1602
	struct super_block *sb = inode->i_sb;
1603
	struct ext4_inode_info *ei = EXT4_I(inode);
1604 1605

	ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld",
1606
	       EXT4_C2B(EXT4_SB(inode->i_sb),
1607
			ext4_count_free_clusters(sb)));
1608 1609
	ext4_msg(sb, KERN_CRIT, "Free/Dirty block details");
	ext4_msg(sb, KERN_CRIT, "free_blocks=%lld",
1610
	       (long long) EXT4_C2B(EXT4_SB(sb),
1611
		percpu_counter_sum(&sbi->s_freeclusters_counter)));
1612
	ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld",
1613
	       (long long) EXT4_C2B(EXT4_SB(sb),
1614
		percpu_counter_sum(&sbi->s_dirtyclusters_counter)));
1615 1616
	ext4_msg(sb, KERN_CRIT, "Block reservation details");
	ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u",
1617
		 ei->i_reserved_data_blocks);
1618 1619 1620
	return;
}

1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
/*
 * ext4_insert_delayed_block - adds a delayed block to the extents status
 *                             tree, incrementing the reserved cluster/block
 *                             count or making a pending reservation
 *                             where needed
 *
 * @inode - file containing the newly added block
 * @lblk - logical block to be added
 *
 * Returns 0 on success, negative error code on failure.
 */
static int ext4_insert_delayed_block(struct inode *inode, ext4_lblk_t lblk)
{
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
	int ret;
	bool allocated = false;

	/*
	 * If the cluster containing lblk is shared with a delayed,
	 * written, or unwritten extent in a bigalloc file system, it's
	 * already been accounted for and does not need to be reserved.
	 * A pending reservation must be made for the cluster if it's
	 * shared with a written or unwritten extent and doesn't already
	 * have one.  Written and unwritten extents can be purged from the
	 * extents status tree if the system is under memory pressure, so
	 * it's necessary to examine the extent tree if a search of the
	 * extents status tree doesn't get a match.
	 */
	if (sbi->s_cluster_ratio == 1) {
		ret = ext4_da_reserve_space(inode);
		if (ret != 0)   /* ENOSPC */
1652
			return ret;
1653 1654 1655 1656 1657 1658 1659
	} else {   /* bigalloc */
		if (!ext4_es_scan_clu(inode, &ext4_es_is_delonly, lblk)) {
			if (!ext4_es_scan_clu(inode,
					      &ext4_es_is_mapped, lblk)) {
				ret = ext4_clu_mapped(inode,
						      EXT4_B2C(sbi, lblk));
				if (ret < 0)
1660
					return ret;
1661 1662 1663
				if (ret == 0) {
					ret = ext4_da_reserve_space(inode);
					if (ret != 0)   /* ENOSPC */
1664
						return ret;
1665 1666 1667 1668 1669 1670 1671 1672 1673
				} else {
					allocated = true;
				}
			} else {
				allocated = true;
			}
		}
	}

1674 1675
	ext4_es_insert_delayed_block(inode, lblk, allocated);
	return 0;
1676 1677
}

1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
/*
 * This function is grabs code from the very beginning of
 * ext4_map_blocks, but assumes that the caller is from delayed write
 * time. This function looks up the requested blocks and sets the
 * buffer delay bit under the protection of i_data_sem.
 */
static int ext4_da_map_blocks(struct inode *inode, sector_t iblock,
			      struct ext4_map_blocks *map,
			      struct buffer_head *bh)
{
1688
	struct extent_status es;
1689 1690
	int retval;
	sector_t invalid_block = ~((sector_t) 0xffff);
1691 1692 1693 1694 1695
#ifdef ES_AGGRESSIVE_TEST
	struct ext4_map_blocks orig_map;

	memcpy(&orig_map, map, sizeof(*map));
#endif
1696 1697 1698 1699 1700

	if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
		invalid_block = ~0;

	map->m_flags = 0;
1701
	ext_debug(inode, "max_blocks %u, logical block %lu\n", map->m_len,
1702
		  (unsigned long) map->m_lblk);
1703 1704

	/* Lookup extent status tree firstly */
1705
	if (ext4_es_lookup_extent(inode, iblock, NULL, &es)) {
1706 1707
		if (ext4_es_is_hole(&es)) {
			retval = 0;
1708
			down_read(&EXT4_I(inode)->i_data_sem);
1709 1710 1711 1712
			goto add_delayed;
		}

		/*
1713 1714
		 * Delayed extent could be allocated by fallocate.
		 * So we need to check it.
1715
		 */
1716 1717 1718 1719
		if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) {
			map_bh(bh, inode->i_sb, invalid_block);
			set_buffer_new(bh);
			set_buffer_delay(bh);
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
			return 0;
		}

		map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk;
		retval = es.es_len - (iblock - es.es_lblk);
		if (retval > map->m_len)
			retval = map->m_len;
		map->m_len = retval;
		if (ext4_es_is_written(&es))
			map->m_flags |= EXT4_MAP_MAPPED;
		else if (ext4_es_is_unwritten(&es))
			map->m_flags |= EXT4_MAP_UNWRITTEN;
		else
1733
			BUG();
1734

1735 1736 1737
#ifdef ES_AGGRESSIVE_TEST
		ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0);
#endif
1738 1739 1740
		return retval;
	}

1741 1742 1743 1744
	/*
	 * Try to see if we can get the block without requesting a new
	 * file system block.
	 */
1745
	down_read(&EXT4_I(inode)->i_data_sem);
1746
	if (ext4_has_inline_data(inode))
1747
		retval = 0;
1748
	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
1749
		retval = ext4_ext_map_blocks(NULL, inode, map, 0);
1750
	else
1751
		retval = ext4_ind_map_blocks(NULL, inode, map, 0);
1752

1753
add_delayed:
1754
	if (retval == 0) {
1755
		int ret;
1756

1757 1758 1759 1760 1761
		/*
		 * XXX: __block_prepare_write() unmaps passed block,
		 * is it OK?
		 */

1762 1763
		ret = ext4_insert_delayed_block(inode, map->m_lblk);
		if (ret != 0) {
1764
			retval = ret;
1765
			goto out_unlock;
1766
		}
1767

1768 1769 1770
		map_bh(bh, inode->i_sb, invalid_block);
		set_buffer_new(bh);
		set_buffer_delay(bh);
1771
	} else if (retval > 0) {
1772
		unsigned int status;
1773

1774 1775 1776 1777 1778 1779
		if (unlikely(retval != map->m_len)) {
			ext4_warning(inode->i_sb,
				     "ES len assertion failed for inode "
				     "%lu: retval %d != map->m_len %d",
				     inode->i_ino, retval, map->m_len);
			WARN_ON(1);
1780 1781
		}

1782 1783
		status = map->m_flags & EXT4_MAP_UNWRITTEN ?
				EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN;
1784 1785
		ext4_es_insert_extent(inode, map->m_lblk, map->m_len,
				      map->m_pblk, status);
1786 1787 1788 1789 1790 1791 1792 1793
	}

out_unlock:
	up_read((&EXT4_I(inode)->i_data_sem));

	return retval;
}

1794
/*
1795
 * This is a special get_block_t callback which is used by
1796 1797
 * ext4_da_write_begin().  It will either return mapped block or
 * reserve space for a single block.
1798 1799 1800 1801 1802 1803 1804
 *
 * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
 * We also have b_blocknr = -1 and b_bdev initialized properly
 *
 * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
 * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
 * initialized properly.
1805
 */
1806 1807
int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
			   struct buffer_head *bh, int create)
1808
{
1809
	struct ext4_map_blocks map;
1810 1811 1812
	int ret = 0;

	BUG_ON(create == 0);
1813 1814 1815 1816
	BUG_ON(bh->b_size != inode->i_sb->s_blocksize);

	map.m_lblk = iblock;
	map.m_len = 1;
1817 1818 1819 1820 1821 1822

	/*
	 * first, we need to know whether the block is allocated already
	 * preallocated blocks are unmapped but should treated
	 * the same as allocated blocks.
	 */
1823 1824
	ret = ext4_da_map_blocks(inode, iblock, &map, bh);
	if (ret <= 0)
1825
		return ret;
1826

1827
	map_bh(bh, inode->i_sb, map.m_pblk);
Jan Kara's avatar
Jan Kara committed
1828
	ext4_update_bh_state(bh, map.m_flags);
1829 1830 1831 1832 1833 1834 1835 1836 1837

	if (buffer_unwritten(bh)) {
		/* A delayed write to unwritten bh should be marked
		 * new and mapped.  Mapped ensures that we don't do
		 * get_block multiple times when we write to the same
		 * offset and new ensures that we do proper zero out
		 * for partial write.
		 */
		set_buffer_new(bh);
1838
		set_buffer_mapped(bh);
1839 1840
	}
	return 0;
1841
}
1842

1843
static void mpage_folio_done(struct mpage_da_data *mpd, struct folio *folio)
1844
{
1845 1846
	mpd->first_page += folio_nr_pages(folio);
	folio_unlock(folio);
1847 1848
}

1849
static int mpage_submit_folio(struct mpage_da_data *mpd, struct folio *folio)
1850
{
1851
	size_t len;
1852
	loff_t size;
1853 1854
	int err;

1855 1856
	BUG_ON(folio->index != mpd->first_page);
	folio_clear_dirty_for_io(folio);
1857 1858 1859 1860
	/*
	 * We have to be very careful here!  Nothing protects writeback path
	 * against i_size changes and the page can be writeably mapped into
	 * page tables. So an application can be growing i_size and writing
1861
	 * data through mmap while writeback runs. folio_clear_dirty_for_io()
1862
	 * write-protects our page in page tables and the page cannot get
1863 1864
	 * written to again until we release folio lock. So only after
	 * folio_clear_dirty_for_io() we are safe to sample i_size for
1865 1866
	 * ext4_bio_write_folio() to zero-out tail of the written page. We rely
	 * on the barrier provided by folio_test_clear_dirty() in
1867
	 * folio_clear_dirty_for_io() to make sure i_size is really sampled only
1868 1869 1870
	 * after page tables are updated.
	 */
	size = i_size_read(mpd->inode);
1871 1872
	len = folio_size(folio);
	if (folio_pos(folio) + len > size &&
1873
	    !ext4_verity_in_progress(mpd->inode))
1874
		len = size & ~PAGE_MASK;
1875
	err = ext4_bio_write_folio(&mpd->io_submit, folio, len);
1876 1877 1878 1879 1880 1881
	if (!err)
		mpd->wbc->nr_to_write--;

	return err;
}

1882
#define BH_FLAGS (BIT(BH_Unwritten) | BIT(BH_Delay))
Jan Kara's avatar
Jan Kara committed
1883

1884
/*
1885 1886
 * mballoc gives us at most this number of blocks...
 * XXX: That seems to be only a limitation of ext4_mb_normalize_request().
1887
 * The rest of mballoc seems to handle chunks up to full group size.
1888
 */
1889
#define MAX_WRITEPAGES_EXTENT_LEN 2048
1890

Jan Kara's avatar
Jan Kara committed
1891 1892 1893 1894 1895
/*
 * mpage_add_bh_to_extent - try to add bh to extent of blocks to map
 *
 * @mpd - extent of blocks
 * @lblk - logical number of the block in the file
1896
 * @bh - buffer head we want to add to the extent
Jan Kara's avatar
Jan Kara committed
1897
 *
1898 1899 1900 1901 1902 1903
 * The function is used to collect contig. blocks in the same state. If the
 * buffer doesn't require mapping for writeback and we haven't started the
 * extent of buffers to map yet, the function returns 'true' immediately - the
 * caller can write the buffer right away. Otherwise the function returns true
 * if the block has been added to the extent, false if the block couldn't be
 * added.
Jan Kara's avatar
Jan Kara committed
1904
 */
1905 1906
static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk,
				   struct buffer_head *bh)
Jan Kara's avatar
Jan Kara committed
1907 1908 1909
{
	struct ext4_map_blocks *map = &mpd->map;

1910 1911 1912 1913 1914 1915 1916 1917
	/* Buffer that doesn't need mapping for writeback? */
	if (!buffer_dirty(bh) || !buffer_mapped(bh) ||
	    (!buffer_delay(bh) && !buffer_unwritten(bh))) {
		/* So far no extent to map => we write the buffer right away */
		if (map->m_len == 0)
			return true;
		return false;
	}
Jan Kara's avatar
Jan Kara committed
1918 1919 1920

	/* First block in the extent? */
	if (map->m_len == 0) {
1921 1922 1923
		/* We cannot map unless handle is started... */
		if (!mpd->do_map)
			return false;
Jan Kara's avatar
Jan Kara committed
1924 1925
		map->m_lblk = lblk;
		map->m_len = 1;
1926 1927
		map->m_flags = bh->b_state & BH_FLAGS;
		return true;
Jan Kara's avatar
Jan Kara committed
1928 1929
	}

1930 1931 1932 1933
	/* Don't go larger than mballoc is willing to allocate */
	if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN)
		return false;

Jan Kara's avatar
Jan Kara committed
1934 1935
	/* Can we merge the block to our big extent? */
	if (lblk == map->m_lblk + map->m_len &&
1936
	    (bh->b_state & BH_FLAGS) == map->m_flags) {
Jan Kara's avatar
Jan Kara committed
1937
		map->m_len++;
1938
		return true;
Jan Kara's avatar
Jan Kara committed
1939
	}
1940
	return false;
Jan Kara's avatar
Jan Kara committed
1941 1942
}

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
/*
 * mpage_process_page_bufs - submit page buffers for IO or add them to extent
 *
 * @mpd - extent of blocks for mapping
 * @head - the first buffer in the page
 * @bh - buffer we should start processing from
 * @lblk - logical number of the block in the file corresponding to @bh
 *
 * Walk through page buffers from @bh upto @head (exclusive) and either submit
 * the page for IO if all buffers in this page were mapped and there's no
 * accumulated extent of buffers to map or add buffers in the page to the
 * extent of buffers to map. The function returns 1 if the caller can continue
 * by processing the next page, 0 if it should stop adding buffers to the
 * extent to map because we cannot extend it anymore. It can also return value
 * < 0 in case of error during IO submission.
 */
static int mpage_process_page_bufs(struct mpage_da_data *mpd,
				   struct buffer_head *head,
				   struct buffer_head *bh,
				   ext4_lblk_t lblk)
Jan Kara's avatar
Jan Kara committed
1963 1964
{
	struct inode *inode = mpd->inode;
1965
	int err;
Fabian Frederick's avatar
Fabian Frederick committed
1966
	ext4_lblk_t blocks = (i_size_read(inode) + i_blocksize(inode) - 1)
Jan Kara's avatar
Jan Kara committed
1967 1968
							>> inode->i_blkbits;

1969 1970 1971
	if (ext4_verity_in_progress(inode))
		blocks = EXT_MAX_BLOCKS;

Jan Kara's avatar
Jan Kara committed
1972 1973 1974
	do {
		BUG_ON(buffer_locked(bh));

1975
		if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) {
Jan Kara's avatar
Jan Kara committed
1976 1977
			/* Found extent to map? */
			if (mpd->map.m_len)
1978
				return 0;
1979 1980 1981
			/* Buffer needs mapping and handle is not started? */
			if (!mpd->do_map)
				return 0;
1982
			/* Everything mapped so far and we hit EOF */
1983
			break;
Jan Kara's avatar
Jan Kara committed
1984 1985
		}
	} while (lblk++, (bh = bh->b_this_page) != head);
1986 1987
	/* So far everything mapped? Submit the page for IO. */
	if (mpd->map.m_len == 0) {
1988
		err = mpage_submit_folio(mpd, head->b_folio);
1989 1990
		if (err < 0)
			return err;
1991
		mpage_folio_done(mpd, head->b_folio);
1992
	}
1993 1994 1995 1996 1997
	if (lblk >= blocks) {
		mpd->scanned_until_end = 1;
		return 0;
	}
	return 1;
Jan Kara's avatar
Jan Kara committed
1998 1999
}

2000
/*
2001 2002 2003 2004 2005 2006 2007
 * mpage_process_folio - update folio buffers corresponding to changed extent
 *			 and may submit fully mapped page for IO
 * @mpd: description of extent to map, on return next extent to map
 * @folio: Contains these buffers.
 * @m_lblk: logical block mapping.
 * @m_pblk: corresponding physical mapping.
 * @map_bh: determines on return whether this page requires any further
2008
 *		  mapping or not.
2009 2010
 *
 * Scan given folio buffers corresponding to changed extent and update buffer
2011 2012
 * state according to new extent state.
 * We map delalloc buffers to their physical location, clear unwritten bits.
2013 2014
 * If the given folio is not fully mapped, we update @mpd to the next extent in
 * the given folio that needs mapping & return @map_bh as true.
2015
 */
2016
static int mpage_process_folio(struct mpage_da_data *mpd, struct folio *folio,
2017 2018 2019 2020 2021 2022 2023 2024
			      ext4_lblk_t *m_lblk, ext4_fsblk_t *m_pblk,
			      bool *map_bh)
{
	struct buffer_head *head, *bh;
	ext4_io_end_t *io_end = mpd->io_submit.io_end;
	ext4_lblk_t lblk = *m_lblk;
	ext4_fsblk_t pblock = *m_pblk;
	int err = 0;
2025 2026 2027
	int blkbits = mpd->inode->i_blkbits;
	ssize_t io_end_size = 0;
	struct ext4_io_end_vec *io_end_vec = ext4_last_io_end_vec(io_end);
2028

2029
	bh = head = folio_buffers(folio);
2030 2031 2032 2033 2034 2035
	do {
		if (lblk < mpd->map.m_lblk)
			continue;
		if (lblk >= mpd->map.m_lblk + mpd->map.m_len) {
			/*
			 * Buffer after end of mapped extent.
2036
			 * Find next buffer in the folio to map.
2037 2038 2039
			 */
			mpd->map.m_len = 0;
			mpd->map.m_flags = 0;
2040
			io_end_vec->size += io_end_size;
2041 2042 2043 2044

			err = mpage_process_page_bufs(mpd, head, bh, lblk);
			if (err > 0)
				err = 0;
2045 2046
			if (!err && mpd->map.m_len && mpd->map.m_lblk > lblk) {
				io_end_vec = ext4_alloc_io_end_vec(io_end);
2047 2048 2049 2050
				if (IS_ERR(io_end_vec)) {
					err = PTR_ERR(io_end_vec);
					goto out;
				}
2051
				io_end_vec->offset = (loff_t)mpd->map.m_lblk << blkbits;
2052
			}
2053 2054 2055 2056 2057 2058 2059 2060
			*map_bh = true;
			goto out;
		}
		if (buffer_delay(bh)) {
			clear_buffer_delay(bh);
			bh->b_blocknr = pblock++;
		}
		clear_buffer_unwritten(bh);
2061
		io_end_size += (1 << blkbits);
2062
	} while (lblk++, (bh = bh->b_this_page) != head);
2063 2064

	io_end_vec->size += io_end_size;
2065 2066 2067 2068 2069 2070 2071
	*map_bh = false;
out:
	*m_lblk = lblk;
	*m_pblk = pblock;
	return err;
}

Jan Kara's avatar
Jan Kara committed
2072 2073 2074 2075 2076 2077 2078 2079 2080
/*
 * mpage_map_buffers - update buffers corresponding to changed extent and
 *		       submit fully mapped pages for IO
 *
 * @mpd - description of extent to map, on return next extent to map
 *
 * Scan buffers corresponding to changed extent (we expect corresponding pages
 * to be already locked) and update buffer state according to new extent state.
 * We map delalloc buffers to their physical location, clear unwritten bits,
2081
 * and mark buffers as uninit when we perform writes to unwritten extents
Jan Kara's avatar
Jan Kara committed
2082 2083 2084 2085 2086 2087
 * and do extent conversion after IO is finished. If the last page is not fully
 * mapped, we update @map to the next extent in the last page that needs
 * mapping. Otherwise we submit the page for IO.
 */
static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd)
{
2088 2089
	struct folio_batch fbatch;
	unsigned nr, i;
Jan Kara's avatar
Jan Kara committed
2090
	struct inode *inode = mpd->inode;
2091
	int bpp_bits = PAGE_SHIFT - inode->i_blkbits;
Jan Kara's avatar
Jan Kara committed
2092 2093
	pgoff_t start, end;
	ext4_lblk_t lblk;
2094
	ext4_fsblk_t pblock;
Jan Kara's avatar
Jan Kara committed
2095
	int err;
2096
	bool map_bh = false;
Jan Kara's avatar
Jan Kara committed
2097 2098 2099 2100 2101 2102

	start = mpd->map.m_lblk >> bpp_bits;
	end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits;
	lblk = start << bpp_bits;
	pblock = mpd->map.m_pblk;

2103
	folio_batch_init(&fbatch);
Jan Kara's avatar
Jan Kara committed
2104
	while (start <= end) {
2105 2106
		nr = filemap_get_folios(inode->i_mapping, &start, end, &fbatch);
		if (nr == 0)
Jan Kara's avatar
Jan Kara committed
2107
			break;
2108
		for (i = 0; i < nr; i++) {
2109
			struct folio *folio = fbatch.folios[i];
Jan Kara's avatar
Jan Kara committed
2110

2111
			err = mpage_process_folio(mpd, folio, &lblk, &pblock,
2112
						 &map_bh);
Jan Kara's avatar
Jan Kara committed
2113
			/*
2114 2115 2116
			 * If map_bh is true, means page may require further bh
			 * mapping, or maybe the page was submitted for IO.
			 * So we return to call further extent mapping.
Jan Kara's avatar
Jan Kara committed
2117
			 */
2118
			if (err < 0 || map_bh)
2119
				goto out;
Jan Kara's avatar
Jan Kara committed
2120
			/* Page fully mapped - let IO run! */
2121
			err = mpage_submit_folio(mpd, folio);
2122 2123
			if (err < 0)
				goto out;
2124
			mpage_folio_done(mpd, folio);
Jan Kara's avatar
Jan Kara committed
2125
		}
2126
		folio_batch_release(&fbatch);
Jan Kara's avatar
Jan Kara committed
2127 2128 2129 2130 2131
	}
	/* Extent fully mapped and matches with page boundary. We are done. */
	mpd->map.m_len = 0;
	mpd->map.m_flags = 0;
	return 0;
2132
out:
2133
	folio_batch_release(&fbatch);
2134
	return err;
Jan Kara's avatar
Jan Kara committed
2135 2136 2137 2138 2139 2140 2141
}

static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd)
{
	struct inode *inode = mpd->inode;
	struct ext4_map_blocks *map = &mpd->map;
	int get_blocks_flags;
2142
	int err, dioread_nolock;
Jan Kara's avatar
Jan Kara committed
2143 2144 2145 2146

	trace_ext4_da_write_pages_extent(inode, map);
	/*
	 * Call ext4_map_blocks() to allocate any delayed allocation blocks, or
2147
	 * to convert an unwritten extent to be initialized (in the case
Jan Kara's avatar
Jan Kara committed
2148 2149 2150 2151 2152 2153 2154
	 * where we have written into one or more preallocated blocks).  It is
	 * possible that we're going to need more metadata blocks than
	 * previously reserved. However we must not fail because we're in
	 * writeback and there is nothing we can do about it so it might result
	 * in data loss.  So use reserved blocks to allocate metadata if
	 * possible.
	 *
2155 2156 2157 2158
	 * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if
	 * the blocks in question are delalloc blocks.  This indicates
	 * that the blocks and quotas has already been checked when
	 * the data was copied into the page cache.
Jan Kara's avatar
Jan Kara committed
2159 2160
	 */
	get_blocks_flags = EXT4_GET_BLOCKS_CREATE |
2161 2162
			   EXT4_GET_BLOCKS_METADATA_NOFAIL |
			   EXT4_GET_BLOCKS_IO_SUBMIT;
2163 2164
	dioread_nolock = ext4_should_dioread_nolock(inode);
	if (dioread_nolock)
Jan Kara's avatar
Jan Kara committed
2165
		get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
2166
	if (map->m_flags & BIT(BH_Delay))
Jan Kara's avatar
Jan Kara committed
2167 2168 2169 2170 2171
		get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;

	err = ext4_map_blocks(handle, inode, map, get_blocks_flags);
	if (err < 0)
		return err;
2172
	if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) {
2173 2174 2175 2176 2177
		if (!mpd->io_submit.io_end->handle &&
		    ext4_handle_valid(handle)) {
			mpd->io_submit.io_end->handle = handle->h_rsv_handle;
			handle->h_rsv_handle = NULL;
		}
Jan Kara's avatar
Jan Kara committed
2178
		ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end);
2179
	}
Jan Kara's avatar
Jan Kara committed
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190

	BUG_ON(map->m_len == 0);
	return 0;
}

/*
 * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length
 *				 mpd->len and submit pages underlying it for IO
 *
 * @handle - handle for journal operations
 * @mpd - extent to map
2191 2192 2193
 * @give_up_on_write - we set this to true iff there is a fatal error and there
 *                     is no hope of writing the data. The caller should discard
 *                     dirty pages to avoid infinite loops.
Jan Kara's avatar
Jan Kara committed
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
 *
 * The function maps extent starting at mpd->lblk of length mpd->len. If it is
 * delayed, blocks are allocated, if it is unwritten, we may need to convert
 * them to initialized or split the described range from larger unwritten
 * extent. Note that we need not map all the described range since allocation
 * can return less blocks or the range is covered by more unwritten extents. We
 * cannot map more because we are limited by reserved transaction credits. On
 * the other hand we always make sure that the last touched page is fully
 * mapped so that it can be written out (and thus forward progress is
 * guaranteed). After mapping we submit all mapped pages for IO.
 */
static int mpage_map_and_submit_extent(handle_t *handle,
2206 2207
				       struct mpage_da_data *mpd,
				       bool *give_up_on_write)
Jan Kara's avatar
Jan Kara committed
2208 2209 2210 2211 2212
{
	struct inode *inode = mpd->inode;
	struct ext4_map_blocks *map = &mpd->map;
	int err;
	loff_t disksize;
2213
	int progress = 0;
2214
	ext4_io_end_t *io_end = mpd->io_submit.io_end;
2215
	struct ext4_io_end_vec *io_end_vec;
Jan Kara's avatar
Jan Kara committed
2216

2217 2218 2219
	io_end_vec = ext4_alloc_io_end_vec(io_end);
	if (IS_ERR(io_end_vec))
		return PTR_ERR(io_end_vec);
2220
	io_end_vec->offset = ((loff_t)map->m_lblk) << inode->i_blkbits;
2221
	do {
Jan Kara's avatar
Jan Kara committed
2222 2223 2224 2225
		err = mpage_map_one_extent(handle, mpd);
		if (err < 0) {
			struct super_block *sb = inode->i_sb;

2226
			if (ext4_forced_shutdown(sb))
2227
				goto invalidate_dirty_pages;
Jan Kara's avatar
Jan Kara committed
2228
			/*
2229 2230 2231
			 * Let the uper layers retry transient errors.
			 * In the case of ENOSPC, if ext4_count_free_blocks()
			 * is non-zero, a commit should free up blocks.
Jan Kara's avatar
Jan Kara committed
2232
			 */
2233
			if ((err == -ENOMEM) ||
2234 2235 2236
			    (err == -ENOSPC && ext4_count_free_clusters(sb))) {
				if (progress)
					goto update_disksize;
2237
				return err;
2238
			}
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
			ext4_msg(sb, KERN_CRIT,
				 "Delayed block allocation failed for "
				 "inode %lu at logical offset %llu with"
				 " max blocks %u with error %d",
				 inode->i_ino,
				 (unsigned long long)map->m_lblk,
				 (unsigned)map->m_len, -err);
			ext4_msg(sb, KERN_CRIT,
				 "This should not happen!! Data will "
				 "be lost\n");
			if (err == -ENOSPC)
				ext4_print_free_blocks(inode);
		invalidate_dirty_pages:
			*give_up_on_write = true;
Jan Kara's avatar
Jan Kara committed
2253 2254
			return err;
		}
2255
		progress = 1;
Jan Kara's avatar
Jan Kara committed
2256 2257 2258 2259 2260 2261
		/*
		 * Update buffer state, submit mapped pages, and get us new
		 * extent to map
		 */
		err = mpage_map_and_submit_buffers(mpd);
		if (err < 0)
2262
			goto update_disksize;
2263
	} while (map->m_len);
Jan Kara's avatar
Jan Kara committed
2264

2265
update_disksize:
2266 2267 2268 2269
	/*
	 * Update on-disk size after IO is submitted.  Races with
	 * truncate are avoided by checking i_size under i_data_sem.
	 */
2270
	disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT;
2271
	if (disksize > READ_ONCE(EXT4_I(inode)->i_disksize)) {
Jan Kara's avatar
Jan Kara committed
2272
		int err2;
2273 2274 2275 2276 2277 2278 2279 2280 2281
		loff_t i_size;

		down_write(&EXT4_I(inode)->i_data_sem);
		i_size = i_size_read(inode);
		if (disksize > i_size)
			disksize = i_size;
		if (disksize > EXT4_I(inode)->i_disksize)
			EXT4_I(inode)->i_disksize = disksize;
		up_write(&EXT4_I(inode)->i_data_sem);
2282
		err2 = ext4_mark_inode_dirty(handle, inode);
2283
		if (err2) {
2284 2285 2286
			ext4_error_err(inode->i_sb, -err2,
				       "Failed to mark inode %lu dirty",
				       inode->i_ino);
2287
		}
Jan Kara's avatar
Jan Kara committed
2288 2289 2290 2291 2292 2293
		if (!err)
			err = err2;
	}
	return err;
}

2294 2295
/*
 * Calculate the total number of credits to reserve for one writepages
2296
 * iteration. This is called from ext4_writepages(). We map an extent of
2297
 * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping
2298 2299 2300
 * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN +
 * bpp - 1 blocks in bpp different extents.
 */
2301 2302
static int ext4_da_writepages_trans_blocks(struct inode *inode)
{
2303
	int bpp = ext4_journal_blocks_per_page(inode);
2304

2305 2306
	return ext4_meta_trans_blocks(inode,
				MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp);
2307
}
2308

2309 2310
static int ext4_journal_folio_buffers(handle_t *handle, struct folio *folio,
				     size_t len)
2311
{
2312 2313
	struct buffer_head *page_bufs = folio_buffers(folio);
	struct inode *inode = folio->mapping->host;
2314 2315 2316 2317 2318 2319 2320 2321
	int ret, err;

	ret = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
				     NULL, do_journal_get_write_access);
	err = ext4_walk_page_buffers(handle, inode, page_bufs, 0, len,
				     NULL, write_end_fn);
	if (ret == 0)
		ret = err;
2322
	err = ext4_jbd2_inode_add_write(handle, inode, folio_pos(folio), len);
2323 2324 2325 2326 2327 2328 2329 2330 2331
	if (ret == 0)
		ret = err;
	EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;

	return ret;
}

static int mpage_journal_page_buffers(handle_t *handle,
				      struct mpage_da_data *mpd,
2332
				      struct folio *folio)
2333 2334 2335
{
	struct inode *inode = mpd->inode;
	loff_t size = i_size_read(inode);
2336
	size_t len = folio_size(folio);
2337

2338
	folio_clear_checked(folio);
2339 2340
	mpd->wbc->nr_to_write--;

2341
	if (folio_pos(folio) + len > size &&
2342
	    !ext4_verity_in_progress(inode))
2343
		len = size - folio_pos(folio);
2344

2345
	return ext4_journal_folio_buffers(handle, folio, len);
2346 2347
}

2348
/*
Jan Kara's avatar
Jan Kara committed
2349
 * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages
2350
 * 				 needing mapping, submit mapped pages
Jan Kara's avatar
Jan Kara committed
2351 2352 2353 2354
 *
 * @mpd - where to look for pages
 *
 * Walk dirty pages in the mapping. If they are fully mapped, submit them for
2355 2356 2357 2358 2359 2360 2361
 * IO immediately. If we cannot map blocks, we submit just already mapped
 * buffers in the page for IO and keep page dirty. When we can map blocks and
 * we find a page which isn't mapped we start accumulating extent of buffers
 * underlying these pages that needs mapping (formed by either delayed or
 * unwritten buffers). We also lock the pages containing these buffers. The
 * extent found is returned in @mpd structure (starting at mpd->lblk with
 * length mpd->len blocks).
Jan Kara's avatar
Jan Kara committed
2362 2363 2364 2365 2366
 *
 * Note that this function can attach bios to one io_end structure which are
 * neither logically nor physically contiguous. Although it may seem as an
 * unnecessary complication, it is actually inevitable in blocksize < pagesize
 * case as we need to track IO to all buffers underlying a page in one io_end.
2367
 */
Jan Kara's avatar
Jan Kara committed
2368
static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd)
2369
{
Jan Kara's avatar
Jan Kara committed
2370
	struct address_space *mapping = mpd->inode->i_mapping;
2371 2372
	struct folio_batch fbatch;
	unsigned int nr_folios;
Jan Kara's avatar
Jan Kara committed
2373 2374
	pgoff_t index = mpd->first_page;
	pgoff_t end = mpd->last_page;
Matthew Wilcox's avatar
Matthew Wilcox committed
2375
	xa_mark_t tag;
Jan Kara's avatar
Jan Kara committed
2376 2377 2378 2379
	int i, err = 0;
	int blkbits = mpd->inode->i_blkbits;
	ext4_lblk_t lblk;
	struct buffer_head *head;
2380 2381
	handle_t *handle = NULL;
	int bpp = ext4_journal_blocks_per_page(mpd->inode);
2382

Jan Kara's avatar
Jan Kara committed
2383
	if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages)
2384 2385 2386
		tag = PAGECACHE_TAG_TOWRITE;
	else
		tag = PAGECACHE_TAG_DIRTY;
2387

2388 2389
	mpd->map.m_len = 0;
	mpd->next_page = index;
2390
	if (ext4_should_journal_data(mpd->inode)) {
2391 2392 2393 2394 2395
		handle = ext4_journal_start(mpd->inode, EXT4_HT_WRITE_PAGE,
					    bpp);
		if (IS_ERR(handle))
			return PTR_ERR(handle);
	}
2396
	folio_batch_init(&fbatch);
2397
	while (index <= end) {
2398 2399 2400
		nr_folios = filemap_get_folios_tag(mapping, &index, end,
				tag, &fbatch);
		if (nr_folios == 0)
2401
			break;
2402

2403 2404
		for (i = 0; i < nr_folios; i++) {
			struct folio *folio = fbatch.folios[i];
2405

2406 2407 2408 2409 2410 2411 2412 2413
			/*
			 * Accumulated enough dirty pages? This doesn't apply
			 * to WB_SYNC_ALL mode. For integrity sync we have to
			 * keep going because someone may be concurrently
			 * dirtying pages, and we might have synced a lot of
			 * newly appeared dirty pages, but have not synced all
			 * of the old dirty pages.
			 */
2414 2415 2416
			if (mpd->wbc->sync_mode == WB_SYNC_NONE &&
			    mpd->wbc->nr_to_write <=
			    mpd->map.m_len >> (PAGE_SHIFT - blkbits))
2417 2418
				goto out;

Jan Kara's avatar
Jan Kara committed
2419
			/* If we can't merge this page, we are done. */
2420
			if (mpd->map.m_len > 0 && mpd->next_page != folio->index)
Jan Kara's avatar
Jan Kara committed
2421
				goto out;
2422

2423 2424 2425 2426 2427 2428 2429
			if (handle) {
				err = ext4_journal_ensure_credits(handle, bpp,
								  0);
				if (err < 0)
					goto out;
			}

2430
			folio_lock(folio);
2431
			/*
Jan Kara's avatar
Jan Kara committed
2432 2433 2434 2435 2436
			 * If the page is no longer dirty, or its mapping no
			 * longer corresponds to inode we are writing (which
			 * means it has been truncated or invalidated), or the
			 * page is already under writeback and we are not doing
			 * a data integrity writeback, skip the page
2437
			 */
2438 2439
			if (!folio_test_dirty(folio) ||
			    (folio_test_writeback(folio) &&
Jan Kara's avatar
Jan Kara committed
2440
			     (mpd->wbc->sync_mode == WB_SYNC_NONE)) ||
2441 2442
			    unlikely(folio->mapping != mapping)) {
				folio_unlock(folio);
2443 2444 2445
				continue;
			}

2446 2447
			folio_wait_writeback(folio);
			BUG_ON(folio_test_writeback(folio));
2448

2449 2450 2451 2452 2453 2454 2455 2456 2457
			/*
			 * Should never happen but for buggy code in
			 * other subsystems that call
			 * set_page_dirty() without properly warning
			 * the file system first.  See [1] for more
			 * information.
			 *
			 * [1] https://lore.kernel.org/linux-mm/20180103100430.GE4911@quack2.suse.cz
			 */
2458 2459 2460 2461
			if (!folio_buffers(folio)) {
				ext4_warning_inode(mpd->inode, "page %lu does not have buffers attached", folio->index);
				folio_clear_dirty(folio);
				folio_unlock(folio);
2462 2463 2464
				continue;
			}

Jan Kara's avatar
Jan Kara committed
2465
			if (mpd->map.m_len == 0)
2466
				mpd->first_page = folio->index;
2467
			mpd->next_page = folio_next_index(folio);
2468
			/*
2469 2470 2471 2472
			 * Writeout when we cannot modify metadata is simple.
			 * Just submit the page. For data=journal mode we
			 * first handle writeout of the page for checkpoint and
			 * only after that handle delayed page dirtying. This
2473 2474 2475 2476
			 * makes sure current data is checkpointed to the final
			 * location before possibly journalling it again which
			 * is desirable when the page is frequently dirtied
			 * through a pin.
2477 2478
			 */
			if (!mpd->can_map) {
2479 2480 2481
				err = mpage_submit_folio(mpd, folio);
				if (err < 0)
					goto out;
2482
				/* Pending dirtying of journalled data? */
2483
				if (folio_test_checked(folio)) {
2484
					err = mpage_journal_page_buffers(handle,
2485
						mpd, folio);
2486 2487
					if (err < 0)
						goto out;
2488
					mpd->journalled_more_data = 1;
2489
				}
2490
				mpage_folio_done(mpd, folio);
2491 2492
			} else {
				/* Add all dirty buffers to mpd */
2493
				lblk = ((ext4_lblk_t)folio->index) <<
2494
					(PAGE_SHIFT - blkbits);
2495
				head = folio_buffers(folio);
2496
				err = mpage_process_page_bufs(mpd, head, head,
2497
						lblk);
2498 2499 2500 2501
				if (err <= 0)
					goto out;
				err = 0;
			}
2502
		}
2503
		folio_batch_release(&fbatch);
2504 2505
		cond_resched();
	}
2506
	mpd->scanned_until_end = 1;
2507 2508
	if (handle)
		ext4_journal_stop(handle);
2509
	return 0;
2510
out:
2511
	folio_batch_release(&fbatch);
2512 2513
	if (handle)
		ext4_journal_stop(handle);
Jan Kara's avatar
Jan Kara committed
2514
	return err;
2515 2516
}

Jan Kara's avatar
Jan Kara committed
2517
static int ext4_do_writepages(struct mpage_da_data *mpd)
2518
{
Jan Kara's avatar
Jan Kara committed
2519
	struct writeback_control *wbc = mpd->wbc;
Jan Kara's avatar
Jan Kara committed
2520 2521
	pgoff_t	writeback_index = 0;
	long nr_to_write = wbc->nr_to_write;
2522
	int range_whole = 0;
Jan Kara's avatar
Jan Kara committed
2523
	int cycled = 1;
2524
	handle_t *handle = NULL;
Jan Kara's avatar
Jan Kara committed
2525 2526
	struct inode *inode = mpd->inode;
	struct address_space *mapping = inode->i_mapping;
2527
	int needed_blocks, rsv_blocks = 0, ret = 0;
2528
	struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
2529
	struct blk_plug plug;
2530
	bool give_up_on_write = false;
2531

2532
	trace_ext4_writepages(inode, wbc);
2533

2534 2535 2536 2537 2538
	/*
	 * No pages to write? This is mainly a kludge to avoid starting
	 * a transaction for special inodes like journal inode on last iput()
	 * because that could violate lock ordering on umount
	 */
2539
	if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
2540
		goto out_writepages;
2541 2542 2543 2544 2545

	/*
	 * If the filesystem has aborted, it is read-only, so return
	 * right away instead of dumping stack traces later on that
	 * will obscure the real source of the problem.  We test
2546
	 * fs shutdown state instead of sb->s_flag's SB_RDONLY because
2547
	 * the latter could be true if the filesystem is mounted
2548
	 * read-only, and in that case, ext4_writepages should
2549 2550 2551
	 * *never* be called, so if that ever happens, we would want
	 * the stack trace.
	 */
2552
	if (unlikely(ext4_forced_shutdown(mapping->host->i_sb))) {
2553 2554 2555
		ret = -EROFS;
		goto out_writepages;
	}
2556

Jan Kara's avatar
Jan Kara committed
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
	/*
	 * If we have inline data and arrive here, it means that
	 * we will soon create the block for the 1st page, so
	 * we'd better clear the inline data here.
	 */
	if (ext4_has_inline_data(inode)) {
		/* Just inode will be modified... */
		handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
		if (IS_ERR(handle)) {
			ret = PTR_ERR(handle);
			goto out_writepages;
		}
		BUG_ON(ext4_test_inode_state(inode,
				EXT4_STATE_MAY_INLINE_DATA));
		ext4_destroy_inline_data(handle, inode);
		ext4_journal_stop(handle);
	}

2575 2576
	/*
	 * data=journal mode does not do delalloc so we just need to writeout /
2577 2578 2579 2580 2581 2582 2583 2584 2585
	 * journal already mapped buffers. On the other hand we need to commit
	 * transaction to make data stable. We expect all the data to be
	 * already in the journal (the only exception are DMA pinned pages
	 * dirtied behind our back) so we commit transaction here and run the
	 * writeback loop to checkpoint them. The checkpointing is not actually
	 * necessary to make data persistent *but* quite a few places (extent
	 * shifting operations, fsverity, ...) depend on being able to drop
	 * pagecache pages after calling filemap_write_and_wait() and for that
	 * checkpointing needs to happen.
2586
	 */
2587
	if (ext4_should_journal_data(inode)) {
2588
		mpd->can_map = 0;
2589 2590 2591 2592 2593
		if (wbc->sync_mode == WB_SYNC_ALL)
			ext4_fc_commit(sbi->s_journal,
				       EXT4_I(inode)->i_datasync_tid);
	}
	mpd->journalled_more_data = 0;
2594

2595 2596 2597 2598 2599 2600 2601 2602 2603
	if (ext4_should_dioread_nolock(inode)) {
		/*
		 * We may need to convert up to one extent per block in
		 * the page and we may dirty the inode.
		 */
		rsv_blocks = 1 + ext4_chunk_trans_blocks(inode,
						PAGE_SIZE >> inode->i_blkbits);
	}

2604 2605
	if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
		range_whole = 1;
2606

2607
	if (wbc->range_cyclic) {
Jan Kara's avatar
Jan Kara committed
2608 2609
		writeback_index = mapping->writeback_index;
		if (writeback_index)
2610
			cycled = 0;
Jan Kara's avatar
Jan Kara committed
2611 2612
		mpd->first_page = writeback_index;
		mpd->last_page = -1;
2613
	} else {
Jan Kara's avatar
Jan Kara committed
2614 2615
		mpd->first_page = wbc->range_start >> PAGE_SHIFT;
		mpd->last_page = wbc->range_end >> PAGE_SHIFT;
2616
	}
2617

Jan Kara's avatar
Jan Kara committed
2618
	ext4_io_submit_init(&mpd->io_submit, wbc);
2619
retry:
2620
	if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
Jan Kara's avatar
Jan Kara committed
2621 2622
		tag_pages_for_writeback(mapping, mpd->first_page,
					mpd->last_page);
2623
	blk_start_plug(&plug);
2624 2625 2626 2627 2628 2629 2630

	/*
	 * First writeback pages that don't need mapping - we can avoid
	 * starting a transaction unnecessarily and also avoid being blocked
	 * in the block layer on device congestion while having transaction
	 * started.
	 */
Jan Kara's avatar
Jan Kara committed
2631 2632 2633 2634
	mpd->do_map = 0;
	mpd->scanned_until_end = 0;
	mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
	if (!mpd->io_submit.io_end) {
2635 2636 2637
		ret = -ENOMEM;
		goto unplug;
	}
Jan Kara's avatar
Jan Kara committed
2638
	ret = mpage_prepare_extent_to_map(mpd);
2639
	/* Unlock pages we didn't use */
Jan Kara's avatar
Jan Kara committed
2640
	mpage_release_unused_pages(mpd, false);
2641
	/* Submit prepared bio */
Jan Kara's avatar
Jan Kara committed
2642 2643 2644
	ext4_io_submit(&mpd->io_submit);
	ext4_put_io_end_defer(mpd->io_submit.io_end);
	mpd->io_submit.io_end = NULL;
2645 2646 2647
	if (ret < 0)
		goto unplug;

Jan Kara's avatar
Jan Kara committed
2648
	while (!mpd->scanned_until_end && wbc->nr_to_write > 0) {
Jan Kara's avatar
Jan Kara committed
2649
		/* For each extent of pages we use new io_end */
Jan Kara's avatar
Jan Kara committed
2650 2651
		mpd->io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL);
		if (!mpd->io_submit.io_end) {
Jan Kara's avatar
Jan Kara committed
2652 2653 2654
			ret = -ENOMEM;
			break;
		}
2655

2656
		WARN_ON_ONCE(!mpd->can_map);
2657
		/*
Jan Kara's avatar
Jan Kara committed
2658 2659 2660 2661 2662
		 * We have two constraints: We find one extent to map and we
		 * must always write out whole page (makes a difference when
		 * blocksize < pagesize) so that we don't block on IO when we
		 * try to write out the rest of the page. Journalled mode is
		 * not supported by delalloc.
2663 2664
		 */
		BUG_ON(ext4_should_journal_data(inode));
2665
		needed_blocks = ext4_da_writepages_trans_blocks(inode);
2666

Jan Kara's avatar
Jan Kara committed
2667
		/* start a new transaction */
2668 2669
		handle = ext4_journal_start_with_reserve(inode,
				EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks);
2670 2671
		if (IS_ERR(handle)) {
			ret = PTR_ERR(handle);
2672
			ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
2673
			       "%ld pages, ino %lu; err %d", __func__,
2674
				wbc->nr_to_write, inode->i_ino, ret);
Jan Kara's avatar
Jan Kara committed
2675
			/* Release allocated io_end */
Jan Kara's avatar
Jan Kara committed
2676 2677
			ext4_put_io_end(mpd->io_submit.io_end);
			mpd->io_submit.io_end = NULL;
Jan Kara's avatar
Jan Kara committed
2678
			break;
2679
		}
Jan Kara's avatar
Jan Kara committed
2680
		mpd->do_map = 1;
2681

Jan Kara's avatar
Jan Kara committed
2682 2683 2684 2685
		trace_ext4_da_write_pages(inode, mpd->first_page, wbc);
		ret = mpage_prepare_extent_to_map(mpd);
		if (!ret && mpd->map.m_len)
			ret = mpage_map_and_submit_extent(handle, mpd,
2686
					&give_up_on_write);
2687 2688 2689 2690 2691
		/*
		 * Caution: If the handle is synchronous,
		 * ext4_journal_stop() can wait for transaction commit
		 * to finish which may depend on writeback of pages to
		 * complete or on page lock to be released.  In that
2692
		 * case, we have to wait until after we have
2693 2694 2695 2696 2697 2698 2699
		 * submitted all the IO, released page locks we hold,
		 * and dropped io_end reference (for extent conversion
		 * to be able to complete) before stopping the handle.
		 */
		if (!ext4_handle_valid(handle) || handle->h_sync == 0) {
			ext4_journal_stop(handle);
			handle = NULL;
Jan Kara's avatar
Jan Kara committed
2700
			mpd->do_map = 0;
2701
		}
Jan Kara's avatar
Jan Kara committed
2702
		/* Unlock pages we didn't use */
Jan Kara's avatar
Jan Kara committed
2703
		mpage_release_unused_pages(mpd, give_up_on_write);
2704
		/* Submit prepared bio */
Jan Kara's avatar
Jan Kara committed
2705
		ext4_io_submit(&mpd->io_submit);
2706

2707 2708 2709 2710 2711 2712 2713 2714
		/*
		 * Drop our io_end reference we got from init. We have
		 * to be careful and use deferred io_end finishing if
		 * we are still holding the transaction as we can
		 * release the last reference to io_end which may end
		 * up doing unwritten extent conversion.
		 */
		if (handle) {
Jan Kara's avatar
Jan Kara committed
2715
			ext4_put_io_end_defer(mpd->io_submit.io_end);
2716 2717
			ext4_journal_stop(handle);
		} else
Jan Kara's avatar
Jan Kara committed
2718 2719
			ext4_put_io_end(mpd->io_submit.io_end);
		mpd->io_submit.io_end = NULL;
Jan Kara's avatar
Jan Kara committed
2720 2721 2722 2723

		if (ret == -ENOSPC && sbi->s_journal) {
			/*
			 * Commit the transaction which would
2724 2725 2726
			 * free blocks released in the transaction
			 * and try again
			 */
2727
			jbd2_journal_force_commit_nested(sbi->s_journal);
2728
			ret = 0;
Jan Kara's avatar
Jan Kara committed
2729 2730 2731 2732
			continue;
		}
		/* Fatal error - ENOMEM, EIO... */
		if (ret)
2733
			break;
2734
	}
2735
unplug:
2736
	blk_finish_plug(&plug);
2737
	if (!ret && !cycled && wbc->nr_to_write > 0) {
2738
		cycled = 1;
Jan Kara's avatar
Jan Kara committed
2739 2740
		mpd->last_page = writeback_index - 1;
		mpd->first_page = 0;
2741 2742
		goto retry;
	}
2743 2744 2745 2746

	/* Update index */
	if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
		/*
Jan Kara's avatar
Jan Kara committed
2747
		 * Set the writeback_index so that range_cyclic
2748 2749
		 * mode will write it back later
		 */
Jan Kara's avatar
Jan Kara committed
2750
		mapping->writeback_index = mpd->first_page;
2751

2752
out_writepages:
2753 2754
	trace_ext4_writepages_result(inode, wbc, ret,
				     nr_to_write - wbc->nr_to_write);
2755
	return ret;
2756 2757
}

Jan Kara's avatar
Jan Kara committed
2758 2759 2760
static int ext4_writepages(struct address_space *mapping,
			   struct writeback_control *wbc)
{
2761
	struct super_block *sb = mapping->host->i_sb;
Jan Kara's avatar
Jan Kara committed
2762 2763 2764 2765 2766
	struct mpage_da_data mpd = {
		.inode = mapping->host,
		.wbc = wbc,
		.can_map = 1,
	};
2767
	int ret;
2768
	int alloc_ctx;
2769

2770
	if (unlikely(ext4_forced_shutdown(sb)))
2771
		return -EIO;
Jan Kara's avatar
Jan Kara committed
2772

2773
	alloc_ctx = ext4_writepages_down_read(sb);
2774
	ret = ext4_do_writepages(&mpd);
2775 2776 2777 2778 2779 2780 2781
	/*
	 * For data=journal writeback we could have come across pages marked
	 * for delayed dirtying (PageChecked) which were just added to the
	 * running transaction. Try once more to get them to stable storage.
	 */
	if (!ret && mpd.journalled_more_data)
		ret = ext4_do_writepages(&mpd);
2782
	ext4_writepages_up_read(sb, alloc_ctx);
2783 2784

	return ret;
Jan Kara's avatar
Jan Kara committed
2785 2786
}

2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802
int ext4_normal_submit_inode_data_buffers(struct jbd2_inode *jinode)
{
	struct writeback_control wbc = {
		.sync_mode = WB_SYNC_ALL,
		.nr_to_write = LONG_MAX,
		.range_start = jinode->i_dirty_start,
		.range_end = jinode->i_dirty_end,
	};
	struct mpage_da_data mpd = {
		.inode = jinode->i_vfs_inode,
		.wbc = &wbc,
		.can_map = 0,
	};
	return ext4_do_writepages(&mpd);
}

2803 2804 2805 2806 2807 2808
static int ext4_dax_writepages(struct address_space *mapping,
			       struct writeback_control *wbc)
{
	int ret;
	long nr_to_write = wbc->nr_to_write;
	struct inode *inode = mapping->host;
2809
	int alloc_ctx;
2810

2811
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2812 2813
		return -EIO;

2814
	alloc_ctx = ext4_writepages_down_read(inode->i_sb);
2815 2816
	trace_ext4_writepages(inode, wbc);

2817 2818
	ret = dax_writeback_mapping_range(mapping,
					  EXT4_SB(inode->i_sb)->s_daxdev, wbc);
2819 2820
	trace_ext4_writepages_result(inode, wbc, ret,
				     nr_to_write - wbc->nr_to_write);
2821
	ext4_writepages_up_read(inode->i_sb, alloc_ctx);
2822 2823 2824
	return ret;
}

2825 2826
static int ext4_nonda_switch(struct super_block *sb)
{
2827
	s64 free_clusters, dirty_clusters;
2828 2829 2830 2831 2832
	struct ext4_sb_info *sbi = EXT4_SB(sb);

	/*
	 * switch to non delalloc mode if we are running low
	 * on free block. The free block accounting via percpu
2833
	 * counters can get slightly wrong with percpu_counter_batch getting
2834 2835 2836 2837
	 * accumulated on each CPU without updating global counters
	 * Delalloc need an accurate free block accounting. So switch
	 * to non delalloc when we are near to error range.
	 */
2838 2839 2840 2841
	free_clusters =
		percpu_counter_read_positive(&sbi->s_freeclusters_counter);
	dirty_clusters =
		percpu_counter_read_positive(&sbi->s_dirtyclusters_counter);
2842 2843 2844
	/*
	 * Start pushing delalloc when 1/2 of free blocks are dirty.
	 */
2845
	if (dirty_clusters && (free_clusters < 2 * dirty_clusters))
2846
		try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE);
2847

2848 2849
	if (2 * free_clusters < 3 * dirty_clusters ||
	    free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) {
2850
		/*
2851 2852
		 * free block count is less than 150% of dirty blocks
		 * or free blocks is less than watermark
2853 2854 2855 2856 2857 2858
		 */
		return 1;
	}
	return 0;
}

2859
static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
2860
			       loff_t pos, unsigned len,
2861
			       struct page **pagep, void **fsdata)
2862
{
2863
	int ret, retries = 0;
2864
	struct folio *folio;
2865 2866 2867
	pgoff_t index;
	struct inode *inode = mapping->host;

2868
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
2869 2870
		return -EIO;

2871
	index = pos >> PAGE_SHIFT;
2872

2873
	if (ext4_nonda_switch(inode->i_sb) || ext4_verity_in_progress(inode)) {
2874 2875
		*fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
		return ext4_write_begin(file, mapping, pos,
2876
					len, pagep, fsdata);
2877 2878
	}
	*fsdata = (void *)0;
2879
	trace_ext4_da_write_begin(inode, pos, len);
2880 2881

	if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) {
2882
		ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len,
2883 2884
						      pagep, fsdata);
		if (ret < 0)
2885 2886 2887
			return ret;
		if (ret == 1)
			return 0;
2888 2889
	}

2890
retry:
2891 2892
	folio = __filemap_get_folio(mapping, index, FGP_WRITEBEGIN,
			mapping_gfp_mask(mapping));
2893 2894
	if (IS_ERR(folio))
		return PTR_ERR(folio);
2895

2896 2897
	/* In case writeback began while the folio was unlocked */
	folio_wait_stable(folio);
2898

2899
#ifdef CONFIG_FS_ENCRYPTION
2900
	ret = ext4_block_write_begin(folio, pos, len, ext4_da_get_block_prep);
2901
#else
2902
	ret = __block_write_begin(&folio->page, pos, len, ext4_da_get_block_prep);
2903
#endif
2904
	if (ret < 0) {
2905 2906
		folio_unlock(folio);
		folio_put(folio);
2907 2908 2909
		/*
		 * block_write_begin may have instantiated a few blocks
		 * outside i_size.  Trim these off again. Don't need
2910
		 * i_size_read because we hold inode lock.
2911 2912
		 */
		if (pos + len > inode->i_size)
2913
			ext4_truncate_failed_write(inode);
2914 2915 2916

		if (ret == -ENOSPC &&
		    ext4_should_retry_alloc(inode->i_sb, &retries))
2917
			goto retry;
2918
		return ret;
2919 2920
	}

2921
	*pagep = &folio->page;
2922 2923 2924
	return ret;
}

2925 2926 2927 2928
/*
 * Check if we should update i_disksize
 * when write to the end of file but not require block allocation
 */
2929
static int ext4_da_should_update_i_disksize(struct folio *folio,
2930
					    unsigned long offset)
2931 2932
{
	struct buffer_head *bh;
2933
	struct inode *inode = folio->mapping->host;
2934 2935 2936
	unsigned int idx;
	int i;

2937
	bh = folio_buffers(folio);
2938 2939
	idx = offset >> inode->i_blkbits;

2940
	for (i = 0; i < idx; i++)
2941 2942
		bh = bh->b_this_page;

2943
	if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
2944 2945 2946 2947
		return 0;
	return 1;
}

2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
static int ext4_da_do_write_end(struct address_space *mapping,
			loff_t pos, unsigned len, unsigned copied,
			struct page *page)
{
	struct inode *inode = mapping->host;
	loff_t old_size = inode->i_size;
	bool disksize_changed = false;
	loff_t new_i_size;

	/*
	 * block_write_end() will mark the inode as dirty with I_DIRTY_PAGES
	 * flag, which all that's needed to trigger page writeback.
	 */
	copied = block_write_end(NULL, mapping, pos, len, copied, page, NULL);
	new_i_size = pos + copied;

	/*
	 * It's important to update i_size while still holding page lock,
	 * because page writeout could otherwise come in and zero beyond
	 * i_size.
	 *
	 * Since we are holding inode lock, we are sure i_disksize <=
	 * i_size. We also know that if i_disksize < i_size, there are
	 * delalloc writes pending in the range up to i_size. If the end of
	 * the current write is <= i_size, there's no need to touch
	 * i_disksize since writeback will push i_disksize up to i_size
	 * eventually. If the end of the current write is > i_size and
	 * inside an allocated block which ext4_da_should_update_i_disksize()
	 * checked, we need to update i_disksize here as certain
	 * ext4_writepages() paths not allocating blocks and update i_disksize.
	 */
	if (new_i_size > inode->i_size) {
		unsigned long end;

		i_size_write(inode, new_i_size);
		end = (new_i_size - 1) & (PAGE_SIZE - 1);
		if (copied && ext4_da_should_update_i_disksize(page_folio(page), end)) {
			ext4_update_i_disksize(inode, new_i_size);
			disksize_changed = true;
		}
	}

	unlock_page(page);
	put_page(page);

	if (old_size < pos)
		pagecache_isize_extended(inode, old_size, pos);

	if (disksize_changed) {
		handle_t *handle;

		handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
		if (IS_ERR(handle))
			return PTR_ERR(handle);
		ext4_mark_inode_dirty(handle, inode);
		ext4_journal_stop(handle);
	}

	return copied;
}

3009
static int ext4_da_write_end(struct file *file,
3010 3011 3012
			     struct address_space *mapping,
			     loff_t pos, unsigned len, unsigned copied,
			     struct page *page, void *fsdata)
3013 3014
{
	struct inode *inode = mapping->host;
3015
	int write_mode = (int)(unsigned long)fsdata;
3016
	struct folio *folio = page_folio(page);
3017

3018 3019
	if (write_mode == FALL_BACK_TO_NONDELALLOC)
		return ext4_write_end(file, mapping, pos,
3020
				      len, copied, &folio->page, fsdata);
3021

3022
	trace_ext4_da_write_end(inode, pos, len, copied);
3023 3024 3025 3026

	if (write_mode != CONVERT_INLINE_DATA &&
	    ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) &&
	    ext4_has_inline_data(inode))
3027 3028
		return ext4_write_inline_data_end(inode, pos, len, copied,
						  folio);
3029

3030 3031 3032
	if (unlikely(copied < len) && !PageUptodate(page))
		copied = 0;

3033
	return ext4_da_do_write_end(mapping, pos, len, copied, &folio->page);
3034 3035
}

3036 3037 3038 3039 3040
/*
 * Force all delayed allocation blocks to be allocated for a given inode.
 */
int ext4_alloc_da_blocks(struct inode *inode)
{
3041 3042
	trace_ext4_alloc_da_blocks(inode);

3043
	if (!EXT4_I(inode)->i_reserved_data_blocks)
3044 3045 3046 3047 3048 3049 3050 3051
		return 0;

	/*
	 * We do something simple for now.  The filemap_flush() will
	 * also start triggering a write of the data blocks, which is
	 * not strictly speaking necessary (and for users of
	 * laptop_mode, not even desirable).  However, to do otherwise
	 * would require replicating code paths in:
3052
	 *
3053
	 * ext4_writepages() ->
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064
	 *    write_cache_pages() ---> (via passed in callback function)
	 *        __mpage_da_writepage() -->
	 *           mpage_add_bh_to_extent()
	 *           mpage_da_map_blocks()
	 *
	 * The problem is that write_cache_pages(), located in
	 * mm/page-writeback.c, marks pages clean in preparation for
	 * doing I/O, which is not desirable if we're not planning on
	 * doing I/O at all.
	 *
	 * We could call write_cache_pages(), and then redirty all of
3065
	 * the pages by calling redirty_page_for_writepage() but that
3066 3067
	 * would be ugly in the extreme.  So instead we would need to
	 * replicate parts of the code in the above functions,
Lucas De Marchi's avatar
Lucas De Marchi committed
3068
	 * simplifying them because we wouldn't actually intend to
3069 3070 3071
	 * write out the pages, but rather only collect contiguous
	 * logical block extents, call the multi-block allocator, and
	 * then update the buffer heads with the block allocations.
3072
	 *
3073 3074 3075 3076 3077 3078
	 * For now, though, we'll cheat by calling filemap_flush(),
	 * which will map the blocks, and start the I/O, but not
	 * actually wait for the I/O to complete.
	 */
	return filemap_flush(inode->i_mapping);
}
3079

3080 3081 3082 3083 3084
/*
 * bmap() is special.  It gets used by applications such as lilo and by
 * the swapper to find the on-disk block of a specific piece of data.
 *
 * Naturally, this is dangerous if the block concerned is still in the
3085
 * journal.  If somebody makes a swapfile on an ext4 data-journaling
3086 3087 3088 3089 3090 3091 3092 3093
 * filesystem and enables swap, then they may get a nasty shock when the
 * data getting swapped to that swapfile suddenly gets overwritten by
 * the original zero's written out previously to the journal and
 * awaiting writeback in the kernel's buffer cache.
 *
 * So, if we see any bmap calls here on a modified, data-journaled file,
 * take extra steps to flush any blocks which might be in the cache.
 */
3094
static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
3095 3096
{
	struct inode *inode = mapping->host;
3097
	sector_t ret = 0;
3098

3099
	inode_lock_shared(inode);
3100 3101 3102 3103
	/*
	 * We can get here for an inline file via the FIBMAP ioctl
	 */
	if (ext4_has_inline_data(inode))
3104
		goto out;
3105

3106
	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
3107 3108
	    (test_opt(inode->i_sb, DELALLOC) ||
	     ext4_should_journal_data(inode))) {
3109
		/*
3110 3111 3112
		 * With delalloc or journalled data we want to sync the file so
		 * that we can make sure we allocate blocks for file and data
		 * is in place for the user to see it
3113 3114 3115 3116
		 */
		filemap_write_and_wait(mapping);
	}

3117 3118 3119 3120 3121
	ret = iomap_bmap(mapping, block, &ext4_iomap_ops);

out:
	inode_unlock_shared(inode);
	return ret;
3122 3123
}

3124
static int ext4_read_folio(struct file *file, struct folio *folio)
3125
{
3126
	int ret = -EAGAIN;
3127
	struct inode *inode = folio->mapping->host;
3128

3129
	trace_ext4_read_folio(inode, folio);
3130 3131

	if (ext4_has_inline_data(inode))
3132
		ret = ext4_readpage_inline(inode, folio);
3133 3134

	if (ret == -EAGAIN)
3135
		return ext4_mpage_readpages(inode, NULL, folio);
3136 3137

	return ret;
3138 3139
}

3140
static void ext4_readahead(struct readahead_control *rac)
3141
{
3142
	struct inode *inode = rac->mapping->host;
3143

3144
	/* If the file has inline data, no need to do readahead. */
3145
	if (ext4_has_inline_data(inode))
3146
		return;
3147

3148
	ext4_mpage_readpages(inode, rac, NULL);
3149 3150
}

3151 3152
static void ext4_invalidate_folio(struct folio *folio, size_t offset,
				size_t length)
3153
{
3154
	trace_ext4_invalidate_folio(folio, offset, length);
3155

3156
	/* No journalling happens on data buffers when this function is used */
3157
	WARN_ON(folio_buffers(folio) && buffer_jbd(folio_buffers(folio)));
3158

3159
	block_invalidate_folio(folio, offset, length);
3160 3161
}

3162 3163
static int __ext4_journalled_invalidate_folio(struct folio *folio,
					    size_t offset, size_t length)
3164
{
3165
	journal_t *journal = EXT4_JOURNAL(folio->mapping->host);
3166

3167
	trace_ext4_journalled_invalidate_folio(folio, offset, length);
3168

3169 3170 3171
	/*
	 * If it's a full truncate we just forget about the pending dirtying
	 */
3172 3173
	if (offset == 0 && length == folio_size(folio))
		folio_clear_checked(folio);
3174

3175
	return jbd2_journal_invalidate_folio(journal, folio, offset, length);
3176 3177 3178
}

/* Wrapper for aops... */
3179 3180 3181
static void ext4_journalled_invalidate_folio(struct folio *folio,
					   size_t offset,
					   size_t length)
3182
{
3183
	WARN_ON(__ext4_journalled_invalidate_folio(folio, offset, length) < 0);
3184 3185
}

3186
static bool ext4_release_folio(struct folio *folio, gfp_t wait)
3187
{
3188 3189
	struct inode *inode = folio->mapping->host;
	journal_t *journal = EXT4_JOURNAL(inode);
3190

3191
	trace_ext4_release_folio(inode, folio);
3192

3193
	/* Page has dirty journalled data -> cannot release */
3194 3195
	if (folio_test_checked(folio))
		return false;
3196
	if (journal)
3197
		return jbd2_journal_try_to_free_buffers(journal, folio);
3198
	else
3199
		return try_to_free_buffers(folio);
3200 3201
}

3202 3203 3204 3205
static bool ext4_inode_datasync_dirty(struct inode *inode)
{
	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;

3206 3207
	if (journal) {
		if (jbd2_transaction_committed(journal,
3208 3209 3210
			EXT4_I(inode)->i_datasync_tid))
			return false;
		if (test_opt2(inode->i_sb, JOURNAL_FAST_COMMIT))
3211
			return !list_empty(&EXT4_I(inode)->i_fc_list);
3212
		return true;
3213 3214
	}

3215 3216 3217 3218 3219 3220
	/* Any metadata buffers to write? */
	if (!list_empty(&inode->i_mapping->private_list))
		return true;
	return inode->i_state & I_DIRTY_DATASYNC;
}

3221 3222
static void ext4_set_iomap(struct inode *inode, struct iomap *iomap,
			   struct ext4_map_blocks *map, loff_t offset,
3223
			   loff_t length, unsigned int flags)
3224
{
3225
	u8 blkbits = inode->i_blkbits;
3226

3227 3228 3229 3230 3231
	/*
	 * Writes that span EOF might trigger an I/O size update on completion,
	 * so consider them to be dirty for the purpose of O_DSYNC, even if
	 * there is no other metadata changes being made or are pending.
	 */
3232
	iomap->flags = 0;
3233 3234
	if (ext4_inode_datasync_dirty(inode) ||
	    offset + length > i_size_read(inode))
3235
		iomap->flags |= IOMAP_F_DIRTY;
3236 3237 3238 3239

	if (map->m_flags & EXT4_MAP_NEW)
		iomap->flags |= IOMAP_F_NEW;

3240 3241 3242 3243
	if (flags & IOMAP_DAX)
		iomap->dax_dev = EXT4_SB(inode->i_sb)->s_daxdev;
	else
		iomap->bdev = inode->i_sb->s_bdev;
3244 3245
	iomap->offset = (u64) map->m_lblk << blkbits;
	iomap->length = (u64) map->m_len << blkbits;
3246

3247 3248 3249 3250
	if ((map->m_flags & EXT4_MAP_MAPPED) &&
	    !ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
		iomap->flags |= IOMAP_F_MERGED;

3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
	/*
	 * Flags passed to ext4_map_blocks() for direct I/O writes can result
	 * in m_flags having both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN bits
	 * set. In order for any allocated unwritten extents to be converted
	 * into written extents correctly within the ->end_io() handler, we
	 * need to ensure that the iomap->type is set appropriately. Hence, the
	 * reason why we need to check whether the EXT4_MAP_UNWRITTEN bit has
	 * been set first.
	 */
	if (map->m_flags & EXT4_MAP_UNWRITTEN) {
		iomap->type = IOMAP_UNWRITTEN;
		iomap->addr = (u64) map->m_pblk << blkbits;
3263 3264
		if (flags & IOMAP_DAX)
			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3265 3266 3267
	} else if (map->m_flags & EXT4_MAP_MAPPED) {
		iomap->type = IOMAP_MAPPED;
		iomap->addr = (u64) map->m_pblk << blkbits;
3268 3269
		if (flags & IOMAP_DAX)
			iomap->addr += EXT4_SB(inode->i_sb)->s_dax_part_off;
3270
	} else {
3271 3272
		iomap->type = IOMAP_HOLE;
		iomap->addr = IOMAP_NULL_ADDR;
3273 3274 3275
	}
}

3276 3277
static int ext4_iomap_alloc(struct inode *inode, struct ext4_map_blocks *map,
			    unsigned int flags)
Jan Kara's avatar
Jan Kara committed
3278 3279
{
	handle_t *handle;
3280 3281
	u8 blkbits = inode->i_blkbits;
	int ret, dio_credits, m_flags = 0, retries = 0;
Jan Kara's avatar
Jan Kara committed
3282 3283

	/*
3284 3285
	 * Trim the mapping request to the maximum value that we can map at
	 * once for direct I/O.
Jan Kara's avatar
Jan Kara committed
3286
	 */
3287 3288 3289
	if (map->m_len > DIO_MAX_BLOCKS)
		map->m_len = DIO_MAX_BLOCKS;
	dio_credits = ext4_chunk_trans_blocks(inode, map->m_len);
Jan Kara's avatar
Jan Kara committed
3290

3291
retry:
Jan Kara's avatar
Jan Kara committed
3292
	/*
3293 3294 3295 3296
	 * Either we allocate blocks and then don't get an unwritten extent, so
	 * in that case we have reserved enough credits. Or, the blocks are
	 * already allocated and unwritten. In that case, the extent conversion
	 * fits into the credits as well.
Jan Kara's avatar
Jan Kara committed
3297
	 */
3298 3299 3300
	handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits);
	if (IS_ERR(handle))
		return PTR_ERR(handle);
3301

3302 3303 3304 3305
	/*
	 * DAX and direct I/O are the only two operations that are currently
	 * supported with IOMAP_WRITE.
	 */
3306 3307
	WARN_ON(!(flags & (IOMAP_DAX | IOMAP_DIRECT)));
	if (flags & IOMAP_DAX)
3308 3309 3310 3311 3312 3313 3314
		m_flags = EXT4_GET_BLOCKS_CREATE_ZERO;
	/*
	 * We use i_size instead of i_disksize here because delalloc writeback
	 * can complete at any point during the I/O and subsequently push the
	 * i_disksize out to i_size. This could be beyond where direct I/O is
	 * happening and thus expose allocated blocks to direct I/O reads.
	 */
3315
	else if (((loff_t)map->m_lblk << blkbits) >= i_size_read(inode))
3316 3317 3318
		m_flags = EXT4_GET_BLOCKS_CREATE;
	else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
		m_flags = EXT4_GET_BLOCKS_IO_CREATE_EXT;
3319

3320
	ret = ext4_map_blocks(handle, inode, map, m_flags);
3321

3322
	/*
3323 3324 3325
	 * We cannot fill holes in indirect tree based inodes as that could
	 * expose stale data in the case of a crash. Use the magic error code
	 * to fallback to buffered I/O.
3326
	 */
3327 3328
	if (!m_flags && !ret)
		ret = -ENOTBLK;
3329

3330 3331 3332 3333 3334
	ext4_journal_stop(handle);
	if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
		goto retry;

	return ret;
3335
}
3336

3337

3338
static int ext4_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
3339
		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
3340
{
3341
	int ret;
3342 3343
	struct ext4_map_blocks map;
	u8 blkbits = inode->i_blkbits;
3344

3345 3346
	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
		return -EINVAL;
3347

3348 3349
	if (WARN_ON_ONCE(ext4_has_inline_data(inode)))
		return -ERANGE;
3350

3351
	/*
3352
	 * Calculate the first and last logical blocks respectively.
3353
	 */
3354 3355 3356
	map.m_lblk = offset >> blkbits;
	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3357

3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
	if (flags & IOMAP_WRITE) {
		/*
		 * We check here if the blocks are already allocated, then we
		 * don't need to start a journal txn and we can directly return
		 * the mapping information. This could boost performance
		 * especially in multi-threaded overwrite requests.
		 */
		if (offset + length <= i_size_read(inode)) {
			ret = ext4_map_blocks(NULL, inode, &map, 0);
			if (ret > 0 && (map.m_flags & EXT4_MAP_MAPPED))
				goto out;
		}
3370
		ret = ext4_iomap_alloc(inode, &map, flags);
3371
	} else {
3372
		ret = ext4_map_blocks(NULL, inode, &map, 0);
3373
	}
3374

3375 3376
	if (ret < 0)
		return ret;
3377
out:
3378 3379 3380 3381 3382 3383 3384
	/*
	 * When inline encryption is enabled, sometimes I/O to an encrypted file
	 * has to be broken up to guarantee DUN contiguity.  Handle this by
	 * limiting the length of the mapping returned.
	 */
	map.m_len = fscrypt_limit_io_blocks(inode, map.m_lblk, map.m_len);

3385
	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3386

3387 3388
	return 0;
}
3389

Jan Kara's avatar
Jan Kara committed
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401
static int ext4_iomap_overwrite_begin(struct inode *inode, loff_t offset,
		loff_t length, unsigned flags, struct iomap *iomap,
		struct iomap *srcmap)
{
	int ret;

	/*
	 * Even for writes we don't need to allocate blocks, so just pretend
	 * we are reading to save overhead of starting a transaction.
	 */
	flags &= ~IOMAP_WRITE;
	ret = ext4_iomap_begin(inode, offset, length, flags, iomap, srcmap);
3402
	WARN_ON_ONCE(!ret && iomap->type != IOMAP_MAPPED);
Jan Kara's avatar
Jan Kara committed
3403 3404 3405
	return ret;
}

Jan Kara's avatar
Jan Kara committed
3406 3407 3408
static int ext4_iomap_end(struct inode *inode, loff_t offset, loff_t length,
			  ssize_t written, unsigned flags, struct iomap *iomap)
{
3409
	/*
3410 3411 3412 3413 3414
	 * Check to see whether an error occurred while writing out the data to
	 * the allocated blocks. If so, return the magic error code so that we
	 * fallback to buffered I/O and attempt to complete the remainder of
	 * the I/O. Any blocks that may have been allocated in preparation for
	 * the direct I/O will be reused during buffered I/O.
3415
	 */
3416 3417
	if (flags & (IOMAP_WRITE | IOMAP_DIRECT) && written == 0)
		return -ENOTBLK;
3418

3419
	return 0;
Jan Kara's avatar
Jan Kara committed
3420
}
3421

3422
const struct iomap_ops ext4_iomap_ops = {
3423
	.iomap_begin		= ext4_iomap_begin,
Jan Kara's avatar
Jan Kara committed
3424
	.iomap_end		= ext4_iomap_end,
3425
};
3426

Jan Kara's avatar
Jan Kara committed
3427 3428 3429 3430 3431
const struct iomap_ops ext4_iomap_overwrite_ops = {
	.iomap_begin		= ext4_iomap_overwrite_begin,
	.iomap_end		= ext4_iomap_end,
};

3432 3433 3434 3435 3436
static bool ext4_iomap_is_delalloc(struct inode *inode,
				   struct ext4_map_blocks *map)
{
	struct extent_status es;
	ext4_lblk_t offset = 0, end = map->m_lblk + map->m_len - 1;
Jan Kara's avatar
Jan Kara committed
3437

3438 3439
	ext4_es_find_extent_range(inode, &ext4_es_is_delayed,
				  map->m_lblk, end, &es);
Jan Kara's avatar
Jan Kara committed
3440

3441 3442
	if (!es.es_len || es.es_lblk > end)
		return false;
Jan Kara's avatar
Jan Kara committed
3443

3444 3445 3446
	if (es.es_lblk > map->m_lblk) {
		map->m_len = es.es_lblk - map->m_lblk;
		return false;
Jan Kara's avatar
Jan Kara committed
3447 3448
	}

3449 3450
	offset = map->m_lblk - es.es_lblk;
	map->m_len = es.es_len - offset;
Jan Kara's avatar
Jan Kara committed
3451

3452
	return true;
3453 3454
}

3455 3456 3457
static int ext4_iomap_begin_report(struct inode *inode, loff_t offset,
				   loff_t length, unsigned int flags,
				   struct iomap *iomap, struct iomap *srcmap)
3458
{
3459 3460 3461 3462
	int ret;
	bool delalloc = false;
	struct ext4_map_blocks map;
	u8 blkbits = inode->i_blkbits;
3463

3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474
	if ((offset >> blkbits) > EXT4_MAX_LOGICAL_BLOCK)
		return -EINVAL;

	if (ext4_has_inline_data(inode)) {
		ret = ext4_inline_data_iomap(inode, iomap);
		if (ret != -EAGAIN) {
			if (ret == 0 && offset >= iomap->length)
				ret = -ENOENT;
			return ret;
		}
	}
3475

3476
	/*
3477
	 * Calculate the first and last logical block respectively.
3478
	 */
3479 3480 3481
	map.m_lblk = offset >> blkbits;
	map.m_len = min_t(loff_t, (offset + length - 1) >> blkbits,
			  EXT4_MAX_LOGICAL_BLOCK) - map.m_lblk + 1;
3482

3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
	/*
	 * Fiemap callers may call for offset beyond s_bitmap_maxbytes.
	 * So handle it here itself instead of querying ext4_map_blocks().
	 * Since ext4_map_blocks() will warn about it and will return
	 * -EIO error.
	 */
	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);

		if (offset >= sbi->s_bitmap_maxbytes) {
			map.m_flags = 0;
			goto set_iomap;
		}
	}

3498 3499 3500 3501 3502
	ret = ext4_map_blocks(NULL, inode, &map, 0);
	if (ret < 0)
		return ret;
	if (ret == 0)
		delalloc = ext4_iomap_is_delalloc(inode, &map);
3503

3504
set_iomap:
3505
	ext4_set_iomap(inode, iomap, &map, offset, length, flags);
3506 3507 3508 3509
	if (delalloc && iomap->type == IOMAP_HOLE)
		iomap->type = IOMAP_DELALLOC;

	return 0;
3510 3511
}

3512 3513 3514 3515
const struct iomap_ops ext4_iomap_report_ops = {
	.iomap_begin = ext4_iomap_begin_report,
};

3516
/*
3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
 * For data=journal mode, folio should be marked dirty only when it was
 * writeably mapped. When that happens, it was already attached to the
 * transaction and marked as jbddirty (we take care of this in
 * ext4_page_mkwrite()). On transaction commit, we writeprotect page mappings
 * so we should have nothing to do here, except for the case when someone
 * had the page pinned and dirtied the page through this pin (e.g. by doing
 * direct IO to it). In that case we'd need to attach buffers here to the
 * transaction but we cannot due to lock ordering.  We cannot just dirty the
 * folio and leave attached buffers clean, because the buffers' dirty state is
 * "definitive".  We cannot just set the buffers dirty or jbddirty because all
 * the journalling code will explode.  So what we do is to mark the folio
 * "pending dirty" and next time ext4_writepages() is called, attach buffers
 * to the transaction appropriately.
3530
 */
3531 3532
static bool ext4_journalled_dirty_folio(struct address_space *mapping,
		struct folio *folio)
3533
{
3534
	WARN_ON_ONCE(!folio_buffers(folio));
3535 3536
	if (folio_maybe_dma_pinned(folio))
		folio_set_checked(folio);
3537
	return filemap_dirty_folio(mapping, folio);
3538 3539
}

3540
static bool ext4_dirty_folio(struct address_space *mapping, struct folio *folio)
3541
{
3542 3543 3544
	WARN_ON_ONCE(!folio_test_locked(folio) && !folio_test_dirty(folio));
	WARN_ON_ONCE(!folio_buffers(folio));
	return block_dirty_folio(mapping, folio);
3545 3546
}

3547 3548 3549 3550 3551 3552 3553
static int ext4_iomap_swap_activate(struct swap_info_struct *sis,
				    struct file *file, sector_t *span)
{
	return iomap_swapfile_activate(sis, file, span,
				       &ext4_iomap_report_ops);
}

3554
static const struct address_space_operations ext4_aops = {
3555
	.read_folio		= ext4_read_folio,
3556
	.readahead		= ext4_readahead,
3557
	.writepages		= ext4_writepages,
3558
	.write_begin		= ext4_write_begin,
3559
	.write_end		= ext4_write_end,
3560
	.dirty_folio		= ext4_dirty_folio,
3561
	.bmap			= ext4_bmap,
3562
	.invalidate_folio	= ext4_invalidate_folio,
3563
	.release_folio		= ext4_release_folio,
3564
	.direct_IO		= noop_direct_IO,
3565
	.migrate_folio		= buffer_migrate_folio,
3566
	.is_partially_uptodate  = block_is_partially_uptodate,
3567
	.error_remove_page	= generic_error_remove_page,
3568
	.swap_activate		= ext4_iomap_swap_activate,
3569 3570
};

3571
static const struct address_space_operations ext4_journalled_aops = {
3572
	.read_folio		= ext4_read_folio,
3573
	.readahead		= ext4_readahead,
3574
	.writepages		= ext4_writepages,
3575 3576
	.write_begin		= ext4_write_begin,
	.write_end		= ext4_journalled_write_end,
3577
	.dirty_folio		= ext4_journalled_dirty_folio,
3578
	.bmap			= ext4_bmap,
3579
	.invalidate_folio	= ext4_journalled_invalidate_folio,
3580
	.release_folio		= ext4_release_folio,
3581
	.direct_IO		= noop_direct_IO,
3582
	.migrate_folio		= buffer_migrate_folio_norefs,
3583
	.is_partially_uptodate  = block_is_partially_uptodate,
3584
	.error_remove_page	= generic_error_remove_page,
3585
	.swap_activate		= ext4_iomap_swap_activate,
3586 3587
};

3588
static const struct address_space_operations ext4_da_aops = {
3589
	.read_folio		= ext4_read_folio,
3590
	.readahead		= ext4_readahead,
3591
	.writepages		= ext4_writepages,
3592 3593
	.write_begin		= ext4_da_write_begin,
	.write_end		= ext4_da_write_end,
3594
	.dirty_folio		= ext4_dirty_folio,
3595
	.bmap			= ext4_bmap,
3596
	.invalidate_folio	= ext4_invalidate_folio,
3597
	.release_folio		= ext4_release_folio,
3598
	.direct_IO		= noop_direct_IO,
3599
	.migrate_folio		= buffer_migrate_folio,
3600
	.is_partially_uptodate  = block_is_partially_uptodate,
3601
	.error_remove_page	= generic_error_remove_page,
3602
	.swap_activate		= ext4_iomap_swap_activate,
3603 3604
};

3605 3606 3607
static const struct address_space_operations ext4_dax_aops = {
	.writepages		= ext4_dax_writepages,
	.direct_IO		= noop_direct_IO,
3608
	.dirty_folio		= noop_dirty_folio,
3609
	.bmap			= ext4_bmap,
3610
	.swap_activate		= ext4_iomap_swap_activate,
3611 3612
};

3613
void ext4_set_aops(struct inode *inode)
3614
{
3615 3616 3617 3618 3619
	switch (ext4_inode_journal_mode(inode)) {
	case EXT4_INODE_ORDERED_DATA_MODE:
	case EXT4_INODE_WRITEBACK_DATA_MODE:
		break;
	case EXT4_INODE_JOURNAL_DATA_MODE:
3620
		inode->i_mapping->a_ops = &ext4_journalled_aops;
3621
		return;
3622 3623 3624
	default:
		BUG();
	}
3625 3626 3627
	if (IS_DAX(inode))
		inode->i_mapping->a_ops = &ext4_dax_aops;
	else if (test_opt(inode->i_sb, DELALLOC))
3628 3629 3630
		inode->i_mapping->a_ops = &ext4_da_aops;
	else
		inode->i_mapping->a_ops = &ext4_aops;
3631 3632
}

3633 3634 3635 3636 3637 3638
/*
 * Here we can't skip an unwritten buffer even though it usually reads zero
 * because it might have data in pagecache (eg, if called from ext4_zero_range,
 * ext4_punch_hole, etc) which needs to be properly zeroed out. Otherwise a
 * racing writeback can come later and flush the stale pagecache to disk.
 */
Ross Zwisler's avatar
Ross Zwisler committed
3639
static int __ext4_block_zero_page_range(handle_t *handle,
3640 3641
		struct address_space *mapping, loff_t from, loff_t length)
{
3642 3643
	ext4_fsblk_t index = from >> PAGE_SHIFT;
	unsigned offset = from & (PAGE_SIZE-1);
Ross Zwisler's avatar
Ross Zwisler committed
3644
	unsigned blocksize, pos;
3645 3646 3647
	ext4_lblk_t iblock;
	struct inode *inode = mapping->host;
	struct buffer_head *bh;
3648
	struct folio *folio;
3649 3650
	int err = 0;

3651 3652 3653
	folio = __filemap_get_folio(mapping, from >> PAGE_SHIFT,
				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
				    mapping_gfp_constraint(mapping, ~__GFP_FS));
3654 3655
	if (IS_ERR(folio))
		return PTR_ERR(folio);
3656 3657 3658

	blocksize = inode->i_sb->s_blocksize;

3659
	iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits);
3660

3661
	bh = folio_buffers(folio);
3662
	if (!bh)
3663
		bh = create_empty_buffers(folio, blocksize, 0);
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686

	/* Find the buffer that contains "offset" */
	pos = blocksize;
	while (offset >= pos) {
		bh = bh->b_this_page;
		iblock++;
		pos += blocksize;
	}
	if (buffer_freed(bh)) {
		BUFFER_TRACE(bh, "freed: skip");
		goto unlock;
	}
	if (!buffer_mapped(bh)) {
		BUFFER_TRACE(bh, "unmapped");
		ext4_get_block(inode, iblock, bh, 0);
		/* unmapped? It's a hole - nothing to do */
		if (!buffer_mapped(bh)) {
			BUFFER_TRACE(bh, "still unmapped");
			goto unlock;
		}
	}

	/* Ok, it's mapped. Make sure it's up-to-date */
3687
	if (folio_test_uptodate(folio))
3688 3689 3690
		set_buffer_uptodate(bh);

	if (!buffer_uptodate(bh)) {
3691 3692
		err = ext4_read_bh_lock(bh, 0, true);
		if (err)
3693
			goto unlock;
3694
		if (fscrypt_inode_uses_fs_layer_crypto(inode)) {
3695
			/* We expect the key to be set. */
3696
			BUG_ON(!fscrypt_has_encryption_key(inode));
3697
			err = fscrypt_decrypt_pagecache_blocks(folio,
3698
							       blocksize,
3699 3700 3701 3702 3703
							       bh_offset(bh));
			if (err) {
				clear_buffer_uptodate(bh);
				goto unlock;
			}
3704
		}
3705 3706 3707
	}
	if (ext4_should_journal_data(inode)) {
		BUFFER_TRACE(bh, "get write access");
3708 3709
		err = ext4_journal_get_write_access(handle, inode->i_sb, bh,
						    EXT4_JTR_NONE);
3710 3711 3712
		if (err)
			goto unlock;
	}
3713
	folio_zero_range(folio, offset, length);
3714 3715 3716
	BUFFER_TRACE(bh, "zeroed end of block");

	if (ext4_should_journal_data(inode)) {
3717
		err = ext4_dirty_journalled_data(handle, bh);
3718
	} else {
3719
		err = 0;
3720
		mark_buffer_dirty(bh);
3721
		if (ext4_should_order_data(inode))
3722 3723
			err = ext4_jbd2_inode_add_write(handle, inode, from,
					length);
3724
	}
3725 3726

unlock:
3727 3728
	folio_unlock(folio);
	folio_put(folio);
3729 3730 3731
	return err;
}

Ross Zwisler's avatar
Ross Zwisler committed
3732 3733 3734 3735 3736
/*
 * ext4_block_zero_page_range() zeros out a mapping of length 'length'
 * starting from file offset 'from'.  The range to be zero'd must
 * be contained with in one block.  If the specified range exceeds
 * the end of the block it will be shortened to end of the block
3737
 * that corresponds to 'from'
Ross Zwisler's avatar
Ross Zwisler committed
3738 3739 3740 3741 3742
 */
static int ext4_block_zero_page_range(handle_t *handle,
		struct address_space *mapping, loff_t from, loff_t length)
{
	struct inode *inode = mapping->host;
3743
	unsigned offset = from & (PAGE_SIZE-1);
Ross Zwisler's avatar
Ross Zwisler committed
3744 3745 3746 3747 3748 3749 3750 3751 3752 3753
	unsigned blocksize = inode->i_sb->s_blocksize;
	unsigned max = blocksize - (offset & (blocksize - 1));

	/*
	 * correct length if it does not fall between
	 * 'from' and the end of the block
	 */
	if (length > max || length < 0)
		length = max;

3754
	if (IS_DAX(inode)) {
3755 3756
		return dax_zero_range(inode, from, length, NULL,
				      &ext4_iomap_ops);
3757
	}
Ross Zwisler's avatar
Ross Zwisler committed
3758 3759 3760
	return __ext4_block_zero_page_range(handle, mapping, from, length);
}

3761 3762 3763 3764 3765 3766
/*
 * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
 * up to the end of the block which corresponds to `from'.
 * This required during truncate. We need to physically zero the tail end
 * of that block so it doesn't yield old data if the file is later grown.
 */
3767
static int ext4_block_truncate_page(handle_t *handle,
3768 3769
		struct address_space *mapping, loff_t from)
{
3770
	unsigned offset = from & (PAGE_SIZE-1);
3771 3772 3773 3774
	unsigned length;
	unsigned blocksize;
	struct inode *inode = mapping->host;

3775
	/* If we are processing an encrypted inode during orphan list handling */
3776
	if (IS_ENCRYPTED(inode) && !fscrypt_has_encryption_key(inode))
3777 3778
		return 0;

3779 3780 3781 3782 3783 3784
	blocksize = inode->i_sb->s_blocksize;
	length = blocksize - (offset & (blocksize - 1));

	return ext4_block_zero_page_range(handle, mapping, from, length);
}

3785 3786 3787 3788 3789
int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode,
			     loff_t lstart, loff_t length)
{
	struct super_block *sb = inode->i_sb;
	struct address_space *mapping = inode->i_mapping;
3790
	unsigned partial_start, partial_end;
3791 3792 3793 3794
	ext4_fsblk_t start, end;
	loff_t byte_end = (lstart + length - 1);
	int err = 0;

3795 3796 3797
	partial_start = lstart & (sb->s_blocksize - 1);
	partial_end = byte_end & (sb->s_blocksize - 1);

3798 3799 3800 3801
	start = lstart >> sb->s_blocksize_bits;
	end = byte_end >> sb->s_blocksize_bits;

	/* Handle partial zero within the single block */
3802 3803
	if (start == end &&
	    (partial_start || (partial_end != sb->s_blocksize - 1))) {
3804 3805 3806 3807 3808
		err = ext4_block_zero_page_range(handle, mapping,
						 lstart, length);
		return err;
	}
	/* Handle partial zero out on the start of the range */
3809
	if (partial_start) {
3810 3811 3812 3813 3814 3815
		err = ext4_block_zero_page_range(handle, mapping,
						 lstart, sb->s_blocksize);
		if (err)
			return err;
	}
	/* Handle partial zero out on the end of the range */
3816
	if (partial_end != sb->s_blocksize - 1)
3817
		err = ext4_block_zero_page_range(handle, mapping,
3818 3819
						 byte_end - partial_end,
						 partial_end + 1);
3820 3821 3822
	return err;
}

3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833
int ext4_can_truncate(struct inode *inode)
{
	if (S_ISREG(inode->i_mode))
		return 1;
	if (S_ISDIR(inode->i_mode))
		return 1;
	if (S_ISLNK(inode->i_mode))
		return !ext4_inode_is_fast_symlink(inode);
	return 0;
}

3834 3835 3836 3837 3838 3839 3840 3841 3842 3843
/*
 * We have to make sure i_disksize gets properly updated before we truncate
 * page cache due to hole punching or zero range. Otherwise i_disksize update
 * can get lost as it may have been postponed to submission of writeback but
 * that will never happen after we truncate page cache.
 */
int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset,
				      loff_t len)
{
	handle_t *handle;
3844 3845
	int ret;

3846 3847
	loff_t size = i_size_read(inode);

Al Viro's avatar
Al Viro committed
3848
	WARN_ON(!inode_is_locked(inode));
3849 3850 3851 3852 3853 3854 3855 3856 3857 3858
	if (offset > size || offset + len < size)
		return 0;

	if (EXT4_I(inode)->i_disksize >= size)
		return 0;

	handle = ext4_journal_start(inode, EXT4_HT_MISC, 1);
	if (IS_ERR(handle))
		return PTR_ERR(handle);
	ext4_update_i_disksize(inode, size);
3859
	ret = ext4_mark_inode_dirty(handle, inode);
3860 3861
	ext4_journal_stop(handle);

3862
	return ret;
3863 3864
}

3865
static void ext4_wait_dax_page(struct inode *inode)
3866
{
3867
	filemap_invalidate_unlock(inode->i_mapping);
3868
	schedule();
3869
	filemap_invalidate_lock(inode->i_mapping);
3870 3871 3872 3873 3874 3875 3876
}

int ext4_break_layouts(struct inode *inode)
{
	struct page *page;
	int error;

3877
	if (WARN_ON_ONCE(!rwsem_is_locked(&inode->i_mapping->invalidate_lock)))
3878 3879 3880 3881 3882 3883 3884 3885 3886 3887
		return -EINVAL;

	do {
		page = dax_layout_busy_page(inode->i_mapping);
		if (!page)
			return 0;

		error = ___wait_var_event(&page->_refcount,
				atomic_read(&page->_refcount) == 1,
				TASK_INTERRUPTIBLE, 0, 0,
3888
				ext4_wait_dax_page(inode));
3889
	} while (error == 0);
3890 3891 3892 3893

	return error;
}

3894
/*
3895
 * ext4_punch_hole: punches a hole in a file by releasing the blocks
3896 3897 3898 3899 3900 3901
 * associated with the given offset and length
 *
 * @inode:  File inode
 * @offset: The offset where the hole will begin
 * @len:    The length of the hole
 *
3902
 * Returns: 0 on success or negative on failure
3903 3904
 */

3905
int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
3906
{
3907
	struct inode *inode = file_inode(file);
Theodore Ts'o's avatar
Theodore Ts'o committed
3908 3909 3910
	struct super_block *sb = inode->i_sb;
	ext4_lblk_t first_block, stop_block;
	struct address_space *mapping = inode->i_mapping;
3911 3912
	loff_t first_block_offset, last_block_offset, max_length;
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
Theodore Ts'o's avatar
Theodore Ts'o committed
3913 3914
	handle_t *handle;
	unsigned int credits;
3915
	int ret = 0, ret2 = 0;
Theodore Ts'o's avatar
Theodore Ts'o committed
3916

3917
	trace_ext4_punch_hole(inode, offset, length, 0);
3918

Theodore Ts'o's avatar
Theodore Ts'o committed
3919 3920 3921 3922
	/*
	 * Write out all dirty pages to avoid race conditions
	 * Then release them.
	 */
3923
	if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
Theodore Ts'o's avatar
Theodore Ts'o committed
3924 3925 3926 3927 3928 3929
		ret = filemap_write_and_wait_range(mapping, offset,
						   offset + length - 1);
		if (ret)
			return ret;
	}

Al Viro's avatar
Al Viro committed
3930
	inode_lock(inode);
3931

Theodore Ts'o's avatar
Theodore Ts'o committed
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941
	/* No need to punch hole beyond i_size */
	if (offset >= inode->i_size)
		goto out_mutex;

	/*
	 * If the hole extends beyond i_size, set the hole
	 * to end after the page that contains i_size
	 */
	if (offset + length > inode->i_size) {
		length = inode->i_size +
3942
		   PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) -
Theodore Ts'o's avatar
Theodore Ts'o committed
3943 3944 3945
		   offset;
	}

3946 3947 3948 3949 3950 3951 3952 3953
	/*
	 * For punch hole the length + offset needs to be within one block
	 * before last range. Adjust the length if it goes beyond that limit.
	 */
	max_length = sbi->s_bitmap_maxbytes - inode->i_sb->s_blocksize;
	if (offset + length > max_length)
		length = max_length - offset;

3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
	if (offset & (sb->s_blocksize - 1) ||
	    (offset + length) & (sb->s_blocksize - 1)) {
		/*
		 * Attach jinode to inode for jbd2 if we do any zeroing of
		 * partial block
		 */
		ret = ext4_inode_attach_jinode(inode);
		if (ret < 0)
			goto out_mutex;

	}

3966
	/* Wait all existing dio workers, newcomers will block on i_rwsem */
3967 3968
	inode_dio_wait(inode);

3969 3970 3971 3972
	ret = file_modified(file);
	if (ret)
		goto out_mutex;

3973 3974 3975 3976
	/*
	 * Prevent page faults from reinstantiating pages we have released from
	 * page cache.
	 */
3977
	filemap_invalidate_lock(mapping);
3978 3979 3980 3981 3982

	ret = ext4_break_layouts(inode);
	if (ret)
		goto out_dio;

3983 3984
	first_block_offset = round_up(offset, sb->s_blocksize);
	last_block_offset = round_down((offset + length), sb->s_blocksize) - 1;
Theodore Ts'o's avatar
Theodore Ts'o committed
3985

3986
	/* Now release the pages and zero block aligned part of pages*/
3987 3988 3989 3990
	if (last_block_offset > first_block_offset) {
		ret = ext4_update_disksize_before_punch(inode, offset, length);
		if (ret)
			goto out_dio;
3991 3992
		truncate_pagecache_range(inode, first_block_offset,
					 last_block_offset);
3993
	}
Theodore Ts'o's avatar
Theodore Ts'o committed
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005

	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
		credits = ext4_writepage_trans_blocks(inode);
	else
		credits = ext4_blocks_for_truncate(inode);
	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
	if (IS_ERR(handle)) {
		ret = PTR_ERR(handle);
		ext4_std_error(sb, ret);
		goto out_dio;
	}

4006 4007 4008 4009
	ret = ext4_zero_partial_blocks(handle, inode, offset,
				       length);
	if (ret)
		goto out_stop;
Theodore Ts'o's avatar
Theodore Ts'o committed
4010 4011 4012 4013 4014

	first_block = (offset + sb->s_blocksize - 1) >>
		EXT4_BLOCK_SIZE_BITS(sb);
	stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb);

4015 4016
	/* If there are blocks to remove, do it */
	if (stop_block > first_block) {
Theodore Ts'o's avatar
Theodore Ts'o committed
4017

4018
		down_write(&EXT4_I(inode)->i_data_sem);
4019
		ext4_discard_preallocations(inode, 0);
Theodore Ts'o's avatar
Theodore Ts'o committed
4020

4021 4022
		ext4_es_remove_extent(inode, first_block,
				      stop_block - first_block);
Theodore Ts'o's avatar
Theodore Ts'o committed
4023

4024 4025 4026 4027 4028 4029
		if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
			ret = ext4_ext_remove_space(inode, first_block,
						    stop_block - 1);
		else
			ret = ext4_ind_remove_space(handle, inode, first_block,
						    stop_block);
Theodore Ts'o's avatar
Theodore Ts'o committed
4030

4031 4032
		up_write(&EXT4_I(inode)->i_data_sem);
	}
4033
	ext4_fc_track_range(handle, inode, first_block, stop_block);
Theodore Ts'o's avatar
Theodore Ts'o committed
4034 4035
	if (IS_SYNC(inode))
		ext4_handle_sync(handle);
4036

4037
	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4038 4039 4040
	ret2 = ext4_mark_inode_dirty(handle, inode);
	if (unlikely(ret2))
		ret = ret2;
4041 4042
	if (ret >= 0)
		ext4_update_inode_fsync_trans(handle, inode, 1);
Theodore Ts'o's avatar
Theodore Ts'o committed
4043 4044 4045
out_stop:
	ext4_journal_stop(handle);
out_dio:
4046
	filemap_invalidate_unlock(mapping);
Theodore Ts'o's avatar
Theodore Ts'o committed
4047
out_mutex:
Al Viro's avatar
Al Viro committed
4048
	inode_unlock(inode);
Theodore Ts'o's avatar
Theodore Ts'o committed
4049
	return ret;
4050 4051
}

4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
int ext4_inode_attach_jinode(struct inode *inode)
{
	struct ext4_inode_info *ei = EXT4_I(inode);
	struct jbd2_inode *jinode;

	if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal)
		return 0;

	jinode = jbd2_alloc_inode(GFP_KERNEL);
	spin_lock(&inode->i_lock);
	if (!ei->jinode) {
		if (!jinode) {
			spin_unlock(&inode->i_lock);
			return -ENOMEM;
		}
		ei->jinode = jinode;
		jbd2_journal_init_jbd_inode(ei->jinode, inode);
		jinode = NULL;
	}
	spin_unlock(&inode->i_lock);
	if (unlikely(jinode != NULL))
		jbd2_free_inode(jinode);
	return 0;
}

4077
/*
4078
 * ext4_truncate()
4079
 *
4080 4081
 * We block out ext4_get_block() block instantiations across the entire
 * transaction, and VFS/VM ensures that ext4_truncate() cannot run
4082 4083
 * simultaneously on behalf of the same inode.
 *
4084
 * As we work through the truncate and commit bits of it to the journal there
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097
 * is one core, guiding principle: the file's tree must always be consistent on
 * disk.  We must be able to restart the truncate after a crash.
 *
 * The file's tree may be transiently inconsistent in memory (although it
 * probably isn't), but whenever we close off and commit a journal transaction,
 * the contents of (the filesystem + the journal) must be consistent and
 * restartable.  It's pretty simple, really: bottom up, right to left (although
 * left-to-right works OK too).
 *
 * Note that at recovery time, journal replay occurs *before* the restart of
 * truncate against the orphan inode list.
 *
 * The committed inode has the new, desired i_size (which is the same as
4098
 * i_disksize in this case).  After a crash, ext4_orphan_cleanup() will see
4099
 * that this inode's truncate did not complete and it will again call
4100 4101
 * ext4_truncate() to have another go.  So there will be instantiated blocks
 * to the right of the truncation point in a crashed ext4 filesystem.  But
4102
 * that's fine - as long as they are linked from the inode, the post-crash
4103
 * ext4_truncate() run will find them and release them.
4104
 */
4105
int ext4_truncate(struct inode *inode)
4106
{
Theodore Ts'o's avatar
Theodore Ts'o committed
4107 4108
	struct ext4_inode_info *ei = EXT4_I(inode);
	unsigned int credits;
4109
	int err = 0, err2;
Theodore Ts'o's avatar
Theodore Ts'o committed
4110 4111 4112
	handle_t *handle;
	struct address_space *mapping = inode->i_mapping;

4113 4114
	/*
	 * There is a possibility that we're either freeing the inode
Matthew Wilcox's avatar
Matthew Wilcox committed
4115
	 * or it's a completely new inode. In those cases we might not
4116
	 * have i_rwsem locked because it's not necessary.
4117 4118
	 */
	if (!(inode->i_state & (I_NEW|I_FREEING)))
Al Viro's avatar
Al Viro committed
4119
		WARN_ON(!inode_is_locked(inode));
4120 4121
	trace_ext4_truncate_enter(inode);

4122
	if (!ext4_can_truncate(inode))
4123
		goto out_trace;
4124

4125
	if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
4126
		ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
4127

4128 4129 4130
	if (ext4_has_inline_data(inode)) {
		int has_inline = 1;

4131
		err = ext4_inline_data_truncate(inode, &has_inline);
4132 4133
		if (err || has_inline)
			goto out_trace;
4134 4135
	}

4136 4137
	/* If we zero-out tail of the page, we have to create jinode for jbd2 */
	if (inode->i_size & (inode->i_sb->s_blocksize - 1)) {
4138 4139
		err = ext4_inode_attach_jinode(inode);
		if (err)
4140
			goto out_trace;
4141 4142
	}

Theodore Ts'o's avatar
Theodore Ts'o committed
4143 4144 4145 4146 4147 4148
	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
		credits = ext4_writepage_trans_blocks(inode);
	else
		credits = ext4_blocks_for_truncate(inode);

	handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits);
4149 4150 4151 4152
	if (IS_ERR(handle)) {
		err = PTR_ERR(handle);
		goto out_trace;
	}
Theodore Ts'o's avatar
Theodore Ts'o committed
4153

4154 4155
	if (inode->i_size & (inode->i_sb->s_blocksize - 1))
		ext4_block_truncate_page(handle, mapping, inode->i_size);
Theodore Ts'o's avatar
Theodore Ts'o committed
4156 4157 4158 4159 4160 4161 4162 4163 4164 4165

	/*
	 * We add the inode to the orphan list, so that if this
	 * truncate spans multiple transactions, and we crash, we will
	 * resume the truncate when the filesystem recovers.  It also
	 * marks the inode dirty, to catch the new size.
	 *
	 * Implication: the file must always be in a sane, consistent
	 * truncatable state while each transaction commits.
	 */
4166 4167
	err = ext4_orphan_add(handle, inode);
	if (err)
Theodore Ts'o's avatar
Theodore Ts'o committed
4168 4169 4170 4171
		goto out_stop;

	down_write(&EXT4_I(inode)->i_data_sem);

4172
	ext4_discard_preallocations(inode, 0);
Theodore Ts'o's avatar
Theodore Ts'o committed
4173

4174
	if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4175
		err = ext4_ext_truncate(handle, inode);
4176
	else
Theodore Ts'o's avatar
Theodore Ts'o committed
4177 4178 4179
		ext4_ind_truncate(handle, inode);

	up_write(&ei->i_data_sem);
4180 4181
	if (err)
		goto out_stop;
Theodore Ts'o's avatar
Theodore Ts'o committed
4182 4183 4184 4185 4186 4187 4188 4189 4190

	if (IS_SYNC(inode))
		ext4_handle_sync(handle);

out_stop:
	/*
	 * If this was a simple ftruncate() and the file will remain alive,
	 * then we need to clear up the orphan record which we created above.
	 * However, if this was a real unlink then we were called by
4191
	 * ext4_evict_inode(), and we allow that function to clean up the
Theodore Ts'o's avatar
Theodore Ts'o committed
4192 4193 4194 4195 4196
	 * orphan info for us.
	 */
	if (inode->i_nlink)
		ext4_orphan_del(handle, inode);

4197
	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
4198 4199 4200
	err2 = ext4_mark_inode_dirty(handle, inode);
	if (unlikely(err2 && !err))
		err = err2;
Theodore Ts'o's avatar
Theodore Ts'o committed
4201
	ext4_journal_stop(handle);
4202

4203
out_trace:
4204
	trace_ext4_truncate_exit(inode);
4205
	return err;
4206 4207
}

4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299
static inline u64 ext4_inode_peek_iversion(const struct inode *inode)
{
	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
		return inode_peek_iversion_raw(inode);
	else
		return inode_peek_iversion(inode);
}

static int ext4_inode_blocks_set(struct ext4_inode *raw_inode,
				 struct ext4_inode_info *ei)
{
	struct inode *inode = &(ei->vfs_inode);
	u64 i_blocks = READ_ONCE(inode->i_blocks);
	struct super_block *sb = inode->i_sb;

	if (i_blocks <= ~0U) {
		/*
		 * i_blocks can be represented in a 32 bit variable
		 * as multiple of 512 bytes
		 */
		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
		raw_inode->i_blocks_high = 0;
		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
		return 0;
	}

	/*
	 * This should never happen since sb->s_maxbytes should not have
	 * allowed this, sb->s_maxbytes was set according to the huge_file
	 * feature in ext4_fill_super().
	 */
	if (!ext4_has_feature_huge_file(sb))
		return -EFSCORRUPTED;

	if (i_blocks <= 0xffffffffffffULL) {
		/*
		 * i_blocks can be represented in a 48 bit variable
		 * as multiple of 512 bytes
		 */
		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
		ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
	} else {
		ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
		/* i_block is stored in file system block size */
		i_blocks = i_blocks >> (inode->i_blkbits - 9);
		raw_inode->i_blocks_lo   = cpu_to_le32(i_blocks);
		raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
	}
	return 0;
}

static int ext4_fill_raw_inode(struct inode *inode, struct ext4_inode *raw_inode)
{
	struct ext4_inode_info *ei = EXT4_I(inode);
	uid_t i_uid;
	gid_t i_gid;
	projid_t i_projid;
	int block;
	int err;

	err = ext4_inode_blocks_set(raw_inode, ei);

	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
	i_uid = i_uid_read(inode);
	i_gid = i_gid_read(inode);
	i_projid = from_kprojid(&init_user_ns, ei->i_projid);
	if (!(test_opt(inode->i_sb, NO_UID32))) {
		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid));
		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid));
		/*
		 * Fix up interoperability with old kernels. Otherwise,
		 * old inodes get re-used with the upper 16 bits of the
		 * uid/gid intact.
		 */
		if (ei->i_dtime && list_empty(&ei->i_orphan)) {
			raw_inode->i_uid_high = 0;
			raw_inode->i_gid_high = 0;
		} else {
			raw_inode->i_uid_high =
				cpu_to_le16(high_16_bits(i_uid));
			raw_inode->i_gid_high =
				cpu_to_le16(high_16_bits(i_gid));
		}
	} else {
		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid));
		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid));
		raw_inode->i_uid_high = 0;
		raw_inode->i_gid_high = 0;
	}
	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);

4300
	EXT4_INODE_SET_CTIME(inode, raw_inode);
4301 4302
	EXT4_INODE_SET_MTIME(inode, raw_inode);
	EXT4_INODE_SET_ATIME(inode, raw_inode);
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354
	EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);

	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
	raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT)))
		raw_inode->i_file_acl_high =
			cpu_to_le16(ei->i_file_acl >> 32);
	raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
	ext4_isize_set(raw_inode, ei->i_disksize);

	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
		if (old_valid_dev(inode->i_rdev)) {
			raw_inode->i_block[0] =
				cpu_to_le32(old_encode_dev(inode->i_rdev));
			raw_inode->i_block[1] = 0;
		} else {
			raw_inode->i_block[0] = 0;
			raw_inode->i_block[1] =
				cpu_to_le32(new_encode_dev(inode->i_rdev));
			raw_inode->i_block[2] = 0;
		}
	} else if (!ext4_has_inline_data(inode)) {
		for (block = 0; block < EXT4_N_BLOCKS; block++)
			raw_inode->i_block[block] = ei->i_data[block];
	}

	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
		u64 ivers = ext4_inode_peek_iversion(inode);

		raw_inode->i_disk_version = cpu_to_le32(ivers);
		if (ei->i_extra_isize) {
			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
				raw_inode->i_version_hi =
					cpu_to_le32(ivers >> 32);
			raw_inode->i_extra_isize =
				cpu_to_le16(ei->i_extra_isize);
		}
	}

	if (i_projid != EXT4_DEF_PROJID &&
	    !ext4_has_feature_project(inode->i_sb))
		err = err ?: -EFSCORRUPTED;

	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE &&
	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
		raw_inode->i_projid = cpu_to_le32(i_projid);

	ext4_inode_csum_set(inode, raw_inode, ei);
	return err;
}

4355
/*
4356
 * ext4_get_inode_loc returns with an extra refcount against the inode's
4357 4358 4359
 * underlying buffer_head on success. If we pass 'inode' and it does not
 * have in-inode xattr, we have all inode data in memory that is needed
 * to recreate the on-disk version of this inode.
4360
 */
4361
static int __ext4_get_inode_loc(struct super_block *sb, unsigned long ino,
4362
				struct inode *inode, struct ext4_iloc *iloc,
4363
				ext4_fsblk_t *ret_block)
4364
{
4365 4366 4367
	struct ext4_group_desc	*gdp;
	struct buffer_head	*bh;
	ext4_fsblk_t		block;
4368
	struct blk_plug		plug;
4369 4370
	int			inodes_per_block, inode_offset;

Aneesh Kumar K.V's avatar
Aneesh Kumar K.V committed
4371
	iloc->bh = NULL;
4372 4373
	if (ino < EXT4_ROOT_INO ||
	    ino > le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))
4374
		return -EFSCORRUPTED;
4375

4376
	iloc->block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
4377 4378
	gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
	if (!gdp)
4379 4380
		return -EIO;

4381 4382 4383
	/*
	 * Figure out the offset within the block group inode table
	 */
4384
	inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
4385
	inode_offset = ((ino - 1) %
4386 4387 4388
			EXT4_INODES_PER_GROUP(sb));
	iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);

4389 4390 4391 4392 4393 4394 4395 4396 4397
	block = ext4_inode_table(sb, gdp);
	if ((block <= le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block)) ||
	    (block >= ext4_blocks_count(EXT4_SB(sb)->s_es))) {
		ext4_error(sb, "Invalid inode table block %llu in "
			   "block_group %u", block, iloc->block_group);
		return -EFSCORRUPTED;
	}
	block += (inode_offset / inodes_per_block);

4398
	bh = sb_getblk(sb, block);
4399
	if (unlikely(!bh))
4400
		return -ENOMEM;
4401 4402
	if (ext4_buffer_uptodate(bh))
		goto has_buffer;
4403

4404
	lock_buffer(bh);
4405 4406 4407 4408 4409 4410
	if (ext4_buffer_uptodate(bh)) {
		/* Someone brought it uptodate while we waited */
		unlock_buffer(bh);
		goto has_buffer;
	}

4411 4412 4413 4414 4415
	/*
	 * If we have all information of the inode in memory and this
	 * is the only valid inode in the block, we need not read the
	 * block.
	 */
4416
	if (inode && !ext4_test_inode_state(inode, EXT4_STATE_XATTR)) {
4417 4418
		struct buffer_head *bitmap_bh;
		int i, start;
4419

4420
		start = inode_offset & ~(inodes_per_block - 1);
4421

4422 4423 4424 4425
		/* Is the inode bitmap in cache? */
		bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
		if (unlikely(!bitmap_bh))
			goto make_io;
4426

4427 4428 4429 4430 4431 4432
		/*
		 * If the inode bitmap isn't in cache then the
		 * optimisation may end up performing two reads instead
		 * of one, so skip it.
		 */
		if (!buffer_uptodate(bitmap_bh)) {
4433
			brelse(bitmap_bh);
4434
			goto make_io;
4435
		}
4436 4437 4438 4439 4440
		for (i = start; i < start + inodes_per_block; i++) {
			if (i == inode_offset)
				continue;
			if (ext4_test_bit(i, bitmap_bh->b_data))
				break;
4441
		}
4442 4443
		brelse(bitmap_bh);
		if (i == start + inodes_per_block) {
4444 4445 4446
			struct ext4_inode *raw_inode =
				(struct ext4_inode *) (bh->b_data + iloc->offset);

4447 4448
			/* all other inodes are free, so skip I/O */
			memset(bh->b_data, 0, bh->b_size);
4449 4450
			if (!ext4_test_inode_state(inode, EXT4_STATE_NEW))
				ext4_fill_raw_inode(inode, raw_inode);
4451 4452 4453 4454 4455
			set_buffer_uptodate(bh);
			unlock_buffer(bh);
			goto has_buffer;
		}
	}
4456 4457

make_io:
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482
	/*
	 * If we need to do any I/O, try to pre-readahead extra
	 * blocks from the inode table.
	 */
	blk_start_plug(&plug);
	if (EXT4_SB(sb)->s_inode_readahead_blks) {
		ext4_fsblk_t b, end, table;
		unsigned num;
		__u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks;

		table = ext4_inode_table(sb, gdp);
		/* s_inode_readahead_blks is always a power of 2 */
		b = block & ~((ext4_fsblk_t) ra_blks - 1);
		if (table > b)
			b = table;
		end = b + ra_blks;
		num = EXT4_INODES_PER_GROUP(sb);
		if (ext4_has_group_desc_csum(sb))
			num -= ext4_itable_unused_count(sb, gdp);
		table += num / inodes_per_block;
		if (end > table)
			end = table;
		while (b <= end)
			ext4_sb_breadahead_unmovable(sb, b++);
	}
4483

4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498
	/*
	 * There are other valid inodes in the buffer, this inode
	 * has in-inode xattrs, or we don't have this inode in memory.
	 * Read the block from disk.
	 */
	trace_ext4_load_inode(sb, ino);
	ext4_read_bh_nowait(bh, REQ_META | REQ_PRIO, NULL);
	blk_finish_plug(&plug);
	wait_on_buffer(bh);
	ext4_simulate_fail_bh(sb, bh, EXT4_SIM_INODE_EIO);
	if (!buffer_uptodate(bh)) {
		if (ret_block)
			*ret_block = block;
		brelse(bh);
		return -EIO;
4499 4500 4501 4502 4503 4504
	}
has_buffer:
	iloc->bh = bh;
	return 0;
}

4505 4506 4507
static int __ext4_get_inode_loc_noinmem(struct inode *inode,
					struct ext4_iloc *iloc)
{
4508
	ext4_fsblk_t err_blk = 0;
4509 4510
	int ret;

4511
	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, NULL, iloc,
4512 4513 4514 4515 4516 4517 4518 4519 4520
					&err_blk);

	if (ret == -EIO)
		ext4_error_inode_block(inode, err_blk, EIO,
					"unable to read itable block");

	return ret;
}

4521
int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
4522
{
4523
	ext4_fsblk_t err_blk = 0;
4524 4525
	int ret;

4526 4527
	ret = __ext4_get_inode_loc(inode->i_sb, inode->i_ino, inode, iloc,
					&err_blk);
4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539

	if (ret == -EIO)
		ext4_error_inode_block(inode, err_blk, EIO,
					"unable to read itable block");

	return ret;
}


int ext4_get_fc_inode_loc(struct super_block *sb, unsigned long ino,
			  struct ext4_iloc *iloc)
{
4540
	return __ext4_get_inode_loc(sb, ino, NULL, iloc, NULL);
4541 4542
}

4543
static bool ext4_should_enable_dax(struct inode *inode)
4544
{
4545 4546
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);

4547
	if (test_opt2(inode->i_sb, DAX_NEVER))
4548 4549 4550 4551 4552 4553 4554
		return false;
	if (!S_ISREG(inode->i_mode))
		return false;
	if (ext4_should_journal_data(inode))
		return false;
	if (ext4_has_inline_data(inode))
		return false;
4555
	if (ext4_test_inode_flag(inode, EXT4_INODE_ENCRYPT))
4556
		return false;
4557 4558
	if (ext4_test_inode_flag(inode, EXT4_INODE_VERITY))
		return false;
4559 4560 4561 4562 4563
	if (!test_bit(EXT4_FLAGS_BDEV_IS_DAX, &sbi->s_ext4_flags))
		return false;
	if (test_opt(inode->i_sb, DAX_ALWAYS))
		return true;

Ira Weiny's avatar
Ira Weiny committed
4564
	return ext4_test_inode_flag(inode, EXT4_INODE_DAX);
4565 4566
}

4567
void ext4_set_inode_flags(struct inode *inode, bool init)
4568
{
4569
	unsigned int flags = EXT4_I(inode)->i_flags;
4570
	unsigned int new_fl = 0;
4571

4572 4573
	WARN_ON_ONCE(IS_DAX(inode) && init);

4574
	if (flags & EXT4_SYNC_FL)
4575
		new_fl |= S_SYNC;
4576
	if (flags & EXT4_APPEND_FL)
4577
		new_fl |= S_APPEND;
4578
	if (flags & EXT4_IMMUTABLE_FL)
4579
		new_fl |= S_IMMUTABLE;
4580
	if (flags & EXT4_NOATIME_FL)
4581
		new_fl |= S_NOATIME;
4582
	if (flags & EXT4_DIRSYNC_FL)
4583
		new_fl |= S_DIRSYNC;
4584 4585 4586 4587 4588

	/* Because of the way inode_set_flags() works we must preserve S_DAX
	 * here if already set. */
	new_fl |= (inode->i_flags & S_DAX);
	if (init && ext4_should_enable_dax(inode))
Ross Zwisler's avatar
Ross Zwisler committed
4589
		new_fl |= S_DAX;
4590

4591 4592
	if (flags & EXT4_ENCRYPT_FL)
		new_fl |= S_ENCRYPTED;
4593 4594
	if (flags & EXT4_CASEFOLD_FL)
		new_fl |= S_CASEFOLD;
4595 4596
	if (flags & EXT4_VERITY_FL)
		new_fl |= S_VERITY;
4597
	inode_set_flags(inode, new_fl,
4598
			S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX|
4599
			S_ENCRYPTED|S_CASEFOLD|S_VERITY);
4600 4601
}

4602
static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
4603
				  struct ext4_inode_info *ei)
4604 4605
{
	blkcnt_t i_blocks ;
Aneesh Kumar K.V's avatar
Aneesh Kumar K.V committed
4606 4607
	struct inode *inode = &(ei->vfs_inode);
	struct super_block *sb = inode->i_sb;
4608

4609
	if (ext4_has_feature_huge_file(sb)) {
4610 4611 4612
		/* we are using combined 48 bit field */
		i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
					le32_to_cpu(raw_inode->i_blocks_lo);
4613
		if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
Aneesh Kumar K.V's avatar
Aneesh Kumar K.V committed
4614 4615 4616 4617 4618
			/* i_blocks represent file system block size */
			return i_blocks  << (inode->i_blkbits - 9);
		} else {
			return i_blocks;
		}
4619 4620 4621 4622
	} else {
		return le32_to_cpu(raw_inode->i_blocks_lo);
	}
}
4623

4624
static inline int ext4_iget_extra_inode(struct inode *inode,
4625 4626 4627 4628 4629
					 struct ext4_inode *raw_inode,
					 struct ext4_inode_info *ei)
{
	__le32 *magic = (void *)raw_inode +
			EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize;
4630

4631
	if (EXT4_INODE_HAS_XATTR_SPACE(inode)  &&
4632
	    *magic == cpu_to_le32(EXT4_XATTR_MAGIC)) {
4633 4634
		int err;

4635
		ext4_set_inode_state(inode, EXT4_STATE_XATTR);
4636 4637 4638 4639
		err = ext4_find_inline_data_nolock(inode);
		if (!err && ext4_has_inline_data(inode))
			ext4_set_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA);
		return err;
4640 4641
	} else
		EXT4_I(inode)->i_inline_off = 0;
4642
	return 0;
4643 4644
}

Li Xi's avatar
Li Xi committed
4645 4646
int ext4_get_projid(struct inode *inode, kprojid_t *projid)
{
Kaho Ng's avatar
Kaho Ng committed
4647
	if (!ext4_has_feature_project(inode->i_sb))
Li Xi's avatar
Li Xi committed
4648 4649 4650 4651 4652
		return -EOPNOTSUPP;
	*projid = EXT4_I(inode)->i_projid;
	return 0;
}

4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665
/*
 * ext4 has self-managed i_version for ea inodes, it stores the lower 32bit of
 * refcount in i_version, so use raw values if inode has EXT4_EA_INODE_FL flag
 * set.
 */
static inline void ext4_inode_set_iversion_queried(struct inode *inode, u64 val)
{
	if (unlikely(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
		inode_set_iversion_raw(inode, val);
	else
		inode_set_iversion_queried(inode, val);
}

4666 4667 4668 4669 4670 4671
static const char *check_igot_inode(struct inode *inode, ext4_iget_flags flags)

{
	if (flags & EXT4_IGET_EA_INODE) {
		if (!(EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
			return "missing EA_INODE flag";
4672 4673 4674
		if (ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
		    EXT4_I(inode)->i_file_acl)
			return "ea_inode with extended attributes";
4675 4676 4677 4678 4679 4680 4681 4682 4683
	} else {
		if ((EXT4_I(inode)->i_flags & EXT4_EA_INODE_FL))
			return "unexpected EA_INODE flag";
	}
	if (is_bad_inode(inode) && !(flags & EXT4_IGET_BAD))
		return "unexpected bad inode w/o EXT4_IGET_BAD";
	return NULL;
}

4684 4685 4686
struct inode *__ext4_iget(struct super_block *sb, unsigned long ino,
			  ext4_iget_flags flags, const char *function,
			  unsigned int line)
4687
{
4688 4689
	struct ext4_iloc iloc;
	struct ext4_inode *raw_inode;
4690
	struct ext4_inode_info *ei;
4691
	struct ext4_super_block *es = EXT4_SB(sb)->s_es;
4692
	struct inode *inode;
4693
	const char *err_str;
4694
	journal_t *journal = EXT4_SB(sb)->s_journal;
4695
	long ret;
4696
	loff_t size;
4697
	int block;
4698 4699
	uid_t i_uid;
	gid_t i_gid;
Li Xi's avatar
Li Xi committed
4700
	projid_t i_projid;
4701

4702
	if ((!(flags & EXT4_IGET_SPECIAL) &&
4703 4704 4705
	     ((ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) ||
	      ino == le32_to_cpu(es->s_usr_quota_inum) ||
	      ino == le32_to_cpu(es->s_grp_quota_inum) ||
4706 4707
	      ino == le32_to_cpu(es->s_prj_quota_inum) ||
	      ino == le32_to_cpu(es->s_orphan_file_inum))) ||
4708
	    (ino < EXT4_ROOT_INO) ||
4709
	    (ino > le32_to_cpu(es->s_inodes_count))) {
4710 4711
		if (flags & EXT4_IGET_HANDLE)
			return ERR_PTR(-ESTALE);
4712
		__ext4_error(sb, function, line, false, EFSCORRUPTED, 0,
4713 4714 4715 4716 4717
			     "inode #%lu: comm %s: iget: illegal inode #",
			     ino, current->comm);
		return ERR_PTR(-EFSCORRUPTED);
	}

4718 4719 4720
	inode = iget_locked(sb, ino);
	if (!inode)
		return ERR_PTR(-ENOMEM);
4721 4722 4723 4724 4725 4726
	if (!(inode->i_state & I_NEW)) {
		if ((err_str = check_igot_inode(inode, flags)) != NULL) {
			ext4_error_inode(inode, function, line, 0, err_str);
			iput(inode);
			return ERR_PTR(-EFSCORRUPTED);
		}
4727
		return inode;
4728
	}
4729 4730

	ei = EXT4_I(inode);
4731
	iloc.bh = NULL;
4732

4733
	ret = __ext4_get_inode_loc_noinmem(inode, &iloc);
4734
	if (ret < 0)
4735
		goto bad_inode;
4736
	raw_inode = ext4_raw_inode(&iloc);
4737

4738 4739 4740 4741 4742 4743
	if ((flags & EXT4_IGET_HANDLE) &&
	    (raw_inode->i_links_count == 0) && (raw_inode->i_mode == 0)) {
		ret = -ESTALE;
		goto bad_inode;
	}

4744 4745 4746
	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
		ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
		if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
4747 4748
			EXT4_INODE_SIZE(inode->i_sb) ||
		    (ei->i_extra_isize & 3)) {
4749 4750 4751
			ext4_error_inode(inode, function, line, 0,
					 "iget: bad extra_isize %u "
					 "(inode size %u)",
4752 4753
					 ei->i_extra_isize,
					 EXT4_INODE_SIZE(inode->i_sb));
4754
			ret = -EFSCORRUPTED;
4755 4756 4757 4758 4759 4760
			goto bad_inode;
		}
	} else
		ei->i_extra_isize = 0;

	/* Precompute checksum seed for inode metadata */
4761
	if (ext4_has_metadata_csum(sb)) {
4762 4763 4764 4765 4766 4767 4768 4769 4770 4771
		struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
		__u32 csum;
		__le32 inum = cpu_to_le32(inode->i_ino);
		__le32 gen = raw_inode->i_generation;
		csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum,
				   sizeof(inum));
		ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen,
					      sizeof(gen));
	}

4772 4773 4774 4775 4776
	if ((!ext4_inode_csum_verify(inode, raw_inode, ei) ||
	    ext4_simulate_fail(sb, EXT4_SIM_INODE_CRC)) &&
	     (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY))) {
		ext4_error_inode_err(inode, function, line, 0,
				EFSBADCRC, "iget: checksum invalid");
4777
		ret = -EFSBADCRC;
4778 4779 4780
		goto bad_inode;
	}

4781
	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
4782 4783
	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
Kaho Ng's avatar
Kaho Ng committed
4784
	if (ext4_has_feature_project(sb) &&
Li Xi's avatar
Li Xi committed
4785 4786 4787 4788 4789 4790
	    EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE &&
	    EXT4_FITS_IN_INODE(raw_inode, ei, i_projid))
		i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid);
	else
		i_projid = EXT4_DEF_PROJID;

4791
	if (!(test_opt(inode->i_sb, NO_UID32))) {
4792 4793
		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
4794
	}
4795 4796
	i_uid_write(inode, i_uid);
	i_gid_write(inode, i_gid);
Li Xi's avatar
Li Xi committed
4797
	ei->i_projid = make_kprojid(&init_user_ns, i_projid);
Miklos Szeredi's avatar
Miklos Szeredi committed
4798
	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
4799

4800
	ext4_clear_state_flags(ei);	/* Only relevant on 32-bit archs */
4801
	ei->i_inline_off = 0;
4802 4803 4804 4805 4806 4807 4808 4809
	ei->i_dir_start_lookup = 0;
	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
	/* We now have enough fields to check if the inode was active or not.
	 * This is needed because nfsd might try to access dead inodes
	 * the test is that same one that e2fsck uses
	 * NeilBrown 1999oct15
	 */
	if (inode->i_nlink == 0) {
4810
		if ((inode->i_mode == 0 || flags & EXT4_IGET_SPECIAL ||
4811 4812
		     !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) &&
		    ino != EXT4_BOOT_LOADER_INO) {
4813 4814 4815 4816 4817 4818 4819
			/* this inode is deleted or unallocated */
			if (flags & EXT4_IGET_SPECIAL) {
				ext4_error_inode(inode, function, line, 0,
						 "iget: special inode unallocated");
				ret = -EFSCORRUPTED;
			} else
				ret = -ESTALE;
4820 4821 4822 4823 4824
			goto bad_inode;
		}
		/* The only unlinked inodes we let through here have
		 * valid i_mode and are being read by the orphan
		 * recovery code: that's fine, we're about to complete
4825 4826 4827
		 * the process of deleting those.
		 * OR it is the EXT4_BOOT_LOADER_INO which is
		 * not initialized on a new filesystem. */
4828 4829
	}
	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
4830
	ext4_set_inode_flags(inode, true);
4831
	inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
4832
	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
4833
	if (ext4_has_feature_64bit(sb))
4834 4835
		ei->i_file_acl |=
			((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
4836
	inode->i_size = ext4_isize(sb, raw_inode);
4837
	if ((size = i_size_read(inode)) < 0) {
4838 4839
		ext4_error_inode(inode, function, line, 0,
				 "iget: bad i_size value: %lld", size);
4840 4841 4842
		ret = -EFSCORRUPTED;
		goto bad_inode;
	}
4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854
	/*
	 * If dir_index is not enabled but there's dir with INDEX flag set,
	 * we'd normally treat htree data as empty space. But with metadata
	 * checksumming that corrupts checksums so forbid that.
	 */
	if (!ext4_has_feature_dir_index(sb) && ext4_has_metadata_csum(sb) &&
	    ext4_test_inode_flag(inode, EXT4_INODE_INDEX)) {
		ext4_error_inode(inode, function, line, 0,
			 "iget: Dir with htree data on filesystem without dir_index feature.");
		ret = -EFSCORRUPTED;
		goto bad_inode;
	}
4855
	ei->i_disksize = inode->i_size;
4856 4857 4858
#ifdef CONFIG_QUOTA
	ei->i_reserved_quota = 0;
#endif
4859 4860
	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
	ei->i_block_group = iloc.block_group;
4861
	ei->i_last_alloc_group = ~0;
4862 4863 4864 4865
	/*
	 * NOTE! The in-memory inode i_data array is in little-endian order
	 * even on big-endian machines: we do NOT byteswap the block numbers!
	 */
4866
	for (block = 0; block < EXT4_N_BLOCKS; block++)
4867 4868
		ei->i_data[block] = raw_inode->i_block[block];
	INIT_LIST_HEAD(&ei->i_orphan);
4869
	ext4_fc_init_inode(&ei->vfs_inode);
4870

4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881
	/*
	 * Set transaction id's of transactions that have to be committed
	 * to finish f[data]sync. We set them to currently running transaction
	 * as we cannot be sure that the inode or some of its metadata isn't
	 * part of the transaction - the inode could have been reclaimed and
	 * now it is reread from disk.
	 */
	if (journal) {
		transaction_t *transaction;
		tid_t tid;

4882
		read_lock(&journal->j_state_lock);
4883 4884 4885 4886 4887 4888 4889 4890
		if (journal->j_running_transaction)
			transaction = journal->j_running_transaction;
		else
			transaction = journal->j_committing_transaction;
		if (transaction)
			tid = transaction->t_tid;
		else
			tid = journal->j_commit_sequence;
4891
		read_unlock(&journal->j_state_lock);
4892 4893 4894 4895
		ei->i_sync_tid = tid;
		ei->i_datasync_tid = tid;
	}

4896
	if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
4897 4898
		if (ei->i_extra_isize == 0) {
			/* The extra space is currently unused. Use it. */
4899
			BUILD_BUG_ON(sizeof(struct ext4_inode) & 3);
4900 4901
			ei->i_extra_isize = sizeof(struct ext4_inode) -
					    EXT4_GOOD_OLD_INODE_SIZE;
4902
		} else {
4903 4904 4905
			ret = ext4_iget_extra_inode(inode, raw_inode, ei);
			if (ret)
				goto bad_inode;
4906
		}
4907
	}
4908

4909
	EXT4_INODE_GET_CTIME(inode, raw_inode);
4910 4911
	EXT4_INODE_GET_ATIME(inode, raw_inode);
	EXT4_INODE_GET_MTIME(inode, raw_inode);
Kalpak Shah's avatar
Kalpak Shah committed
4912 4913
	EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);

4914
	if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) {
4915 4916
		u64 ivers = le32_to_cpu(raw_inode->i_disk_version);

4917 4918
		if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
			if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
4919
				ivers |=
4920 4921
		    (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
		}
4922
		ext4_inode_set_iversion_queried(inode, ivers);
4923 4924
	}

4925
	ret = 0;
4926
	if (ei->i_file_acl &&
4927
	    !ext4_inode_block_valid(inode, ei->i_file_acl, 1)) {
4928 4929
		ext4_error_inode(inode, function, line, 0,
				 "iget: bad extended attribute block %llu",
4930
				 ei->i_file_acl);
4931
		ret = -EFSCORRUPTED;
4932
		goto bad_inode;
4933
	} else if (!ext4_has_inline_data(inode)) {
4934
		/* validate the block references in the inode */
4935 4936 4937 4938
		if (!(EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY) &&
			(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
			(S_ISLNK(inode->i_mode) &&
			!ext4_inode_is_fast_symlink(inode)))) {
4939
			if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
4940
				ret = ext4_ext_check_inode(inode);
4941 4942
			else
				ret = ext4_ind_check_inode(inode);
4943
		}
4944
	}
4945
	if (ret)
4946
		goto bad_inode;
4947

4948
	if (S_ISREG(inode->i_mode)) {
4949
		inode->i_op = &ext4_file_inode_operations;
4950
		inode->i_fop = &ext4_file_operations;
4951
		ext4_set_aops(inode);
4952
	} else if (S_ISDIR(inode->i_mode)) {
4953 4954
		inode->i_op = &ext4_dir_inode_operations;
		inode->i_fop = &ext4_dir_operations;
4955
	} else if (S_ISLNK(inode->i_mode)) {
4956 4957
		/* VFS does not allow setting these so must be corruption */
		if (IS_APPEND(inode) || IS_IMMUTABLE(inode)) {
4958 4959 4960
			ext4_error_inode(inode, function, line, 0,
					 "iget: immutable or append flags "
					 "not allowed on symlinks");
4961 4962 4963
			ret = -EFSCORRUPTED;
			goto bad_inode;
		}
4964
		if (IS_ENCRYPTED(inode)) {
4965 4966
			inode->i_op = &ext4_encrypted_symlink_inode_operations;
		} else if (ext4_inode_is_fast_symlink(inode)) {
4967
			inode->i_link = (char *)ei->i_data;
4968
			inode->i_op = &ext4_fast_symlink_inode_operations;
4969 4970 4971
			nd_terminate_link(ei->i_data, inode->i_size,
				sizeof(ei->i_data) - 1);
		} else {
4972
			inode->i_op = &ext4_symlink_inode_operations;
4973
		}
4974 4975
	} else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
	      S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
4976
		inode->i_op = &ext4_special_inode_operations;
4977 4978 4979 4980 4981 4982
		if (raw_inode->i_block[0])
			init_special_inode(inode, inode->i_mode,
			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
		else
			init_special_inode(inode, inode->i_mode,
			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
4983 4984
	} else if (ino == EXT4_BOOT_LOADER_INO) {
		make_bad_inode(inode);
4985
	} else {
4986
		ret = -EFSCORRUPTED;
4987 4988
		ext4_error_inode(inode, function, line, 0,
				 "iget: bogus i_mode (%o)", inode->i_mode);
4989
		goto bad_inode;
4990
	}
4991
	if (IS_CASEFOLDED(inode) && !ext4_has_feature_casefold(inode->i_sb)) {
4992 4993
		ext4_error_inode(inode, function, line, 0,
				 "casefold flag without casefold feature");
4994 4995 4996
		ret = -EFSCORRUPTED;
		goto bad_inode;
	}
4997 4998 4999
	if ((err_str = check_igot_inode(inode, flags)) != NULL) {
		ext4_error_inode(inode, function, line, 0, err_str);
		ret = -EFSCORRUPTED;
5000 5001
		goto bad_inode;
	}
5002

5003
	brelse(iloc.bh);
5004 5005
	unlock_new_inode(inode);
	return inode;
5006 5007

bad_inode:
5008
	brelse(iloc.bh);
5009 5010
	iget_failed(inode);
	return ERR_PTR(ret);
5011 5012
}

5013 5014 5015 5016
static void __ext4_update_other_inode_time(struct super_block *sb,
					   unsigned long orig_ino,
					   unsigned long ino,
					   struct ext4_inode *raw_inode)
5017
{
5018 5019 5020 5021 5022
	struct inode *inode;

	inode = find_inode_by_ino_rcu(sb, ino);
	if (!inode)
		return;
5023

5024
	if (!inode_is_dirtytime_only(inode))
5025 5026
		return;

5027
	spin_lock(&inode->i_lock);
5028
	if (inode_is_dirtytime_only(inode)) {
5029 5030
		struct ext4_inode_info	*ei = EXT4_I(inode);

5031
		inode->i_state &= ~I_DIRTY_TIME;
5032 5033 5034
		spin_unlock(&inode->i_lock);

		spin_lock(&ei->i_raw_lock);
5035
		EXT4_INODE_SET_CTIME(inode, raw_inode);
5036 5037
		EXT4_INODE_SET_MTIME(inode, raw_inode);
		EXT4_INODE_SET_ATIME(inode, raw_inode);
5038
		ext4_inode_csum_set(inode, raw_inode, ei);
5039
		spin_unlock(&ei->i_raw_lock);
5040 5041
		trace_ext4_other_inode_update_time(inode, orig_ino);
		return;
5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056
	}
	spin_unlock(&inode->i_lock);
}

/*
 * Opportunistically update the other time fields for other inodes in
 * the same inode table block.
 */
static void ext4_update_other_inodes_time(struct super_block *sb,
					  unsigned long orig_ino, char *buf)
{
	unsigned long ino;
	int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
	int inode_size = EXT4_INODE_SIZE(sb);

5057 5058 5059 5060 5061 5062
	/*
	 * Calculate the first inode in the inode table block.  Inode
	 * numbers are one-based.  That is, the first inode in a block
	 * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1).
	 */
	ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1;
5063
	rcu_read_lock();
5064 5065 5066
	for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) {
		if (ino == orig_ino)
			continue;
5067 5068
		__ext4_update_other_inode_time(sb, orig_ino, ino,
					       (struct ext4_inode *)buf);
5069
	}
5070
	rcu_read_unlock();
5071 5072
}

5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108
/*
 * Post the struct inode info into an on-disk inode location in the
 * buffer-cache.  This gobbles the caller's reference to the
 * buffer_head in the inode location struct.
 *
 * The caller must have write access to iloc->bh.
 */
static int ext4_do_update_inode(handle_t *handle,
				struct inode *inode,
				struct ext4_iloc *iloc)
{
	struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
	struct ext4_inode_info *ei = EXT4_I(inode);
	struct buffer_head *bh = iloc->bh;
	struct super_block *sb = inode->i_sb;
	int err;
	int need_datasync = 0, set_large_file = 0;

	spin_lock(&ei->i_raw_lock);

	/*
	 * For fields not tracked in the in-memory inode, initialise them
	 * to zero for new inodes.
	 */
	if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
		memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);

	if (READ_ONCE(ei->i_disksize) != ext4_isize(inode->i_sb, raw_inode))
		need_datasync = 1;
	if (ei->i_disksize > 0x7fffffffULL) {
		if (!ext4_has_feature_large_file(sb) ||
		    EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV))
			set_large_file = 1;
	}

	err = ext4_fill_raw_inode(inode, raw_inode);
5109
	spin_unlock(&ei->i_raw_lock);
5110 5111 5112 5113 5114
	if (err) {
		EXT4_ERROR_INODE(inode, "corrupted inode contents");
		goto out_brelse;
	}

5115
	if (inode->i_sb->s_flags & SB_LAZYTIME)
5116 5117
		ext4_update_other_inodes_time(inode->i_sb, inode->i_ino,
					      bh->b_data);
5118

5119
	BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
5120 5121
	err = ext4_handle_dirty_metadata(handle, NULL, bh);
	if (err)
5122
		goto out_error;
5123
	ext4_clear_inode_state(inode, EXT4_STATE_NEW);
5124
	if (set_large_file) {
5125
		BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access");
5126 5127 5128
		err = ext4_journal_get_write_access(handle, sb,
						    EXT4_SB(sb)->s_sbh,
						    EXT4_JTR_NONE);
5129
		if (err)
5130
			goto out_error;
5131
		lock_buffer(EXT4_SB(sb)->s_sbh);
5132
		ext4_set_feature_large_file(sb);
5133 5134
		ext4_superblock_csum_set(sb);
		unlock_buffer(EXT4_SB(sb)->s_sbh);
5135
		ext4_handle_sync(handle);
5136 5137
		err = ext4_handle_dirty_metadata(handle, NULL,
						 EXT4_SB(sb)->s_sbh);
5138
	}
5139
	ext4_update_inode_fsync_trans(handle, inode, need_datasync);
5140 5141
out_error:
	ext4_std_error(inode->i_sb, err);
5142
out_brelse:
5143
	brelse(bh);
5144 5145 5146 5147
	return err;
}

/*
5148
 * ext4_write_inode()
5149 5150 5151
 *
 * We are called from a few places:
 *
5152
 * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files.
5153
 *   Here, there will be no transaction running. We wait for any running
5154
 *   transaction to commit.
5155
 *
5156 5157
 * - Within flush work (sys_sync(), kupdate and such).
 *   We wait on commit, if told to.
5158
 *
5159 5160
 * - Within iput_final() -> write_inode_now()
 *   We wait on commit, if told to.
5161 5162 5163
 *
 * In all cases it is actually safe for us to return without doing anything,
 * because the inode has been copied into a raw inode buffer in
5164 5165
 * ext4_mark_inode_dirty().  This is a correctness thing for WB_SYNC_ALL
 * writeback.
5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176
 *
 * Note that we are absolutely dependent upon all inode dirtiers doing the
 * right thing: they *must* call mark_inode_dirty() after dirtying info in
 * which we are interested.
 *
 * It would be a bug for them to not do this.  The code:
 *
 *	mark_inode_dirty(inode)
 *	stuff();
 *	inode->i_size = expr;
 *
5177 5178 5179
 * is in error because write_inode() could occur while `stuff()' is running,
 * and the new i_size will be lost.  Plus the inode will no longer be on the
 * superblock's dirty inode list.
5180
 */
5181
int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
5182
{
5183 5184
	int err;

5185
	if (WARN_ON_ONCE(current->flags & PF_MEMALLOC))
5186 5187
		return 0;

5188
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5189 5190
		return -EIO;

5191 5192
	if (EXT4_SB(inode->i_sb)->s_journal) {
		if (ext4_journal_current_handle()) {
5193
			ext4_debug("called recursively, non-PF_MEMALLOC!\n");
5194 5195 5196
			dump_stack();
			return -EIO;
		}
5197

5198 5199 5200 5201 5202 5203
		/*
		 * No need to force transaction in WB_SYNC_NONE mode. Also
		 * ext4_sync_fs() will force the commit after everything is
		 * written.
		 */
		if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync)
5204 5205
			return 0;

5206
		err = ext4_fc_commit(EXT4_SB(inode->i_sb)->s_journal,
5207
						EXT4_I(inode)->i_sync_tid);
5208 5209
	} else {
		struct ext4_iloc iloc;
5210

5211
		err = __ext4_get_inode_loc_noinmem(inode, &iloc);
5212 5213
		if (err)
			return err;
5214 5215 5216 5217 5218
		/*
		 * sync(2) will flush the whole buffer cache. No need to do
		 * it here separately for each inode.
		 */
		if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync)
5219 5220
			sync_dirty_buffer(iloc.bh);
		if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
5221 5222
			ext4_error_inode_block(inode, iloc.bh->b_blocknr, EIO,
					       "IO error syncing inode");
5223 5224
			err = -EIO;
		}
5225
		brelse(iloc.bh);
5226 5227
	}
	return err;
5228 5229
}

5230
/*
5231 5232
 * In data=journal mode ext4_journalled_invalidate_folio() may fail to invalidate
 * buffers that are attached to a folio straddling i_size and are undergoing
5233 5234 5235 5236 5237 5238 5239 5240 5241
 * commit. In that case we have to wait for commit to finish and try again.
 */
static void ext4_wait_for_tail_page_commit(struct inode *inode)
{
	unsigned offset;
	journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
	tid_t commit_tid = 0;
	int ret;

5242
	offset = inode->i_size & (PAGE_SIZE - 1);
5243
	/*
5244 5245 5246
	 * If the folio is fully truncated, we don't need to wait for any commit
	 * (and we even should not as __ext4_journalled_invalidate_folio() may
	 * strip all buffers from the folio but keep the folio dirty which can then
5247
	 * confuse e.g. concurrent ext4_writepages() seeing dirty folio without
5248
	 * buffers). Also we don't need to wait for any commit if all buffers in
5249
	 * the folio remain valid. This is most beneficial for the common case of
5250
	 * blocksize == PAGESIZE.
5251
	 */
5252
	if (!offset || offset > (PAGE_SIZE - i_blocksize(inode)))
5253 5254
		return;
	while (1) {
5255
		struct folio *folio = filemap_lock_folio(inode->i_mapping,
5256
				      inode->i_size >> PAGE_SHIFT);
5257
		if (IS_ERR(folio))
5258
			return;
5259 5260 5261 5262
		ret = __ext4_journalled_invalidate_folio(folio, offset,
						folio_size(folio) - offset);
		folio_unlock(folio);
		folio_put(folio);
5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274
		if (ret != -EBUSY)
			return;
		commit_tid = 0;
		read_lock(&journal->j_state_lock);
		if (journal->j_committing_transaction)
			commit_tid = journal->j_committing_transaction->t_tid;
		read_unlock(&journal->j_state_lock);
		if (commit_tid)
			jbd2_log_wait_commit(journal, commit_tid);
	}
}

5275
/*
5276
 * ext4_setattr()
5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289
 *
 * Called from notify_change.
 *
 * We want to trap VFS attempts to truncate the file as soon as
 * possible.  In particular, we want to make sure that when the VFS
 * shrinks i_size, we put the inode on the orphan list and modify
 * i_disksize immediately, so that during the subsequent flushing of
 * dirty pages and freeing of disk blocks, we can guarantee that any
 * commit will leave the blocks being flushed in an unused state on
 * disk.  (On recovery, the inode will get truncated and the blocks will
 * be freed, so we have a strong guarantee that no future commit will
 * leave these blocks visible to the user.)
 *
5290 5291 5292 5293 5294 5295 5296
 * Another thing we have to assure is that if we are in ordered mode
 * and inode is still attached to the committing transaction, we must
 * we start writeout of all the dirty pages which are being truncated.
 * This way we are sure that all the data written in the previous
 * transaction are already on disk (truncate waits for pages under
 * writeback).
 *
5297
 * Called with inode->i_rwsem down.
5298
 */
5299
int ext4_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5300
		 struct iattr *attr)
5301
{
5302
	struct inode *inode = d_inode(dentry);
5303
	int error, rc = 0;
5304
	int orphan = 0;
5305
	const unsigned int ia_valid = attr->ia_valid;
5306
	bool inc_ivers = true;
5307

5308
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5309 5310
		return -EIO;

5311 5312 5313 5314 5315 5316 5317 5318
	if (unlikely(IS_IMMUTABLE(inode)))
		return -EPERM;

	if (unlikely(IS_APPEND(inode) &&
		     (ia_valid & (ATTR_MODE | ATTR_UID |
				  ATTR_GID | ATTR_TIMES_SET))))
		return -EPERM;

5319
	error = setattr_prepare(idmap, dentry, attr);
5320 5321 5322
	if (error)
		return error;

5323 5324 5325 5326
	error = fscrypt_prepare_setattr(dentry, attr);
	if (error)
		return error;

5327 5328 5329 5330
	error = fsverity_prepare_setattr(dentry, attr);
	if (error)
		return error;

Christian Brauner's avatar
Christian Brauner committed
5331
	if (is_quota_modification(idmap, inode, attr)) {
5332 5333 5334 5335
		error = dquot_initialize(inode);
		if (error)
			return error;
	}
5336

5337 5338
	if (i_uid_needs_update(idmap, attr, inode) ||
	    i_gid_needs_update(idmap, attr, inode)) {
5339 5340 5341 5342
		handle_t *handle;

		/* (user+group)*(old+new) structure, inode write (sb,
		 * inode block, ? - but truncate inode update has it) */
5343 5344 5345
		handle = ext4_journal_start(inode, EXT4_HT_QUOTA,
			(EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) +
			 EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3);
5346 5347 5348 5349
		if (IS_ERR(handle)) {
			error = PTR_ERR(handle);
			goto err_out;
		}
5350 5351 5352 5353 5354

		/* dquot_transfer() calls back ext4_get_inode_usage() which
		 * counts xattr inode references.
		 */
		down_read(&EXT4_I(inode)->xattr_sem);
Christian Brauner's avatar
Christian Brauner committed
5355
		error = dquot_transfer(idmap, inode, attr);
5356 5357
		up_read(&EXT4_I(inode)->xattr_sem);

5358
		if (error) {
5359
			ext4_journal_stop(handle);
5360 5361 5362 5363
			return error;
		}
		/* Update corresponding info in inode so that everything is in
		 * one transaction */
5364 5365
		i_uid_update(idmap, attr, inode);
		i_gid_update(idmap, attr, inode);
5366 5367
		error = ext4_mark_inode_dirty(handle, inode);
		ext4_journal_stop(handle);
5368
		if (unlikely(error)) {
5369
			return error;
5370
		}
5371 5372
	}

5373
	if (attr->ia_valid & ATTR_SIZE) {
5374
		handle_t *handle;
5375
		loff_t oldsize = inode->i_size;
5376
		loff_t old_disksize;
5377
		int shrink = (attr->ia_size < inode->i_size);
5378

5379
		if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
5380 5381
			struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);

5382
			if (attr->ia_size > sbi->s_bitmap_maxbytes) {
5383
				return -EFBIG;
5384
			}
5385
		}
5386
		if (!S_ISREG(inode->i_mode)) {
5387
			return -EINVAL;
5388
		}
Christoph Hellwig's avatar
Christoph Hellwig committed
5389

5390 5391
		if (attr->ia_size == inode->i_size)
			inc_ivers = false;
Christoph Hellwig's avatar
Christoph Hellwig committed
5392

5393 5394 5395
		if (shrink) {
			if (ext4_should_order_data(inode)) {
				error = ext4_begin_ordered_truncate(inode,
5396
							    attr->ia_size);
5397 5398 5399 5400 5401 5402 5403 5404 5405 5406
				if (error)
					goto err_out;
			}
			/*
			 * Blocks are going to be removed from the inode. Wait
			 * for dio in flight.
			 */
			inode_dio_wait(inode);
		}

5407
		filemap_invalidate_lock(inode->i_mapping);
5408 5409 5410

		rc = ext4_break_layouts(inode);
		if (rc) {
5411
			filemap_invalidate_unlock(inode->i_mapping);
5412
			goto err_out;
5413
		}
5414

5415
		if (attr->ia_size != inode->i_size) {
5416 5417 5418
			handle = ext4_journal_start(inode, EXT4_HT_INODE, 3);
			if (IS_ERR(handle)) {
				error = PTR_ERR(handle);
5419
				goto out_mmap_sem;
5420
			}
5421
			if (ext4_handle_valid(handle) && shrink) {
5422 5423 5424
				error = ext4_orphan_add(handle, inode);
				orphan = 1;
			}
5425 5426 5427 5428
			/*
			 * Update c/mtime on truncate up, ext4_truncate() will
			 * update c/mtime in shrink case below
			 */
5429
			if (!shrink)
5430 5431
				inode_set_mtime_to_ts(inode,
						      inode_set_ctime_current(inode));
5432 5433

			if (shrink)
5434
				ext4_fc_track_range(handle, inode,
5435 5436
					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
					inode->i_sb->s_blocksize_bits,
5437
					EXT_MAX_BLOCKS - 1);
5438 5439
			else
				ext4_fc_track_range(
5440
					handle, inode,
5441 5442 5443 5444 5445
					(oldsize > 0 ? oldsize - 1 : oldsize) >>
					inode->i_sb->s_blocksize_bits,
					(attr->ia_size > 0 ? attr->ia_size - 1 : 0) >>
					inode->i_sb->s_blocksize_bits);

5446
			down_write(&EXT4_I(inode)->i_data_sem);
5447
			old_disksize = EXT4_I(inode)->i_disksize;
5448 5449 5450 5451
			EXT4_I(inode)->i_disksize = attr->ia_size;
			rc = ext4_mark_inode_dirty(handle, inode);
			if (!error)
				error = rc;
5452 5453 5454 5455 5456 5457 5458
			/*
			 * We have to update i_size under i_data_sem together
			 * with i_disksize to avoid races with writeback code
			 * running ext4_wb_update_i_disksize().
			 */
			if (!error)
				i_size_write(inode, attr->ia_size);
5459 5460
			else
				EXT4_I(inode)->i_disksize = old_disksize;
5461
			up_write(&EXT4_I(inode)->i_data_sem);
5462
			ext4_journal_stop(handle);
5463 5464 5465 5466 5467 5468 5469
			if (error)
				goto out_mmap_sem;
			if (!shrink) {
				pagecache_isize_extended(inode, oldsize,
							 inode->i_size);
			} else if (ext4_should_journal_data(inode)) {
				ext4_wait_for_tail_page_commit(inode);
5470
			}
5471
		}
5472

5473 5474 5475 5476
		/*
		 * Truncate pagecache after we've waited for commit
		 * in data=journal mode to make pages freeable.
		 */
Ross Zwisler's avatar
Ross Zwisler committed
5477
		truncate_pagecache(inode, inode->i_size);
5478 5479 5480 5481 5482
		/*
		 * Call ext4_truncate() even if i_size didn't change to
		 * truncate possible preallocated blocks.
		 */
		if (attr->ia_size <= oldsize) {
5483 5484 5485 5486
			rc = ext4_truncate(inode);
			if (rc)
				error = rc;
		}
5487
out_mmap_sem:
5488
		filemap_invalidate_unlock(inode->i_mapping);
5489
	}
5490

5491
	if (!error) {
5492 5493
		if (inc_ivers)
			inode_inc_iversion(inode);
5494
		setattr_copy(idmap, inode, attr);
Christoph Hellwig's avatar
Christoph Hellwig committed
5495 5496 5497 5498 5499 5500 5501
		mark_inode_dirty(inode);
	}

	/*
	 * If the call to ext4_truncate failed to get a transaction handle at
	 * all, we need to clean up the in-core orphan list manually.
	 */
5502
	if (orphan && inode->i_nlink)
5503
		ext4_orphan_del(NULL, inode);
5504

5505
	if (!error && (ia_valid & ATTR_MODE))
5506
		rc = posix_acl_chmod(idmap, dentry, inode->i_mode);
5507 5508

err_out:
5509 5510
	if  (error)
		ext4_std_error(inode->i_sb, error);
5511 5512 5513 5514 5515
	if (!error)
		error = rc;
	return error;
}

Eric Biggers's avatar
Eric Biggers committed
5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531
u32 ext4_dio_alignment(struct inode *inode)
{
	if (fsverity_active(inode))
		return 0;
	if (ext4_should_journal_data(inode))
		return 0;
	if (ext4_has_inline_data(inode))
		return 0;
	if (IS_ENCRYPTED(inode)) {
		if (!fscrypt_dio_supported(inode))
			return 0;
		return i_blocksize(inode);
	}
	return 1; /* use the iomap defaults */
}

5532
int ext4_getattr(struct mnt_idmap *idmap, const struct path *path,
5533
		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
5534
{
David Howells's avatar
David Howells committed
5535 5536 5537 5538 5539
	struct inode *inode = d_inode(path->dentry);
	struct ext4_inode *raw_inode;
	struct ext4_inode_info *ei = EXT4_I(inode);
	unsigned int flags;

5540 5541
	if ((request_mask & STATX_BTIME) &&
	    EXT4_FITS_IN_INODE(raw_inode, ei, i_crtime)) {
David Howells's avatar
David Howells committed
5542 5543 5544 5545 5546
		stat->result_mask |= STATX_BTIME;
		stat->btime.tv_sec = ei->i_crtime.tv_sec;
		stat->btime.tv_nsec = ei->i_crtime.tv_nsec;
	}

Eric Biggers's avatar
Eric Biggers committed
5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567
	/*
	 * Return the DIO alignment restrictions if requested.  We only return
	 * this information when requested, since on encrypted files it might
	 * take a fair bit of work to get if the file wasn't opened recently.
	 */
	if ((request_mask & STATX_DIOALIGN) && S_ISREG(inode->i_mode)) {
		u32 dio_align = ext4_dio_alignment(inode);

		stat->result_mask |= STATX_DIOALIGN;
		if (dio_align == 1) {
			struct block_device *bdev = inode->i_sb->s_bdev;

			/* iomap defaults */
			stat->dio_mem_align = bdev_dma_alignment(bdev) + 1;
			stat->dio_offset_align = bdev_logical_block_size(bdev);
		} else {
			stat->dio_mem_align = dio_align;
			stat->dio_offset_align = dio_align;
		}
	}

David Howells's avatar
David Howells committed
5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578
	flags = ei->i_flags & EXT4_FL_USER_VISIBLE;
	if (flags & EXT4_APPEND_FL)
		stat->attributes |= STATX_ATTR_APPEND;
	if (flags & EXT4_COMPR_FL)
		stat->attributes |= STATX_ATTR_COMPRESSED;
	if (flags & EXT4_ENCRYPT_FL)
		stat->attributes |= STATX_ATTR_ENCRYPTED;
	if (flags & EXT4_IMMUTABLE_FL)
		stat->attributes |= STATX_ATTR_IMMUTABLE;
	if (flags & EXT4_NODUMP_FL)
		stat->attributes |= STATX_ATTR_NODUMP;
5579 5580
	if (flags & EXT4_VERITY_FL)
		stat->attributes |= STATX_ATTR_VERITY;
5581

5582 5583 5584 5585
	stat->attributes_mask |= (STATX_ATTR_APPEND |
				  STATX_ATTR_COMPRESSED |
				  STATX_ATTR_ENCRYPTED |
				  STATX_ATTR_IMMUTABLE |
5586 5587
				  STATX_ATTR_NODUMP |
				  STATX_ATTR_VERITY);
5588

5589
	generic_fillattr(idmap, request_mask, inode, stat);
David Howells's avatar
David Howells committed
5590 5591 5592
	return 0;
}

5593
int ext4_file_getattr(struct mnt_idmap *idmap,
5594
		      const struct path *path, struct kstat *stat,
David Howells's avatar
David Howells committed
5595 5596 5597 5598 5599
		      u32 request_mask, unsigned int query_flags)
{
	struct inode *inode = d_inode(path->dentry);
	u64 delalloc_blocks;

5600
	ext4_getattr(idmap, path, stat, request_mask, query_flags);
5601

5602 5603 5604 5605
	/*
	 * If there is inline data in the inode, the inode will normally not
	 * have data blocks allocated (it may have an external xattr block).
	 * Report at least one sector for such files, so tools like tar, rsync,
Theodore Ts'o's avatar
Theodore Ts'o committed
5606
	 * others don't incorrectly think the file is completely sparse.
5607 5608 5609 5610
	 */
	if (unlikely(ext4_has_inline_data(inode)))
		stat->blocks += (stat->size + 511) >> 9;

5611 5612 5613 5614 5615 5616 5617 5618 5619 5620
	/*
	 * We can't update i_blocks if the block allocation is delayed
	 * otherwise in the case of system crash before the real block
	 * allocation is done, we will have i_blocks inconsistent with
	 * on-disk file blocks.
	 * We always keep i_blocks updated together with real
	 * allocation. But to not confuse with user, stat
	 * will return the blocks that include the delayed allocation
	 * blocks for this file.
	 */
5621
	delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb),
5622 5623
				   EXT4_I(inode)->i_reserved_data_blocks);
	stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9);
5624 5625
	return 0;
}
5626

5627 5628
static int ext4_index_trans_blocks(struct inode *inode, int lblocks,
				   int pextents)
5629
{
5630
	if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
5631 5632
		return ext4_ind_trans_blocks(inode, lblocks);
	return ext4_ext_index_trans_blocks(inode, pextents);
5633
}
5634

5635
/*
5636 5637 5638
 * Account for index blocks, block groups bitmaps and block group
 * descriptor blocks if modify datablocks and index blocks
 * worse case, the indexs blocks spread over different block groups
5639
 *
5640
 * If datablocks are discontiguous, they are possible to spread over
5641
 * different block groups too. If they are contiguous, with flexbg,
5642
 * they could still across block group boundary.
5643
 *
5644 5645
 * Also account for superblock, inode, quota and xattr blocks
 */
5646
static int ext4_meta_trans_blocks(struct inode *inode, int lblocks,
5647
				  int pextents)
5648
{
5649 5650
	ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
	int gdpblocks;
5651
	int idxblocks;
5652
	int ret;
5653 5654

	/*
5655 5656
	 * How many index blocks need to touch to map @lblocks logical blocks
	 * to @pextents physical extents?
5657
	 */
5658
	idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents);
5659 5660 5661 5662 5663 5664 5665

	ret = idxblocks;

	/*
	 * Now let's see how many group bitmaps and group descriptors need
	 * to account
	 */
5666
	groups = idxblocks + pextents;
5667
	gdpblocks = groups;
5668 5669
	if (groups > ngroups)
		groups = ngroups;
5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682
	if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
		gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;

	/* bitmaps and block group descriptor blocks */
	ret += groups + gdpblocks;

	/* Blocks for super block, inode, quota and xattr blocks */
	ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);

	return ret;
}

/*
Lucas De Marchi's avatar
Lucas De Marchi committed
5683
 * Calculate the total number of credits to reserve to fit
5684 5685
 * the modification of a single pages into a single transaction,
 * which may include multiple chunks of block allocations.
5686
 *
5687
 * This could be called via ext4_write_begin()
5688
 *
5689
 * We need to consider the worse case, when
5690
 * one new block per extent.
5691
 */
5692
int ext4_writepage_trans_blocks(struct inode *inode)
5693
{
5694
	int bpp = ext4_journal_blocks_per_page(inode);
5695 5696
	int ret;

5697
	ret = ext4_meta_trans_blocks(inode, bpp, bpp);
5698

5699
	/* Account for data blocks for journalled mode */
5700
	if (ext4_should_journal_data(inode))
5701
		ret += bpp;
5702 5703
	return ret;
}
5704 5705 5706 5707 5708

/*
 * Calculate the journal credits for a chunk of data modification.
 *
 * This is called from DIO, fallocate or whoever calling
5709
 * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
5710 5711 5712 5713 5714 5715 5716 5717 5718
 *
 * journal buffers for data blocks are not included here, as DIO
 * and fallocate do no need to journal data buffers.
 */
int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
{
	return ext4_meta_trans_blocks(inode, nrblocks, 1);
}

5719
/*
5720
 * The caller must have previously called ext4_reserve_inode_write().
5721 5722
 * Give this, we know that the caller already has write access to iloc->bh.
 */
5723
int ext4_mark_iloc_dirty(handle_t *handle,
5724
			 struct inode *inode, struct ext4_iloc *iloc)
5725 5726 5727
{
	int err = 0;

5728
	if (unlikely(ext4_forced_shutdown(inode->i_sb))) {
5729
		put_bh(iloc->bh);
5730
		return -EIO;
5731
	}
5732
	ext4_fc_track_inode(handle, inode);
5733

5734 5735 5736
	/* the do_update_inode consumes one bh->b_count */
	get_bh(iloc->bh);

5737
	/* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
5738
	err = ext4_do_update_inode(handle, inode, iloc);
5739 5740 5741 5742 5743 5744 5745 5746 5747 5748
	put_bh(iloc->bh);
	return err;
}

/*
 * On success, We end up with an outstanding reference count against
 * iloc->bh.  This _must_ be cleaned up later.
 */

int
5749 5750
ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
			 struct ext4_iloc *iloc)
5751
{
5752 5753
	int err;

5754
	if (unlikely(ext4_forced_shutdown(inode->i_sb)))
5755 5756
		return -EIO;

5757 5758 5759
	err = ext4_get_inode_loc(inode, iloc);
	if (!err) {
		BUFFER_TRACE(iloc->bh, "get_write_access");
5760 5761
		err = ext4_journal_get_write_access(handle, inode->i_sb,
						    iloc->bh, EXT4_JTR_NONE);
5762 5763 5764
		if (err) {
			brelse(iloc->bh);
			iloc->bh = NULL;
5765 5766
		}
	}
5767
	ext4_std_error(inode->i_sb, err);
5768 5769 5770
	return err;
}

5771 5772 5773 5774 5775 5776 5777
static int __ext4_expand_extra_isize(struct inode *inode,
				     unsigned int new_extra_isize,
				     struct ext4_iloc *iloc,
				     handle_t *handle, int *no_expand)
{
	struct ext4_inode *raw_inode;
	struct ext4_xattr_ibody_header *header;
5778 5779
	unsigned int inode_size = EXT4_INODE_SIZE(inode->i_sb);
	struct ext4_inode_info *ei = EXT4_I(inode);
5780 5781
	int error;

5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794
	/* this was checked at iget time, but double check for good measure */
	if ((EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > inode_size) ||
	    (ei->i_extra_isize & 3)) {
		EXT4_ERROR_INODE(inode, "bad extra_isize %u (inode size %u)",
				 ei->i_extra_isize,
				 EXT4_INODE_SIZE(inode->i_sb));
		return -EFSCORRUPTED;
	}
	if ((new_extra_isize < ei->i_extra_isize) ||
	    (new_extra_isize < 4) ||
	    (new_extra_isize > inode_size - EXT4_GOOD_OLD_INODE_SIZE))
		return -EINVAL;	/* Should never happen */

5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808
	raw_inode = ext4_raw_inode(iloc);

	header = IHDR(inode, raw_inode);

	/* No extended attributes present */
	if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
	    header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
		memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE +
		       EXT4_I(inode)->i_extra_isize, 0,
		       new_extra_isize - EXT4_I(inode)->i_extra_isize);
		EXT4_I(inode)->i_extra_isize = new_extra_isize;
		return 0;
	}

5809 5810 5811 5812 5813 5814 5815 5816
	/*
	 * We may need to allocate external xattr block so we need quotas
	 * initialized. Here we can be called with various locks held so we
	 * cannot affort to initialize quotas ourselves. So just bail.
	 */
	if (dquot_initialize_needed(inode))
		return -EAGAIN;

5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829
	/* try to expand with EAs present */
	error = ext4_expand_extra_isize_ea(inode, new_extra_isize,
					   raw_inode, handle);
	if (error) {
		/*
		 * Inode size expansion failed; don't try again
		 */
		*no_expand = 1;
	}

	return error;
}

5830 5831 5832 5833
/*
 * Expand an inode by new_extra_isize bytes.
 * Returns 0 on success or negative error number on failure.
 */
5834 5835 5836 5837
static int ext4_try_to_expand_extra_isize(struct inode *inode,
					  unsigned int new_extra_isize,
					  struct ext4_iloc iloc,
					  handle_t *handle)
5838
{
5839 5840
	int no_expand;
	int error;
5841

5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853
	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND))
		return -EOVERFLOW;

	/*
	 * In nojournal mode, we can immediately attempt to expand
	 * the inode.  When journaled, we first need to obtain extra
	 * buffer credits since we may write into the EA block
	 * with this same handle. If journal_extend fails, then it will
	 * only result in a minor loss of functionality for that inode.
	 * If this is felt to be critical, then e2fsck should be run to
	 * force a large enough s_min_extra_isize.
	 */
5854
	if (ext4_journal_extend(handle,
5855
				EXT4_DATA_TRANS_BLOCKS(inode->i_sb), 0) != 0)
5856
		return -ENOSPC;
5857

5858
	if (ext4_write_trylock_xattr(inode, &no_expand) == 0)
5859
		return -EBUSY;
5860

5861 5862 5863
	error = __ext4_expand_extra_isize(inode, new_extra_isize, &iloc,
					  handle, &no_expand);
	ext4_write_unlock_xattr(inode, &no_expand);
5864

5865 5866
	return error;
}
5867

5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878
int ext4_expand_extra_isize(struct inode *inode,
			    unsigned int new_extra_isize,
			    struct ext4_iloc *iloc)
{
	handle_t *handle;
	int no_expand;
	int error, rc;

	if (ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
		brelse(iloc->bh);
		return -EOVERFLOW;
5879 5880
	}

5881 5882 5883 5884 5885 5886 5887 5888 5889 5890
	handle = ext4_journal_start(inode, EXT4_HT_INODE,
				    EXT4_DATA_TRANS_BLOCKS(inode->i_sb));
	if (IS_ERR(handle)) {
		error = PTR_ERR(handle);
		brelse(iloc->bh);
		return error;
	}

	ext4_write_lock_xattr(inode, &no_expand);

5891
	BUFFER_TRACE(iloc->bh, "get_write_access");
5892 5893
	error = ext4_journal_get_write_access(handle, inode->i_sb, iloc->bh,
					      EXT4_JTR_NONE);
5894
	if (error) {
5895
		brelse(iloc->bh);
5896
		goto out_unlock;
5897
	}
5898

5899 5900 5901 5902 5903 5904 5905
	error = __ext4_expand_extra_isize(inode, new_extra_isize, iloc,
					  handle, &no_expand);

	rc = ext4_mark_iloc_dirty(handle, inode, iloc);
	if (!error)
		error = rc;

5906
out_unlock:
5907 5908
	ext4_write_unlock_xattr(inode, &no_expand);
	ext4_journal_stop(handle);
5909
	return error;
5910 5911
}

5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924
/*
 * What we do here is to mark the in-core inode as clean with respect to inode
 * dirtiness (it may still be data-dirty).
 * This means that the in-core inode may be reaped by prune_icache
 * without having to perform any I/O.  This is a very good thing,
 * because *any* task may call prune_icache - even ones which
 * have a transaction open against a different journal.
 *
 * Is this cheating?  Not really.  Sure, we haven't written the
 * inode out, but prune_icache isn't a user-visible syncing function.
 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
 * we start and wait on commits.
 */
5925 5926
int __ext4_mark_inode_dirty(handle_t *handle, struct inode *inode,
				const char *func, unsigned int line)
5927
{
5928
	struct ext4_iloc iloc;
5929
	struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
5930
	int err;
5931 5932

	might_sleep();
5933
	trace_ext4_mark_inode_dirty(inode, _RET_IP_);
5934
	err = ext4_reserve_inode_write(handle, inode, &iloc);
5935
	if (err)
5936
		goto out;
5937 5938 5939 5940 5941

	if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize)
		ext4_try_to_expand_extra_isize(inode, sbi->s_want_extra_isize,
					       iloc, handle);

5942 5943 5944 5945 5946 5947
	err = ext4_mark_iloc_dirty(handle, inode, &iloc);
out:
	if (unlikely(err))
		ext4_error_inode_err(inode, func, line, 0, err,
					"mark_inode_dirty error");
	return err;
5948 5949 5950
}

/*
5951
 * ext4_dirty_inode() is called from __mark_inode_dirty()
5952 5953 5954 5955 5956
 *
 * We're really interested in the case where a file is being extended.
 * i_size has been changed by generic_commit_write() and we thus need
 * to include the updated inode in the current transaction.
 *
5957
 * Also, dquot_alloc_block() will always dirty the inode when blocks
5958 5959 5960 5961 5962 5963
 * are allocated to the file.
 *
 * If the inode is marked synchronous, we don't honour that here - doing
 * so would cause a commit on atime updates, which we don't bother doing.
 * We handle synchronous inodes at the highest possible level.
 */
5964
void ext4_dirty_inode(struct inode *inode, int flags)
5965 5966 5967
{
	handle_t *handle;

5968
	handle = ext4_journal_start(inode, EXT4_HT_INODE, 2);
5969
	if (IS_ERR(handle))
5970
		return;
5971
	ext4_mark_inode_dirty(handle, inode);
5972
	ext4_journal_stop(handle);
5973 5974
}

5975
int ext4_change_inode_journal_flag(struct inode *inode, int val)
5976 5977 5978 5979
{
	journal_t *journal;
	handle_t *handle;
	int err;
5980
	int alloc_ctx;
5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991

	/*
	 * We have to be very careful here: changing a data block's
	 * journaling status dynamically is dangerous.  If we write a
	 * data block to the journal, change the status and then delete
	 * that block, we risk forgetting to revoke the old log record
	 * from the journal and so a subsequent replay can corrupt data.
	 * So, first we make sure that the journal is empty and that
	 * nobody is changing anything.
	 */

5992
	journal = EXT4_JOURNAL(inode);
5993 5994
	if (!journal)
		return 0;
5995
	if (is_journal_aborted(journal))
5996 5997
		return -EROFS;

5998 5999 6000
	/* Wait for all existing dio workers */
	inode_dio_wait(inode);

6001 6002 6003 6004 6005 6006 6007 6008 6009
	/*
	 * Before flushing the journal and switching inode's aops, we have
	 * to flush all dirty data the inode has. There can be outstanding
	 * delayed allocations, there can be unwritten extents created by
	 * fallocate or buffered writes in dioread_nolock mode covered by
	 * dirty data which can be converted only after flushing the dirty
	 * data (and journalled aops don't know how to handle these cases).
	 */
	if (val) {
6010
		filemap_invalidate_lock(inode->i_mapping);
6011 6012
		err = filemap_write_and_wait(inode->i_mapping);
		if (err < 0) {
6013
			filemap_invalidate_unlock(inode->i_mapping);
6014 6015 6016 6017
			return err;
		}
	}

6018
	alloc_ctx = ext4_writepages_down_write(inode->i_sb);
6019
	jbd2_journal_lock_updates(journal);
6020 6021 6022 6023 6024 6025 6026 6027 6028 6029

	/*
	 * OK, there are no updates running now, and all cached data is
	 * synced to disk.  We are now in a completely consistent state
	 * which doesn't have anything in the journal, and we know that
	 * no filesystem updates are running, so it is safe to modify
	 * the inode's in-core data-journaling state flag now.
	 */

	if (val)
6030
		ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6031
	else {
6032
		err = jbd2_journal_flush(journal, 0);
6033 6034
		if (err < 0) {
			jbd2_journal_unlock_updates(journal);
6035
			ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6036 6037
			return err;
		}
6038
		ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
6039
	}
6040
	ext4_set_aops(inode);
6041

6042
	jbd2_journal_unlock_updates(journal);
6043
	ext4_writepages_up_write(inode->i_sb, alloc_ctx);
6044

6045
	if (val)
6046
		filemap_invalidate_unlock(inode->i_mapping);
6047 6048 6049

	/* Finally we can mark the inode as dirty. */

6050
	handle = ext4_journal_start(inode, EXT4_HT_INODE, 1);
6051 6052 6053
	if (IS_ERR(handle))
		return PTR_ERR(handle);

6054
	ext4_fc_mark_ineligible(inode->i_sb,
6055
		EXT4_FC_REASON_JOURNAL_FLAG_CHANGE, handle);
6056
	err = ext4_mark_inode_dirty(handle, inode);
6057
	ext4_handle_sync(handle);
6058 6059
	ext4_journal_stop(handle);
	ext4_std_error(inode->i_sb, err);
6060 6061 6062

	return err;
}
6063

6064 6065
static int ext4_bh_unmapped(handle_t *handle, struct inode *inode,
			    struct buffer_head *bh)
6066 6067 6068 6069
{
	return !buffer_mapped(bh);
}

6070
vm_fault_t ext4_page_mkwrite(struct vm_fault *vmf)
6071
{
6072
	struct vm_area_struct *vma = vmf->vma;
6073
	struct folio *folio = page_folio(vmf->page);
6074 6075
	loff_t size;
	unsigned long len;
6076 6077
	int err;
	vm_fault_t ret;
6078
	struct file *file = vma->vm_file;
Al Viro's avatar
Al Viro committed
6079
	struct inode *inode = file_inode(file);
6080
	struct address_space *mapping = inode->i_mapping;
6081 6082 6083
	handle_t *handle;
	get_block_t *get_block;
	int retries = 0;
6084

6085 6086 6087
	if (unlikely(IS_IMMUTABLE(inode)))
		return VM_FAULT_SIGBUS;

6088
	sb_start_pagefault(inode->i_sb);
6089
	file_update_time(vma->vm_file);
6090

6091
	filemap_invalidate_lock_shared(mapping);
6092

6093 6094
	err = ext4_convert_inline_data(inode);
	if (err)
6095 6096
		goto out_ret;

6097 6098 6099 6100 6101 6102 6103 6104 6105
	/*
	 * On data journalling we skip straight to the transaction handle:
	 * there's no delalloc; page truncated will be checked later; the
	 * early return w/ all buffers mapped (calculates size/len) can't
	 * be used; and there's no dioread_nolock, so only ext4_get_block.
	 */
	if (ext4_should_journal_data(inode))
		goto retry_alloc;

6106 6107 6108 6109
	/* Delalloc case is easy... */
	if (test_opt(inode->i_sb, DELALLOC) &&
	    !ext4_nonda_switch(inode->i_sb)) {
		do {
6110
			err = block_page_mkwrite(vma, vmf,
6111
						   ext4_da_get_block_prep);
6112
		} while (err == -ENOSPC &&
6113 6114
		       ext4_should_retry_alloc(inode->i_sb, &retries));
		goto out_ret;
6115
	}
6116

6117
	folio_lock(folio);
6118 6119
	size = i_size_read(inode);
	/* Page got truncated from under us? */
6120 6121
	if (folio->mapping != mapping || folio_pos(folio) > size) {
		folio_unlock(folio);
6122 6123
		ret = VM_FAULT_NOPAGE;
		goto out;
6124
	}
6125

6126 6127 6128
	len = folio_size(folio);
	if (folio_pos(folio) + len > size)
		len = size - folio_pos(folio);
6129
	/*
6130 6131
	 * Return if we have all the buffers mapped. This avoids the need to do
	 * journal_start/journal_stop which can block and take a long time
6132 6133 6134
	 *
	 * This cannot be done for data journalling, as we have to add the
	 * inode to the transaction's list to writeprotect pages on commit.
6135
	 */
6136 6137
	if (folio_buffers(folio)) {
		if (!ext4_walk_page_buffers(NULL, inode, folio_buffers(folio),
6138 6139
					    0, len, NULL,
					    ext4_bh_unmapped)) {
6140
			/* Wait so that we don't change page under IO */
6141
			folio_wait_stable(folio);
6142 6143
			ret = VM_FAULT_LOCKED;
			goto out;
6144
		}
6145
	}
6146
	folio_unlock(folio);
6147 6148
	/* OK, we need to fill the hole... */
	if (ext4_should_dioread_nolock(inode))
6149
		get_block = ext4_get_block_unwritten;
6150 6151 6152
	else
		get_block = ext4_get_block;
retry_alloc:
6153 6154
	handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE,
				    ext4_writepage_trans_blocks(inode));
6155
	if (IS_ERR(handle)) {
6156
		ret = VM_FAULT_SIGBUS;
6157 6158
		goto out;
	}
6159 6160 6161 6162 6163 6164 6165 6166
	/*
	 * Data journalling can't use block_page_mkwrite() because it
	 * will set_buffer_dirty() before do_journal_get_write_access()
	 * thus might hit warning messages for dirty metadata buffers.
	 */
	if (!ext4_should_journal_data(inode)) {
		err = block_page_mkwrite(vma, vmf, get_block);
	} else {
6167
		folio_lock(folio);
6168 6169
		size = i_size_read(inode);
		/* Page got truncated from under us? */
6170
		if (folio->mapping != mapping || folio_pos(folio) > size) {
6171
			ret = VM_FAULT_NOPAGE;
6172
			goto out_error;
6173
		}
6174

6175 6176 6177
		len = folio_size(folio);
		if (folio_pos(folio) + len > size)
			len = size - folio_pos(folio);
6178

6179
		err = __block_write_begin(&folio->page, 0, len, ext4_get_block);
6180
		if (!err) {
6181
			ret = VM_FAULT_SIGBUS;
6182
			if (ext4_journal_folio_buffers(handle, folio, len))
6183
				goto out_error;
6184
		} else {
6185
			folio_unlock(folio);
6186
		}
6187 6188
	}
	ext4_journal_stop(handle);
6189
	if (err == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
6190 6191
		goto retry_alloc;
out_ret:
6192
	ret = vmf_fs_error(err);
6193
out:
6194
	filemap_invalidate_unlock_shared(mapping);
6195
	sb_end_pagefault(inode->i_sb);
6196
	return ret;
6197
out_error:
6198
	folio_unlock(folio);
6199 6200
	ext4_journal_stop(handle);
	goto out;
6201
}