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