File Index
Files and directories
Sign in
FILE

aops.c

File preview with syntax highlighting.

linux-6.19.14/fs/ocfs2/aops.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
   4 */
   5
   6#include <linux/fs.h>
   7#include <linux/slab.h>
   8#include <linux/highmem.h>
   9#include <linux/pagemap.h>
  10#include <asm/byteorder.h>
  11#include <linux/swap.h>
  12#include <linux/mpage.h>
  13#include <linux/quotaops.h>
  14#include <linux/blkdev.h>
  15#include <linux/uio.h>
  16#include <linux/mm.h>
  17
  18#include <cluster/masklog.h>
  19
  20#include "ocfs2.h"
  21
  22#include "alloc.h"
  23#include "aops.h"
  24#include "dlmglue.h"
  25#include "extent_map.h"
  26#include "file.h"
  27#include "inode.h"
  28#include "journal.h"
  29#include "suballoc.h"
  30#include "super.h"
  31#include "symlink.h"
  32#include "refcounttree.h"
  33#include "ocfs2_trace.h"
  34
  35#include "buffer_head_io.h"
  36#include "dir.h"
  37#include "namei.h"
  38#include "sysfile.h"
  39
  40static int ocfs2_symlink_get_block(struct inode *inode, sector_t iblock,
  41				   struct buffer_head *bh_result, int create)
  42{
  43	int err = -EIO;
  44	int status;
  45	struct ocfs2_dinode *fe = NULL;
  46	struct buffer_head *bh = NULL;
  47	struct buffer_head *buffer_cache_bh = NULL;
  48	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
  49
  50	trace_ocfs2_symlink_get_block(
  51			(unsigned long long)OCFS2_I(inode)->ip_blkno,
  52			(unsigned long long)iblock, bh_result, create);
  53
  54	BUG_ON(ocfs2_inode_is_fast_symlink(inode));
  55
  56	if ((iblock << inode->i_sb->s_blocksize_bits) > PATH_MAX + 1) {
  57		mlog(ML_ERROR, "block offset > PATH_MAX: %llu",
  58		     (unsigned long long)iblock);
  59		goto bail;
  60	}
  61
  62	status = ocfs2_read_inode_block(inode, &bh);
  63	if (status < 0) {
  64		mlog_errno(status);
  65		goto bail;
  66	}
  67	fe = (struct ocfs2_dinode *) bh->b_data;
  68
  69	if ((u64)iblock >= ocfs2_clusters_to_blocks(inode->i_sb,
  70						    le32_to_cpu(fe->i_clusters))) {
  71		err = -ENOMEM;
  72		mlog(ML_ERROR, "block offset is outside the allocated size: "
  73		     "%llu\n", (unsigned long long)iblock);
  74		goto bail;
  75	}
  76
  77	/* We don't use the page cache to create symlink data, so if
  78	 * need be, copy it over from the buffer cache. */
  79	if (!buffer_uptodate(bh_result) && ocfs2_inode_is_new(inode)) {
  80		u64 blkno = le64_to_cpu(fe->id2.i_list.l_recs[0].e_blkno) +
  81			    iblock;
  82		buffer_cache_bh = sb_getblk(osb->sb, blkno);
  83		if (!buffer_cache_bh) {
  84			err = -ENOMEM;
  85			mlog(ML_ERROR, "couldn't getblock for symlink!\n");
  86			goto bail;
  87		}
  88
  89		/* we haven't locked out transactions, so a commit
  90		 * could've happened. Since we've got a reference on
  91		 * the bh, even if it commits while we're doing the
  92		 * copy, the data is still good. */
  93		if (buffer_jbd(buffer_cache_bh) && ocfs2_inode_is_new(inode)) {
  94			memcpy_to_folio(bh_result->b_folio,
  95					bh_result->b_size * iblock,
  96					buffer_cache_bh->b_data,
  97					bh_result->b_size);
  98			set_buffer_uptodate(bh_result);
  99		}
 100		brelse(buffer_cache_bh);
 101	}
 102
 103	map_bh(bh_result, inode->i_sb,
 104	       le64_to_cpu(fe->id2.i_list.l_recs[0].e_blkno) + iblock);
 105
 106	err = 0;
 107
 108bail:
 109	brelse(bh);
 110
 111	return err;
 112}
 113
 114static int ocfs2_lock_get_block(struct inode *inode, sector_t iblock,
 115		    struct buffer_head *bh_result, int create)
 116{
 117	int ret = 0;
 118	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 119
 120	down_read(&oi->ip_alloc_sem);
 121	ret = ocfs2_get_block(inode, iblock, bh_result, create);
 122	up_read(&oi->ip_alloc_sem);
 123
 124	return ret;
 125}
 126
 127int ocfs2_get_block(struct inode *inode, sector_t iblock,
 128		    struct buffer_head *bh_result, int create)
 129{
 130	int err = 0;
 131	unsigned int ext_flags;
 132	u64 max_blocks = bh_result->b_size >> inode->i_blkbits;
 133	u64 p_blkno, count, past_eof;
 134	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
 135
 136	trace_ocfs2_get_block((unsigned long long)OCFS2_I(inode)->ip_blkno,
 137			      (unsigned long long)iblock, bh_result, create);
 138
 139	if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SYSTEM_FILE)
 140		mlog(ML_NOTICE, "get_block on system inode 0x%p (%lu)\n",
 141		     inode, inode->i_ino);
 142
 143	if (S_ISLNK(inode->i_mode)) {
 144		/* this always does I/O for some reason. */
 145		err = ocfs2_symlink_get_block(inode, iblock, bh_result, create);
 146		goto bail;
 147	}
 148
 149	err = ocfs2_extent_map_get_blocks(inode, iblock, &p_blkno, &count,
 150					  &ext_flags);
 151	if (err) {
 152		mlog(ML_ERROR, "get_blocks() failed, inode: 0x%p, "
 153		     "block: %llu\n", inode, (unsigned long long)iblock);
 154		goto bail;
 155	}
 156
 157	if (max_blocks < count)
 158		count = max_blocks;
 159
 160	/*
 161	 * ocfs2 never allocates in this function - the only time we
 162	 * need to use BH_New is when we're extending i_size on a file
 163	 * system which doesn't support holes, in which case BH_New
 164	 * allows __block_write_begin() to zero.
 165	 *
 166	 * If we see this on a sparse file system, then a truncate has
 167	 * raced us and removed the cluster. In this case, we clear
 168	 * the buffers dirty and uptodate bits and let the buffer code
 169	 * ignore it as a hole.
 170	 */
 171	if (create && p_blkno == 0 && ocfs2_sparse_alloc(osb)) {
 172		clear_buffer_dirty(bh_result);
 173		clear_buffer_uptodate(bh_result);
 174		goto bail;
 175	}
 176
 177	/* Treat the unwritten extent as a hole for zeroing purposes. */
 178	if (p_blkno && !(ext_flags & OCFS2_EXT_UNWRITTEN))
 179		map_bh(bh_result, inode->i_sb, p_blkno);
 180
 181	bh_result->b_size = count << inode->i_blkbits;
 182
 183	if (!ocfs2_sparse_alloc(osb)) {
 184		if (p_blkno == 0) {
 185			err = -EIO;
 186			mlog(ML_ERROR,
 187			     "iblock = %llu p_blkno = %llu blkno=(%llu)\n",
 188			     (unsigned long long)iblock,
 189			     (unsigned long long)p_blkno,
 190			     (unsigned long long)OCFS2_I(inode)->ip_blkno);
 191			mlog(ML_ERROR, "Size %llu, clusters %u\n", (unsigned long long)i_size_read(inode), OCFS2_I(inode)->ip_clusters);
 192			dump_stack();
 193			goto bail;
 194		}
 195	}
 196
 197	past_eof = ocfs2_blocks_for_bytes(inode->i_sb, i_size_read(inode));
 198
 199	trace_ocfs2_get_block_end((unsigned long long)OCFS2_I(inode)->ip_blkno,
 200				  (unsigned long long)past_eof);
 201	if (create && (iblock >= past_eof))
 202		set_buffer_new(bh_result);
 203
 204bail:
 205	if (err < 0)
 206		err = -EIO;
 207
 208	return err;
 209}
 210
 211int ocfs2_read_inline_data(struct inode *inode, struct folio *folio,
 212			   struct buffer_head *di_bh)
 213{
 214	loff_t size;
 215	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
 216
 217	if (!(le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_DATA_FL)) {
 218		ocfs2_error(inode->i_sb, "Inode %llu lost inline data flag\n",
 219			    (unsigned long long)OCFS2_I(inode)->ip_blkno);
 220		return -EROFS;
 221	}
 222
 223	size = i_size_read(inode);
 224
 225	if (size > folio_size(folio) ||
 226	    size > ocfs2_max_inline_data_with_xattr(inode->i_sb, di)) {
 227		ocfs2_error(inode->i_sb,
 228			    "Inode %llu has with inline data has bad size: %Lu\n",
 229			    (unsigned long long)OCFS2_I(inode)->ip_blkno,
 230			    (unsigned long long)size);
 231		return -EROFS;
 232	}
 233
 234	folio_fill_tail(folio, 0, di->id2.i_data.id_data, size);
 235	folio_mark_uptodate(folio);
 236
 237	return 0;
 238}
 239
 240static int ocfs2_readpage_inline(struct inode *inode, struct folio *folio)
 241{
 242	int ret;
 243	struct buffer_head *di_bh = NULL;
 244
 245	BUG_ON(!folio_test_locked(folio));
 246	BUG_ON(!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL));
 247
 248	ret = ocfs2_read_inode_block(inode, &di_bh);
 249	if (ret) {
 250		mlog_errno(ret);
 251		goto out;
 252	}
 253
 254	ret = ocfs2_read_inline_data(inode, folio, di_bh);
 255out:
 256	folio_unlock(folio);
 257
 258	brelse(di_bh);
 259	return ret;
 260}
 261
 262static int ocfs2_read_folio(struct file *file, struct folio *folio)
 263{
 264	struct inode *inode = folio->mapping->host;
 265	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 266	loff_t start = folio_pos(folio);
 267	int ret, unlock = 1;
 268
 269	trace_ocfs2_readpage((unsigned long long)oi->ip_blkno, folio->index);
 270
 271	ret = ocfs2_inode_lock_with_folio(inode, NULL, 0, folio);
 272	if (ret != 0) {
 273		if (ret == AOP_TRUNCATED_PAGE)
 274			unlock = 0;
 275		mlog_errno(ret);
 276		goto out;
 277	}
 278
 279	if (down_read_trylock(&oi->ip_alloc_sem) == 0) {
 280		/*
 281		 * Unlock the folio and cycle ip_alloc_sem so that we don't
 282		 * busyloop waiting for ip_alloc_sem to unlock
 283		 */
 284		ret = AOP_TRUNCATED_PAGE;
 285		folio_unlock(folio);
 286		unlock = 0;
 287		down_read(&oi->ip_alloc_sem);
 288		up_read(&oi->ip_alloc_sem);
 289		goto out_inode_unlock;
 290	}
 291
 292	/*
 293	 * i_size might have just been updated as we grabbed the meta lock.  We
 294	 * might now be discovering a truncate that hit on another node.
 295	 * block_read_full_folio->get_block freaks out if it is asked to read
 296	 * beyond the end of a file, so we check here.  Callers
 297	 * (generic_file_read, vm_ops->fault) are clever enough to check i_size
 298	 * and notice that the folio they just read isn't needed.
 299	 *
 300	 * XXX sys_readahead() seems to get that wrong?
 301	 */
 302	if (start >= i_size_read(inode)) {
 303		folio_zero_segment(folio, 0, folio_size(folio));
 304		folio_mark_uptodate(folio);
 305		ret = 0;
 306		goto out_alloc;
 307	}
 308
 309	if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL)
 310		ret = ocfs2_readpage_inline(inode, folio);
 311	else
 312		ret = block_read_full_folio(folio, ocfs2_get_block);
 313	unlock = 0;
 314
 315out_alloc:
 316	up_read(&oi->ip_alloc_sem);
 317out_inode_unlock:
 318	ocfs2_inode_unlock(inode, 0);
 319out:
 320	if (unlock)
 321		folio_unlock(folio);
 322	return ret;
 323}
 324
 325/*
 326 * This is used only for read-ahead. Failures or difficult to handle
 327 * situations are safe to ignore.
 328 *
 329 * Right now, we don't bother with BH_Boundary - in-inode extent lists
 330 * are quite large (243 extents on 4k blocks), so most inodes don't
 331 * grow out to a tree. If need be, detecting boundary extents could
 332 * trivially be added in a future version of ocfs2_get_block().
 333 */
 334static void ocfs2_readahead(struct readahead_control *rac)
 335{
 336	int ret;
 337	struct inode *inode = rac->mapping->host;
 338	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 339
 340	/*
 341	 * Use the nonblocking flag for the dlm code to avoid page
 342	 * lock inversion, but don't bother with retrying.
 343	 */
 344	ret = ocfs2_inode_lock_full(inode, NULL, 0, OCFS2_LOCK_NONBLOCK);
 345	if (ret)
 346		return;
 347
 348	if (down_read_trylock(&oi->ip_alloc_sem) == 0)
 349		goto out_unlock;
 350
 351	/*
 352	 * Don't bother with inline-data. There isn't anything
 353	 * to read-ahead in that case anyway...
 354	 */
 355	if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL)
 356		goto out_up;
 357
 358	/*
 359	 * Check whether a remote node truncated this file - we just
 360	 * drop out in that case as it's not worth handling here.
 361	 */
 362	if (readahead_pos(rac) >= i_size_read(inode))
 363		goto out_up;
 364
 365	mpage_readahead(rac, ocfs2_get_block);
 366
 367out_up:
 368	up_read(&oi->ip_alloc_sem);
 369out_unlock:
 370	ocfs2_inode_unlock(inode, 0);
 371}
 372
 373/* Note: Because we don't support holes, our allocation has
 374 * already happened (allocation writes zeros to the file data)
 375 * so we don't have to worry about ordered writes in
 376 * ocfs2_writepages.
 377 *
 378 * ->writepages is called during the process of invalidating the page cache
 379 * during blocked lock processing.  It can't block on any cluster locks
 380 * to during block mapping.  It's relying on the fact that the block
 381 * mapping can't have disappeared under the dirty pages that it is
 382 * being asked to write back.
 383 */
 384static int ocfs2_writepages(struct address_space *mapping,
 385		struct writeback_control *wbc)
 386{
 387	return mpage_writepages(mapping, wbc, ocfs2_get_block);
 388}
 389
 390/* Taken from ext3. We don't necessarily need the full blown
 391 * functionality yet, but IMHO it's better to cut and paste the whole
 392 * thing so we can avoid introducing our own bugs (and easily pick up
 393 * their fixes when they happen) --Mark */
 394int walk_page_buffers(	handle_t *handle,
 395			struct buffer_head *head,
 396			unsigned from,
 397			unsigned to,
 398			int *partial,
 399			int (*fn)(	handle_t *handle,
 400					struct buffer_head *bh))
 401{
 402	struct buffer_head *bh;
 403	unsigned block_start, block_end;
 404	unsigned blocksize = head->b_size;
 405	int err, ret = 0;
 406	struct buffer_head *next;
 407
 408	for (	bh = head, block_start = 0;
 409		ret == 0 && (bh != head || !block_start);
 410	    	block_start = block_end, bh = next)
 411	{
 412		next = bh->b_this_page;
 413		block_end = block_start + blocksize;
 414		if (block_end <= from || block_start >= to) {
 415			if (partial && !buffer_uptodate(bh))
 416				*partial = 1;
 417			continue;
 418		}
 419		err = (*fn)(handle, bh);
 420		if (!ret)
 421			ret = err;
 422	}
 423	return ret;
 424}
 425
 426static sector_t ocfs2_bmap(struct address_space *mapping, sector_t block)
 427{
 428	sector_t status;
 429	u64 p_blkno = 0;
 430	int err = 0;
 431	struct inode *inode = mapping->host;
 432
 433	trace_ocfs2_bmap((unsigned long long)OCFS2_I(inode)->ip_blkno,
 434			 (unsigned long long)block);
 435
 436	/*
 437	 * The swap code (ab-)uses ->bmap to get a block mapping and then
 438	 * bypasseѕ the file system for actual I/O.  We really can't allow
 439	 * that on refcounted inodes, so we have to skip out here.  And yes,
 440	 * 0 is the magic code for a bmap error..
 441	 */
 442	if (ocfs2_is_refcount_inode(inode))
 443		return 0;
 444
 445	/* We don't need to lock journal system files, since they aren't
 446	 * accessed concurrently from multiple nodes.
 447	 */
 448	if (!INODE_JOURNAL(inode)) {
 449		err = ocfs2_inode_lock(inode, NULL, 0);
 450		if (err) {
 451			if (err != -ENOENT)
 452				mlog_errno(err);
 453			goto bail;
 454		}
 455		down_read(&OCFS2_I(inode)->ip_alloc_sem);
 456	}
 457
 458	if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
 459		err = ocfs2_extent_map_get_blocks(inode, block, &p_blkno, NULL,
 460						  NULL);
 461
 462	if (!INODE_JOURNAL(inode)) {
 463		up_read(&OCFS2_I(inode)->ip_alloc_sem);
 464		ocfs2_inode_unlock(inode, 0);
 465	}
 466
 467	if (err) {
 468		mlog(ML_ERROR, "get_blocks() failed, block = %llu\n",
 469		     (unsigned long long)block);
 470		mlog_errno(err);
 471		goto bail;
 472	}
 473
 474bail:
 475	status = err ? 0 : p_blkno;
 476
 477	return status;
 478}
 479
 480static bool ocfs2_release_folio(struct folio *folio, gfp_t wait)
 481{
 482	if (!folio_buffers(folio))
 483		return false;
 484	return try_to_free_buffers(folio);
 485}
 486
 487static void ocfs2_figure_cluster_boundaries(struct ocfs2_super *osb,
 488					    u32 cpos,
 489					    unsigned int *start,
 490					    unsigned int *end)
 491{
 492	unsigned int cluster_start = 0, cluster_end = PAGE_SIZE;
 493
 494	if (unlikely(PAGE_SHIFT > osb->s_clustersize_bits)) {
 495		unsigned int cpp;
 496
 497		cpp = 1 << (PAGE_SHIFT - osb->s_clustersize_bits);
 498
 499		cluster_start = cpos % cpp;
 500		cluster_start = cluster_start << osb->s_clustersize_bits;
 501
 502		cluster_end = cluster_start + osb->s_clustersize;
 503	}
 504
 505	BUG_ON(cluster_start > PAGE_SIZE);
 506	BUG_ON(cluster_end > PAGE_SIZE);
 507
 508	if (start)
 509		*start = cluster_start;
 510	if (end)
 511		*end = cluster_end;
 512}
 513
 514/*
 515 * 'from' and 'to' are the region in the page to avoid zeroing.
 516 *
 517 * If pagesize > clustersize, this function will avoid zeroing outside
 518 * of the cluster boundary.
 519 *
 520 * from == to == 0 is code for "zero the entire cluster region"
 521 */
 522static void ocfs2_clear_folio_regions(struct folio *folio,
 523				     struct ocfs2_super *osb, u32 cpos,
 524				     unsigned from, unsigned to)
 525{
 526	void *kaddr;
 527	unsigned int cluster_start, cluster_end;
 528
 529	ocfs2_figure_cluster_boundaries(osb, cpos, &cluster_start, &cluster_end);
 530
 531	kaddr = kmap_local_folio(folio, 0);
 532
 533	if (from || to) {
 534		if (from > cluster_start)
 535			memset(kaddr + cluster_start, 0, from - cluster_start);
 536		if (to < cluster_end)
 537			memset(kaddr + to, 0, cluster_end - to);
 538	} else {
 539		memset(kaddr + cluster_start, 0, cluster_end - cluster_start);
 540	}
 541
 542	kunmap_local(kaddr);
 543}
 544
 545/*
 546 * Nonsparse file systems fully allocate before we get to the write
 547 * code. This prevents ocfs2_write() from tagging the write as an
 548 * allocating one, which means ocfs2_map_folio_blocks() might try to
 549 * read-in the blocks at the tail of our file. Avoid reading them by
 550 * testing i_size against each block offset.
 551 */
 552static int ocfs2_should_read_blk(struct inode *inode, struct folio *folio,
 553				 unsigned int block_start)
 554{
 555	u64 offset = folio_pos(folio) + block_start;
 556
 557	if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))
 558		return 1;
 559
 560	if (i_size_read(inode) > offset)
 561		return 1;
 562
 563	return 0;
 564}
 565
 566/*
 567 * Some of this taken from __block_write_begin(). We already have our
 568 * mapping by now though, and the entire write will be allocating or
 569 * it won't, so not much need to use BH_New.
 570 *
 571 * This will also skip zeroing, which is handled externally.
 572 */
 573int ocfs2_map_folio_blocks(struct folio *folio, u64 *p_blkno,
 574			  struct inode *inode, unsigned int from,
 575			  unsigned int to, int new)
 576{
 577	int ret = 0;
 578	struct buffer_head *head, *bh, *wait[2], **wait_bh = wait;
 579	unsigned int block_end, block_start;
 580	unsigned int bsize = i_blocksize(inode);
 581
 582	head = folio_buffers(folio);
 583	if (!head)
 584		head = create_empty_buffers(folio, bsize, 0);
 585
 586	for (bh = head, block_start = 0; bh != head || !block_start;
 587	     bh = bh->b_this_page, block_start += bsize) {
 588		block_end = block_start + bsize;
 589
 590		clear_buffer_new(bh);
 591
 592		/*
 593		 * Ignore blocks outside of our i/o range -
 594		 * they may belong to unallocated clusters.
 595		 */
 596		if (block_start >= to || block_end <= from) {
 597			if (folio_test_uptodate(folio))
 598				set_buffer_uptodate(bh);
 599			continue;
 600		}
 601
 602		/*
 603		 * For an allocating write with cluster size >= page
 604		 * size, we always write the entire page.
 605		 */
 606		if (new)
 607			set_buffer_new(bh);
 608
 609		if (!buffer_mapped(bh)) {
 610			map_bh(bh, inode->i_sb, *p_blkno);
 611			clean_bdev_bh_alias(bh);
 612		}
 613
 614		if (folio_test_uptodate(folio)) {
 615			set_buffer_uptodate(bh);
 616		} else if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
 617			   !buffer_new(bh) &&
 618			   ocfs2_should_read_blk(inode, folio, block_start) &&
 619			   (block_start < from || block_end > to)) {
 620			bh_read_nowait(bh, 0);
 621			*wait_bh++=bh;
 622		}
 623
 624		*p_blkno = *p_blkno + 1;
 625	}
 626
 627	/*
 628	 * If we issued read requests - let them complete.
 629	 */
 630	while(wait_bh > wait) {
 631		wait_on_buffer(*--wait_bh);
 632		if (!buffer_uptodate(*wait_bh))
 633			ret = -EIO;
 634	}
 635
 636	if (ret == 0 || !new)
 637		return ret;
 638
 639	/*
 640	 * If we get -EIO above, zero out any newly allocated blocks
 641	 * to avoid exposing stale data.
 642	 */
 643	bh = head;
 644	block_start = 0;
 645	do {
 646		block_end = block_start + bsize;
 647		if (block_end <= from)
 648			goto next_bh;
 649		if (block_start >= to)
 650			break;
 651
 652		folio_zero_range(folio, block_start, bh->b_size);
 653		set_buffer_uptodate(bh);
 654		mark_buffer_dirty(bh);
 655
 656next_bh:
 657		block_start = block_end;
 658		bh = bh->b_this_page;
 659	} while (bh != head);
 660
 661	return ret;
 662}
 663
 664#if (PAGE_SIZE >= OCFS2_MAX_CLUSTERSIZE)
 665#define OCFS2_MAX_CTXT_PAGES	1
 666#else
 667#define OCFS2_MAX_CTXT_PAGES	(OCFS2_MAX_CLUSTERSIZE / PAGE_SIZE)
 668#endif
 669
 670#define OCFS2_MAX_CLUSTERS_PER_PAGE	(PAGE_SIZE / OCFS2_MIN_CLUSTERSIZE)
 671
 672struct ocfs2_unwritten_extent {
 673	struct list_head	ue_node;
 674	struct list_head	ue_ip_node;
 675	u32			ue_cpos;
 676	u32			ue_phys;
 677};
 678
 679/*
 680 * Describe the state of a single cluster to be written to.
 681 */
 682struct ocfs2_write_cluster_desc {
 683	u32		c_cpos;
 684	u32		c_phys;
 685	/*
 686	 * Give this a unique field because c_phys eventually gets
 687	 * filled.
 688	 */
 689	unsigned	c_new;
 690	unsigned	c_clear_unwritten;
 691	unsigned	c_needs_zero;
 692};
 693
 694struct ocfs2_write_ctxt {
 695	/* Logical cluster position / len of write */
 696	u32				w_cpos;
 697	u32				w_clen;
 698
 699	/* First cluster allocated in a nonsparse extend */
 700	u32				w_first_new_cpos;
 701
 702	/* Type of caller. Must be one of buffer, mmap, direct.  */
 703	ocfs2_write_type_t		w_type;
 704
 705	struct ocfs2_write_cluster_desc	w_desc[OCFS2_MAX_CLUSTERS_PER_PAGE];
 706
 707	/*
 708	 * This is true if page_size > cluster_size.
 709	 *
 710	 * It triggers a set of special cases during write which might
 711	 * have to deal with allocating writes to partial pages.
 712	 */
 713	unsigned int			w_large_pages;
 714
 715	/*
 716	 * Folios involved in this write.
 717	 *
 718	 * w_target_folio is the folio being written to by the user.
 719	 *
 720	 * w_folios is an array of folios which always contains
 721	 * w_target_folio, and in the case of an allocating write with
 722	 * page_size < cluster size, it will contain zero'd and mapped
 723	 * pages adjacent to w_target_folio which need to be written
 724	 * out in so that future reads from that region will get
 725	 * zero's.
 726	 */
 727	unsigned int			w_num_folios;
 728	struct folio			*w_folios[OCFS2_MAX_CTXT_PAGES];
 729	struct folio			*w_target_folio;
 730
 731	/*
 732	 * w_target_locked is used for page_mkwrite path indicating no unlocking
 733	 * against w_target_folio in ocfs2_write_end_nolock.
 734	 */
 735	unsigned int			w_target_locked:1;
 736
 737	/*
 738	 * ocfs2_write_end() uses this to know what the real range to
 739	 * write in the target should be.
 740	 */
 741	unsigned int			w_target_from;
 742	unsigned int			w_target_to;
 743
 744	/*
 745	 * We could use journal_current_handle() but this is cleaner,
 746	 * IMHO -Mark
 747	 */
 748	handle_t			*w_handle;
 749
 750	struct buffer_head		*w_di_bh;
 751
 752	struct ocfs2_cached_dealloc_ctxt w_dealloc;
 753
 754	struct list_head		w_unwritten_list;
 755	unsigned int			w_unwritten_count;
 756};
 757
 758void ocfs2_unlock_and_free_folios(struct folio **folios, int num_folios)
 759{
 760	int i;
 761
 762	for(i = 0; i < num_folios; i++) {
 763		if (!folios[i])
 764			continue;
 765		folio_unlock(folios[i]);
 766		folio_mark_accessed(folios[i]);
 767		folio_put(folios[i]);
 768	}
 769}
 770
 771static void ocfs2_unlock_folios(struct ocfs2_write_ctxt *wc)
 772{
 773	int i;
 774
 775	/*
 776	 * w_target_locked is only set to true in the page_mkwrite() case.
 777	 * The intent is to allow us to lock the target page from write_begin()
 778	 * to write_end(). The caller must hold a ref on w_target_folio.
 779	 */
 780	if (wc->w_target_locked) {
 781		BUG_ON(!wc->w_target_folio);
 782		for (i = 0; i < wc->w_num_folios; i++) {
 783			if (wc->w_target_folio == wc->w_folios[i]) {
 784				wc->w_folios[i] = NULL;
 785				break;
 786			}
 787		}
 788		folio_mark_accessed(wc->w_target_folio);
 789		folio_put(wc->w_target_folio);
 790	}
 791	ocfs2_unlock_and_free_folios(wc->w_folios, wc->w_num_folios);
 792}
 793
 794static void ocfs2_free_unwritten_list(struct inode *inode,
 795				 struct list_head *head)
 796{
 797	struct ocfs2_inode_info *oi = OCFS2_I(inode);
 798	struct ocfs2_unwritten_extent *ue = NULL, *tmp = NULL;
 799
 800	list_for_each_entry_safe(ue, tmp, head, ue_node) {
 801		list_del(&ue->ue_node);
 802		spin_lock(&oi->ip_lock);
 803		list_del(&ue->ue_ip_node);
 804		spin_unlock(&oi->ip_lock);
 805		kfree(ue);
 806	}
 807}
 808
 809static void ocfs2_free_write_ctxt(struct inode *inode,
 810				  struct ocfs2_write_ctxt *wc)
 811{
 812	ocfs2_free_unwritten_list(inode, &wc->w_unwritten_list);
 813	ocfs2_unlock_folios(wc);
 814	brelse(wc->w_di_bh);
 815	kfree(wc);
 816}
 817
 818static int ocfs2_alloc_write_ctxt(struct ocfs2_write_ctxt **wcp,
 819				  struct ocfs2_super *osb, loff_t pos,
 820				  unsigned len, ocfs2_write_type_t type,
 821				  struct buffer_head *di_bh)
 822{
 823	u32 cend;
 824	struct ocfs2_write_ctxt *wc;
 825
 826	wc = kzalloc(sizeof(struct ocfs2_write_ctxt), GFP_NOFS);
 827	if (!wc)
 828		return -ENOMEM;
 829
 830	wc->w_cpos = pos >> osb->s_clustersize_bits;
 831	wc->w_first_new_cpos = UINT_MAX;
 832	cend = (pos + len - 1) >> osb->s_clustersize_bits;
 833	wc->w_clen = cend - wc->w_cpos + 1;
 834	get_bh(di_bh);
 835	wc->w_di_bh = di_bh;
 836	wc->w_type = type;
 837
 838	if (unlikely(PAGE_SHIFT > osb->s_clustersize_bits))
 839		wc->w_large_pages = 1;
 840	else
 841		wc->w_large_pages = 0;
 842
 843	ocfs2_init_dealloc_ctxt(&wc->w_dealloc);
 844	INIT_LIST_HEAD(&wc->w_unwritten_list);
 845
 846	*wcp = wc;
 847
 848	return 0;
 849}
 850
 851/*
 852 * If a page has any new buffers, zero them out here, and mark them uptodate
 853 * and dirty so they'll be written out (in order to prevent uninitialised
 854 * block data from leaking). And clear the new bit.
 855 */
 856static void ocfs2_zero_new_buffers(struct folio *folio, size_t from, size_t to)
 857{
 858	unsigned int block_start, block_end;
 859	struct buffer_head *head, *bh;
 860
 861	BUG_ON(!folio_test_locked(folio));
 862	head = folio_buffers(folio);
 863	if (!head)
 864		return;
 865
 866	bh = head;
 867	block_start = 0;
 868	do {
 869		block_end = block_start + bh->b_size;
 870
 871		if (buffer_new(bh)) {
 872			if (block_end > from && block_start < to) {
 873				if (!folio_test_uptodate(folio)) {
 874					unsigned start, end;
 875
 876					start = max(from, block_start);
 877					end = min(to, block_end);
 878
 879					folio_zero_segment(folio, start, end);
 880					set_buffer_uptodate(bh);
 881				}
 882
 883				clear_buffer_new(bh);
 884				mark_buffer_dirty(bh);
 885			}
 886		}
 887
 888		block_start = block_end;
 889		bh = bh->b_this_page;
 890	} while (bh != head);
 891}
 892
 893/*
 894 * Only called when we have a failure during allocating write to write
 895 * zero's to the newly allocated region.
 896 */
 897static void ocfs2_write_failure(struct inode *inode,
 898				struct ocfs2_write_ctxt *wc,
 899				loff_t user_pos, unsigned user_len)
 900{
 901	int i;
 902	unsigned from = user_pos & (PAGE_SIZE - 1),
 903		to = user_pos + user_len;
 904
 905	if (wc->w_target_folio)
 906		ocfs2_zero_new_buffers(wc->w_target_folio, from, to);
 907
 908	for (i = 0; i < wc->w_num_folios; i++) {
 909		struct folio *folio = wc->w_folios[i];
 910
 911		if (folio && folio_buffers(folio)) {
 912			if (ocfs2_should_order_data(inode))
 913				ocfs2_jbd2_inode_add_write(wc->w_handle, inode,
 914							   user_pos, user_len);
 915
 916			block_commit_write(folio, from, to);
 917		}
 918	}
 919}
 920
 921static int ocfs2_prepare_folio_for_write(struct inode *inode, u64 *p_blkno,
 922		struct ocfs2_write_ctxt *wc, struct folio *folio, u32 cpos,
 923		loff_t user_pos, unsigned user_len, int new)
 924{
 925	int ret;
 926	unsigned int map_from = 0, map_to = 0;
 927	unsigned int cluster_start, cluster_end;
 928	unsigned int user_data_from = 0, user_data_to = 0;
 929
 930	ocfs2_figure_cluster_boundaries(OCFS2_SB(inode->i_sb), cpos,
 931					&cluster_start, &cluster_end);
 932
 933	/* treat the write as new if the a hole/lseek spanned across
 934	 * the page boundary.
 935	 */
 936	new = new | ((i_size_read(inode) <= folio_pos(folio)) &&
 937			(folio_pos(folio) <= user_pos));
 938
 939	if (folio == wc->w_target_folio) {
 940		map_from = user_pos & (PAGE_SIZE - 1);
 941		map_to = map_from + user_len;
 942
 943		if (new)
 944			ret = ocfs2_map_folio_blocks(folio, p_blkno, inode,
 945					cluster_start, cluster_end, new);
 946		else
 947			ret = ocfs2_map_folio_blocks(folio, p_blkno, inode,
 948					map_from, map_to, new);
 949		if (ret) {
 950			mlog_errno(ret);
 951			goto out;
 952		}
 953
 954		user_data_from = map_from;
 955		user_data_to = map_to;
 956		if (new) {
 957			map_from = cluster_start;
 958			map_to = cluster_end;
 959		}
 960	} else {
 961		/*
 962		 * If we haven't allocated the new folio yet, we
 963		 * shouldn't be writing it out without copying user
 964		 * data. This is likely a math error from the caller.
 965		 */
 966		BUG_ON(!new);
 967
 968		map_from = cluster_start;
 969		map_to = cluster_end;
 970
 971		ret = ocfs2_map_folio_blocks(folio, p_blkno, inode,
 972				cluster_start, cluster_end, new);
 973		if (ret) {
 974			mlog_errno(ret);
 975			goto out;
 976		}
 977	}
 978
 979	/*
 980	 * Parts of newly allocated folios need to be zero'd.
 981	 *
 982	 * Above, we have also rewritten 'to' and 'from' - as far as
 983	 * the rest of the function is concerned, the entire cluster
 984	 * range inside of a folio needs to be written.
 985	 *
 986	 * We can skip this if the folio is uptodate - it's already
 987	 * been zero'd from being read in as a hole.
 988	 */
 989	if (new && !folio_test_uptodate(folio))
 990		ocfs2_clear_folio_regions(folio, OCFS2_SB(inode->i_sb),
 991					 cpos, user_data_from, user_data_to);
 992
 993	flush_dcache_folio(folio);
 994
 995out:
 996	return ret;
 997}
 998
 999/*
1000 * This function will only grab one clusters worth of pages.
1001 */
1002static int ocfs2_grab_folios_for_write(struct address_space *mapping,
1003		struct ocfs2_write_ctxt *wc, u32 cpos, loff_t user_pos,
1004		unsigned user_len, int new, struct folio *mmap_folio)
1005{
1006	int ret = 0, i;
1007	unsigned long start, target_index, end_index, index;
1008	struct inode *inode = mapping->host;
1009	loff_t last_byte;
1010
1011	target_index = user_pos >> PAGE_SHIFT;
1012
1013	/*
1014	 * Figure out how many pages we'll be manipulating here. For
1015	 * non allocating write, we just change the one
1016	 * page. Otherwise, we'll need a whole clusters worth.  If we're
1017	 * writing past i_size, we only need enough pages to cover the
1018	 * last page of the write.
1019	 */
1020	if (new) {
1021		wc->w_num_folios = ocfs2_pages_per_cluster(inode->i_sb);
1022		start = ocfs2_align_clusters_to_page_index(inode->i_sb, cpos);
1023		/*
1024		 * We need the index *past* the last page we could possibly
1025		 * touch.  This is the page past the end of the write or
1026		 * i_size, whichever is greater.
1027		 */
1028		last_byte = max(user_pos + user_len, i_size_read(inode));
1029		BUG_ON(last_byte < 1);
1030		end_index = ((last_byte - 1) >> PAGE_SHIFT) + 1;
1031		if ((start + wc->w_num_folios) > end_index)
1032			wc->w_num_folios = end_index - start;
1033	} else {
1034		wc->w_num_folios = 1;
1035		start = target_index;
1036	}
1037	end_index = (user_pos + user_len - 1) >> PAGE_SHIFT;
1038
1039	for(i = 0; i < wc->w_num_folios; i++) {
1040		index = start + i;
1041
1042		if (index >= target_index && index <= end_index &&
1043		    wc->w_type == OCFS2_WRITE_MMAP) {
1044			/*
1045			 * ocfs2_pagemkwrite() is a little different
1046			 * and wants us to directly use the page
1047			 * passed in.
1048			 */
1049			folio_lock(mmap_folio);
1050
1051			/* Exit and let the caller retry */
1052			if (mmap_folio->mapping != mapping) {
1053				WARN_ON(mmap_folio->mapping);
1054				folio_unlock(mmap_folio);
1055				ret = -EAGAIN;
1056				goto out;
1057			}
1058
1059			folio_get(mmap_folio);
1060			wc->w_folios[i] = mmap_folio;
1061			wc->w_target_locked = true;
1062		} else if (index >= target_index && index <= end_index &&
1063			   wc->w_type == OCFS2_WRITE_DIRECT) {
1064			/* Direct write has no mapping page. */
1065			wc->w_folios[i] = NULL;
1066			continue;
1067		} else {
1068			wc->w_folios[i] = __filemap_get_folio(mapping, index,
1069					FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
1070					GFP_NOFS);
1071			if (IS_ERR(wc->w_folios[i])) {
1072				ret = PTR_ERR(wc->w_folios[i]);
1073				mlog_errno(ret);
1074				wc->w_folios[i] = NULL;
1075				goto out;
1076			}
1077		}
1078		folio_wait_stable(wc->w_folios[i]);
1079
1080		if (index == target_index)
1081			wc->w_target_folio = wc->w_folios[i];
1082	}
1083out:
1084	if (ret)
1085		wc->w_target_locked = false;
1086	return ret;
1087}
1088
1089/*
1090 * Prepare a single cluster for write one cluster into the file.
1091 */
1092static int ocfs2_write_cluster(struct address_space *mapping,
1093			       u32 *phys, unsigned int new,
1094			       unsigned int clear_unwritten,
1095			       unsigned int should_zero,
1096			       struct ocfs2_alloc_context *data_ac,
1097			       struct ocfs2_alloc_context *meta_ac,
1098			       struct ocfs2_write_ctxt *wc, u32 cpos,
1099			       loff_t user_pos, unsigned user_len)
1100{
1101	int ret, i;
1102	u64 p_blkno;
1103	struct inode *inode = mapping->host;
1104	struct ocfs2_extent_tree et;
1105	int bpc = ocfs2_clusters_to_blocks(inode->i_sb, 1);
1106
1107	if (new) {
1108		u32 tmp_pos;
1109
1110		/*
1111		 * This is safe to call with the page locks - it won't take
1112		 * any additional semaphores or cluster locks.
1113		 */
1114		tmp_pos = cpos;
1115		ret = ocfs2_add_inode_data(OCFS2_SB(inode->i_sb), inode,
1116					   &tmp_pos, 1, !clear_unwritten,
1117					   wc->w_di_bh, wc->w_handle,
1118					   data_ac, meta_ac, NULL);
1119		/*
1120		 * This shouldn't happen because we must have already
1121		 * calculated the correct meta data allocation required. The
1122		 * internal tree allocation code should know how to increase
1123		 * transaction credits itself.
1124		 *
1125		 * If need be, we could handle -EAGAIN for a
1126		 * RESTART_TRANS here.
1127		 */
1128		mlog_bug_on_msg(ret == -EAGAIN,
1129				"Inode %llu: EAGAIN return during allocation.\n",
1130				(unsigned long long)OCFS2_I(inode)->ip_blkno);
1131		if (ret < 0) {
1132			mlog_errno(ret);
1133			goto out;
1134		}
1135	} else if (clear_unwritten) {
1136		ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode),
1137					      wc->w_di_bh);
1138		ret = ocfs2_mark_extent_written(inode, &et,
1139						wc->w_handle, cpos, 1, *phys,
1140						meta_ac, &wc->w_dealloc);
1141		if (ret < 0) {
1142			mlog_errno(ret);
1143			goto out;
1144		}
1145	}
1146
1147	/*
1148	 * The only reason this should fail is due to an inability to
1149	 * find the extent added.
1150	 */
1151	ret = ocfs2_get_clusters(inode, cpos, phys, NULL, NULL);
1152	if (ret < 0) {
1153		mlog(ML_ERROR, "Get physical blkno failed for inode %llu, "
1154			    "at logical cluster %u",
1155			    (unsigned long long)OCFS2_I(inode)->ip_blkno, cpos);
1156		goto out;
1157	}
1158
1159	BUG_ON(*phys == 0);
1160
1161	p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *phys);
1162	if (!should_zero)
1163		p_blkno += (user_pos >> inode->i_sb->s_blocksize_bits) & (u64)(bpc - 1);
1164
1165	for (i = 0; i < wc->w_num_folios; i++) {
1166		int tmpret;
1167
1168		/* This is the direct io target page. */
1169		if (wc->w_folios[i] == NULL) {
1170			p_blkno += (1 << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits));
1171			continue;
1172		}
1173
1174		tmpret = ocfs2_prepare_folio_for_write(inode, &p_blkno, wc,
1175				wc->w_folios[i], cpos, user_pos, user_len,
1176				should_zero);
1177		if (tmpret) {
1178			mlog_errno(tmpret);
1179			if (ret == 0)
1180				ret = tmpret;
1181		}
1182	}
1183
1184	/*
1185	 * We only have cleanup to do in case of allocating write.
1186	 */
1187	if (ret && new)
1188		ocfs2_write_failure(inode, wc, user_pos, user_len);
1189
1190out:
1191
1192	return ret;
1193}
1194
1195static int ocfs2_write_cluster_by_desc(struct address_space *mapping,
1196				       struct ocfs2_alloc_context *data_ac,
1197				       struct ocfs2_alloc_context *meta_ac,
1198				       struct ocfs2_write_ctxt *wc,
1199				       loff_t pos, unsigned len)
1200{
1201	int ret, i;
1202	loff_t cluster_off;
1203	unsigned int local_len = len;
1204	struct ocfs2_write_cluster_desc *desc;
1205	struct ocfs2_super *osb = OCFS2_SB(mapping->host->i_sb);
1206
1207	for (i = 0; i < wc->w_clen; i++) {
1208		desc = &wc->w_desc[i];
1209
1210		/*
1211		 * We have to make sure that the total write passed in
1212		 * doesn't extend past a single cluster.
1213		 */
1214		local_len = len;
1215		cluster_off = pos & (osb->s_clustersize - 1);
1216		if ((cluster_off + local_len) > osb->s_clustersize)
1217			local_len = osb->s_clustersize - cluster_off;
1218
1219		ret = ocfs2_write_cluster(mapping, &desc->c_phys,
1220					  desc->c_new,
1221					  desc->c_clear_unwritten,
1222					  desc->c_needs_zero,
1223					  data_ac, meta_ac,
1224					  wc, desc->c_cpos, pos, local_len);
1225		if (ret) {
1226			mlog_errno(ret);
1227			goto out;
1228		}
1229
1230		len -= local_len;
1231		pos += local_len;
1232	}
1233
1234	ret = 0;
1235out:
1236	return ret;
1237}
1238
1239/*
1240 * ocfs2_write_end() wants to know which parts of the target page it
1241 * should complete the write on. It's easiest to compute them ahead of
1242 * time when a more complete view of the write is available.
1243 */
1244static void ocfs2_set_target_boundaries(struct ocfs2_super *osb,
1245					struct ocfs2_write_ctxt *wc,
1246					loff_t pos, unsigned len, int alloc)
1247{
1248	struct ocfs2_write_cluster_desc *desc;
1249
1250	wc->w_target_from = pos & (PAGE_SIZE - 1);
1251	wc->w_target_to = wc->w_target_from + len;
1252
1253	if (alloc == 0)
1254		return;
1255
1256	/*
1257	 * Allocating write - we may have different boundaries based
1258	 * on page size and cluster size.
1259	 *
1260	 * NOTE: We can no longer compute one value from the other as
1261	 * the actual write length and user provided length may be
1262	 * different.
1263	 */
1264
1265	if (wc->w_large_pages) {
1266		/*
1267		 * We only care about the 1st and last cluster within
1268		 * our range and whether they should be zero'd or not. Either
1269		 * value may be extended out to the start/end of a
1270		 * newly allocated cluster.
1271		 */
1272		desc = &wc->w_desc[0];
1273		if (desc->c_needs_zero)
1274			ocfs2_figure_cluster_boundaries(osb,
1275							desc->c_cpos,
1276							&wc->w_target_from,
1277							NULL);
1278
1279		desc = &wc->w_desc[wc->w_clen - 1];
1280		if (desc->c_needs_zero)
1281			ocfs2_figure_cluster_boundaries(osb,
1282							desc->c_cpos,
1283							NULL,
1284							&wc->w_target_to);
1285	} else {
1286		wc->w_target_from = 0;
1287		wc->w_target_to = PAGE_SIZE;
1288	}
1289}
1290
1291/*
1292 * Check if this extent is marked UNWRITTEN by direct io. If so, we need not to
1293 * do the zero work. And should not to clear UNWRITTEN since it will be cleared
1294 * by the direct io procedure.
1295 * If this is a new extent that allocated by direct io, we should mark it in
1296 * the ip_unwritten_list.
1297 */
1298static int ocfs2_unwritten_check(struct inode *inode,
1299				 struct ocfs2_write_ctxt *wc,
1300				 struct ocfs2_write_cluster_desc *desc)
1301{
1302	struct ocfs2_inode_info *oi = OCFS2_I(inode);
1303	struct ocfs2_unwritten_extent *ue = NULL, *new = NULL;
1304	int ret = 0;
1305
1306	if (!desc->c_needs_zero)
1307		return 0;
1308
1309retry:
1310	spin_lock(&oi->ip_lock);
1311	/* Needs not to zero no metter buffer or direct. The one who is zero
1312	 * the cluster is doing zero. And he will clear unwritten after all
1313	 * cluster io finished. */
1314	list_for_each_entry(ue, &oi->ip_unwritten_list, ue_ip_node) {
1315		if (desc->c_cpos == ue->ue_cpos) {
1316			BUG_ON(desc->c_new);
1317			desc->c_needs_zero = 0;
1318			desc->c_clear_unwritten = 0;
1319			goto unlock;
1320		}
1321	}
1322
1323	if (wc->w_type != OCFS2_WRITE_DIRECT)
1324		goto unlock;
1325
1326	if (new == NULL) {
1327		spin_unlock(&oi->ip_lock);
1328		new = kmalloc(sizeof(struct ocfs2_unwritten_extent),
1329			     GFP_NOFS);
1330		if (new == NULL) {
1331			ret = -ENOMEM;
1332			goto out;
1333		}
1334		goto retry;
1335	}
1336	/* This direct write will doing zero. */
1337	new->ue_cpos = desc->c_cpos;
1338	new->ue_phys = desc->c_phys;
1339	desc->c_clear_unwritten = 0;
1340	list_add_tail(&new->ue_ip_node, &oi->ip_unwritten_list);
1341	list_add_tail(&new->ue_node, &wc->w_unwritten_list);
1342	wc->w_unwritten_count++;
1343	new = NULL;
1344unlock:
1345	spin_unlock(&oi->ip_lock);
1346out:
1347	kfree(new);
1348	return ret;
1349}
1350
1351/*
1352 * Populate each single-cluster write descriptor in the write context
1353 * with information about the i/o to be done.
1354 *
1355 * Returns the number of clusters that will have to be allocated, as
1356 * well as a worst case estimate of the number of extent records that
1357 * would have to be created during a write to an unwritten region.
1358 */
1359static int ocfs2_populate_write_desc(struct inode *inode,
1360				     struct ocfs2_write_ctxt *wc,
1361				     unsigned int *clusters_to_alloc,
1362				     unsigned int *extents_to_split)
1363{
1364	int ret;
1365	struct ocfs2_write_cluster_desc *desc;
1366	unsigned int num_clusters = 0;
1367	unsigned int ext_flags = 0;
1368	u32 phys = 0;
1369	int i;
1370
1371	*clusters_to_alloc = 0;
1372	*extents_to_split = 0;
1373
1374	for (i = 0; i < wc->w_clen; i++) {
1375		desc = &wc->w_desc[i];
1376		desc->c_cpos = wc->w_cpos + i;
1377
1378		if (num_clusters == 0) {
1379			/*
1380			 * Need to look up the next extent record.
1381			 */
1382			ret = ocfs2_get_clusters(inode, desc->c_cpos, &phys,
1383						 &num_clusters, &ext_flags);
1384			if (ret) {
1385				mlog_errno(ret);
1386				goto out;
1387			}
1388
1389			/* We should already CoW the refcountd extent. */
1390			BUG_ON(ext_flags & OCFS2_EXT_REFCOUNTED);
1391
1392			/*
1393			 * Assume worst case - that we're writing in
1394			 * the middle of the extent.
1395			 *
1396			 * We can assume that the write proceeds from
1397			 * left to right, in which case the extent
1398			 * insert code is smart enough to coalesce the
1399			 * next splits into the previous records created.
1400			 */
1401			if (ext_flags & OCFS2_EXT_UNWRITTEN)
1402				*extents_to_split = *extents_to_split + 2;
1403		} else if (phys) {
1404			/*
1405			 * Only increment phys if it doesn't describe
1406			 * a hole.
1407			 */
1408			phys++;
1409		}
1410
1411		/*
1412		 * If w_first_new_cpos is < UINT_MAX, we have a non-sparse
1413		 * file that got extended.  w_first_new_cpos tells us
1414		 * where the newly allocated clusters are so we can
1415		 * zero them.
1416		 */
1417		if (desc->c_cpos >= wc->w_first_new_cpos) {
1418			BUG_ON(phys == 0);
1419			desc->c_needs_zero = 1;
1420		}
1421
1422		desc->c_phys = phys;
1423		if (phys == 0) {
1424			desc->c_new = 1;
1425			desc->c_needs_zero = 1;
1426			desc->c_clear_unwritten = 1;
1427			*clusters_to_alloc = *clusters_to_alloc + 1;
1428		}
1429
1430		if (ext_flags & OCFS2_EXT_UNWRITTEN) {
1431			desc->c_clear_unwritten = 1;
1432			desc->c_needs_zero = 1;
1433		}
1434
1435		ret = ocfs2_unwritten_check(inode, wc, desc);
1436		if (ret) {
1437			mlog_errno(ret);
1438			goto out;
1439		}
1440
1441		num_clusters--;
1442	}
1443
1444	ret = 0;
1445out:
1446	return ret;
1447}
1448
1449static int ocfs2_write_begin_inline(struct address_space *mapping,
1450				    struct inode *inode,
1451				    struct ocfs2_write_ctxt *wc)
1452{
1453	int ret;
1454	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1455	struct folio *folio;
1456	handle_t *handle;
1457	struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1458
1459	handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1460	if (IS_ERR(handle)) {
1461		ret = PTR_ERR(handle);
1462		mlog_errno(ret);
1463		goto out;
1464	}
1465
1466	folio = __filemap_get_folio(mapping, 0,
1467			FGP_LOCK | FGP_ACCESSED | FGP_CREAT, GFP_NOFS);
1468	if (IS_ERR(folio)) {
1469		ocfs2_commit_trans(osb, handle);
1470		ret = PTR_ERR(folio);
1471		mlog_errno(ret);
1472		goto out;
1473	}
1474	/*
1475	 * If we don't set w_num_folios then this folio won't get unlocked
1476	 * and freed on cleanup of the write context.
1477	 */
1478	wc->w_target_folio = folio;
1479	wc->w_folios[0] = folio;
1480	wc->w_num_folios = 1;
1481
1482	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), wc->w_di_bh,
1483				      OCFS2_JOURNAL_ACCESS_WRITE);
1484	if (ret) {
1485		ocfs2_commit_trans(osb, handle);
1486
1487		mlog_errno(ret);
1488		goto out;
1489	}
1490
1491	if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
1492		ocfs2_set_inode_data_inline(inode, di);
1493
1494	if (!folio_test_uptodate(folio)) {
1495		ret = ocfs2_read_inline_data(inode, folio, wc->w_di_bh);
1496		if (ret) {
1497			ocfs2_commit_trans(osb, handle);
1498
1499			goto out;
1500		}
1501	}
1502
1503	wc->w_handle = handle;
1504out:
1505	return ret;
1506}
1507
1508int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size)
1509{
1510	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1511
1512	if (new_size <= le16_to_cpu(di->id2.i_data.id_count))
1513		return 1;
1514	return 0;
1515}
1516
1517static int ocfs2_try_to_write_inline_data(struct address_space *mapping,
1518		struct inode *inode, loff_t pos, size_t len,
1519		struct folio *mmap_folio, struct ocfs2_write_ctxt *wc)
1520{
1521	int ret, written = 0;
1522	loff_t end = pos + len;
1523	struct ocfs2_inode_info *oi = OCFS2_I(inode);
1524	struct ocfs2_dinode *di = NULL;
1525
1526	trace_ocfs2_try_to_write_inline_data((unsigned long long)oi->ip_blkno,
1527					     len, (unsigned long long)pos,
1528					     oi->ip_dyn_features);
1529
1530	/*
1531	 * Handle inodes which already have inline data 1st.
1532	 */
1533	if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1534		if (mmap_folio == NULL &&
1535		    ocfs2_size_fits_inline_data(wc->w_di_bh, end))
1536			goto do_inline_write;
1537
1538		/*
1539		 * The write won't fit - we have to give this inode an
1540		 * inline extent list now.
1541		 */
1542		ret = ocfs2_convert_inline_data_to_extents(inode, wc->w_di_bh);
1543		if (ret)
1544			mlog_errno(ret);
1545		goto out;
1546	}
1547
1548	/*
1549	 * Check whether the inode can accept inline data.
1550	 */
1551	if (oi->ip_clusters != 0 || i_size_read(inode) != 0)
1552		return 0;
1553
1554	/*
1555	 * Check whether the write can fit.
1556	 */
1557	di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1558	if (mmap_folio ||
1559	    end > ocfs2_max_inline_data_with_xattr(inode->i_sb, di))
1560		return 0;
1561
1562do_inline_write:
1563	ret = ocfs2_write_begin_inline(mapping, inode, wc);
1564	if (ret) {
1565		mlog_errno(ret);
1566		goto out;
1567	}
1568
1569	/*
1570	 * This signals to the caller that the data can be written
1571	 * inline.
1572	 */
1573	written = 1;
1574out:
1575	return written ? written : ret;
1576}
1577
1578/*
1579 * This function only does anything for file systems which can't
1580 * handle sparse files.
1581 *
1582 * What we want to do here is fill in any hole between the current end
1583 * of allocation and the end of our write. That way the rest of the
1584 * write path can treat it as an non-allocating write, which has no
1585 * special case code for sparse/nonsparse files.
1586 */
1587static int ocfs2_expand_nonsparse_inode(struct inode *inode,
1588					struct buffer_head *di_bh,
1589					loff_t pos, unsigned len,
1590					struct ocfs2_write_ctxt *wc)
1591{
1592	int ret;
1593	loff_t newsize = pos + len;
1594
1595	BUG_ON(ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)));
1596
1597	if (newsize <= i_size_read(inode))
1598		return 0;
1599
1600	ret = ocfs2_extend_no_holes(inode, di_bh, newsize, pos);
1601	if (ret)
1602		mlog_errno(ret);
1603
1604	/* There is no wc if this is call from direct. */
1605	if (wc)
1606		wc->w_first_new_cpos =
1607			ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode));
1608
1609	return ret;
1610}
1611
1612static int ocfs2_zero_tail(struct inode *inode, struct buffer_head *di_bh,
1613			   loff_t pos)
1614{
1615	int ret = 0;
1616
1617	BUG_ON(!ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)));
1618	if (pos > i_size_read(inode))
1619		ret = ocfs2_zero_extend(inode, di_bh, pos);
1620
1621	return ret;
1622}
1623
1624int ocfs2_write_begin_nolock(struct address_space *mapping,
1625		loff_t pos, unsigned len, ocfs2_write_type_t type,
1626		struct folio **foliop, void **fsdata,
1627		struct buffer_head *di_bh, struct folio *mmap_folio)
1628{
1629	int ret, cluster_of_pages, credits = OCFS2_INODE_UPDATE_CREDITS;
1630	unsigned int clusters_to_alloc, extents_to_split, clusters_need = 0;
1631	struct ocfs2_write_ctxt *wc;
1632	struct inode *inode = mapping->host;
1633	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1634	struct ocfs2_dinode *di;
1635	struct ocfs2_alloc_context *data_ac = NULL;
1636	struct ocfs2_alloc_context *meta_ac = NULL;
1637	handle_t *handle;
1638	struct ocfs2_extent_tree et;
1639	int try_free = 1, ret1;
1640
1641try_again:
1642	ret = ocfs2_alloc_write_ctxt(&wc, osb, pos, len, type, di_bh);
1643	if (ret) {
1644		mlog_errno(ret);
1645		return ret;
1646	}
1647
1648	if (ocfs2_supports_inline_data(osb)) {
1649		ret = ocfs2_try_to_write_inline_data(mapping, inode, pos, len,
1650						     mmap_folio, wc);
1651		if (ret == 1) {
1652			ret = 0;
1653			goto success;
1654		}
1655		if (ret < 0) {
1656			mlog_errno(ret);
1657			goto out;
1658		}
1659	}
1660
1661	/* Direct io change i_size late, should not zero tail here. */
1662	if (type != OCFS2_WRITE_DIRECT) {
1663		if (ocfs2_sparse_alloc(osb))
1664			ret = ocfs2_zero_tail(inode, di_bh, pos);
1665		else
1666			ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos,
1667							   len, wc);
1668		if (ret) {
1669			mlog_errno(ret);
1670			goto out;
1671		}
1672	}
1673
1674	ret = ocfs2_check_range_for_refcount(inode, pos, len);
1675	if (ret < 0) {
1676		mlog_errno(ret);
1677		goto out;
1678	} else if (ret == 1) {
1679		clusters_need = wc->w_clen;
1680		ret = ocfs2_refcount_cow(inode, di_bh,
1681					 wc->w_cpos, wc->w_clen, UINT_MAX);
1682		if (ret) {
1683			mlog_errno(ret);
1684			goto out;
1685		}
1686	}
1687
1688	ret = ocfs2_populate_write_desc(inode, wc, &clusters_to_alloc,
1689					&extents_to_split);
1690	if (ret) {
1691		mlog_errno(ret);
1692		goto out;
1693	}
1694	clusters_need += clusters_to_alloc;
1695
1696	di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1697
1698	trace_ocfs2_write_begin_nolock(
1699			(unsigned long long)OCFS2_I(inode)->ip_blkno,
1700			(long long)i_size_read(inode),
1701			le32_to_cpu(di->i_clusters),
1702			pos, len, type, mmap_folio,
1703			clusters_to_alloc, extents_to_split);
1704
1705	/*
1706	 * We set w_target_from, w_target_to here so that
1707	 * ocfs2_write_end() knows which range in the target page to
1708	 * write out. An allocation requires that we write the entire
1709	 * cluster range.
1710	 */
1711	if (clusters_to_alloc || extents_to_split) {
1712		/*
1713		 * XXX: We are stretching the limits of
1714		 * ocfs2_lock_allocators(). It greatly over-estimates
1715		 * the work to be done.
1716		 */
1717		ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode),
1718					      wc->w_di_bh);
1719		ret = ocfs2_lock_allocators(inode, &et,
1720					    clusters_to_alloc, extents_to_split,
1721					    &data_ac, &meta_ac);
1722		if (ret) {
1723			mlog_errno(ret);
1724			goto out;
1725		}
1726
1727		if (data_ac)
1728			data_ac->ac_resv = &OCFS2_I(inode)->ip_la_data_resv;
1729
1730		credits = ocfs2_calc_extend_credits(inode->i_sb,
1731						    &di->id2.i_list);
1732	} else if (type == OCFS2_WRITE_DIRECT)
1733		/* direct write needs not to start trans if no extents alloc. */
1734		goto success;
1735
1736	/*
1737	 * We have to zero sparse allocated clusters, unwritten extent clusters,
1738	 * and non-sparse clusters we just extended.  For non-sparse writes,
1739	 * we know zeros will only be needed in the first and/or last cluster.
1740	 */
1741	if (wc->w_clen && (wc->w_desc[0].c_needs_zero ||
1742			   wc->w_desc[wc->w_clen - 1].c_needs_zero))
1743		cluster_of_pages = 1;
1744	else
1745		cluster_of_pages = 0;
1746
1747	ocfs2_set_target_boundaries(osb, wc, pos, len, cluster_of_pages);
1748
1749	handle = ocfs2_start_trans(osb, credits);
1750	if (IS_ERR(handle)) {
1751		ret = PTR_ERR(handle);
1752		mlog_errno(ret);
1753		goto out;
1754	}
1755
1756	wc->w_handle = handle;
1757
1758	if (clusters_to_alloc) {
1759		ret = dquot_alloc_space_nodirty(inode,
1760			ocfs2_clusters_to_bytes(osb->sb, clusters_to_alloc));
1761		if (ret)
1762			goto out_commit;
1763	}
1764
1765	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), wc->w_di_bh,
1766				      OCFS2_JOURNAL_ACCESS_WRITE);
1767	if (ret) {
1768		mlog_errno(ret);
1769		goto out_quota;
1770	}
1771
1772	/*
1773	 * Fill our folio array first. That way we've grabbed enough so
1774	 * that we can zero and flush if we error after adding the
1775	 * extent.
1776	 */
1777	ret = ocfs2_grab_folios_for_write(mapping, wc, wc->w_cpos, pos, len,
1778			cluster_of_pages, mmap_folio);
1779	if (ret) {
1780		/*
1781		 * ocfs2_grab_folios_for_write() returns -EAGAIN if it
1782		 * could not lock the target folio. In this case, we exit
1783		 * with no error and no target folio. This will trigger
1784		 * the caller, page_mkwrite(), to re-try the operation.
1785		 */
1786		if (type == OCFS2_WRITE_MMAP && ret == -EAGAIN) {
1787			BUG_ON(wc->w_target_folio);
1788			ret = 0;
1789			goto out_quota;
1790		}
1791
1792		mlog_errno(ret);
1793		goto out_quota;
1794	}
1795
1796	ret = ocfs2_write_cluster_by_desc(mapping, data_ac, meta_ac, wc, pos,
1797					  len);
1798	if (ret) {
1799		mlog_errno(ret);
1800		goto out_quota;
1801	}
1802
1803	if (data_ac)
1804		ocfs2_free_alloc_context(data_ac);
1805	if (meta_ac)
1806		ocfs2_free_alloc_context(meta_ac);
1807
1808success:
1809	if (foliop)
1810		*foliop = wc->w_target_folio;
1811	*fsdata = wc;
1812	return 0;
1813out_quota:
1814	if (clusters_to_alloc)
1815		dquot_free_space(inode,
1816			  ocfs2_clusters_to_bytes(osb->sb, clusters_to_alloc));
1817out_commit:
1818	ocfs2_commit_trans(osb, handle);
1819
1820out:
1821	/*
1822	 * The mmapped page won't be unlocked in ocfs2_free_write_ctxt(),
1823	 * even in case of error here like ENOSPC and ENOMEM. So, we need
1824	 * to unlock the target page manually to prevent deadlocks when
1825	 * retrying again on ENOSPC, or when returning non-VM_FAULT_LOCKED
1826	 * to VM code.
1827	 */
1828	if (wc->w_target_locked)
1829		folio_unlock(mmap_folio);
1830
1831	ocfs2_free_write_ctxt(inode, wc);
1832
1833	if (data_ac) {
1834		ocfs2_free_alloc_context(data_ac);
1835		data_ac = NULL;
1836	}
1837	if (meta_ac) {
1838		ocfs2_free_alloc_context(meta_ac);
1839		meta_ac = NULL;
1840	}
1841
1842	if (ret == -ENOSPC && try_free) {
1843		/*
1844		 * Try to free some truncate log so that we can have enough
1845		 * clusters to allocate.
1846		 */
1847		try_free = 0;
1848
1849		ret1 = ocfs2_try_to_free_truncate_log(osb, clusters_need);
1850		if (ret1 == 1)
1851			goto try_again;
1852
1853		if (ret1 < 0)
1854			mlog_errno(ret1);
1855	}
1856
1857	return ret;
1858}
1859
1860static int ocfs2_write_begin(const struct kiocb *iocb,
1861			     struct address_space *mapping,
1862			     loff_t pos, unsigned len,
1863			     struct folio **foliop, void **fsdata)
1864{
1865	int ret;
1866	struct buffer_head *di_bh = NULL;
1867	struct inode *inode = mapping->host;
1868
1869	ret = ocfs2_inode_lock(inode, &di_bh, 1);
1870	if (ret) {
1871		mlog_errno(ret);
1872		return ret;
1873	}
1874
1875	/*
1876	 * Take alloc sem here to prevent concurrent lookups. That way
1877	 * the mapping, zeroing and tree manipulation within
1878	 * ocfs2_write() will be safe against ->read_folio(). This
1879	 * should also serve to lock out allocation from a shared
1880	 * writeable region.
1881	 */
1882	down_write(&OCFS2_I(inode)->ip_alloc_sem);
1883
1884	ret = ocfs2_write_begin_nolock(mapping, pos, len, OCFS2_WRITE_BUFFER,
1885				       foliop, fsdata, di_bh, NULL);
1886	if (ret) {
1887		mlog_errno(ret);
1888		goto out_fail;
1889	}
1890
1891	brelse(di_bh);
1892
1893	return 0;
1894
1895out_fail:
1896	up_write(&OCFS2_I(inode)->ip_alloc_sem);
1897
1898	brelse(di_bh);
1899	ocfs2_inode_unlock(inode, 1);
1900
1901	return ret;
1902}
1903
1904static void ocfs2_write_end_inline(struct inode *inode, loff_t pos,
1905				   unsigned len, unsigned *copied,
1906				   struct ocfs2_dinode *di,
1907				   struct ocfs2_write_ctxt *wc)
1908{
1909	if (unlikely(*copied < len)) {
1910		if (!folio_test_uptodate(wc->w_target_folio)) {
1911			*copied = 0;
1912			return;
1913		}
1914	}
1915
1916	memcpy_from_folio(di->id2.i_data.id_data + pos, wc->w_target_folio,
1917			pos, *copied);
1918
1919	trace_ocfs2_write_end_inline(
1920	     (unsigned long long)OCFS2_I(inode)->ip_blkno,
1921	     (unsigned long long)pos, *copied,
1922	     le16_to_cpu(di->id2.i_data.id_count),
1923	     le16_to_cpu(di->i_dyn_features));
1924}
1925
1926int ocfs2_write_end_nolock(struct address_space *mapping, loff_t pos,
1927		unsigned len, unsigned copied, void *fsdata)
1928{
1929	int i, ret;
1930	size_t from, to, start = pos & (PAGE_SIZE - 1);
1931	struct inode *inode = mapping->host;
1932	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1933	struct ocfs2_write_ctxt *wc = fsdata;
1934	struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1935	handle_t *handle = wc->w_handle;
1936
1937	BUG_ON(!list_empty(&wc->w_unwritten_list));
1938
1939	if (handle) {
1940		ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode),
1941				wc->w_di_bh, OCFS2_JOURNAL_ACCESS_WRITE);
1942		if (ret) {
1943			copied = ret;
1944			mlog_errno(ret);
1945			goto out;
1946		}
1947	}
1948
1949	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1950		ocfs2_write_end_inline(inode, pos, len, &copied, di, wc);
1951		goto out_write_size;
1952	}
1953
1954	if (unlikely(copied < len) && wc->w_target_folio) {
1955		loff_t new_isize;
1956
1957		if (!folio_test_uptodate(wc->w_target_folio))
1958			copied = 0;
1959
1960		new_isize = max_t(loff_t, i_size_read(inode), pos + copied);
1961		if (new_isize > folio_pos(wc->w_target_folio))
1962			ocfs2_zero_new_buffers(wc->w_target_folio, start+copied,
1963					       start+len);
1964		else {
1965			/*
1966			 * When folio is fully beyond new isize (data copy
1967			 * failed), do not bother zeroing the folio. Invalidate
1968			 * it instead so that writeback does not get confused
1969			 * put page & buffer dirty bits into inconsistent
1970			 * state.
1971			 */
1972			block_invalidate_folio(wc->w_target_folio, 0,
1973					folio_size(wc->w_target_folio));
1974		}
1975	}
1976	if (wc->w_target_folio)
1977		flush_dcache_folio(wc->w_target_folio);
1978
1979	for (i = 0; i < wc->w_num_folios; i++) {
1980		struct folio *folio = wc->w_folios[i];
1981
1982		/* This is the direct io target folio */
1983		if (folio == NULL)
1984			continue;
1985
1986		if (folio == wc->w_target_folio) {
1987			from = wc->w_target_from;
1988			to = wc->w_target_to;
1989
1990			BUG_ON(from > folio_size(folio) ||
1991			       to > folio_size(folio) ||
1992			       to < from);
1993		} else {
1994			/*
1995			 * Pages adjacent to the target (if any) imply
1996			 * a hole-filling write in which case we want
1997			 * to flush their entire range.
1998			 */
1999			from = 0;
2000			to = folio_size(folio);
2001		}
2002
2003		if (folio_buffers(folio)) {
2004			if (handle && ocfs2_should_order_data(inode)) {
2005				loff_t start_byte = folio_pos(folio) + from;
2006				loff_t length = to - from;
2007				ocfs2_jbd2_inode_add_write(handle, inode,
2008							   start_byte, length);
2009			}
2010			block_commit_write(folio, from, to);
2011		}
2012	}
2013
2014out_write_size:
2015	/* Direct io do not update i_size here. */
2016	if (wc->w_type != OCFS2_WRITE_DIRECT) {
2017		pos += copied;
2018		if (pos > i_size_read(inode)) {
2019			i_size_write(inode, pos);
2020			mark_inode_dirty(inode);
2021		}
2022		inode->i_blocks = ocfs2_inode_sector_count(inode);
2023		di->i_size = cpu_to_le64((u64)i_size_read(inode));
2024		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
2025		di->i_mtime = di->i_ctime = cpu_to_le64(inode_get_mtime_sec(inode));
2026		di->i_mtime_nsec = di->i_ctime_nsec = cpu_to_le32(inode_get_mtime_nsec(inode));
2027		if (handle)
2028			ocfs2_update_inode_fsync_trans(handle, inode, 1);
2029	}
2030	if (handle)
2031		ocfs2_journal_dirty(handle, wc->w_di_bh);
2032
2033out:
2034	/* unlock pages before dealloc since it needs acquiring j_trans_barrier
2035	 * lock, or it will cause a deadlock since journal commit threads holds
2036	 * this lock and will ask for the page lock when flushing the data.
2037	 * put it here to preserve the unlock order.
2038	 */
2039	ocfs2_unlock_folios(wc);
2040
2041	if (handle)
2042		ocfs2_commit_trans(osb, handle);
2043
2044	ocfs2_run_deallocs(osb, &wc->w_dealloc);
2045
2046	brelse(wc->w_di_bh);
2047	kfree(wc);
2048
2049	return copied;
2050}
2051
2052static int ocfs2_write_end(const struct kiocb *iocb,
2053			   struct address_space *mapping,
2054			   loff_t pos, unsigned len, unsigned copied,
2055			   struct folio *folio, void *fsdata)
2056{
2057	int ret;
2058	struct inode *inode = mapping->host;
2059
2060	ret = ocfs2_write_end_nolock(mapping, pos, len, copied, fsdata);
2061
2062	up_write(&OCFS2_I(inode)->ip_alloc_sem);
2063	ocfs2_inode_unlock(inode, 1);
2064
2065	return ret;
2066}
2067
2068struct ocfs2_dio_write_ctxt {
2069	struct list_head	dw_zero_list;
2070	unsigned		dw_zero_count;
2071	int			dw_orphaned;
2072	pid_t			dw_writer_pid;
2073};
2074
2075static struct ocfs2_dio_write_ctxt *
2076ocfs2_dio_alloc_write_ctx(struct buffer_head *bh, int *alloc)
2077{
2078	struct ocfs2_dio_write_ctxt *dwc = NULL;
2079
2080	if (bh->b_private)
2081		return bh->b_private;
2082
2083	dwc = kmalloc(sizeof(struct ocfs2_dio_write_ctxt), GFP_NOFS);
2084	if (dwc == NULL)
2085		return NULL;
2086	INIT_LIST_HEAD(&dwc->dw_zero_list);
2087	dwc->dw_zero_count = 0;
2088	dwc->dw_orphaned = 0;
2089	dwc->dw_writer_pid = task_pid_nr(current);
2090	bh->b_private = dwc;
2091	*alloc = 1;
2092
2093	return dwc;
2094}
2095
2096static void ocfs2_dio_free_write_ctx(struct inode *inode,
2097				     struct ocfs2_dio_write_ctxt *dwc)
2098{
2099	ocfs2_free_unwritten_list(inode, &dwc->dw_zero_list);
2100	kfree(dwc);
2101}
2102
2103/*
2104 * TODO: Make this into a generic get_blocks function.
2105 *
2106 * From do_direct_io in direct-io.c:
2107 *  "So what we do is to permit the ->get_blocks function to populate
2108 *   bh.b_size with the size of IO which is permitted at this offset and
2109 *   this i_blkbits."
2110 *
2111 * This function is called directly from get_more_blocks in direct-io.c.
2112 *
2113 * called like this: dio->get_blocks(dio->inode, fs_startblk,
2114 * 					fs_count, map_bh, dio->rw == WRITE);
2115 */
2116static int ocfs2_dio_wr_get_block(struct inode *inode, sector_t iblock,
2117			       struct buffer_head *bh_result, int create)
2118{
2119	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2120	struct ocfs2_inode_info *oi = OCFS2_I(inode);
2121	struct ocfs2_write_ctxt *wc;
2122	struct ocfs2_write_cluster_desc *desc = NULL;
2123	struct ocfs2_dio_write_ctxt *dwc = NULL;
2124	struct buffer_head *di_bh = NULL;
2125	u64 p_blkno;
2126	unsigned int i_blkbits = inode->i_sb->s_blocksize_bits;
2127	loff_t pos = iblock << i_blkbits;
2128	sector_t endblk = (i_size_read(inode) - 1) >> i_blkbits;
2129	unsigned len, total_len = bh_result->b_size;
2130	int ret = 0, first_get_block = 0;
2131
2132	len = osb->s_clustersize - (pos & (osb->s_clustersize - 1));
2133	len = min(total_len, len);
2134
2135	/*
2136	 * bh_result->b_size is count in get_more_blocks according to write
2137	 * "pos" and "end", we need map twice to return different buffer state:
2138	 * 1. area in file size, not set NEW;
2139	 * 2. area out file size, set  NEW.
2140	 *
2141	 *		   iblock    endblk
2142	 * |--------|---------|---------|---------
2143	 * |<-------area in file------->|
2144	 */
2145
2146	if ((iblock <= endblk) &&
2147	    ((iblock + ((len - 1) >> i_blkbits)) > endblk))
2148		len = (endblk - iblock + 1) << i_blkbits;
2149
2150	mlog(0, "get block of %lu at %llu:%u req %u\n",
2151			inode->i_ino, pos, len, total_len);
2152
2153	/*
2154	 * Because we need to change file size in ocfs2_dio_end_io_write(), or
2155	 * we may need to add it to orphan dir. So can not fall to fast path
2156	 * while file size will be changed.
2157	 */
2158	if (pos + total_len <= i_size_read(inode)) {
2159
2160		/* This is the fast path for re-write. */
2161		ret = ocfs2_lock_get_block(inode, iblock, bh_result, create);
2162		if (buffer_mapped(bh_result) &&
2163		    !buffer_new(bh_result) &&
2164		    ret == 0)
2165			goto out;
2166
2167		/* Clear state set by ocfs2_get_block. */
2168		bh_result->b_state = 0;
2169	}
2170
2171	dwc = ocfs2_dio_alloc_write_ctx(bh_result, &first_get_block);
2172	if (unlikely(dwc == NULL)) {
2173		ret = -ENOMEM;
2174		mlog_errno(ret);
2175		goto out;
2176	}
2177
2178	if (ocfs2_clusters_for_bytes(inode->i_sb, pos + total_len) >
2179	    ocfs2_clusters_for_bytes(inode->i_sb, i_size_read(inode)) &&
2180	    !dwc->dw_orphaned) {
2181		/*
2182		 * when we are going to alloc extents beyond file size, add the
2183		 * inode to orphan dir, so we can recall those spaces when
2184		 * system crashed during write.
2185		 */
2186		ret = ocfs2_add_inode_to_orphan(osb, inode);
2187		if (ret < 0) {
2188			mlog_errno(ret);
2189			goto out;
2190		}
2191		dwc->dw_orphaned = 1;
2192	}
2193
2194	ret = ocfs2_inode_lock(inode, &di_bh, 1);
2195	if (ret) {
2196		mlog_errno(ret);
2197		goto out;
2198	}
2199
2200	down_write(&oi->ip_alloc_sem);
2201
2202	if (first_get_block) {
2203		if (ocfs2_sparse_alloc(osb))
2204			ret = ocfs2_zero_tail(inode, di_bh, pos);
2205		else
2206			ret = ocfs2_expand_nonsparse_inode(inode, di_bh, pos,
2207							   total_len, NULL);
2208		if (ret < 0) {
2209			mlog_errno(ret);
2210			goto unlock;
2211		}
2212	}
2213
2214	ret = ocfs2_write_begin_nolock(inode->i_mapping, pos, len,
2215				       OCFS2_WRITE_DIRECT, NULL,
2216				       (void **)&wc, di_bh, NULL);
2217	if (ret) {
2218		mlog_errno(ret);
2219		goto unlock;
2220	}
2221
2222	desc = &wc->w_desc[0];
2223
2224	p_blkno = ocfs2_clusters_to_blocks(inode->i_sb, desc->c_phys);
2225	BUG_ON(p_blkno == 0);
2226	p_blkno += iblock & (u64)(ocfs2_clusters_to_blocks(inode->i_sb, 1) - 1);
2227
2228	map_bh(bh_result, inode->i_sb, p_blkno);
2229	bh_result->b_size = len;
2230	if (desc->c_needs_zero)
2231		set_buffer_new(bh_result);
2232
2233	if (iblock > endblk)
2234		set_buffer_new(bh_result);
2235
2236	/* May sleep in end_io. It should not happen in a irq context. So defer
2237	 * it to dio work queue. */
2238	set_buffer_defer_completion(bh_result);
2239
2240	if (!list_empty(&wc->w_unwritten_list)) {
2241		struct ocfs2_unwritten_extent *ue = NULL;
2242
2243		ue = list_first_entry(&wc->w_unwritten_list,
2244				      struct ocfs2_unwritten_extent,
2245				      ue_node);
2246		BUG_ON(ue->ue_cpos != desc->c_cpos);
2247		/* The physical address may be 0, fill it. */
2248		ue->ue_phys = desc->c_phys;
2249
2250		list_splice_tail_init(&wc->w_unwritten_list, &dwc->dw_zero_list);
2251		dwc->dw_zero_count += wc->w_unwritten_count;
2252	}
2253
2254	ret = ocfs2_write_end_nolock(inode->i_mapping, pos, len, len, wc);
2255	BUG_ON(ret != len);
2256	ret = 0;
2257unlock:
2258	up_write(&oi->ip_alloc_sem);
2259	ocfs2_inode_unlock(inode, 1);
2260	brelse(di_bh);
2261out:
2262	return ret;
2263}
2264
2265static int ocfs2_dio_end_io_write(struct inode *inode,
2266				  struct ocfs2_dio_write_ctxt *dwc,
2267				  loff_t offset,
2268				  ssize_t bytes)
2269{
2270	struct ocfs2_cached_dealloc_ctxt dealloc;
2271	struct ocfs2_extent_tree et;
2272	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2273	struct ocfs2_inode_info *oi = OCFS2_I(inode);
2274	struct ocfs2_unwritten_extent *ue = NULL;
2275	struct buffer_head *di_bh = NULL;
2276	struct ocfs2_dinode *di;
2277	struct ocfs2_alloc_context *data_ac = NULL;
2278	struct ocfs2_alloc_context *meta_ac = NULL;
2279	handle_t *handle = NULL;
2280	loff_t end = offset + bytes;
2281	int ret = 0, credits = 0;
2282
2283	ocfs2_init_dealloc_ctxt(&dealloc);
2284
2285	/* We do clear unwritten, delete orphan, change i_size here. If neither
2286	 * of these happen, we can skip all this. */
2287	if (list_empty(&dwc->dw_zero_list) &&
2288	    end <= i_size_read(inode) &&
2289	    !dwc->dw_orphaned)
2290		goto out;
2291
2292	ret = ocfs2_inode_lock(inode, &di_bh, 1);
2293	if (ret < 0) {
2294		mlog_errno(ret);
2295		goto out;
2296	}
2297
2298	/* Delete orphan before acquire i_rwsem. */
2299	if (dwc->dw_orphaned) {
2300		BUG_ON(dwc->dw_writer_pid != task_pid_nr(current));
2301
2302		end = end > i_size_read(inode) ? end : 0;
2303
2304		ret = ocfs2_del_inode_from_orphan(osb, inode, di_bh,
2305				!!end, end);
2306		if (ret < 0)
2307			mlog_errno(ret);
2308	}
2309
2310	down_write(&oi->ip_alloc_sem);
2311	di = (struct ocfs2_dinode *)di_bh->b_data;
2312
2313	ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(inode), di_bh);
2314
2315	/* Attach dealloc with extent tree in case that we may reuse extents
2316	 * which are already unlinked from current extent tree due to extent
2317	 * rotation and merging.
2318	 */
2319	et.et_dealloc = &dealloc;
2320
2321	ret = ocfs2_lock_allocators(inode, &et, 0, dwc->dw_zero_count*2,
2322				    &data_ac, &meta_ac);
2323	if (ret) {
2324		mlog_errno(ret);
2325		goto unlock;
2326	}
2327
2328	credits = ocfs2_calc_extend_credits(inode->i_sb, &di->id2.i_list);
2329
2330	handle = ocfs2_start_trans(osb, credits);
2331	if (IS_ERR(handle)) {
2332		ret = PTR_ERR(handle);
2333		mlog_errno(ret);
2334		goto unlock;
2335	}
2336	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
2337				      OCFS2_JOURNAL_ACCESS_WRITE);
2338	if (ret) {
2339		mlog_errno(ret);
2340		goto commit;
2341	}
2342
2343	list_for_each_entry(ue, &dwc->dw_zero_list, ue_node) {
2344		ret = ocfs2_assure_trans_credits(handle, credits);
2345		if (ret < 0) {
2346			mlog_errno(ret);
2347			break;
2348		}
2349		ret = ocfs2_mark_extent_written(inode, &et, handle,
2350						ue->ue_cpos, 1,
2351						ue->ue_phys,
2352						meta_ac, &dealloc);
2353		if (ret < 0) {
2354			mlog_errno(ret);
2355			break;
2356		}
2357	}
2358
2359	if (end > i_size_read(inode)) {
2360		ret = ocfs2_set_inode_size(handle, inode, di_bh, end);
2361		if (ret < 0)
2362			mlog_errno(ret);
2363	}
2364commit:
2365	ocfs2_commit_trans(osb, handle);
2366unlock:
2367	up_write(&oi->ip_alloc_sem);
2368	ocfs2_inode_unlock(inode, 1);
2369	brelse(di_bh);
2370out:
2371	if (data_ac)
2372		ocfs2_free_alloc_context(data_ac);
2373	if (meta_ac)
2374		ocfs2_free_alloc_context(meta_ac);
2375	ocfs2_run_deallocs(osb, &dealloc);
2376	ocfs2_dio_free_write_ctx(inode, dwc);
2377
2378	return ret;
2379}
2380
2381/*
2382 * ocfs2_dio_end_io is called by the dio core when a dio is finished.  We're
2383 * particularly interested in the aio/dio case.  We use the rw_lock DLM lock
2384 * to protect io on one node from truncation on another.
2385 */
2386static int ocfs2_dio_end_io(struct kiocb *iocb,
2387			    loff_t offset,
2388			    ssize_t bytes,
2389			    void *private)
2390{
2391	struct inode *inode = file_inode(iocb->ki_filp);
2392	int level;
2393	int ret = 0;
2394
2395	/* this io's submitter should not have unlocked this before we could */
2396	BUG_ON(!ocfs2_iocb_is_rw_locked(iocb));
2397
2398	if (bytes <= 0)
2399		mlog_ratelimited(ML_ERROR, "Direct IO failed, bytes = %lld",
2400				 (long long)bytes);
2401	if (private) {
2402		if (bytes > 0)
2403			ret = ocfs2_dio_end_io_write(inode, private, offset,
2404						     bytes);
2405		else
2406			ocfs2_dio_free_write_ctx(inode, private);
2407	}
2408
2409	ocfs2_iocb_clear_rw_locked(iocb);
2410
2411	level = ocfs2_iocb_rw_locked_level(iocb);
2412	ocfs2_rw_unlock(inode, level);
2413	return ret;
2414}
2415
2416static ssize_t ocfs2_direct_IO(struct kiocb *iocb, struct iov_iter *iter)
2417{
2418	struct file *file = iocb->ki_filp;
2419	struct inode *inode = file->f_mapping->host;
2420	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2421	get_block_t *get_block;
2422
2423	/*
2424	 * Fallback to buffered I/O if we see an inode without
2425	 * extents.
2426	 */
2427	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
2428		return 0;
2429
2430	/* Fallback to buffered I/O if we do not support append dio. */
2431	if (iocb->ki_pos + iter->count > i_size_read(inode) &&
2432	    !ocfs2_supports_append_dio(osb))
2433		return 0;
2434
2435	if (iov_iter_rw(iter) == READ)
2436		get_block = ocfs2_lock_get_block;
2437	else
2438		get_block = ocfs2_dio_wr_get_block;
2439
2440	return __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev,
2441				    iter, get_block,
2442				    ocfs2_dio_end_io, 0);
2443}
2444
2445const struct address_space_operations ocfs2_aops = {
2446	.dirty_folio		= block_dirty_folio,
2447	.read_folio		= ocfs2_read_folio,
2448	.readahead		= ocfs2_readahead,
2449	.writepages		= ocfs2_writepages,
2450	.write_begin		= ocfs2_write_begin,
2451	.write_end		= ocfs2_write_end,
2452	.bmap			= ocfs2_bmap,
2453	.direct_IO		= ocfs2_direct_IO,
2454	.invalidate_folio	= block_invalidate_folio,
2455	.release_folio		= ocfs2_release_folio,
2456	.migrate_folio		= buffer_migrate_folio,
2457	.is_partially_uptodate	= block_is_partially_uptodate,
2458	.error_remove_folio	= generic_error_remove_folio,
2459};
~/ Read-only file preview.