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