xref: /freebsd/sbin/fsck_ffs/inode.c (revision 08aba0aec7b7f676ccc3f7886f59f277d668d5b4)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if 0
33 #ifndef lint
34 static const char sccsid[] = "@(#)inode.c	8.8 (Berkeley) 4/28/95";
35 #endif /* not lint */
36 #endif
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/stdint.h>
42 #include <sys/sysctl.h>
43 
44 #include <ufs/ufs/dinode.h>
45 #include <ufs/ufs/dir.h>
46 #include <ufs/ffs/fs.h>
47 
48 #include <err.h>
49 #include <pwd.h>
50 #include <string.h>
51 #include <time.h>
52 #include <libufs.h>
53 
54 #include "fsck.h"
55 
56 struct bufarea *icachebp;	/* inode cache buffer */
57 
58 static int iblock(struct inodesc *, off_t isize, int type);
59 static ufs2_daddr_t indir_blkatoff(ufs2_daddr_t, ino_t, ufs_lbn_t, ufs_lbn_t,
60     struct bufarea **);
61 
62 int
63 ckinode(union dinode *dp, struct inodesc *idesc)
64 {
65 	off_t remsize, sizepb;
66 	int i, offset, ret;
67 	struct inode ip;
68 	union dinode dino;
69 	ufs2_daddr_t ndb;
70 	mode_t mode;
71 	char pathbuf[MAXPATHLEN + 1];
72 
73 	if (idesc->id_fix != IGNORE)
74 		idesc->id_fix = DONTKNOW;
75 	idesc->id_dp = dp;
76 	idesc->id_lbn = -1;
77 	idesc->id_lballoc = -1;
78 	idesc->id_level = 0;
79 	idesc->id_entryno = 0;
80 	idesc->id_filesize = DIP(dp, di_size);
81 	mode = DIP(dp, di_mode) & IFMT;
82 	if (mode == IFBLK || mode == IFCHR || (mode == IFLNK &&
83 	    DIP(dp, di_size) < (unsigned)sblock.fs_maxsymlinklen))
84 		return (KEEPON);
85 	if (sblock.fs_magic == FS_UFS1_MAGIC)
86 		dino.dp1 = dp->dp1;
87 	else
88 		dino.dp2 = dp->dp2;
89 	ndb = howmany(DIP(&dino, di_size), sblock.fs_bsize);
90 	for (i = 0; i < UFS_NDADDR; i++) {
91 		idesc->id_lbn++;
92 		if (--ndb == 0 &&
93 		    (offset = blkoff(&sblock, DIP(&dino, di_size))) != 0)
94 			idesc->id_numfrags =
95 				numfrags(&sblock, fragroundup(&sblock, offset));
96 		else
97 			idesc->id_numfrags = sblock.fs_frag;
98 		if (DIP(&dino, di_db[i]) == 0) {
99 			if (idesc->id_type == DATA && ndb >= 0) {
100 				/* An empty block in a directory XXX */
101 				getpathname(pathbuf, idesc->id_number,
102 						idesc->id_number);
103 				pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS",
104 					pathbuf);
105 				if (reply("ADJUST LENGTH") == 1) {
106 					ginode(idesc->id_number, &ip);
107 					DIP_SET(ip.i_dp, di_size,
108 					    i * sblock.fs_bsize);
109 					printf(
110 					    "YOU MUST RERUN FSCK AFTERWARDS\n");
111 					rerun = 1;
112 					inodirty(&ip);
113 					irelse(&ip);
114 				}
115 			}
116 			continue;
117 		}
118 		idesc->id_blkno = DIP(&dino, di_db[i]);
119 		if (idesc->id_type != DATA)
120 			ret = (*idesc->id_func)(idesc);
121 		else
122 			ret = dirscan(idesc);
123 		if (ret & STOP)
124 			return (ret);
125 	}
126 	idesc->id_numfrags = sblock.fs_frag;
127 	remsize = DIP(&dino, di_size) - sblock.fs_bsize * UFS_NDADDR;
128 	sizepb = sblock.fs_bsize;
129 	for (i = 0; i < UFS_NIADDR; i++) {
130 		sizepb *= NINDIR(&sblock);
131 		idesc->id_level = i + 1;
132 		if (DIP(&dino, di_ib[i])) {
133 			idesc->id_blkno = DIP(&dino, di_ib[i]);
134 			ret = iblock(idesc, remsize, BT_LEVEL1 + i);
135 			if (ret & STOP)
136 				return (ret);
137 		} else if (remsize > 0) {
138 			idesc->id_lbn += sizepb / sblock.fs_bsize;
139 			if (idesc->id_type == DATA) {
140 				/* An empty block in a directory XXX */
141 				getpathname(pathbuf, idesc->id_number,
142 						idesc->id_number);
143 				pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS",
144 					pathbuf);
145 				if (reply("ADJUST LENGTH") == 1) {
146 					ginode(idesc->id_number, &ip);
147 					DIP_SET(ip.i_dp, di_size,
148 					    DIP(ip.i_dp, di_size) - remsize);
149 					remsize = 0;
150 					printf(
151 					    "YOU MUST RERUN FSCK AFTERWARDS\n");
152 					rerun = 1;
153 					inodirty(&ip);
154 					irelse(&ip);
155 					break;
156 				}
157 			}
158 		}
159 		remsize -= sizepb;
160 	}
161 	return (KEEPON);
162 }
163 
164 static int
165 iblock(struct inodesc *idesc, off_t isize, int type)
166 {
167 	struct inode ip;
168 	struct bufarea *bp;
169 	int i, n, (*func)(struct inodesc *), nif;
170 	off_t sizepb;
171 	char buf[BUFSIZ];
172 	char pathbuf[MAXPATHLEN + 1];
173 
174 	if (idesc->id_type != DATA) {
175 		func = idesc->id_func;
176 		if (((n = (*func)(idesc)) & KEEPON) == 0)
177 			return (n);
178 	} else
179 		func = dirscan;
180 	bp = getdatablk(idesc->id_blkno, sblock.fs_bsize, type);
181 	if (bp->b_errs != 0) {
182 		brelse(bp);
183 		return (SKIP);
184 	}
185 	idesc->id_bp = bp;
186 	idesc->id_level--;
187 	for (sizepb = sblock.fs_bsize, i = 0; i < idesc->id_level; i++)
188 		sizepb *= NINDIR(&sblock);
189 	if (howmany(isize, sizepb) > NINDIR(&sblock))
190 		nif = NINDIR(&sblock);
191 	else
192 		nif = howmany(isize, sizepb);
193 	if (idesc->id_func == pass1check && nif < NINDIR(&sblock)) {
194 		for (i = nif; i < NINDIR(&sblock); i++) {
195 			if (IBLK(bp, i) == 0)
196 				continue;
197 			(void)sprintf(buf, "PARTIALLY TRUNCATED INODE I=%lu",
198 			    (u_long)idesc->id_number);
199 			if (preen) {
200 				pfatal("%s", buf);
201 			} else if (dofix(idesc, buf)) {
202 				IBLK_SET(bp, i, 0);
203 				dirty(bp);
204 			}
205 		}
206 		flush(fswritefd, bp);
207 	}
208 	for (i = 0; i < nif; i++) {
209 		if (IBLK(bp, i)) {
210 			idesc->id_blkno = IBLK(bp, i);
211 			bp->b_index = i;
212 			if (idesc->id_level == 0) {
213 				idesc->id_lbn++;
214 				n = (*func)(idesc);
215 			} else {
216 				n = iblock(idesc, isize, type - 1);
217 				idesc->id_level++;
218 			}
219 			if (n & STOP) {
220 				brelse(bp);
221 				return (n);
222 			}
223 		} else {
224 			idesc->id_lbn += sizepb / sblock.fs_bsize;
225 			if (idesc->id_type == DATA && isize > 0) {
226 				/* An empty block in a directory XXX */
227 				getpathname(pathbuf, idesc->id_number,
228 						idesc->id_number);
229 				pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS",
230 					pathbuf);
231 				if (reply("ADJUST LENGTH") == 1) {
232 					ginode(idesc->id_number, &ip);
233 					DIP_SET(ip.i_dp, di_size,
234 					    DIP(ip.i_dp, di_size) - isize);
235 					isize = 0;
236 					printf(
237 					    "YOU MUST RERUN FSCK AFTERWARDS\n");
238 					rerun = 1;
239 					inodirty(&ip);
240 					brelse(bp);
241 					return(STOP);
242 				}
243 			}
244 		}
245 		isize -= sizepb;
246 	}
247 	brelse(bp);
248 	return (KEEPON);
249 }
250 
251 /*
252  * Finds the disk block address at the specified lbn within the inode
253  * specified by dp.  This follows the whole tree and honors di_size and
254  * di_extsize so it is a true test of reachability.  The lbn may be
255  * negative if an extattr or indirect block is requested.
256  */
257 ufs2_daddr_t
258 ino_blkatoff(union dinode *dp, ino_t ino, ufs_lbn_t lbn, int *frags,
259     struct bufarea **bpp)
260 {
261 	ufs_lbn_t tmpval;
262 	ufs_lbn_t cur;
263 	ufs_lbn_t next;
264 	int i;
265 
266 	*frags = 0;
267 	if (bpp != NULL)
268 		*bpp = NULL;
269 	/*
270 	 * Handle extattr blocks first.
271 	 */
272 	if (lbn < 0 && lbn >= -UFS_NXADDR) {
273 		lbn = -1 - lbn;
274 		if (lbn > lblkno(&sblock, dp->dp2.di_extsize - 1))
275 			return (0);
276 		*frags = numfrags(&sblock,
277 		    sblksize(&sblock, dp->dp2.di_extsize, lbn));
278 		return (dp->dp2.di_extb[lbn]);
279 	}
280 	/*
281 	 * Now direct and indirect.
282 	 */
283 	if (DIP(dp, di_mode) == IFLNK &&
284 	    DIP(dp, di_size) < sblock.fs_maxsymlinklen)
285 		return (0);
286 	if (lbn >= 0 && lbn < UFS_NDADDR) {
287 		*frags = numfrags(&sblock,
288 		    sblksize(&sblock, DIP(dp, di_size), lbn));
289 		return (DIP(dp, di_db[lbn]));
290 	}
291 	*frags = sblock.fs_frag;
292 
293 	for (i = 0, tmpval = NINDIR(&sblock), cur = UFS_NDADDR; i < UFS_NIADDR;
294 	    i++, tmpval *= NINDIR(&sblock), cur = next) {
295 		next = cur + tmpval;
296 		if (lbn == -cur - i)
297 			return (DIP(dp, di_ib[i]));
298 		/*
299 		 * Determine whether the lbn in question is within this tree.
300 		 */
301 		if (lbn < 0 && -lbn >= next)
302 			continue;
303 		if (lbn > 0 && lbn >= next)
304 			continue;
305 		if (DIP(dp, di_ib[i]) == 0)
306 			return (0);
307 		return (indir_blkatoff(DIP(dp, di_ib[i]), ino, -cur - i, lbn,
308 		    bpp));
309 	}
310 	pfatal("lbn %jd not in ino %ju\n", lbn, (uintmax_t)ino);
311 	return (0);
312 }
313 
314 /*
315  * Fetch an indirect block to find the block at a given lbn.  The lbn
316  * may be negative to fetch a specific indirect block pointer or positive
317  * to fetch a specific block.
318  */
319 static ufs2_daddr_t
320 indir_blkatoff(ufs2_daddr_t blk, ino_t ino, ufs_lbn_t cur, ufs_lbn_t lbn,
321     struct bufarea **bpp)
322 {
323 	struct bufarea *bp;
324 	ufs_lbn_t lbnadd;
325 	ufs_lbn_t base;
326 	int i, level;
327 
328 	level = lbn_level(cur);
329 	if (level == -1)
330 		pfatal("Invalid indir lbn %jd in ino %ju\n",
331 		    lbn, (uintmax_t)ino);
332 	if (level == 0 && lbn < 0)
333 		pfatal("Invalid lbn %jd in ino %ju\n",
334 		    lbn, (uintmax_t)ino);
335 	lbnadd = 1;
336 	base = -(cur + level);
337 	for (i = level; i > 0; i--)
338 		lbnadd *= NINDIR(&sblock);
339 	if (lbn > 0)
340 		i = (lbn - base) / lbnadd;
341 	else
342 		i = (-lbn - base) / lbnadd;
343 	if (i < 0 || i >= NINDIR(&sblock)) {
344 		pfatal("Invalid indirect index %d produced by lbn %jd "
345 		    "in ino %ju\n", i, lbn, (uintmax_t)ino);
346 		return (0);
347 	}
348 	if (level == 0)
349 		cur = base + (i * lbnadd);
350 	else
351 		cur = -(base + (i * lbnadd)) - (level - 1);
352 	bp = getdatablk(blk, sblock.fs_bsize, BT_LEVEL1 + level);
353 	if (bp->b_errs != 0)
354 		return (0);
355 	blk = IBLK(bp, i);
356 	bp->b_index = i;
357 	if (cur == lbn || blk == 0) {
358 		if (bpp != NULL)
359 			*bpp = bp;
360 		else
361 			brelse(bp);
362 		return (blk);
363 	}
364 	brelse(bp);
365 	if (level == 0)
366 		pfatal("Invalid lbn %jd at level 0 for ino %ju\n", lbn,
367 		    (uintmax_t)ino);
368 	return (indir_blkatoff(blk, ino, cur, lbn, bpp));
369 }
370 
371 /*
372  * Check that a block in a legal block number.
373  * Return 0 if in range, 1 if out of range.
374  */
375 int
376 chkrange(ufs2_daddr_t blk, int cnt)
377 {
378 	int c;
379 
380 	if (cnt <= 0 || blk <= 0 || blk > maxfsblock ||
381 	    cnt - 1 > maxfsblock - blk)
382 		return (1);
383 	if (cnt > sblock.fs_frag ||
384 	    fragnum(&sblock, blk) + cnt > sblock.fs_frag) {
385 		if (debug)
386 			printf("bad size: blk %ld, offset %i, size %d\n",
387 			    (long)blk, (int)fragnum(&sblock, blk), cnt);
388 		return (1);
389 	}
390 	c = dtog(&sblock, blk);
391 	if (blk < cgdmin(&sblock, c)) {
392 		if ((blk + cnt) > cgsblock(&sblock, c)) {
393 			if (debug) {
394 				printf("blk %ld < cgdmin %ld;",
395 				    (long)blk, (long)cgdmin(&sblock, c));
396 				printf(" blk + cnt %ld > cgsbase %ld\n",
397 				    (long)(blk + cnt),
398 				    (long)cgsblock(&sblock, c));
399 			}
400 			return (1);
401 		}
402 	} else {
403 		if ((blk + cnt) > cgbase(&sblock, c+1)) {
404 			if (debug)  {
405 				printf("blk %ld >= cgdmin %ld;",
406 				    (long)blk, (long)cgdmin(&sblock, c));
407 				printf(" blk + cnt %ld > sblock.fs_fpg %ld\n",
408 				    (long)(blk + cnt), (long)sblock.fs_fpg);
409 			}
410 			return (1);
411 		}
412 	}
413 	return (0);
414 }
415 
416 /*
417  * General purpose interface for reading inodes.
418  *
419  * firstinum and lastinum track contents of getnextino() cache (below).
420  */
421 static ino_t firstinum, lastinum;
422 static struct bufarea inobuf;
423 
424 void
425 ginode(ino_t inumber, struct inode *ip)
426 {
427 	ufs2_daddr_t iblk;
428 	ino_t numinodes;
429 
430 	if (inumber < UFS_ROOTINO || inumber > maxino)
431 		errx(EEXIT, "bad inode number %ju to ginode",
432 		    (uintmax_t)inumber);
433 	ip->i_number = inumber;
434 	if (inumber >= firstinum && inumber < lastinum) {
435 		/* contents in getnextino() cache */
436 		ip->i_bp = &inobuf;
437 		inobuf.b_refcnt++;
438 		inobuf.b_index = firstinum;
439 		numinodes = lastinum - firstinum;
440 	} else if (icachebp != NULL &&
441 	    inumber >= icachebp->b_index &&
442 	    inumber < icachebp->b_index + INOPB(&sblock)) {
443 		/* take an additional reference for the returned inode */
444 		icachebp->b_refcnt++;
445 		ip->i_bp = icachebp;
446 		numinodes = INOPB(&sblock);
447 	} else {
448 		iblk = ino_to_fsba(&sblock, inumber);
449 		/* release our cache-hold reference on old icachebp */
450 		if (icachebp != NULL)
451 			brelse(icachebp);
452 		icachebp = getdatablk(iblk, sblock.fs_bsize, BT_INODES);
453 		if (icachebp->b_errs != 0) {
454 			icachebp = NULL;
455 			ip->i_bp = NULL;
456 			ip->i_dp = &zino;
457 			return;
458 		}
459 		/* take a cache-hold reference on new icachebp */
460 		icachebp->b_refcnt++;
461 		icachebp->b_index = rounddown(inumber, INOPB(&sblock));
462 		ip->i_bp = icachebp;
463 		numinodes = INOPB(&sblock);
464 	}
465 	if (sblock.fs_magic == FS_UFS1_MAGIC) {
466 		ip->i_dp = (union dinode *)
467 		    &ip->i_bp->b_un.b_dinode1[inumber % numinodes];
468 		return;
469 	}
470 	ip->i_dp = (union dinode *)
471 	    &ip->i_bp->b_un.b_dinode2[inumber % numinodes];
472 	if (ffs_verify_dinode_ckhash(&sblock, (struct ufs2_dinode *)ip->i_dp)) {
473 		pwarn("INODE CHECK-HASH FAILED");
474 		prtinode(ip);
475 		if (preen || reply("FIX") != 0) {
476 			if (preen)
477 				printf(" (FIXED)\n");
478 			ffs_update_dinode_ckhash(&sblock,
479 			    (struct ufs2_dinode *)ip->i_dp);
480 			inodirty(ip);
481 		}
482 	}
483 }
484 
485 /*
486  * Release a held inode.
487  */
488 void
489 irelse(struct inode *ip)
490 {
491 
492 	/* Check for failed inode read */
493 	if (ip->i_bp == NULL)
494 		return;
495 	if (ip->i_bp->b_refcnt <= 0)
496 		pfatal("irelse: releasing unreferenced ino %ju\n",
497 		    (uintmax_t) ip->i_number);
498 	brelse(ip->i_bp);
499 }
500 
501 /*
502  * Special purpose version of ginode used to optimize first pass
503  * over all the inodes in numerical order.
504  */
505 static ino_t nextinum, lastvalidinum;
506 static long readcount, readpercg, fullcnt, inobufsize, partialcnt, partialsize;
507 
508 union dinode *
509 getnextinode(ino_t inumber, int rebuildcg)
510 {
511 	int j;
512 	long size;
513 	mode_t mode;
514 	ufs2_daddr_t ndb, blk;
515 	union dinode *dp;
516 	struct inode ip;
517 	static caddr_t nextinop;
518 
519 	if (inumber != nextinum++ || inumber > lastvalidinum)
520 		errx(EEXIT, "bad inode number %ju to nextinode",
521 		    (uintmax_t)inumber);
522 	if (inumber >= lastinum) {
523 		readcount++;
524 		firstinum = lastinum;
525 		blk = ino_to_fsba(&sblock, lastinum);
526 		if (readcount % readpercg == 0) {
527 			size = partialsize;
528 			lastinum += partialcnt;
529 		} else {
530 			size = inobufsize;
531 			lastinum += fullcnt;
532 		}
533 		/*
534 		 * Flush old contents in case they have been updated.
535 		 * If getblk encounters an error, it will already have zeroed
536 		 * out the buffer, so we do not need to do so here.
537 		 */
538 		if (inobuf.b_refcnt != 0)
539 			pfatal("Non-zero getnextinode() ref count %d\n",
540 			    inobuf.b_refcnt);
541 		flush(fswritefd, &inobuf);
542 		getblk(&inobuf, blk, size);
543 		nextinop = inobuf.b_un.b_buf;
544 	}
545 	dp = (union dinode *)nextinop;
546 	if (sblock.fs_magic == FS_UFS1_MAGIC)
547 		nextinop += sizeof(struct ufs1_dinode);
548 	else
549 		nextinop += sizeof(struct ufs2_dinode);
550 	if ((ckhashadd & CK_INODE) != 0) {
551 		ffs_update_dinode_ckhash(&sblock, (struct ufs2_dinode *)dp);
552 		dirty(&inobuf);
553 	}
554 	if (ffs_verify_dinode_ckhash(&sblock, (struct ufs2_dinode *)dp) != 0) {
555 		pwarn("INODE CHECK-HASH FAILED");
556 		ip.i_bp = NULL;
557 		ip.i_dp = dp;
558 		ip.i_number = inumber;
559 		prtinode(&ip);
560 		if (preen || reply("FIX") != 0) {
561 			if (preen)
562 				printf(" (FIXED)\n");
563 			ffs_update_dinode_ckhash(&sblock,
564 			    (struct ufs2_dinode *)dp);
565 			dirty(&inobuf);
566 		}
567 	}
568 	if (rebuildcg && (char *)dp == inobuf.b_un.b_buf) {
569 		/*
570 		 * Try to determine if we have reached the end of the
571 		 * allocated inodes.
572 		 */
573 		mode = DIP(dp, di_mode) & IFMT;
574 		if (mode == 0) {
575 			if (memcmp(dp->dp2.di_db, zino.dp2.di_db,
576 				UFS_NDADDR * sizeof(ufs2_daddr_t)) ||
577 			      memcmp(dp->dp2.di_ib, zino.dp2.di_ib,
578 				UFS_NIADDR * sizeof(ufs2_daddr_t)) ||
579 			      dp->dp2.di_mode || dp->dp2.di_size)
580 				return (NULL);
581 			return (dp);
582 		}
583 		if (!ftypeok(dp))
584 			return (NULL);
585 		ndb = howmany(DIP(dp, di_size), sblock.fs_bsize);
586 		if (ndb < 0)
587 			return (NULL);
588 		if (mode == IFBLK || mode == IFCHR)
589 			ndb++;
590 		if (mode == IFLNK) {
591 			/*
592 			 * Fake ndb value so direct/indirect block checks below
593 			 * will detect any garbage after symlink string.
594 			 */
595 			if (DIP(dp, di_size) < (off_t)sblock.fs_maxsymlinklen) {
596 				ndb = howmany(DIP(dp, di_size),
597 				    sizeof(ufs2_daddr_t));
598 				if (ndb > UFS_NDADDR) {
599 					j = ndb - UFS_NDADDR;
600 					for (ndb = 1; j > 1; j--)
601 						ndb *= NINDIR(&sblock);
602 					ndb += UFS_NDADDR;
603 				}
604 			}
605 		}
606 		for (j = ndb; ndb < UFS_NDADDR && j < UFS_NDADDR; j++)
607 			if (DIP(dp, di_db[j]) != 0)
608 				return (NULL);
609 		for (j = 0, ndb -= UFS_NDADDR; ndb > 0; j++)
610 			ndb /= NINDIR(&sblock);
611 		for (; j < UFS_NIADDR; j++)
612 			if (DIP(dp, di_ib[j]) != 0)
613 				return (NULL);
614 	}
615 	return (dp);
616 }
617 
618 void
619 setinodebuf(int cg, ino_t inosused)
620 {
621 	ino_t inum;
622 
623 	inum = cg * sblock.fs_ipg;
624 	lastvalidinum = inum + inosused - 1;
625 	nextinum = inum;
626 	lastinum = inum;
627 	readcount = 0;
628 	/* Flush old contents in case they have been updated */
629 	flush(fswritefd, &inobuf);
630 	inobuf.b_bno = 0;
631 	if (inobuf.b_un.b_buf == NULL) {
632 		inobufsize = blkroundup(&sblock,
633 		    MAX(INOBUFSIZE, sblock.fs_bsize));
634 		initbarea(&inobuf, BT_INODES);
635 		if ((inobuf.b_un.b_buf = Malloc((unsigned)inobufsize)) == NULL)
636 			errx(EEXIT, "cannot allocate space for inode buffer");
637 	}
638 	fullcnt = inobufsize / ((sblock.fs_magic == FS_UFS1_MAGIC) ?
639 	    sizeof(struct ufs1_dinode) : sizeof(struct ufs2_dinode));
640 	readpercg = inosused / fullcnt;
641 	partialcnt = inosused % fullcnt;
642 	partialsize = fragroundup(&sblock,
643 	    partialcnt * ((sblock.fs_magic == FS_UFS1_MAGIC) ?
644 	    sizeof(struct ufs1_dinode) : sizeof(struct ufs2_dinode)));
645 	if (partialcnt != 0) {
646 		readpercg++;
647 	} else {
648 		partialcnt = fullcnt;
649 		partialsize = inobufsize;
650 	}
651 }
652 
653 int
654 freeblock(struct inodesc *idesc)
655 {
656 	struct dups *dlp;
657 	ufs2_daddr_t blkno;
658 	long nfrags, res;
659 
660 	res = KEEPON;
661 	blkno = idesc->id_blkno;
662 	for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) {
663 		if (chkrange(blkno, 1)) {
664 			res = SKIP;
665 		} else if (testbmap(blkno)) {
666 			for (dlp = duplist; dlp; dlp = dlp->next) {
667 				if (dlp->dup != blkno)
668 					continue;
669 				dlp->dup = duplist->dup;
670 				dlp = duplist;
671 				duplist = duplist->next;
672 				free((char *)dlp);
673 				break;
674 			}
675 			if (dlp == NULL) {
676 				clrbmap(blkno);
677 				n_blks--;
678 			}
679 		}
680 	}
681 	return (res);
682 }
683 
684 void
685 freeinodebuf(void)
686 {
687 
688 	/*
689 	 * Flush old contents in case they have been updated.
690 	 */
691 	flush(fswritefd, &inobuf);
692 	if (inobuf.b_un.b_buf != NULL)
693 		free((char *)inobuf.b_un.b_buf);
694 	inobuf.b_un.b_buf = NULL;
695 	firstinum = lastinum = 0;
696 }
697 
698 /*
699  * Routines to maintain information about directory inodes.
700  * This is built during the first pass and used during the
701  * second and third passes.
702  *
703  * Enter inodes into the cache.
704  */
705 void
706 cacheino(union dinode *dp, ino_t inumber)
707 {
708 	struct inoinfo *inp, **inpp;
709 	int i, blks;
710 
711 	if (howmany(DIP(dp, di_size), sblock.fs_bsize) > UFS_NDADDR)
712 		blks = UFS_NDADDR + UFS_NIADDR;
713 	else if (DIP(dp, di_size) > 0)
714 		blks = howmany(DIP(dp, di_size), sblock.fs_bsize);
715 	else
716 		blks = 1;
717 	inp = (struct inoinfo *)
718 		Malloc(sizeof(*inp) + (blks - 1) * sizeof(ufs2_daddr_t));
719 	if (inp == NULL)
720 		errx(EEXIT, "cannot increase directory list");
721 	inpp = &inphead[inumber % dirhash];
722 	inp->i_nexthash = *inpp;
723 	*inpp = inp;
724 	inp->i_parent = inumber == UFS_ROOTINO ? UFS_ROOTINO : (ino_t)0;
725 	inp->i_dotdot = (ino_t)0;
726 	inp->i_number = inumber;
727 	inp->i_isize = DIP(dp, di_size);
728 	inp->i_numblks = blks;
729 	for (i = 0; i < MIN(blks, UFS_NDADDR); i++)
730 		inp->i_blks[i] = DIP(dp, di_db[i]);
731 	if (blks > UFS_NDADDR)
732 		for (i = 0; i < UFS_NIADDR; i++)
733 			inp->i_blks[UFS_NDADDR + i] = DIP(dp, di_ib[i]);
734 	if (inplast == listmax) {
735 		listmax += 100;
736 		inpsort = (struct inoinfo **)reallocarray((char *)inpsort,
737 		    listmax, sizeof(struct inoinfo *));
738 		if (inpsort == NULL)
739 			errx(EEXIT, "cannot increase directory list");
740 	}
741 	inpsort[inplast++] = inp;
742 }
743 
744 /*
745  * Look up an inode cache structure.
746  */
747 struct inoinfo *
748 getinoinfo(ino_t inumber)
749 {
750 	struct inoinfo *inp;
751 
752 	for (inp = inphead[inumber % dirhash]; inp; inp = inp->i_nexthash) {
753 		if (inp->i_number != inumber)
754 			continue;
755 		return (inp);
756 	}
757 	errx(EEXIT, "cannot find inode %ju", (uintmax_t)inumber);
758 	return ((struct inoinfo *)0);
759 }
760 
761 /*
762  * Clean up all the inode cache structure.
763  */
764 void
765 inocleanup(void)
766 {
767 	struct inoinfo **inpp;
768 
769 	if (inphead == NULL)
770 		return;
771 	for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--)
772 		free((char *)(*inpp));
773 	free((char *)inphead);
774 	free((char *)inpsort);
775 	inphead = inpsort = NULL;
776 }
777 
778 void
779 inodirty(struct inode *ip)
780 {
781 
782 	if (sblock.fs_magic == FS_UFS2_MAGIC)
783 		ffs_update_dinode_ckhash(&sblock,
784 		    (struct ufs2_dinode *)ip->i_dp);
785 	dirty(ip->i_bp);
786 }
787 
788 void
789 clri(struct inodesc *idesc, const char *type, int flag)
790 {
791 	union dinode *dp;
792 	struct inode ip;
793 
794 	ginode(idesc->id_number, &ip);
795 	dp = ip.i_dp;
796 	if (flag == 1) {
797 		pwarn("%s %s", type,
798 		    (DIP(dp, di_mode) & IFMT) == IFDIR ? "DIR" : "FILE");
799 		prtinode(&ip);
800 		printf("\n");
801 	}
802 	if (preen || reply("CLEAR") == 1) {
803 		if (preen)
804 			printf(" (CLEARED)\n");
805 		n_files--;
806 		if (bkgrdflag == 0) {
807 			(void)ckinode(dp, idesc);
808 			inoinfo(idesc->id_number)->ino_state = USTATE;
809 			clearinode(dp);
810 			inodirty(&ip);
811 		} else {
812 			cmd.value = idesc->id_number;
813 			cmd.size = -DIP(dp, di_nlink);
814 			if (debug)
815 				printf("adjrefcnt ino %ld amt %lld\n",
816 				    (long)cmd.value, (long long)cmd.size);
817 			if (sysctl(adjrefcnt, MIBSIZE, 0, 0,
818 			    &cmd, sizeof cmd) == -1)
819 				rwerror("ADJUST INODE", cmd.value);
820 		}
821 	}
822 	irelse(&ip);
823 }
824 
825 int
826 findname(struct inodesc *idesc)
827 {
828 	struct direct *dirp = idesc->id_dirp;
829 
830 	if (dirp->d_ino != idesc->id_parent || idesc->id_entryno < 2) {
831 		idesc->id_entryno++;
832 		return (KEEPON);
833 	}
834 	memmove(idesc->id_name, dirp->d_name, (size_t)dirp->d_namlen + 1);
835 	return (STOP|FOUND);
836 }
837 
838 int
839 findino(struct inodesc *idesc)
840 {
841 	struct direct *dirp = idesc->id_dirp;
842 
843 	if (dirp->d_ino == 0)
844 		return (KEEPON);
845 	if (strcmp(dirp->d_name, idesc->id_name) == 0 &&
846 	    dirp->d_ino >= UFS_ROOTINO && dirp->d_ino <= maxino) {
847 		idesc->id_parent = dirp->d_ino;
848 		return (STOP|FOUND);
849 	}
850 	return (KEEPON);
851 }
852 
853 int
854 clearentry(struct inodesc *idesc)
855 {
856 	struct direct *dirp = idesc->id_dirp;
857 
858 	if (dirp->d_ino != idesc->id_parent || idesc->id_entryno < 2) {
859 		idesc->id_entryno++;
860 		return (KEEPON);
861 	}
862 	dirp->d_ino = 0;
863 	return (STOP|FOUND|ALTERED);
864 }
865 
866 void
867 prtinode(struct inode *ip)
868 {
869 	char *p;
870 	union dinode *dp;
871 	struct passwd *pw;
872 	time_t t;
873 
874 	dp = ip->i_dp;
875 	printf(" I=%lu ", (u_long)ip->i_number);
876 	if (ip->i_number < UFS_ROOTINO || ip->i_number > maxino)
877 		return;
878 	printf(" OWNER=");
879 	if ((pw = getpwuid((int)DIP(dp, di_uid))) != NULL)
880 		printf("%s ", pw->pw_name);
881 	else
882 		printf("%u ", (unsigned)DIP(dp, di_uid));
883 	printf("MODE=%o\n", DIP(dp, di_mode));
884 	if (preen)
885 		printf("%s: ", cdevname);
886 	printf("SIZE=%ju ", (uintmax_t)DIP(dp, di_size));
887 	t = DIP(dp, di_mtime);
888 	p = ctime(&t);
889 	printf("MTIME=%12.12s %4.4s ", &p[4], &p[20]);
890 }
891 
892 void
893 blkerror(ino_t ino, const char *type, ufs2_daddr_t blk)
894 {
895 
896 	pfatal("%jd %s I=%ju", (intmax_t)blk, type, (uintmax_t)ino);
897 	printf("\n");
898 	switch (inoinfo(ino)->ino_state) {
899 
900 	case FSTATE:
901 	case FZLINK:
902 		inoinfo(ino)->ino_state = FCLEAR;
903 		return;
904 
905 	case DSTATE:
906 	case DZLINK:
907 		inoinfo(ino)->ino_state = DCLEAR;
908 		return;
909 
910 	case FCLEAR:
911 	case DCLEAR:
912 		return;
913 
914 	default:
915 		errx(EEXIT, "BAD STATE %d TO BLKERR", inoinfo(ino)->ino_state);
916 		/* NOTREACHED */
917 	}
918 }
919 
920 /*
921  * allocate an unused inode
922  */
923 ino_t
924 allocino(ino_t request, int type)
925 {
926 	ino_t ino;
927 	struct inode ip;
928 	union dinode *dp;
929 	struct bufarea *cgbp;
930 	struct cg *cgp;
931 	int cg, anyino;
932 
933 	anyino = 0;
934 	if (request == 0) {
935 		request = UFS_ROOTINO;
936 		anyino = 1;
937 	} else if (inoinfo(request)->ino_state != USTATE)
938 		return (0);
939 retry:
940 	for (ino = request; ino < maxino; ino++)
941 		if (inoinfo(ino)->ino_state == USTATE)
942 			break;
943 	if (ino >= maxino)
944 		return (0);
945 	cg = ino_to_cg(&sblock, ino);
946 	cgbp = cglookup(cg);
947 	cgp = cgbp->b_un.b_cg;
948 	if (!check_cgmagic(cg, cgbp, 0)) {
949 		if (anyino == 0)
950 			return (0);
951 		request = (cg + 1) * sblock.fs_ipg;
952 		goto retry;
953 	}
954 	setbit(cg_inosused(cgp), ino % sblock.fs_ipg);
955 	cgp->cg_cs.cs_nifree--;
956 	switch (type & IFMT) {
957 	case IFDIR:
958 		inoinfo(ino)->ino_state = DSTATE;
959 		cgp->cg_cs.cs_ndir++;
960 		break;
961 	case IFREG:
962 	case IFLNK:
963 		inoinfo(ino)->ino_state = FSTATE;
964 		break;
965 	default:
966 		return (0);
967 	}
968 	cgdirty(cgbp);
969 	ginode(ino, &ip);
970 	dp = ip.i_dp;
971 	DIP_SET(dp, di_db[0], allocblk((long)1));
972 	if (DIP(dp, di_db[0]) == 0) {
973 		inoinfo(ino)->ino_state = USTATE;
974 		irelse(&ip);
975 		return (0);
976 	}
977 	DIP_SET(dp, di_mode, type);
978 	DIP_SET(dp, di_flags, 0);
979 	DIP_SET(dp, di_atime, time(NULL));
980 	DIP_SET(dp, di_ctime, DIP(dp, di_atime));
981 	DIP_SET(dp, di_mtime, DIP(dp, di_ctime));
982 	DIP_SET(dp, di_mtimensec, 0);
983 	DIP_SET(dp, di_ctimensec, 0);
984 	DIP_SET(dp, di_atimensec, 0);
985 	DIP_SET(dp, di_size, sblock.fs_fsize);
986 	DIP_SET(dp, di_blocks, btodb(sblock.fs_fsize));
987 	n_files++;
988 	inodirty(&ip);
989 	irelse(&ip);
990 	inoinfo(ino)->ino_type = IFTODT(type);
991 	return (ino);
992 }
993 
994 /*
995  * deallocate an inode
996  */
997 void
998 freeino(ino_t ino)
999 {
1000 	struct inodesc idesc;
1001 	union dinode *dp;
1002 	struct inode ip;
1003 
1004 	memset(&idesc, 0, sizeof(struct inodesc));
1005 	idesc.id_type = inoinfo(ino)->ino_idtype;
1006 	idesc.id_func = freeblock;
1007 	idesc.id_number = ino;
1008 	ginode(ino, &ip);
1009 	dp = ip.i_dp;
1010 	(void)ckinode(dp, &idesc);
1011 	clearinode(dp);
1012 	inodirty(&ip);
1013 	irelse(&ip);
1014 	inoinfo(ino)->ino_state = USTATE;
1015 	n_files--;
1016 }
1017