xref: /linux/fs/ext2/inode.c (revision 12d5fc96ebbb3b948861805b32a4c3a96105ccd9)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  linux/fs/ext2/inode.c
4  *
5  * Copyright (C) 1992, 1993, 1994, 1995
6  * Remy Card (card@masi.ibp.fr)
7  * Laboratoire MASI - Institut Blaise Pascal
8  * Universite Pierre et Marie Curie (Paris VI)
9  *
10  *  from
11  *
12  *  linux/fs/minix/inode.c
13  *
14  *  Copyright (C) 1991, 1992  Linus Torvalds
15  *
16  *  Goal-directed block allocation by Stephen Tweedie
17  * 	(sct@dcs.ed.ac.uk), 1993, 1998
18  *  Big-endian to little-endian byte-swapping/bitmaps by
19  *        David S. Miller (davem@caip.rutgers.edu), 1995
20  *  64-bit file support on 64-bit platforms by Jakub Jelinek
21  * 	(jj@sunsite.ms.mff.cuni.cz)
22  *
23  *  Assorted race fixes, rewrite of ext2_get_block() by Al Viro, 2000
24  */
25 
26 #include <linux/time.h>
27 #include <linux/highuid.h>
28 #include <linux/pagemap.h>
29 #include <linux/blkdev.h>
30 #include <linux/quotaops.h>
31 #include <linux/writeback.h>
32 #include <linux/buffer_head.h>
33 #include <linux/mpage.h>
34 #include <linux/fiemap.h>
35 #include <linux/iomap.h>
36 #include <linux/namei.h>
37 #include <linux/uio.h>
38 #include "ext2.h"
39 #include "acl.h"
40 #include "xattr.h"
41 
42 /*
43  * Test whether an inode is a fast symlink.
44  */
45 static inline int ext2_inode_is_fast_symlink(struct inode *inode)
46 {
47 	int ea_blocks = EXT2_I(inode)->i_file_acl ?
48 		(inode->i_sb->s_blocksize >> 9) : 0;
49 
50 	return (S_ISLNK(inode->i_mode) &&
51 		inode->i_blocks - ea_blocks == 0);
52 }
53 
54 static void ext2_truncate_blocks(struct inode *inode, loff_t offset);
55 
56 void ext2_write_failed(struct address_space *mapping, loff_t to)
57 {
58 	struct inode *inode = mapping->host;
59 
60 	if (to > inode->i_size) {
61 		truncate_pagecache(inode, inode->i_size);
62 		ext2_truncate_blocks(inode, inode->i_size);
63 	}
64 }
65 
66 /*
67  * Called at the last iput() if i_nlink is zero.
68  */
69 void ext2_evict_inode(struct inode * inode)
70 {
71 	struct ext2_block_alloc_info *rsv;
72 	int want_delete = 0;
73 
74 	if (!inode->i_nlink && !is_bad_inode(inode)) {
75 		want_delete = 1;
76 		dquot_initialize(inode);
77 	} else {
78 		dquot_drop(inode);
79 	}
80 
81 	truncate_inode_pages_final(&inode->i_data);
82 
83 	if (want_delete) {
84 		sb_start_intwrite(inode->i_sb);
85 		/* set dtime */
86 		EXT2_I(inode)->i_dtime	= ktime_get_real_seconds();
87 		mark_inode_dirty(inode);
88 		sync_inode_metadata(inode, inode_needs_sync(inode));
89 		/* truncate to 0 */
90 		inode->i_size = 0;
91 		if (inode->i_blocks)
92 			ext2_truncate_blocks(inode, 0);
93 		ext2_xattr_delete_inode(inode);
94 	} else {
95 		mmb_sync(&EXT2_I(inode)->i_metadata_bhs);
96 	}
97 	mmb_invalidate(&EXT2_I(inode)->i_metadata_bhs);
98 	clear_inode(inode);
99 
100 	ext2_discard_reservation(inode);
101 	rsv = EXT2_I(inode)->i_block_alloc_info;
102 	EXT2_I(inode)->i_block_alloc_info = NULL;
103 	if (unlikely(rsv))
104 		kfree(rsv);
105 
106 	if (want_delete) {
107 		ext2_free_inode(inode);
108 		sb_end_intwrite(inode->i_sb);
109 	}
110 }
111 
112 typedef struct {
113 	__le32	*p;
114 	__le32	key;
115 	struct buffer_head *bh;
116 } Indirect;
117 
118 static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
119 {
120 	p->key = *(p->p = v);
121 	p->bh = bh;
122 }
123 
124 static inline int verify_chain(Indirect *from, Indirect *to)
125 {
126 	while (from <= to && from->key == *from->p)
127 		from++;
128 	return (from > to);
129 }
130 
131 /**
132  *	ext2_block_to_path - parse the block number into array of offsets
133  *	@inode: inode in question (we are only interested in its superblock)
134  *	@i_block: block number to be parsed
135  *	@offsets: array to store the offsets in
136  *      @boundary: set this non-zero if the referred-to block is likely to be
137  *             followed (on disk) by an indirect block.
138  *	To store the locations of file's data ext2 uses a data structure common
139  *	for UNIX filesystems - tree of pointers anchored in the inode, with
140  *	data blocks at leaves and indirect blocks in intermediate nodes.
141  *	This function translates the block number into path in that tree -
142  *	return value is the path length and @offsets[n] is the offset of
143  *	pointer to (n+1)th node in the nth one. If @block is out of range
144  *	(negative or too large) warning is printed and zero returned.
145  *
146  *	Note: function doesn't find node addresses, so no IO is needed. All
147  *	we need to know is the capacity of indirect blocks (taken from the
148  *	inode->i_sb).
149  */
150 
151 /*
152  * Portability note: the last comparison (check that we fit into triple
153  * indirect block) is spelled differently, because otherwise on an
154  * architecture with 32-bit longs and 8Kb pages we might get into trouble
155  * if our filesystem had 8Kb blocks. We might use long long, but that would
156  * kill us on x86. Oh, well, at least the sign propagation does not matter -
157  * i_block would have to be negative in the very beginning, so we would not
158  * get there at all.
159  */
160 
161 static int ext2_block_to_path(struct inode *inode,
162 			long i_block, int offsets[4], int *boundary)
163 {
164 	int ptrs = EXT2_ADDR_PER_BLOCK(inode->i_sb);
165 	int ptrs_bits = EXT2_ADDR_PER_BLOCK_BITS(inode->i_sb);
166 	const long direct_blocks = EXT2_NDIR_BLOCKS,
167 		indirect_blocks = ptrs,
168 		double_blocks = (1 << (ptrs_bits * 2));
169 	int n = 0;
170 	int final = 0;
171 
172 	if (i_block < 0) {
173 		ext2_msg(inode->i_sb, KERN_WARNING,
174 			"warning: %s: block < 0", __func__);
175 	} else if (i_block < direct_blocks) {
176 		offsets[n++] = i_block;
177 		final = direct_blocks;
178 	} else if ( (i_block -= direct_blocks) < indirect_blocks) {
179 		offsets[n++] = EXT2_IND_BLOCK;
180 		offsets[n++] = i_block;
181 		final = ptrs;
182 	} else if ((i_block -= indirect_blocks) < double_blocks) {
183 		offsets[n++] = EXT2_DIND_BLOCK;
184 		offsets[n++] = i_block >> ptrs_bits;
185 		offsets[n++] = i_block & (ptrs - 1);
186 		final = ptrs;
187 	} else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
188 		offsets[n++] = EXT2_TIND_BLOCK;
189 		offsets[n++] = i_block >> (ptrs_bits * 2);
190 		offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
191 		offsets[n++] = i_block & (ptrs - 1);
192 		final = ptrs;
193 	} else {
194 		ext2_msg(inode->i_sb, KERN_WARNING,
195 			"warning: %s: block is too big", __func__);
196 	}
197 	if (boundary)
198 		*boundary = final - 1 - (i_block & (ptrs - 1));
199 
200 	return n;
201 }
202 
203 /**
204  *	ext2_get_branch - read the chain of indirect blocks leading to data
205  *	@inode: inode in question
206  *	@depth: depth of the chain (1 - direct pointer, etc.)
207  *	@offsets: offsets of pointers in inode/indirect blocks
208  *	@chain: place to store the result
209  *	@err: here we store the error value
210  *
211  *	Function fills the array of triples <key, p, bh> and returns %NULL
212  *	if everything went OK or the pointer to the last filled triple
213  *	(incomplete one) otherwise. Upon the return chain[i].key contains
214  *	the number of (i+1)-th block in the chain (as it is stored in memory,
215  *	i.e. little-endian 32-bit), chain[i].p contains the address of that
216  *	number (it points into struct inode for i==0 and into the bh->b_data
217  *	for i>0) and chain[i].bh points to the buffer_head of i-th indirect
218  *	block for i>0 and NULL for i==0. In other words, it holds the block
219  *	numbers of the chain, addresses they were taken from (and where we can
220  *	verify that chain did not change) and buffer_heads hosting these
221  *	numbers.
222  *
223  *	Function stops when it stumbles upon zero pointer (absent block)
224  *		(pointer to last triple returned, *@err == 0)
225  *	or when it gets an IO error reading an indirect block
226  *		(ditto, *@err == -EIO)
227  *	or when it notices that chain had been changed while it was reading
228  *		(ditto, *@err == -EAGAIN)
229  *	or when it reads all @depth-1 indirect blocks successfully and finds
230  *	the whole chain, all way to the data (returns %NULL, *err == 0).
231  */
232 static Indirect *ext2_get_branch(struct inode *inode,
233 				 int depth,
234 				 int *offsets,
235 				 Indirect chain[4],
236 				 int *err)
237 {
238 	struct super_block *sb = inode->i_sb;
239 	Indirect *p = chain;
240 	struct buffer_head *bh;
241 
242 	*err = 0;
243 	/* i_data is not going away, no lock needed */
244 	add_chain (chain, NULL, EXT2_I(inode)->i_data + *offsets);
245 	if (!p->key)
246 		goto no_block;
247 	while (--depth) {
248 		bh = sb_bread(sb, le32_to_cpu(p->key));
249 		if (!bh)
250 			goto failure;
251 		read_lock(&EXT2_I(inode)->i_meta_lock);
252 		if (!verify_chain(chain, p))
253 			goto changed;
254 		add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
255 		read_unlock(&EXT2_I(inode)->i_meta_lock);
256 		if (!p->key)
257 			goto no_block;
258 	}
259 	return NULL;
260 
261 changed:
262 	read_unlock(&EXT2_I(inode)->i_meta_lock);
263 	brelse(bh);
264 	*err = -EAGAIN;
265 	goto no_block;
266 failure:
267 	*err = -EIO;
268 no_block:
269 	return p;
270 }
271 
272 /**
273  *	ext2_find_near - find a place for allocation with sufficient locality
274  *	@inode: owner
275  *	@ind: descriptor of indirect block.
276  *
277  *	This function returns the preferred place for block allocation.
278  *	It is used when heuristic for sequential allocation fails.
279  *	Rules are:
280  *	  + if there is a block to the left of our position - allocate near it.
281  *	  + if pointer will live in indirect block - allocate near that block.
282  *	  + if pointer will live in inode - allocate in the same cylinder group.
283  *
284  * In the latter case we colour the starting block by the callers PID to
285  * prevent it from clashing with concurrent allocations for a different inode
286  * in the same block group.   The PID is used here so that functionally related
287  * files will be close-by on-disk.
288  *
289  *	Caller must make sure that @ind is valid and will stay that way.
290  */
291 
292 static ext2_fsblk_t ext2_find_near(struct inode *inode, Indirect *ind)
293 {
294 	struct ext2_inode_info *ei = EXT2_I(inode);
295 	__le32 *start = ind->bh ? (__le32 *) ind->bh->b_data : ei->i_data;
296 	__le32 *p;
297 	ext2_fsblk_t bg_start;
298 	ext2_fsblk_t colour;
299 
300 	/* Try to find previous block */
301 	for (p = ind->p - 1; p >= start; p--)
302 		if (*p)
303 			return le32_to_cpu(*p);
304 
305 	/* No such thing, so let's try location of indirect block */
306 	if (ind->bh)
307 		return ind->bh->b_blocknr;
308 
309 	/*
310 	 * It is going to be referred from inode itself? OK, just put it into
311 	 * the same cylinder group then.
312 	 */
313 	bg_start = ext2_group_first_block_no(inode->i_sb, ei->i_block_group);
314 	colour = (current->pid % 16) *
315 			(EXT2_BLOCKS_PER_GROUP(inode->i_sb) / 16);
316 	return bg_start + colour;
317 }
318 
319 /**
320  *	ext2_find_goal - find a preferred place for allocation.
321  *	@inode: owner
322  *	@block:  block we want
323  *	@partial: pointer to the last triple within a chain
324  *
325  *	Returns preferred place for a block (the goal).
326  */
327 
328 static inline ext2_fsblk_t ext2_find_goal(struct inode *inode, long block,
329 					  Indirect *partial)
330 	__must_hold(&EXT2_I(inode)->truncate_mutex)
331 {
332 	struct ext2_block_alloc_info *block_i;
333 
334 	block_i = EXT2_I(inode)->i_block_alloc_info;
335 
336 	/*
337 	 * try the heuristic for sequential allocation,
338 	 * failing that at least try to get decent locality.
339 	 */
340 	if (block_i && (block == block_i->last_alloc_logical_block + 1)
341 		&& (block_i->last_alloc_physical_block != 0)) {
342 		return block_i->last_alloc_physical_block + 1;
343 	}
344 
345 	return ext2_find_near(inode, partial);
346 }
347 
348 /**
349  *	ext2_blks_to_allocate: Look up the block map and count the number
350  *	of direct blocks need to be allocated for the given branch.
351  *
352  * 	@branch: chain of indirect blocks
353  *	@k: number of blocks need for indirect blocks
354  *	@blks: number of data blocks to be mapped.
355  *	@blocks_to_boundary:  the offset in the indirect block
356  *
357  *	return the number of direct blocks to allocate.
358  */
359 static int
360 ext2_blks_to_allocate(Indirect * branch, int k, unsigned long blks,
361 		int blocks_to_boundary)
362 {
363 	unsigned long count = 0;
364 
365 	/*
366 	 * Simple case, [t,d]Indirect block(s) has not allocated yet
367 	 * then it's clear blocks on that path have not allocated
368 	 */
369 	if (k > 0) {
370 		/* right now don't hanel cross boundary allocation */
371 		if (blks < blocks_to_boundary + 1)
372 			count += blks;
373 		else
374 			count += blocks_to_boundary + 1;
375 		return count;
376 	}
377 
378 	count++;
379 	while (count < blks && count <= blocks_to_boundary
380 		&& le32_to_cpu(*(branch[0].p + count)) == 0) {
381 		count++;
382 	}
383 	return count;
384 }
385 
386 /**
387  * ext2_alloc_blocks: Allocate multiple blocks needed for a branch.
388  * @inode: Owner.
389  * @goal: Preferred place for allocation.
390  * @indirect_blks: The number of blocks needed to allocate for indirect blocks.
391  * @blks: The number of blocks need to allocate for direct blocks.
392  * @new_blocks: On return it will store the new block numbers for
393  *	the indirect blocks(if needed) and the first direct block.
394  * @err: Error pointer.
395  *
396  * Return: Number of blocks allocated.
397  */
398 static int ext2_alloc_blocks(struct inode *inode,
399 			ext2_fsblk_t goal, int indirect_blks, int blks,
400 			ext2_fsblk_t new_blocks[4], int *err)
401 	__must_hold(&EXT2_I(inode)->truncate_mutex)
402 {
403 	int target, i;
404 	unsigned long count = 0;
405 	int index = 0;
406 	ext2_fsblk_t current_block = 0;
407 	int ret = 0;
408 
409 	/*
410 	 * Here we try to allocate the requested multiple blocks at once,
411 	 * on a best-effort basis.
412 	 * To build a branch, we should allocate blocks for
413 	 * the indirect blocks(if not allocated yet), and at least
414 	 * the first direct block of this branch.  That's the
415 	 * minimum number of blocks need to allocate(required)
416 	 */
417 	target = blks + indirect_blks;
418 
419 	while (1) {
420 		count = target;
421 		/* allocating blocks for indirect blocks and direct blocks */
422 		current_block = ext2_new_blocks(inode, goal, &count, err, 0);
423 		if (*err)
424 			goto failed_out;
425 
426 		target -= count;
427 		/* allocate blocks for indirect blocks */
428 		while (index < indirect_blks && count) {
429 			new_blocks[index++] = current_block++;
430 			count--;
431 		}
432 
433 		if (count > 0)
434 			break;
435 	}
436 
437 	/* save the new block number for the first direct block */
438 	new_blocks[index] = current_block;
439 
440 	/* total number of blocks allocated for direct blocks */
441 	ret = count;
442 	*err = 0;
443 	return ret;
444 failed_out:
445 	for (i = 0; i <index; i++)
446 		ext2_free_blocks(inode, new_blocks[i], 1);
447 	if (index)
448 		mark_inode_dirty(inode);
449 	return ret;
450 }
451 
452 /**
453  *	ext2_alloc_branch - allocate and set up a chain of blocks.
454  *	@inode: owner
455  *	@indirect_blks: depth of the chain (number of blocks to allocate)
456  *	@blks: number of allocated direct blocks
457  *	@goal: preferred place for allocation
458  *	@offsets: offsets (in the blocks) to store the pointers to next.
459  *	@branch: place to store the chain in.
460  *
461  *	This function allocates @num blocks, zeroes out all but the last one,
462  *	links them into chain and (if we are synchronous) writes them to disk.
463  *	In other words, it prepares a branch that can be spliced onto the
464  *	inode. It stores the information about that chain in the branch[], in
465  *	the same format as ext2_get_branch() would do. We are calling it after
466  *	we had read the existing part of chain and partial points to the last
467  *	triple of that (one with zero ->key). Upon the exit we have the same
468  *	picture as after the successful ext2_get_block(), except that in one
469  *	place chain is disconnected - *branch->p is still zero (we did not
470  *	set the last link), but branch->key contains the number that should
471  *	be placed into *branch->p to fill that gap.
472  *
473  *	If allocation fails we free all blocks we've allocated (and forget
474  *	their buffer_heads) and return the error value the from failed
475  *	ext2_alloc_block() (normally -ENOSPC). Otherwise we set the chain
476  *	as described above and return 0.
477  */
478 
479 static int ext2_alloc_branch(struct inode *inode,
480 			int indirect_blks, int *blks, ext2_fsblk_t goal,
481 			int *offsets, Indirect *branch)
482 	__must_hold(&EXT2_I(inode)->truncate_mutex)
483 {
484 	int blocksize = inode->i_sb->s_blocksize;
485 	int i, n = 0;
486 	int err = 0;
487 	struct buffer_head *bh;
488 	int num;
489 	ext2_fsblk_t new_blocks[4];
490 	ext2_fsblk_t current_block;
491 
492 	num = ext2_alloc_blocks(inode, goal, indirect_blks,
493 				*blks, new_blocks, &err);
494 	if (err)
495 		return err;
496 
497 	branch[0].key = cpu_to_le32(new_blocks[0]);
498 	/*
499 	 * metadata blocks and data blocks are allocated.
500 	 */
501 	for (n = 1; n <= indirect_blks;  n++) {
502 		/*
503 		 * Get buffer_head for parent block, zero it out
504 		 * and set the pointer to new one, then send
505 		 * parent to disk.
506 		 */
507 		bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
508 		if (unlikely(!bh)) {
509 			err = -ENOMEM;
510 			goto failed;
511 		}
512 		branch[n].bh = bh;
513 		lock_buffer(bh);
514 		memset(bh->b_data, 0, blocksize);
515 		branch[n].p = (__le32 *) bh->b_data + offsets[n];
516 		branch[n].key = cpu_to_le32(new_blocks[n]);
517 		*branch[n].p = branch[n].key;
518 		if ( n == indirect_blks) {
519 			current_block = new_blocks[n];
520 			/*
521 			 * End of chain, update the last new metablock of
522 			 * the chain to point to the new allocated
523 			 * data blocks numbers
524 			 */
525 			for (i=1; i < num; i++)
526 				*(branch[n].p + i) = cpu_to_le32(++current_block);
527 		}
528 		set_buffer_uptodate(bh);
529 		unlock_buffer(bh);
530 		mmb_mark_buffer_dirty(bh, &EXT2_I(inode)->i_metadata_bhs);
531 		/* We used to sync bh here if IS_SYNC(inode).
532 		 * But we now rely upon generic_write_sync()
533 		 * and b_inode_buffers.  But not for directories.
534 		 */
535 		if (S_ISDIR(inode->i_mode) && IS_DIRSYNC(inode))
536 			sync_dirty_buffer(bh);
537 	}
538 	*blks = num;
539 	return err;
540 
541 failed:
542 	for (i = 1; i < n; i++)
543 		bforget(branch[i].bh);
544 	for (i = 0; i < indirect_blks; i++)
545 		ext2_free_blocks(inode, new_blocks[i], 1);
546 	ext2_free_blocks(inode, new_blocks[i], num);
547 	return err;
548 }
549 
550 /**
551  * ext2_splice_branch - splice the allocated branch onto inode.
552  * @inode: owner
553  * @block: (logical) number of block we are adding
554  * @where: location of missing link
555  * @num:   number of indirect blocks we are adding
556  * @blks:  number of direct blocks we are adding
557  *
558  * This function fills the missing link and does all housekeeping needed in
559  * inode (->i_blocks, etc.). In case of success we end up with the full
560  * chain to new block and return 0.
561  */
562 static void ext2_splice_branch(struct inode *inode,
563 			long block, Indirect *where, int num, int blks)
564 	__must_hold(&EXT2_I(inode)->truncate_mutex)
565 {
566 	int i;
567 	struct ext2_block_alloc_info *block_i;
568 	ext2_fsblk_t current_block;
569 
570 	block_i = EXT2_I(inode)->i_block_alloc_info;
571 
572 	/* XXX LOCKING probably should have i_meta_lock ?*/
573 	/* That's it */
574 
575 	*where->p = where->key;
576 
577 	/*
578 	 * Update the host buffer_head or inode to point to more just allocated
579 	 * direct blocks blocks
580 	 */
581 	if (num == 0 && blks > 1) {
582 		current_block = le32_to_cpu(where->key) + 1;
583 		for (i = 1; i < blks; i++)
584 			*(where->p + i ) = cpu_to_le32(current_block++);
585 	}
586 
587 	/*
588 	 * update the most recently allocated logical & physical block
589 	 * in i_block_alloc_info, to assist find the proper goal block for next
590 	 * allocation
591 	 */
592 	if (block_i) {
593 		block_i->last_alloc_logical_block = block + blks - 1;
594 		block_i->last_alloc_physical_block =
595 				le32_to_cpu(where[num].key) + blks - 1;
596 	}
597 
598 	/* We are done with atomic stuff, now do the rest of housekeeping */
599 
600 	/* had we spliced it onto indirect block? */
601 	if (where->bh)
602 		mmb_mark_buffer_dirty(where->bh, &EXT2_I(inode)->i_metadata_bhs);
603 
604 	inode_set_ctime_current(inode);
605 	mark_inode_dirty(inode);
606 }
607 
608 /*
609  * Allocation strategy is simple: if we have to allocate something, we will
610  * have to go the whole way to leaf. So let's do it before attaching anything
611  * to tree, set linkage between the newborn blocks, write them if sync is
612  * required, recheck the path, free and repeat if check fails, otherwise
613  * set the last missing link (that will protect us from any truncate-generated
614  * removals - all blocks on the path are immune now) and possibly force the
615  * write on the parent block.
616  * That has a nice additional property: no special recovery from the failed
617  * allocations is needed - we simply release blocks and do not touch anything
618  * reachable from inode.
619  *
620  * `handle' can be NULL if create == 0.
621  *
622  * return > 0, # of blocks mapped or allocated.
623  * return = 0, if plain lookup failed.
624  * return < 0, error case.
625  */
626 static int ext2_get_blocks(struct inode *inode,
627 			   sector_t iblock, unsigned long maxblocks,
628 			   u32 *bno, bool *new, bool *boundary,
629 			   int create)
630 {
631 	int err;
632 	int offsets[4];
633 	Indirect chain[4];
634 	Indirect *partial;
635 	ext2_fsblk_t goal;
636 	int indirect_blks;
637 	int blocks_to_boundary = 0;
638 	int depth;
639 	struct ext2_inode_info *ei = EXT2_I(inode);
640 	int count = 0;
641 	ext2_fsblk_t first_block = 0;
642 
643 	if (WARN_ON_ONCE(maxblocks == 0))
644 		return -EINVAL;
645 
646 	depth = ext2_block_to_path(inode,iblock,offsets,&blocks_to_boundary);
647 
648 	if (depth == 0)
649 		return -EIO;
650 
651 	partial = ext2_get_branch(inode, depth, offsets, chain, &err);
652 	/* Simplest case - block found, no allocation needed */
653 	if (!partial) {
654 		first_block = le32_to_cpu(chain[depth - 1].key);
655 		count++;
656 		/*map more blocks*/
657 		while (count < maxblocks && count <= blocks_to_boundary) {
658 			ext2_fsblk_t blk;
659 
660 			if (!verify_chain(chain, chain + depth - 1)) {
661 				/*
662 				 * Indirect block might be removed by
663 				 * truncate while we were reading it.
664 				 * Handling of that case: forget what we've
665 				 * got now, go to reread.
666 				 */
667 				err = -EAGAIN;
668 				count = 0;
669 				partial = chain + depth - 1;
670 				break;
671 			}
672 			blk = le32_to_cpu(*(chain[depth-1].p + count));
673 			if (blk == first_block + count)
674 				count++;
675 			else
676 				break;
677 		}
678 		if (err != -EAGAIN)
679 			goto got_it;
680 	}
681 
682 	/* Next simple case - plain lookup or failed read of indirect block */
683 	if (!create || err == -EIO)
684 		goto cleanup;
685 
686 	mutex_lock(&ei->truncate_mutex);
687 	/*
688 	 * If the indirect block is missing while we are reading
689 	 * the chain(ext2_get_branch() returns -EAGAIN err), or
690 	 * if the chain has been changed after we grab the semaphore,
691 	 * (either because another process truncated this branch, or
692 	 * another get_block allocated this branch) re-grab the chain to see if
693 	 * the request block has been allocated or not.
694 	 *
695 	 * Since we already block the truncate/other get_block
696 	 * at this point, we will have the current copy of the chain when we
697 	 * splice the branch into the tree.
698 	 */
699 	if (err == -EAGAIN || !verify_chain(chain, partial)) {
700 		while (partial > chain) {
701 			brelse(partial->bh);
702 			partial--;
703 		}
704 		partial = ext2_get_branch(inode, depth, offsets, chain, &err);
705 		if (!partial) {
706 			count++;
707 			mutex_unlock(&ei->truncate_mutex);
708 			goto got_it;
709 		}
710 
711 		if (err) {
712 			mutex_unlock(&ei->truncate_mutex);
713 			goto cleanup;
714 		}
715 	}
716 
717 	/*
718 	 * Okay, we need to do block allocation.  Lazily initialize the block
719 	 * allocation info here if necessary
720 	*/
721 	if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
722 		ext2_init_block_alloc_info(inode);
723 
724 	goal = ext2_find_goal(inode, iblock, partial);
725 
726 	/* the number of blocks need to allocate for [d,t]indirect blocks */
727 	indirect_blks = (chain + depth) - partial - 1;
728 	/*
729 	 * Next look up the indirect map to count the total number of
730 	 * direct blocks to allocate for this branch.
731 	 */
732 	count = ext2_blks_to_allocate(partial, indirect_blks,
733 					maxblocks, blocks_to_boundary);
734 	/*
735 	 * XXX ???? Block out ext2_truncate while we alter the tree
736 	 */
737 	err = ext2_alloc_branch(inode, indirect_blks, &count, goal,
738 				offsets + (partial - chain), partial);
739 
740 	if (err) {
741 		mutex_unlock(&ei->truncate_mutex);
742 		goto cleanup;
743 	}
744 
745 	*new = true;
746 
747 	ext2_splice_branch(inode, iblock, partial, indirect_blks, count);
748 	mutex_unlock(&ei->truncate_mutex);
749 got_it:
750 	if (count > blocks_to_boundary)
751 		*boundary = true;
752 	err = count;
753 	/* Clean up and exit */
754 	partial = chain + depth - 1;	/* the whole chain */
755 cleanup:
756 	while (partial > chain) {
757 		brelse(partial->bh);
758 		partial--;
759 	}
760 	if (err > 0)
761 		*bno = le32_to_cpu(chain[depth-1].key);
762 	return err;
763 }
764 
765 int ext2_get_block(struct inode *inode, sector_t iblock,
766 		struct buffer_head *bh_result, int create)
767 {
768 	unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
769 	bool new = false, boundary = false;
770 	u32 bno;
771 	int ret;
772 
773 	ret = ext2_get_blocks(inode, iblock, max_blocks, &bno, &new, &boundary,
774 			create);
775 	if (ret <= 0)
776 		return ret;
777 
778 	map_bh(bh_result, inode->i_sb, bno);
779 	bh_result->b_size = (ret << inode->i_blkbits);
780 	if (new)
781 		set_buffer_new(bh_result);
782 	if (boundary)
783 		set_buffer_boundary(bh_result);
784 	return 0;
785 
786 }
787 
788 static int ext2_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
789 		unsigned flags, struct iomap *iomap, struct iomap *srcmap)
790 {
791 	unsigned int blkbits = inode->i_blkbits;
792 	unsigned long first_block = offset >> blkbits;
793 	unsigned long max_blocks = (length + (1 << blkbits) - 1) >> blkbits;
794 	bool new = false, boundary = false;
795 	u32 bno;
796 	int ret;
797 	bool create = flags & IOMAP_WRITE;
798 
799 	/*
800 	 * For writes that could fill holes inside i_size on a
801 	 * DIO_SKIP_HOLES filesystem we forbid block creations: only
802 	 * overwrites are permitted.
803 	 */
804 	if ((flags & IOMAP_DIRECT) &&
805 	    (first_block << blkbits) < i_size_read(inode))
806 		create = 0;
807 
808 	/*
809 	 * Writes that span EOF might trigger an IO size update on completion,
810 	 * so consider them to be dirty for the purposes of O_DSYNC even if
811 	 * there is no other metadata changes pending or have been made here.
812 	 */
813 	if ((flags & IOMAP_WRITE) && offset + length > i_size_read(inode))
814 		iomap->flags |= IOMAP_F_DIRTY;
815 
816 	ret = ext2_get_blocks(inode, first_block, max_blocks,
817 			&bno, &new, &boundary, create);
818 	if (ret < 0)
819 		return ret;
820 
821 	iomap->flags = 0;
822 	iomap->offset = (u64)first_block << blkbits;
823 	iomap->bdev = inode->i_sb->s_bdev;
824 
825 	if (ret == 0) {
826 		/*
827 		 * Switch to buffered-io for writing to holes in a non-extent
828 		 * based filesystem to avoid stale data exposure problem.
829 		 */
830 		if (!create && (flags & IOMAP_WRITE) && (flags & IOMAP_DIRECT))
831 			return -ENOTBLK;
832 		iomap->type = IOMAP_HOLE;
833 		iomap->addr = IOMAP_NULL_ADDR;
834 		iomap->length = 1 << blkbits;
835 	} else {
836 		iomap->type = IOMAP_MAPPED;
837 		iomap->addr = (u64)bno << blkbits;
838 		iomap->length = (u64)ret << blkbits;
839 		iomap->flags |= IOMAP_F_MERGED;
840 	}
841 
842 	if (new)
843 		iomap->flags |= IOMAP_F_NEW;
844 	return 0;
845 }
846 
847 static int
848 ext2_iomap_end(struct inode *inode, loff_t offset, loff_t length,
849 		ssize_t written, unsigned flags, struct iomap *iomap)
850 {
851 	/*
852 	 * Switch to buffered-io in case of any error.
853 	 * Blocks allocated can be used by the buffered-io path.
854 	 */
855 	if ((flags & IOMAP_DIRECT) && (flags & IOMAP_WRITE) && written == 0)
856 		return -ENOTBLK;
857 
858 	if (iomap->type == IOMAP_MAPPED &&
859 	    written < length &&
860 	    (flags & IOMAP_WRITE))
861 		ext2_write_failed(inode->i_mapping, offset + length);
862 	return 0;
863 }
864 
865 static DEFINE_IOMAP_ITER_NEXT_END(ext2_iomap_next, ext2_iomap_begin,
866 				  ext2_iomap_end);
867 
868 const struct iomap_ops ext2_iomap_ops = {
869 	.iomap_next		= ext2_iomap_next,
870 };
871 
872 int ext2_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
873 		u64 start, u64 len)
874 {
875 	int ret;
876 	loff_t i_size;
877 
878 	inode_lock(inode);
879 	i_size = i_size_read(inode);
880 	/*
881 	 * iomap_fiemap() returns EINVAL for 0 length. Make sure we don't trim
882 	 * length to 0 but still trim the range as much as possible since
883 	 * ext2_get_blocks() iterates unmapped space block by block which is
884 	 * slow.
885 	 */
886 	if (i_size == 0)
887 		i_size = 1;
888 	len = min_t(u64, len, i_size);
889 	ret = iomap_fiemap(inode, fieinfo, start, len, &ext2_iomap_ops);
890 	inode_unlock(inode);
891 
892 	return ret;
893 }
894 
895 static int ext2_read_folio(struct file *file, struct folio *folio)
896 {
897 	return mpage_read_folio(folio, ext2_get_block);
898 }
899 
900 static void ext2_readahead(struct readahead_control *rac)
901 {
902 	mpage_readahead(rac, ext2_get_block);
903 }
904 
905 static int
906 ext2_write_begin(const struct kiocb *iocb, struct address_space *mapping,
907 		loff_t pos, unsigned len, struct folio **foliop, void **fsdata)
908 {
909 	int ret;
910 
911 	ret = block_write_begin(mapping, pos, len, foliop, ext2_get_block);
912 	if (ret < 0)
913 		ext2_write_failed(mapping, pos + len);
914 	return ret;
915 }
916 
917 static int ext2_write_end(const struct kiocb *iocb,
918 			  struct address_space *mapping,
919 			  loff_t pos, unsigned len, unsigned copied,
920 			  struct folio *folio, void *fsdata)
921 {
922 	int ret;
923 
924 	ret = generic_write_end(iocb, mapping, pos, len, copied, folio, fsdata);
925 	if (ret < len)
926 		ext2_write_failed(mapping, pos + len);
927 	return ret;
928 }
929 
930 static sector_t ext2_bmap(struct address_space *mapping, sector_t block)
931 {
932 	return generic_block_bmap(mapping,block,ext2_get_block);
933 }
934 
935 static int
936 ext2_writepages(struct address_space *mapping, struct writeback_control *wbc)
937 {
938 	return mpage_writepages(mapping, wbc, ext2_get_block);
939 }
940 
941 
942 const struct address_space_operations ext2_aops = {
943 	.dirty_folio		= block_dirty_folio,
944 	.invalidate_folio	= block_invalidate_folio,
945 	.read_folio		= ext2_read_folio,
946 	.readahead		= ext2_readahead,
947 	.write_begin		= ext2_write_begin,
948 	.write_end		= ext2_write_end,
949 	.bmap			= ext2_bmap,
950 	.writepages		= ext2_writepages,
951 	.migrate_folio		= buffer_migrate_folio,
952 	.is_partially_uptodate	= block_is_partially_uptodate,
953 	.error_remove_folio	= generic_error_remove_folio,
954 };
955 
956 
957 /*
958  * Probably it should be a library function... search for first non-zero word
959  * or memcmp with zero_page, whatever is better for particular architecture.
960  * Linus?
961  */
962 static inline int all_zeroes(__le32 *p, __le32 *q)
963 {
964 	while (p < q)
965 		if (*p++)
966 			return 0;
967 	return 1;
968 }
969 
970 /**
971  *	ext2_find_shared - find the indirect blocks for partial truncation.
972  *	@inode:	  inode in question
973  *	@depth:	  depth of the affected branch
974  *	@offsets: offsets of pointers in that branch (see ext2_block_to_path)
975  *	@chain:	  place to store the pointers to partial indirect blocks
976  *	@top:	  place to the (detached) top of branch
977  *
978  *	This is a helper function used by ext2_truncate().
979  *
980  *	When we do truncate() we may have to clean the ends of several indirect
981  *	blocks but leave the blocks themselves alive. Block is partially
982  *	truncated if some data below the new i_size is referred from it (and
983  *	it is on the path to the first completely truncated data block, indeed).
984  *	We have to free the top of that path along with everything to the right
985  *	of the path. Since no allocation past the truncation point is possible
986  *	until ext2_truncate() finishes, we may safely do the latter, but top
987  *	of branch may require special attention - pageout below the truncation
988  *	point might try to populate it.
989  *
990  *	We atomically detach the top of branch from the tree, store the block
991  *	number of its root in *@top, pointers to buffer_heads of partially
992  *	truncated blocks - in @chain[].bh and pointers to their last elements
993  *	that should not be removed - in @chain[].p. Return value is the pointer
994  *	to last filled element of @chain.
995  *
996  *	The work left to caller to do the actual freeing of subtrees:
997  *		a) free the subtree starting from *@top
998  *		b) free the subtrees whose roots are stored in
999  *			(@chain[i].p+1 .. end of @chain[i].bh->b_data)
1000  *		c) free the subtrees growing from the inode past the @chain[0].p
1001  *			(no partially truncated stuff there).
1002  */
1003 
1004 static Indirect *ext2_find_shared(struct inode *inode,
1005 				int depth,
1006 				int offsets[4],
1007 				Indirect chain[4],
1008 				__le32 *top)
1009 	__must_hold(&EXT2_I(inode)->truncate_mutex)
1010 {
1011 	Indirect *partial, *p;
1012 	int k, err;
1013 
1014 	*top = 0;
1015 	for (k = depth; k > 1 && !offsets[k-1]; k--)
1016 		;
1017 	partial = ext2_get_branch(inode, k, offsets, chain, &err);
1018 	if (!partial)
1019 		partial = chain + k-1;
1020 	/*
1021 	 * If the branch acquired continuation since we've looked at it -
1022 	 * fine, it should all survive and (new) top doesn't belong to us.
1023 	 */
1024 	write_lock(&EXT2_I(inode)->i_meta_lock);
1025 	if (!partial->key && *partial->p) {
1026 		write_unlock(&EXT2_I(inode)->i_meta_lock);
1027 		goto no_top;
1028 	}
1029 	for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
1030 		;
1031 	/*
1032 	 * OK, we've found the last block that must survive. The rest of our
1033 	 * branch should be detached before unlocking. However, if that rest
1034 	 * of branch is all ours and does not grow immediately from the inode
1035 	 * it's easier to cheat and just decrement partial->p.
1036 	 */
1037 	if (p == chain + k - 1 && p > chain) {
1038 		p->p--;
1039 	} else {
1040 		*top = *p->p;
1041 		*p->p = 0;
1042 	}
1043 	write_unlock(&EXT2_I(inode)->i_meta_lock);
1044 
1045 	while(partial > p)
1046 	{
1047 		brelse(partial->bh);
1048 		partial--;
1049 	}
1050 no_top:
1051 	return partial;
1052 }
1053 
1054 /**
1055  *	ext2_free_data - free a list of data blocks
1056  *	@inode:	inode we are dealing with
1057  *	@p:	array of block numbers
1058  *	@q:	points immediately past the end of array
1059  *
1060  *	We are freeing all blocks referred from that array (numbers are
1061  *	stored as little-endian 32-bit) and updating @inode->i_blocks
1062  *	appropriately.
1063  */
1064 static inline void ext2_free_data(struct inode *inode, __le32 *p, __le32 *q)
1065 	__must_hold(&EXT2_I(inode)->truncate_mutex)
1066 {
1067 	ext2_fsblk_t block_to_free = 0, count = 0;
1068 	ext2_fsblk_t nr;
1069 
1070 	for ( ; p < q ; p++) {
1071 		nr = le32_to_cpu(*p);
1072 		if (nr) {
1073 			*p = 0;
1074 			/* accumulate blocks to free if they're contiguous */
1075 			if (count == 0)
1076 				goto free_this;
1077 			else if (block_to_free == nr - count)
1078 				count++;
1079 			else {
1080 				ext2_free_blocks (inode, block_to_free, count);
1081 				mark_inode_dirty(inode);
1082 			free_this:
1083 				block_to_free = nr;
1084 				count = 1;
1085 			}
1086 		}
1087 	}
1088 	if (count > 0) {
1089 		ext2_free_blocks (inode, block_to_free, count);
1090 		mark_inode_dirty(inode);
1091 	}
1092 }
1093 
1094 /**
1095  *	ext2_free_branches - free an array of branches
1096  *	@inode:	inode we are dealing with
1097  *	@p:	array of block numbers
1098  *	@q:	pointer immediately past the end of array
1099  *	@depth:	depth of the branches to free
1100  *
1101  *	We are freeing all blocks referred from these branches (numbers are
1102  *	stored as little-endian 32-bit) and updating @inode->i_blocks
1103  *	appropriately.
1104  */
1105 static void ext2_free_branches(struct inode *inode, __le32 *p, __le32 *q, int depth)
1106 	__must_hold(&EXT2_I(inode)->truncate_mutex)
1107 {
1108 	struct buffer_head * bh;
1109 	ext2_fsblk_t nr;
1110 
1111 	if (depth--) {
1112 		int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
1113 		for ( ; p < q ; p++) {
1114 			nr = le32_to_cpu(*p);
1115 			if (!nr)
1116 				continue;
1117 			*p = 0;
1118 			bh = sb_bread(inode->i_sb, nr);
1119 			/*
1120 			 * A read failure? Report error and clear slot
1121 			 * (should be rare).
1122 			 */
1123 			if (!bh) {
1124 				ext2_error(inode->i_sb, "ext2_free_branches",
1125 					"Read failure, inode=%llu, block=%ld",
1126 					inode->i_ino, nr);
1127 				continue;
1128 			}
1129 			ext2_free_branches(inode,
1130 					   (__le32*)bh->b_data,
1131 					   (__le32*)bh->b_data + addr_per_block,
1132 					   depth);
1133 			bforget(bh);
1134 			ext2_free_blocks(inode, nr, 1);
1135 			mark_inode_dirty(inode);
1136 		}
1137 	} else
1138 		ext2_free_data(inode, p, q);
1139 }
1140 
1141 /* mapping->invalidate_lock must be held when calling this function */
1142 static void __ext2_truncate_blocks(struct inode *inode, loff_t offset)
1143 {
1144 	__le32 *i_data = EXT2_I(inode)->i_data;
1145 	struct ext2_inode_info *ei = EXT2_I(inode);
1146 	int addr_per_block = EXT2_ADDR_PER_BLOCK(inode->i_sb);
1147 	int offsets[4];
1148 	Indirect chain[4];
1149 	Indirect *partial;
1150 	__le32 nr = 0;
1151 	int n;
1152 	long iblock;
1153 	unsigned blocksize;
1154 	blocksize = inode->i_sb->s_blocksize;
1155 	iblock = (offset + blocksize-1) >> EXT2_BLOCK_SIZE_BITS(inode->i_sb);
1156 
1157 
1158 	n = ext2_block_to_path(inode, iblock, offsets, NULL);
1159 	if (n == 0)
1160 		return;
1161 
1162 	/*
1163 	 * From here we block out all ext2_get_block() callers who want to
1164 	 * modify the block allocation tree.
1165 	 */
1166 	mutex_lock(&ei->truncate_mutex);
1167 
1168 	if (n == 1) {
1169 		ext2_free_data(inode, i_data+offsets[0],
1170 					i_data + EXT2_NDIR_BLOCKS);
1171 		goto do_indirects;
1172 	}
1173 
1174 	partial = ext2_find_shared(inode, n, offsets, chain, &nr);
1175 	/* Kill the top of shared branch (already detached) */
1176 	if (nr) {
1177 		if (partial == chain)
1178 			mark_inode_dirty(inode);
1179 		else
1180 			mmb_mark_buffer_dirty(partial->bh,
1181 					      &EXT2_I(inode)->i_metadata_bhs);
1182 		ext2_free_branches(inode, &nr, &nr+1, (chain+n-1) - partial);
1183 	}
1184 	/* Clear the ends of indirect blocks on the shared branch */
1185 	while (partial > chain) {
1186 		ext2_free_branches(inode,
1187 				   partial->p + 1,
1188 				   (__le32*)partial->bh->b_data+addr_per_block,
1189 				   (chain+n-1) - partial);
1190 		mmb_mark_buffer_dirty(partial->bh,
1191 				      &EXT2_I(inode)->i_metadata_bhs);
1192 		brelse (partial->bh);
1193 		partial--;
1194 	}
1195 do_indirects:
1196 	/* Kill the remaining (whole) subtrees */
1197 	switch (offsets[0]) {
1198 		default:
1199 			nr = i_data[EXT2_IND_BLOCK];
1200 			if (nr) {
1201 				i_data[EXT2_IND_BLOCK] = 0;
1202 				mark_inode_dirty(inode);
1203 				ext2_free_branches(inode, &nr, &nr+1, 1);
1204 			}
1205 			fallthrough;
1206 		case EXT2_IND_BLOCK:
1207 			nr = i_data[EXT2_DIND_BLOCK];
1208 			if (nr) {
1209 				i_data[EXT2_DIND_BLOCK] = 0;
1210 				mark_inode_dirty(inode);
1211 				ext2_free_branches(inode, &nr, &nr+1, 2);
1212 			}
1213 			fallthrough;
1214 		case EXT2_DIND_BLOCK:
1215 			nr = i_data[EXT2_TIND_BLOCK];
1216 			if (nr) {
1217 				i_data[EXT2_TIND_BLOCK] = 0;
1218 				mark_inode_dirty(inode);
1219 				ext2_free_branches(inode, &nr, &nr+1, 3);
1220 			}
1221 			break;
1222 		case EXT2_TIND_BLOCK:
1223 			;
1224 	}
1225 
1226 	ext2_discard_reservation(inode);
1227 
1228 	mutex_unlock(&ei->truncate_mutex);
1229 }
1230 
1231 static void ext2_truncate_blocks(struct inode *inode, loff_t offset)
1232 {
1233 	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1234 	    S_ISLNK(inode->i_mode)))
1235 		return;
1236 	if (ext2_inode_is_fast_symlink(inode))
1237 		return;
1238 
1239 	filemap_invalidate_lock(inode->i_mapping);
1240 	__ext2_truncate_blocks(inode, offset);
1241 	filemap_invalidate_unlock(inode->i_mapping);
1242 }
1243 
1244 static int ext2_setsize(struct inode *inode, loff_t newsize)
1245 {
1246 	int error;
1247 
1248 	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1249 	    S_ISLNK(inode->i_mode)))
1250 		return -EINVAL;
1251 	if (ext2_inode_is_fast_symlink(inode))
1252 		return -EINVAL;
1253 	if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1254 		return -EPERM;
1255 
1256 	inode_dio_wait(inode);
1257 
1258 	error = block_truncate_page(inode->i_mapping, newsize, ext2_get_block);
1259 	if (error)
1260 		return error;
1261 
1262 	filemap_invalidate_lock(inode->i_mapping);
1263 	truncate_setsize(inode, newsize);
1264 	__ext2_truncate_blocks(inode, newsize);
1265 	filemap_invalidate_unlock(inode->i_mapping);
1266 
1267 	inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
1268 	mark_inode_dirty(inode);
1269 	if (inode_needs_sync(inode))
1270 		sync_inode_metadata(inode, 1);
1271 
1272 	return 0;
1273 }
1274 
1275 static struct ext2_inode *ext2_get_inode(struct super_block *sb, ino_t ino,
1276 					struct buffer_head **p)
1277 {
1278 	struct buffer_head * bh;
1279 	unsigned long block_group;
1280 	unsigned long block;
1281 	unsigned long offset;
1282 	struct ext2_group_desc * gdp;
1283 
1284 	*p = NULL;
1285 	if ((ino != EXT2_ROOT_INO && ino < EXT2_FIRST_INO(sb)) ||
1286 	    ino > le32_to_cpu(EXT2_SB(sb)->s_es->s_inodes_count))
1287 		goto Einval;
1288 
1289 	block_group = (ino - 1) / EXT2_INODES_PER_GROUP(sb);
1290 	gdp = ext2_get_group_desc(sb, block_group, NULL);
1291 	if (!gdp)
1292 		goto Egdp;
1293 	/*
1294 	 * Figure out the offset within the block group inode table
1295 	 */
1296 	offset = ((ino - 1) % EXT2_INODES_PER_GROUP(sb)) * EXT2_INODE_SIZE(sb);
1297 	block = le32_to_cpu(gdp->bg_inode_table) +
1298 		(offset >> EXT2_BLOCK_SIZE_BITS(sb));
1299 	if (!(bh = sb_bread(sb, block)))
1300 		goto Eio;
1301 
1302 	*p = bh;
1303 	offset &= (EXT2_BLOCK_SIZE(sb) - 1);
1304 	return (struct ext2_inode *) (bh->b_data + offset);
1305 
1306 Einval:
1307 	ext2_error(sb, "ext2_get_inode", "bad inode number: %lu",
1308 		   (unsigned long) ino);
1309 	return ERR_PTR(-EINVAL);
1310 Eio:
1311 	ext2_error(sb, "ext2_get_inode",
1312 		   "unable to read inode block - inode=%lu, block=%lu",
1313 		   (unsigned long) ino, block);
1314 Egdp:
1315 	return ERR_PTR(-EIO);
1316 }
1317 
1318 void ext2_set_inode_flags(struct inode *inode)
1319 {
1320 	unsigned int flags = EXT2_I(inode)->i_flags;
1321 
1322 	inode->i_flags &= ~(S_SYNC | S_APPEND | S_IMMUTABLE | S_NOATIME |
1323 				S_DIRSYNC);
1324 	if (flags & EXT2_SYNC_FL)
1325 		inode->i_flags |= S_SYNC;
1326 	if (flags & EXT2_APPEND_FL)
1327 		inode->i_flags |= S_APPEND;
1328 	if (flags & EXT2_IMMUTABLE_FL)
1329 		inode->i_flags |= S_IMMUTABLE;
1330 	if (flags & EXT2_NOATIME_FL)
1331 		inode->i_flags |= S_NOATIME;
1332 	if (flags & EXT2_DIRSYNC_FL)
1333 		inode->i_flags |= S_DIRSYNC;
1334 }
1335 
1336 void ext2_set_file_ops(struct inode *inode)
1337 {
1338 	inode->i_op = &ext2_file_inode_operations;
1339 	inode->i_fop = &ext2_file_operations;
1340 	inode->i_mapping->a_ops = &ext2_aops;
1341 }
1342 
1343 struct inode *ext2_iget (struct super_block *sb, unsigned long ino)
1344 {
1345 	struct ext2_inode_info *ei;
1346 	struct buffer_head * bh = NULL;
1347 	struct ext2_inode *raw_inode;
1348 	struct inode *inode;
1349 	long ret = -EIO;
1350 	int n;
1351 	uid_t i_uid;
1352 	gid_t i_gid;
1353 
1354 	inode = iget_locked(sb, ino);
1355 	if (!inode)
1356 		return ERR_PTR(-ENOMEM);
1357 	if (!(inode_state_read_once(inode) & I_NEW))
1358 		return inode;
1359 
1360 	ei = EXT2_I(inode);
1361 	ei->i_block_alloc_info = NULL;
1362 
1363 	raw_inode = ext2_get_inode(inode->i_sb, ino, &bh);
1364 	if (IS_ERR(raw_inode)) {
1365 		ret = PTR_ERR(raw_inode);
1366  		goto bad_inode;
1367 	}
1368 
1369 	inode->i_mode = le16_to_cpu(raw_inode->i_mode);
1370 	i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
1371 	i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
1372 	if (!(test_opt (inode->i_sb, NO_UID32))) {
1373 		i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
1374 		i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
1375 	}
1376 	i_uid_write(inode, i_uid);
1377 	i_gid_write(inode, i_gid);
1378 	set_nlink(inode, le16_to_cpu(raw_inode->i_links_count));
1379 	inode->i_size = le32_to_cpu(raw_inode->i_size);
1380 	inode_set_atime(inode, (signed)le32_to_cpu(raw_inode->i_atime), 0);
1381 	inode_set_ctime(inode, (signed)le32_to_cpu(raw_inode->i_ctime), 0);
1382 	inode_set_mtime(inode, (signed)le32_to_cpu(raw_inode->i_mtime), 0);
1383 	ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
1384 	/* We now have enough fields to check if the inode was active or not.
1385 	 * This is needed because nfsd might try to access dead inodes
1386 	 * the test is that same one that e2fsck uses
1387 	 * NeilBrown 1999oct15
1388 	 */
1389 	if (inode->i_nlink == 0) {
1390 		if (inode->i_mode == 0 || ei->i_dtime) {
1391 			/* this inode is deleted */
1392 			ret = -ESTALE;
1393 		} else {
1394 			ext2_error(sb, __func__,
1395 				   "inode %lu has zero i_nlink with mode 0%o and no dtime, "
1396 				   "filesystem may be corrupt",
1397 				   ino, inode->i_mode);
1398 			ret = -EFSCORRUPTED;
1399 		}
1400 		goto bad_inode;
1401 	}
1402 	inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
1403 	ei->i_flags = le32_to_cpu(raw_inode->i_flags);
1404 	ext2_set_inode_flags(inode);
1405 	ei->i_faddr = le32_to_cpu(raw_inode->i_faddr);
1406 	ei->i_frag_no = raw_inode->i_frag;
1407 	ei->i_frag_size = raw_inode->i_fsize;
1408 	ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
1409 	ei->i_dir_acl = 0;
1410 
1411 	if (ei->i_file_acl &&
1412 	    !ext2_data_block_valid(EXT2_SB(sb), ei->i_file_acl, 1)) {
1413 		ext2_error(sb, "ext2_iget", "bad extended attribute block %u",
1414 			   ei->i_file_acl);
1415 		ret = -EFSCORRUPTED;
1416 		goto bad_inode;
1417 	}
1418 
1419 	if (S_ISREG(inode->i_mode))
1420 		inode->i_size |= ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
1421 	else
1422 		ei->i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
1423 	if (i_size_read(inode) < 0) {
1424 		ret = -EFSCORRUPTED;
1425 		goto bad_inode;
1426 	}
1427 	ei->i_dtime = 0;
1428 	inode->i_generation = le32_to_cpu(raw_inode->i_generation);
1429 	ei->i_state = 0;
1430 	ei->i_block_group = (ino - 1) / EXT2_INODES_PER_GROUP(inode->i_sb);
1431 	ei->i_dir_start_lookup = 0;
1432 
1433 	/*
1434 	 * NOTE! The in-memory inode i_data array is in little-endian order
1435 	 * even on big-endian machines: we do NOT byteswap the block numbers!
1436 	 */
1437 	for (n = 0; n < EXT2_N_BLOCKS; n++)
1438 		ei->i_data[n] = raw_inode->i_block[n];
1439 
1440 	if (S_ISREG(inode->i_mode)) {
1441 		ext2_set_file_ops(inode);
1442 	} else if (S_ISDIR(inode->i_mode)) {
1443 		inode->i_op = &ext2_dir_inode_operations;
1444 		inode->i_fop = &ext2_dir_operations;
1445 		inode->i_mapping->a_ops = &ext2_aops;
1446 	} else if (S_ISLNK(inode->i_mode)) {
1447 		if (ext2_inode_is_fast_symlink(inode)) {
1448 			inode->i_link = (char *)ei->i_data;
1449 			inode->i_op = &ext2_fast_symlink_inode_operations;
1450 			nd_terminate_link(ei->i_data, inode->i_size,
1451 				sizeof(ei->i_data) - 1);
1452 		} else {
1453 			inode->i_op = &ext2_symlink_inode_operations;
1454 			inode_nohighmem(inode);
1455 			inode->i_mapping->a_ops = &ext2_aops;
1456 		}
1457 	} else {
1458 		inode->i_op = &ext2_special_inode_operations;
1459 		if (raw_inode->i_block[0])
1460 			init_special_inode(inode, inode->i_mode,
1461 			   old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
1462 		else
1463 			init_special_inode(inode, inode->i_mode,
1464 			   new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
1465 	}
1466 	brelse (bh);
1467 	unlock_new_inode(inode);
1468 	return inode;
1469 
1470 bad_inode:
1471 	brelse(bh);
1472 	iget_failed(inode);
1473 	return ERR_PTR(ret);
1474 }
1475 
1476 int ext2_write_inode(struct inode *inode, struct writeback_control *wbc)
1477 {
1478 	struct ext2_inode_info *ei = EXT2_I(inode);
1479 	struct super_block *sb = inode->i_sb;
1480 	ino_t ino = inode->i_ino;
1481 	uid_t uid = i_uid_read(inode);
1482 	gid_t gid = i_gid_read(inode);
1483 	struct buffer_head * bh;
1484 	struct ext2_inode * raw_inode = ext2_get_inode(sb, ino, &bh);
1485 	int n;
1486 	int err = 0;
1487 
1488 	if (IS_ERR(raw_inode))
1489  		return -EIO;
1490 
1491 	/* For fields not tracking in the in-memory inode,
1492 	 * initialise them to zero for new inodes. */
1493 	if (ei->i_state & EXT2_STATE_NEW)
1494 		memset(raw_inode, 0, EXT2_SB(sb)->s_inode_size);
1495 
1496 	raw_inode->i_mode = cpu_to_le16(inode->i_mode);
1497 	if (!(test_opt(sb, NO_UID32))) {
1498 		raw_inode->i_uid_low = cpu_to_le16(low_16_bits(uid));
1499 		raw_inode->i_gid_low = cpu_to_le16(low_16_bits(gid));
1500 /*
1501  * Fix up interoperability with old kernels. Otherwise, old inodes get
1502  * re-used with the upper 16 bits of the uid/gid intact
1503  */
1504 		if (!ei->i_dtime) {
1505 			raw_inode->i_uid_high = cpu_to_le16(high_16_bits(uid));
1506 			raw_inode->i_gid_high = cpu_to_le16(high_16_bits(gid));
1507 		} else {
1508 			raw_inode->i_uid_high = 0;
1509 			raw_inode->i_gid_high = 0;
1510 		}
1511 	} else {
1512 		raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(uid));
1513 		raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(gid));
1514 		raw_inode->i_uid_high = 0;
1515 		raw_inode->i_gid_high = 0;
1516 	}
1517 	raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
1518 	raw_inode->i_size = cpu_to_le32(inode->i_size);
1519 	raw_inode->i_atime = cpu_to_le32(inode_get_atime_sec(inode));
1520 	raw_inode->i_ctime = cpu_to_le32(inode_get_ctime_sec(inode));
1521 	raw_inode->i_mtime = cpu_to_le32(inode_get_mtime_sec(inode));
1522 
1523 	raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
1524 	raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
1525 	raw_inode->i_flags = cpu_to_le32(ei->i_flags);
1526 	raw_inode->i_faddr = cpu_to_le32(ei->i_faddr);
1527 	raw_inode->i_frag = ei->i_frag_no;
1528 	raw_inode->i_fsize = ei->i_frag_size;
1529 	raw_inode->i_file_acl = cpu_to_le32(ei->i_file_acl);
1530 	if (!S_ISREG(inode->i_mode))
1531 		raw_inode->i_dir_acl = cpu_to_le32(ei->i_dir_acl);
1532 	else {
1533 		raw_inode->i_size_high = cpu_to_le32(inode->i_size >> 32);
1534 		if (inode->i_size > 0x7fffffffULL) {
1535 			if (!EXT2_HAS_RO_COMPAT_FEATURE(sb,
1536 					EXT2_FEATURE_RO_COMPAT_LARGE_FILE) ||
1537 			    EXT2_SB(sb)->s_es->s_rev_level ==
1538 					cpu_to_le32(EXT2_GOOD_OLD_REV)) {
1539 			       /* If this is the first large file
1540 				* created, add a flag to the superblock.
1541 				*/
1542 				spin_lock(&EXT2_SB(sb)->s_lock);
1543 				ext2_update_dynamic_rev(sb);
1544 				EXT2_SET_RO_COMPAT_FEATURE(sb,
1545 					EXT2_FEATURE_RO_COMPAT_LARGE_FILE);
1546 				spin_unlock(&EXT2_SB(sb)->s_lock);
1547 				ext2_sync_super(sb, EXT2_SB(sb)->s_es, 1);
1548 			}
1549 		}
1550 	}
1551 
1552 	raw_inode->i_generation = cpu_to_le32(inode->i_generation);
1553 	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
1554 		if (old_valid_dev(inode->i_rdev)) {
1555 			raw_inode->i_block[0] =
1556 				cpu_to_le32(old_encode_dev(inode->i_rdev));
1557 			raw_inode->i_block[1] = 0;
1558 		} else {
1559 			raw_inode->i_block[0] = 0;
1560 			raw_inode->i_block[1] =
1561 				cpu_to_le32(new_encode_dev(inode->i_rdev));
1562 			raw_inode->i_block[2] = 0;
1563 		}
1564 	} else for (n = 0; n < EXT2_N_BLOCKS; n++)
1565 		raw_inode->i_block[n] = ei->i_data[n];
1566 	mark_buffer_dirty(bh);
1567 	ei->i_state &= ~EXT2_STATE_NEW;
1568 	brelse (bh);
1569 	set_inode_metadata_writeback(inode);
1570 	return err;
1571 }
1572 
1573 int ext2_sync_inode_metadata(struct inode *inode, struct writeback_control *wbc)
1574 {
1575 	struct buffer_head *bh;
1576 	struct ext2_inode *raw_inode = ext2_get_inode(inode->i_sb, inode->i_ino,
1577 						      &bh);
1578 	int err = 0;
1579 
1580 	if (IS_ERR(raw_inode))
1581 		return -EIO;
1582 	err = mmb_sync(&EXT2_I(inode)->i_metadata_bhs);
1583 	if (err) {
1584 		ext2_error(inode->i_sb, __func__,
1585 			"Error syncing inode metadata ino=%lu\n",
1586 			(unsigned long)inode->i_ino);
1587 		goto out;
1588 	}
1589 	sync_dirty_buffer(bh);
1590 	if (buffer_write_io_error(bh)) {
1591 		ext2_error(inode->i_sb, __func__,
1592 			"IO error syncing inode %lu\n",
1593 			(unsigned long)inode->i_ino);
1594 		err = -EIO;
1595 	}
1596 out:
1597 	brelse(bh);
1598 	return err;
1599 }
1600 
1601 int ext2_getattr(const struct mnt_idmap *idmap, const struct path *path,
1602 		 struct kstat *stat, u32 request_mask, unsigned int query_flags)
1603 {
1604 	struct inode *inode = d_inode(path->dentry);
1605 	struct ext2_inode_info *ei = EXT2_I(inode);
1606 	unsigned int flags;
1607 
1608 	flags = ei->i_flags & EXT2_FL_USER_VISIBLE;
1609 	if (flags & EXT2_APPEND_FL)
1610 		stat->attributes |= STATX_ATTR_APPEND;
1611 	if (flags & EXT2_COMPR_FL)
1612 		stat->attributes |= STATX_ATTR_COMPRESSED;
1613 	if (flags & EXT2_IMMUTABLE_FL)
1614 		stat->attributes |= STATX_ATTR_IMMUTABLE;
1615 	if (flags & EXT2_NODUMP_FL)
1616 		stat->attributes |= STATX_ATTR_NODUMP;
1617 	stat->attributes_mask |= (STATX_ATTR_APPEND |
1618 			STATX_ATTR_COMPRESSED |
1619 			STATX_ATTR_ENCRYPTED |
1620 			STATX_ATTR_IMMUTABLE |
1621 			STATX_ATTR_NODUMP);
1622 
1623 	generic_fillattr(&nop_mnt_idmap, request_mask, inode, stat);
1624 	return 0;
1625 }
1626 
1627 int ext2_setattr(const struct mnt_idmap *idmap, struct dentry *dentry,
1628 		 struct iattr *iattr)
1629 {
1630 	struct inode *inode = d_inode(dentry);
1631 	int error;
1632 
1633 	error = setattr_prepare(&nop_mnt_idmap, dentry, iattr);
1634 	if (error)
1635 		return error;
1636 
1637 	if (is_quota_modification(&nop_mnt_idmap, inode, iattr)) {
1638 		error = dquot_initialize(inode);
1639 		if (error)
1640 			return error;
1641 	}
1642 	if (i_uid_needs_update(&nop_mnt_idmap, iattr, inode) ||
1643 	    i_gid_needs_update(&nop_mnt_idmap, iattr, inode)) {
1644 		error = dquot_transfer(&nop_mnt_idmap, inode, iattr);
1645 		if (error)
1646 			return error;
1647 	}
1648 	if (iattr->ia_valid & ATTR_SIZE && iattr->ia_size != inode->i_size) {
1649 		error = ext2_setsize(inode, iattr->ia_size);
1650 		if (error)
1651 			return error;
1652 	}
1653 	setattr_copy(&nop_mnt_idmap, inode, iattr);
1654 	if (iattr->ia_valid & ATTR_MODE)
1655 		error = posix_acl_chmod(&nop_mnt_idmap, dentry, inode->i_mode);
1656 	mark_inode_dirty(inode);
1657 
1658 	return error;
1659 }
1660