xref: /titanic_50/usr/src/cmd/fs.d/ufs/fsck/inode.c (revision 8b464eb836173b92f2b7a65623cd06c8c3c59289)
1 /*
2  * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
3  * Use is subject to license terms.
4  */
5 
6 /*	Copyright (c) 1983, 1984, 1985, 1986, 1987, 1988, 1989 AT&T	*/
7 /*	  All Rights Reserved  	*/
8 
9 /*
10  * Copyright (c) 1980, 1986, 1990 The Regents of the University of California.
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms are permitted
14  * provided that: (1) source distributions retain this entire copyright
15  * notice and comment, and (2) distributions including binaries display
16  * the following acknowledgement:  ``This product includes software
17  * developed by the University of California, Berkeley and its contributors''
18  * in the documentation or other materials provided with the distribution
19  * and in all advertising materials mentioning features or use of this
20  * software. Neither the name of the University nor the names of its
21  * contributors may be used to endorse or promote products derived
22  * from this software without specific prior written permission.
23  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
25  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
26  */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <time.h>
35 #include <limits.h>
36 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/sysmacros.h>
39 #include <sys/mntent.h>
40 #include <sys/vnode.h>
41 #include <sys/fs/ufs_inode.h>
42 #include <sys/fs/ufs_fs.h>
43 #define	_KERNEL
44 #include <sys/fs/ufs_fsdir.h>
45 #undef _KERNEL
46 #include <pwd.h>
47 #include "fsck.h"
48 
49 static int get_indir_offsets(int, daddr_t, int *, int *);
50 static int clearanentry(struct inodesc *);
51 static void pdinode(struct dinode *);
52 static void inoflush(void);
53 static void mark_delayed_inodes(fsck_ino_t, daddr32_t);
54 static int iblock(struct inodesc *, int, u_offset_t, enum cki_action);
55 static struct inoinfo *search_cache(struct inoinfo *, fsck_ino_t);
56 static int ckinode_common(struct dinode *, struct inodesc *, enum cki_action);
57 static int lookup_dotdot_ino(fsck_ino_t);
58 
59 /*
60  * ckinode() essentially traverses the blocklist of the provided
61  * inode.  For each block either the caller-supplied callback (id_func
62  * in the provided struct inodesc) or dirscan() is invoked.  Which is
63  * chosen is controlled by what type of traversal was requested
64  * (id_type) - if it was for an ADDR or ACL, use the callback,
65  * otherwise it is assumed to be DATA (i.e., a directory) whose
66  * contents need to be scanned.
67  *
68  * Note that a directory inode can get passed in with a type of ADDR;
69  * the type field is orthogonal to the IFMT value.  This is so that
70  * the file aspects (no duplicate blocks, etc) of a directory can be
71  * verified just like is done for any other file, or the actual
72  * contents can be scanned so that connectivity and such can be
73  * investigated.
74  *
75  * The traversal is controlled by flags in the return value of
76  * dirscan() or the callback.  Five flags are defined, STOP, SKIP,
77  * KEEPON, ALTERED, and FOUND.  Their semantics are:
78  *
79  *     STOP -    no further processing of this inode is desired/possible/
80  *               feasible/etc.  This can mean that whatever the scan
81  *               was searching for was found, or a serious
82  *               inconsistency was encountered, or anything else
83  *               appropriate.
84  *
85  *     SKIP -    something that made it impossible to continue was
86  *               encountered, and the caller should go on to the next
87  *               inode.  This is more for i/o failures than for
88  *               logical inconsistencies.  Nothing actually looks for
89  *               this.
90  *
91  *     KEEPON -  no more blocks of this inode need to be scanned, but
92  *               nothing's wrong, so keep on going with the next
93  *               inode.  It is similar to STOP, except that
94  *               ckinode()'s caller will typically advance to the next
95  *               inode for KEEPON, whereas it ceases scanning through
96  *               the inodes completely for STOP.
97  *
98  *     ALTERED - a change was made to the inode.  If the caller sees
99  *               this set, it should make sure to flush out the
100  *               changes.  Note that any data blocks read in by the
101  *               function need to be marked dirty by it directly;
102  *               flushing of those will happen automatically later.
103  *
104  *     FOUND -   whatever was being searched for was located.
105  *               Typically combined with STOP to avoid wasting time
106  *               doing additional looking.
107  *
108  * During a traversal, some state needs to be carried around.  At the
109  * least, the callback functions need to know what inode they're
110  * working on, which logical block, and whether or not fixing problems
111  * when they're encountered is desired.  Rather than try to guess what
112  * else might be needed (and thus end up passing way more arguments
113  * than is reasonable), all the possibilities have been bundled in
114  * struct inodesc.  About half of the fields are specific to directory
115  * traversals, and the rest are pretty much generic to any traversal.
116  *
117  * The general fields are:
118  *
119  *     id_fix        What to do when an error is found.  Generally, this
120  *                   is set to DONTKNOW before a traversal.  If a
121  *                   problem is encountered, it is changed to either FIX
122  *                   or NOFIX by the dofix() query function.  If id_fix
123  *                   has already been set to FIX when dofix() is called, then
124  *                   it includes the ALTERED flag (see above) in its return
125  *                   value; the net effect is that the inode's buffer
126  *                   will get marked dirty and written to disk at some
127  *                   point.  If id_fix is DONTKNOW, then dofix() will
128  *                   query the user.  If it is NOFIX, then dofix()
129  *                   essentially does nothing.  A few routines set NOFIX
130  *                   as the initial value, as they are performing a best-
131  *                   effort informational task, rather than an actual
132  *                   repair operation.
133  *
134  *     id_func       This is the function that will be called for every
135  *                   logical block in the file (assuming id_type is not
136  *                   DATA).  The logical block may represent a hole, so
137  *                   the callback needs to be prepared to handle that
138  *                   case.  Its return value is a combination of the flags
139  *                   described above (SKIP, ALTERED, etc).
140  *
141  *     id_number     The inode number whose block list or data is being
142  *                   scanned.
143  *
144  *     id_parent     When id_type is DATA, this is the inode number for
145  *                   the parent of id_number.  Otherwise, it is
146  *                   available for use as an extra parameter or return
147  *                   value between the callback and ckinode()'s caller.
148  *                   Which, if either, of those is left completely up to
149  *                   the two routines involved, so nothing can generally
150  *                   be assumed about the id_parent value for non-DATA
151  *                   traversals.
152  *
153  *     id_lbn        This is the current logical block (not fragment)
154  *                   number being visited by the traversal.
155  *
156  *     id_blkno      This is the physical block corresponding to id_lbn.
157  *
158  *     id_numfrags   This defines how large a block is being processed in
159  *                   this particular invocation of the callback.
160  *                   Usually, it will be the same as sblock.fs_frag.
161  *                   However, if a direct block is being processed and
162  *                   it is less than a full filesystem block,
163  *                   id_numfrags will indicate just how many fragments
164  *                   (starting from id_lbn) are actually part of the
165  *                   file.
166  *
167  *     id_truncto    The pass 4 callback is used in several places to
168  *                   free the blocks of a file (the `FILE HAS PROBLEM
169  *                   FOO; CLEAR?' scenario).  This has been generalized
170  *                   to allow truncating a file to a particular length
171  *                   rather than always completely discarding it.  If
172  *                   id_truncto is -1, then the entire file is released,
173  *                   otherwise it is logical block number to truncate
174  *                   to.  This generalized interface was motivated by a
175  *                   desire to be able to discard everything after a
176  *                   hole in a directory, rather than the entire
177  *                   directory.
178  *
179  *     id_type       Selects the type of traversal.  DATA for dirscan(),
180  *                   ADDR or ACL for using the provided callback.
181  *
182  * There are several more fields used just for dirscan() traversals:
183  *
184  *     id_filesize   The number of bytes in the overall directory left to
185  *                   process.
186  *
187  *     id_loc        Byte position within the directory block.  Should always
188  *                   point to the start of a directory entry.
189  *
190  *     id_entryno    Which logical directory entry is being processed (0
191  *                   is `.', 1 is `..', 2 and on are normal entries).
192  *                   This field is primarily used to enable special
193  *                   checks when looking at the first two entries.
194  *
195  *                   The exception (there's always an exception in fsck)
196  *                   is that in pass 1, it tracks how many fragments are
197  *                   being used by a particular inode.
198  *
199  *     id_firsthole  The first logical block number that was found to
200  *                   be zero.  As directories are not supposed to have
201  *                   holes, this marks where a directory should be
202  *                   truncated down to.  A value of -1 indicates that
203  *                   no holes were found.
204  *
205  *     id_dirp       A pointer to the in-memory copy of the current
206  *                   directory entry (as identified by id_loc).
207  *
208  *     id_name       This is a directory entry name to either create
209  *                   (callback is mkentry) or locate (callback is
210  *                   chgino, findino, or findname).
211  */
212 int
213 ckinode(struct dinode *dp, struct inodesc *idesc, enum cki_action action)
214 {
215 	struct inodesc cleardesc;
216 	mode_t	mode;
217 
218 	if (idesc->id_filesize == 0)
219 		idesc->id_filesize = (offset_t)dp->di_size;
220 
221 	/*
222 	 * Our caller should be filtering out completely-free inodes
223 	 * (mode == zero), so we'll work on the assumption that what
224 	 * we're given has some basic validity.
225 	 *
226 	 * The kernel is inconsistent about MAXPATHLEN including the
227 	 * trailing \0, so allow the more-generous length for symlinks.
228 	 */
229 	mode = dp->di_mode & IFMT;
230 	if (mode == IFBLK || mode == IFCHR)
231 		return (KEEPON);
232 	if (mode == IFLNK && dp->di_size > MAXPATHLEN) {
233 		pwarn("I=%d  Symlink longer than supported maximum",
234 		    idesc->id_number);
235 		init_inodesc(&cleardesc);
236 		cleardesc.id_type = ADDR;
237 		cleardesc.id_number = idesc->id_number;
238 		cleardesc.id_fix = DONTKNOW;
239 		clri(&cleardesc, "BAD", CLRI_VERBOSE, CLRI_NOP_CORRUPT);
240 		return (STOP);
241 	}
242 	return (ckinode_common(dp, idesc, action));
243 }
244 
245 /*
246  * This was split out from ckinode() to allow it to be used
247  * without having to pass in kludge flags to suppress the
248  * wrong-for-deletion initialization and irrelevant checks.
249  * This feature is no longer needed, but is being kept in case
250  * the need comes back.
251  */
252 static int
253 ckinode_common(struct dinode *dp, struct inodesc *idesc,
254 	enum cki_action action)
255 {
256 	offset_t offset;
257 	struct dinode dino;
258 	daddr_t ndb;
259 	int indir_data_blks, last_indir_blk;
260 	int ret, i, frags;
261 
262 	(void) memmove(&dino, dp, sizeof (struct dinode));
263 	ndb = howmany(dino.di_size, (u_offset_t)sblock.fs_bsize);
264 
265 	for (i = 0; i < NDADDR; i++) {
266 		idesc->id_lbn++;
267 		offset = blkoff(&sblock, dino.di_size);
268 		if ((--ndb == 0) && (offset != 0)) {
269 			idesc->id_numfrags =
270 			    numfrags(&sblock, fragroundup(&sblock, offset));
271 		} else {
272 			idesc->id_numfrags = sblock.fs_frag;
273 		}
274 		if (dino.di_db[i] == 0) {
275 			if ((ndb > 0) && (idesc->id_firsthole < 0)) {
276 				idesc->id_firsthole = i;
277 			}
278 			continue;
279 		}
280 		idesc->id_blkno = dino.di_db[i];
281 		if (idesc->id_type == ADDR || idesc->id_type == ACL)
282 			ret = (*idesc->id_func)(idesc);
283 		else
284 			ret = dirscan(idesc);
285 
286 		/*
287 		 * Need to clear the entry, now that we're done with
288 		 * it.  We depend on freeblk() ignoring a request to
289 		 * free already-free fragments to handle the problem of
290 		 * a partial block.
291 		 */
292 		if ((action == CKI_TRUNCATE) &&
293 		    (idesc->id_truncto >= 0) &&
294 		    (idesc->id_lbn >= idesc->id_truncto)) {
295 			dp = ginode(idesc->id_number);
296 			/*
297 			 * The (int) cast is safe, in that if di_size won't
298 			 * fit, it'll be a multiple of any legal fs_frag,
299 			 * thus giving a zero result.  That value, in turn
300 			 * means we're doing an entire block.
301 			 */
302 			frags = howmany((int)dp->di_size, sblock.fs_fsize) %
303 			    sblock.fs_frag;
304 			if (frags == 0)
305 				frags = sblock.fs_frag;
306 			freeblk(idesc->id_number, dp->di_db[i],
307 			    frags);
308 			dp = ginode(idesc->id_number);
309 			dp->di_db[i] = 0;
310 			inodirty();
311 			ret |= ALTERED;
312 		}
313 
314 		if (ret & STOP)
315 			return (ret);
316 	}
317 
318 #ifdef lint
319 	/*
320 	 * Cure a lint complaint of ``possible use before set''.
321 	 * Apparently it can't quite figure out the switch statement.
322 	 */
323 	indir_data_blks = 0;
324 #endif
325 	/*
326 	 * indir_data_blks contains the number of data blocks in all
327 	 * the previous levels for this iteration.  E.g., for the
328 	 * single indirect case (i = 0, di_ib[i] != 0), NDADDR's worth
329 	 * of blocks have already been covered by the direct blocks
330 	 * (di_db[]).  At the triple indirect level (i = NIADDR - 1),
331 	 * it is all of the number of data blocks that were covered
332 	 * by the second indirect, single indirect, and direct block
333 	 * levels.
334 	 */
335 	idesc->id_numfrags = sblock.fs_frag;
336 	ndb = howmany(dino.di_size, (u_offset_t)sblock.fs_bsize);
337 	for (i = 0; i < NIADDR; i++) {
338 		(void) get_indir_offsets(i, ndb, &indir_data_blks,
339 		    &last_indir_blk);
340 		if (dino.di_ib[i] != 0) {
341 			/*
342 			 * We'll only clear di_ib[i] if the first entry (and
343 			 * therefore all of them) is to be cleared, since we
344 			 * only go through this code on the first entry of
345 			 * each level of indirection.  The +1 is to account
346 			 * for the fact that we don't modify id_lbn until
347 			 * we actually start processing on a data block.
348 			 */
349 			idesc->id_blkno = dino.di_ib[i];
350 			ret = iblock(idesc, i + 1,
351 			    (u_offset_t)howmany(dino.di_size,
352 						(u_offset_t)sblock.fs_bsize) -
353 						    indir_data_blks,
354 						action);
355 			if ((action == CKI_TRUNCATE) &&
356 			    (idesc->id_truncto <= indir_data_blks) &&
357 			    ((idesc->id_lbn + 1) >= indir_data_blks) &&
358 			    ((idesc->id_lbn + 1) <= last_indir_blk)) {
359 				dp = ginode(idesc->id_number);
360 				if (dp->di_ib[i] != 0) {
361 					freeblk(idesc->id_number, dp->di_ib[i],
362 					    sblock.fs_frag);
363 				}
364 			}
365 			if (ret & STOP)
366 				return (ret);
367 		} else {
368 			/*
369 			 * Need to know which of the file's logical blocks
370 			 * reside in the missing indirect block.  However, the
371 			 * precise location is only needed for truncating
372 			 * directories, and level-of-indirection precision is
373 			 * sufficient for that.
374 			 */
375 			if ((indir_data_blks < ndb) &&
376 			    (idesc->id_firsthole < 0)) {
377 				idesc->id_firsthole = indir_data_blks;
378 			}
379 		}
380 	}
381 	return (KEEPON);
382 }
383 
384 static int
385 get_indir_offsets(int ilevel_wanted, daddr_t ndb, int *data_blks,
386 	int *last_blk)
387 {
388 	int ndb_ilevel = -1;
389 	int ilevel;
390 	int dblks, lblk;
391 
392 	for (ilevel = 0; ilevel < NIADDR; ilevel++) {
393 		switch (ilevel) {
394 		case 0:	/* SINGLE */
395 			dblks = NDADDR;
396 			lblk = dblks + NINDIR(&sblock) - 1;
397 			break;
398 		case 1:	/* DOUBLE */
399 			dblks = NDADDR + NINDIR(&sblock);
400 			lblk = dblks + (NINDIR(&sblock) * NINDIR(&sblock)) - 1;
401 			break;
402 		case 2:	/* TRIPLE */
403 			dblks = NDADDR + NINDIR(&sblock) +
404 			    (NINDIR(&sblock) * NINDIR(&sblock));
405 			lblk = dblks + (NINDIR(&sblock) * NINDIR(&sblock) *
406 			    NINDIR(&sblock)) - 1;
407 			break;
408 		default:
409 			exitstat = EXERRFATAL;
410 			/*
411 			 * Translate from zero-based array to
412 			 * one-based human-style counting.
413 			 */
414 			errexit("panic: indirection level %d not 1, 2, or 3",
415 			    ilevel + 1);
416 			/* NOTREACHED */
417 		}
418 
419 		if (dblks < ndb && ndb <= lblk)
420 			ndb_ilevel = ilevel;
421 
422 		if (ilevel == ilevel_wanted) {
423 			if (data_blks != NULL)
424 				*data_blks = dblks;
425 			if (last_blk != NULL)
426 				*last_blk = lblk;
427 		}
428 	}
429 
430 	return (ndb_ilevel);
431 }
432 
433 static int
434 iblock(struct inodesc *idesc, int ilevel, u_offset_t iblks,
435 	enum cki_action action)
436 {
437 	struct bufarea *bp;
438 	int i, n;
439 	int (*func)(struct inodesc *) = NULL;
440 	u_offset_t fsbperindirb;
441 	daddr32_t last_lbn;
442 	int nif;
443 	char buf[BUFSIZ];
444 
445 	n = KEEPON;
446 
447 	switch (idesc->id_type) {
448 	case ADDR:
449 		func = idesc->id_func;
450 		if (((n = (*func)(idesc)) & KEEPON) == 0)
451 				return (n);
452 		break;
453 	case ACL:
454 		func = idesc->id_func;
455 		break;
456 	case DATA:
457 		func = dirscan;
458 		break;
459 	default:
460 		errexit("unknown inodesc type %d in iblock()", idesc->id_type);
461 		/* NOTREACHED */
462 	}
463 	if (chkrange(idesc->id_blkno, idesc->id_numfrags)) {
464 		return ((idesc->id_type == ACL) ? STOP : SKIP);
465 	}
466 
467 	bp = getdatablk(idesc->id_blkno, (size_t)sblock.fs_bsize);
468 	if (bp->b_errs != 0) {
469 		brelse(bp);
470 		return (SKIP);
471 	}
472 
473 	ilevel--;
474 	/*
475 	 * Trivia note: the BSD fsck has the number of bytes remaining
476 	 * as the third argument to iblock(), so the equivalent of
477 	 * fsbperindirb starts at fs_bsize instead of one.  We're
478 	 * working in units of filesystem blocks here, not bytes or
479 	 * fragments.
480 	 */
481 	for (fsbperindirb = 1, i = 0; i < ilevel; i++) {
482 		fsbperindirb *= (u_offset_t)NINDIR(&sblock);
483 	}
484 	/*
485 	 * nif indicates the next "free" pointer (as an array index) in this
486 	 * indirect block, based on counting the blocks remaining in the
487 	 * file after subtracting all previously processed blocks.
488 	 * This figure is based on the size field of the inode.
489 	 *
490 	 * Note that in normal operation, nif may initially be calculated
491 	 * as larger than the number of pointers in this block (as when
492 	 * there are more indirect blocks following); if that is
493 	 * the case, nif is limited to the max number of pointers per
494 	 * indirect block.
495 	 *
496 	 * Also note that if an inode is inconsistent (has more blocks
497 	 * allocated to it than the size field would indicate), the sweep
498 	 * through any indirect blocks directly pointed at by the inode
499 	 * continues. Since the block offset of any data blocks referenced
500 	 * by these indirect blocks is greater than the size of the file,
501 	 * the index nif may be computed as a negative value.
502 	 * In this case, we reset nif to indicate that all pointers in
503 	 * this retrieval block should be zeroed and the resulting
504 	 * unreferenced data and/or retrieval blocks will be recovered
505 	 * through garbage collection later.
506 	 */
507 	nif = (offset_t)howmany(iblks, fsbperindirb);
508 	if (nif > NINDIR(&sblock))
509 		nif = NINDIR(&sblock);
510 	else if (nif < 0)
511 		nif = 0;
512 	/*
513 	 * first pass: all "free" retrieval pointers (from [nif] thru
514 	 * 	the end of the indirect block) should be zero. (This
515 	 *	assertion does not hold for directories, which may be
516 	 *	truncated without releasing their allocated space)
517 	 */
518 	if (nif < NINDIR(&sblock) && (idesc->id_func == pass1check ||
519 	    idesc->id_func == pass3bcheck)) {
520 		for (i = nif; i < NINDIR(&sblock); i++) {
521 			if (bp->b_un.b_indir[i] == 0)
522 				continue;
523 			(void) sprintf(buf, "PARTIALLY TRUNCATED INODE I=%lu",
524 			    (ulong_t)idesc->id_number);
525 			if (preen) {
526 				pfatal(buf);
527 			} else if (dofix(idesc, buf)) {
528 				freeblk(idesc->id_number,
529 				    bp->b_un.b_indir[i],
530 				    sblock.fs_frag);
531 				bp->b_un.b_indir[i] = 0;
532 				dirty(bp);
533 			}
534 		}
535 		flush(fswritefd, bp);
536 	}
537 	/*
538 	 * second pass: all retrieval pointers referring to blocks within
539 	 *	a valid range [0..filesize] (both indirect and data blocks)
540 	 *	are examined in the same manner as ckinode() checks the
541 	 *	direct blocks in the inode.  Sweep through from
542 	 *	the first pointer in this retrieval block to [nif-1].
543 	 */
544 	last_lbn = howmany(idesc->id_filesize, sblock.fs_bsize);
545 	for (i = 0; i < nif; i++) {
546 		if (ilevel == 0)
547 			idesc->id_lbn++;
548 		if (bp->b_un.b_indir[i] != 0) {
549 			idesc->id_blkno = bp->b_un.b_indir[i];
550 			if (ilevel > 0) {
551 				n = iblock(idesc, ilevel, iblks, action);
552 				/*
553 				 * Each iteration decreases "remaining block
554 				 * count" by the number of blocks accessible
555 				 * by a pointer at this indirect block level.
556 				 */
557 				iblks -= fsbperindirb;
558 			} else {
559 				/*
560 				 * If we're truncating, func will discard
561 				 * the data block for us.
562 				 */
563 				n = (*func)(idesc);
564 			}
565 
566 			if ((action == CKI_TRUNCATE) &&
567 			    (idesc->id_truncto >= 0) &&
568 			    (idesc->id_lbn >= idesc->id_truncto)) {
569 				freeblk(idesc->id_number,  bp->b_un.b_indir[i],
570 				    sblock.fs_frag);
571 			}
572 
573 			/*
574 			 * Note that truncation never gets STOP back
575 			 * under normal circumstances.  Abnormal would
576 			 * be a bad acl short-circuit in iblock() or
577 			 * an out-of-range failure in pass4check().
578 			 * We still want to keep going when truncating
579 			 * under those circumstances, since the whole
580 			 * point of truncating is to get rid of all
581 			 * that.
582 			 */
583 			if ((n & STOP) && (action != CKI_TRUNCATE)) {
584 				brelse(bp);
585 				return (n);
586 			}
587 		} else {
588 			if ((idesc->id_lbn < last_lbn) &&
589 			    (idesc->id_firsthole < 0)) {
590 				idesc->id_firsthole = idesc->id_lbn;
591 			}
592 			if (idesc->id_type == DATA) {
593 				/*
594 				 * No point in continuing in the indirect
595 				 * blocks of a directory, since they'll just
596 				 * get freed anyway.
597 				 */
598 				brelse(bp);
599 				return ((n & ~KEEPON) | STOP);
600 			}
601 		}
602 	}
603 
604 	brelse(bp);
605 	return (KEEPON);
606 }
607 
608 /*
609  * Check that a block is a legal block number.
610  * Return 0 if in range, 1 if out of range.
611  */
612 int
613 chkrange(daddr32_t blk, int cnt)
614 {
615 	int c;
616 
617 	if (cnt <= 0 || blk <= 0 || ((unsigned)blk >= (unsigned)maxfsblock) ||
618 	    ((cnt - 1) > (maxfsblock - blk))) {
619 		if (debug)
620 			(void) printf(
621 			    "Bad fragment range: should be 1 <= %d..%d < %d\n",
622 			    blk, blk + cnt, maxfsblock);
623 		return (1);
624 	}
625 	if ((cnt > sblock.fs_frag) ||
626 	    ((fragnum(&sblock, blk) + cnt) > sblock.fs_frag)) {
627 		if (debug)
628 			(void) printf("Bad fragment size: size %d\n", cnt);
629 		return (1);
630 	}
631 	c = dtog(&sblock, blk);
632 	if (blk < cgdmin(&sblock, c)) {
633 		if ((unsigned)(blk + cnt) > (unsigned)cgsblock(&sblock, c)) {
634 			if (debug)
635 				(void) printf(
636 	    "Bad fragment position: %d..%d spans start of cg metadata\n",
637 				    blk, blk + cnt);
638 			return (1);
639 		}
640 	} else {
641 		if ((unsigned)(blk + cnt) > (unsigned)cgbase(&sblock, c+1)) {
642 			if (debug)
643 				(void) printf(
644 				    "Bad frag pos: %d..%d crosses end of cg\n",
645 				    blk, blk + cnt);
646 			return (1);
647 		}
648 	}
649 	return (0);
650 }
651 
652 /*
653  * General purpose interface for reading inodes.
654  */
655 
656 /*
657  * Note that any call to ginode() can potentially invalidate any
658  * dinode pointers previously acquired from it.  To avoid pain,
659  * make sure to always call inodirty() immediately after modifying
660  * an inode, if there's any chance of ginode() being called after
661  * that.  Also, always call ginode() right before you need to access
662  * an inode, so that there won't be any surprises from functions
663  * called between the previous ginode() invocation and the dinode
664  * use.
665  *
666  * Despite all that, we aren't doing the amount of i/o that's implied,
667  * as we use the buffer cache that getdatablk() and friends maintain.
668  */
669 static fsck_ino_t startinum = -1;
670 
671 struct dinode *
672 ginode(fsck_ino_t inum)
673 {
674 	daddr32_t iblk;
675 	struct dinode *dp;
676 
677 	if (inum < UFSROOTINO || inum > maxino) {
678 		errexit("bad inode number %d to ginode\n", inum);
679 	}
680 	if (startinum == -1 ||
681 	    pbp == NULL ||
682 	    inum < startinum ||
683 	    inum >= (fsck_ino_t)(startinum + (fsck_ino_t)INOPB(&sblock))) {
684 		iblk = itod(&sblock, inum);
685 		if (pbp != NULL) {
686 			brelse(pbp);
687 		}
688 		/*
689 		 * We don't check for errors here, because we can't
690 		 * tell our caller about it, and the zeros that will
691 		 * be in the buffer are just as good as anything we
692 		 * could fake.
693 		 */
694 		pbp = getdatablk(iblk, (size_t)sblock.fs_bsize);
695 		startinum =
696 		    (fsck_ino_t)((inum / INOPB(&sblock)) * INOPB(&sblock));
697 	}
698 	dp = &pbp->b_un.b_dinode[inum % INOPB(&sblock)];
699 	if (dp->di_suid != UID_LONG)
700 		dp->di_uid = dp->di_suid;
701 	if (dp->di_sgid != GID_LONG)
702 		dp->di_gid = dp->di_sgid;
703 	return (dp);
704 }
705 
706 /*
707  * Special purpose version of ginode used to optimize first pass
708  * over all the inodes in numerical order.  It bypasses the buffer
709  * system used by ginode(), etc in favour of reading the bulk of a
710  * cg's inodes at one time.
711  */
712 static fsck_ino_t nextino, lastinum;
713 static int64_t readcnt, readpercg, fullcnt, inobufsize;
714 static int64_t partialcnt, partialsize;
715 static size_t lastsize;
716 static struct dinode *inodebuf;
717 static diskaddr_t currentdblk;
718 static struct dinode *currentinode;
719 
720 struct dinode *
721 getnextinode(fsck_ino_t inum)
722 {
723 	size_t size;
724 	diskaddr_t dblk;
725 	static struct dinode *dp;
726 
727 	if (inum != nextino++ || inum > maxino)
728 		errexit("bad inode number %d to nextinode\n", inum);
729 
730 	/*
731 	 * Will always go into the if() the first time we're called,
732 	 * so dp will always be valid.
733 	 */
734 	if (inum >= lastinum) {
735 		readcnt++;
736 		dblk = fsbtodb(&sblock, itod(&sblock, lastinum));
737 		currentdblk = dblk;
738 		if (readcnt % readpercg == 0) {
739 			if (partialsize > SIZE_MAX)
740 				errexit(
741 				    "Internal error: partialsize overflow");
742 			size = (size_t)partialsize;
743 			lastinum += partialcnt;
744 		} else {
745 			if (inobufsize > SIZE_MAX)
746 				errexit("Internal error: inobufsize overflow");
747 			size = (size_t)inobufsize;
748 			lastinum += fullcnt;
749 		}
750 		/*
751 		 * If fsck_bread() returns an error, it will already have
752 		 * zeroed out the buffer, so we do not need to do so here.
753 		 */
754 		(void) fsck_bread(fsreadfd, (caddr_t)inodebuf, dblk, size);
755 		lastsize = size;
756 		dp = inodebuf;
757 	}
758 	currentinode = dp;
759 	return (dp++);
760 }
761 
762 /*
763  * Reread the current getnext() buffer.  This allows for changing inodes
764  * other than the current one via ginode()/inodirty()/inoflush().
765  *
766  * Just reuses all the interesting variables that getnextinode() set up
767  * last time it was called.  This shouldn't get called often, so we don't
768  * try to figure out if the caller's actually touched an inode in the
769  * range we have cached.  There could have been an arbitrary number of
770  * them, after all.
771  */
772 struct dinode *
773 getnextrefresh(void)
774 {
775 	if (inodebuf == NULL) {
776 		return (NULL);
777 	}
778 
779 	inoflush();
780 	(void) fsck_bread(fsreadfd, (caddr_t)inodebuf, currentdblk, lastsize);
781 	return (currentinode);
782 }
783 
784 void
785 resetinodebuf(void)
786 {
787 	startinum = 0;
788 	nextino = 0;
789 	lastinum = 0;
790 	readcnt = 0;
791 	inobufsize = blkroundup(&sblock, INOBUFSIZE);
792 	fullcnt = inobufsize / sizeof (struct dinode);
793 	readpercg = sblock.fs_ipg / fullcnt;
794 	partialcnt = sblock.fs_ipg % fullcnt;
795 	partialsize = partialcnt * sizeof (struct dinode);
796 	if (partialcnt != 0) {
797 		readpercg++;
798 	} else {
799 		partialcnt = fullcnt;
800 		partialsize = inobufsize;
801 	}
802 	if (inodebuf == NULL &&
803 	    (inodebuf = (struct dinode *)malloc((unsigned)inobufsize)) == NULL)
804 		errexit("Cannot allocate space for inode buffer\n");
805 	while (nextino < UFSROOTINO)
806 		(void) getnextinode(nextino);
807 }
808 
809 void
810 freeinodebuf(void)
811 {
812 	if (inodebuf != NULL) {
813 		free((void *)inodebuf);
814 	}
815 	inodebuf = NULL;
816 }
817 
818 /*
819  * Routines to maintain information about directory inodes.
820  * This is built during the first pass and used during the
821  * second and third passes.
822  *
823  * Enter inodes into the cache.
824  */
825 void
826 cacheino(struct dinode *dp, fsck_ino_t inum)
827 {
828 	struct inoinfo *inp;
829 	struct inoinfo **inpp;
830 	uint_t blks;
831 
832 	blks = NDADDR + NIADDR;
833 	inp = (struct inoinfo *)
834 		malloc(sizeof (*inp) + (blks - 1) * sizeof (daddr32_t));
835 	if (inp == NULL)
836 		errexit("Cannot increase directory list\n");
837 	init_inoinfo(inp, dp, inum); /* doesn't touch i_nextlist or i_number */
838 	inpp = &inphead[inum % numdirs];
839 	inp->i_nextlist = *inpp;
840 	*inpp = inp;
841 	inp->i_number = inum;
842 	if (inplast == listmax) {
843 		listmax += 100;
844 		inpsort = (struct inoinfo **)realloc((void *)inpsort,
845 		    (unsigned)listmax * sizeof (struct inoinfo *));
846 		if (inpsort == NULL)
847 			errexit("cannot increase directory list");
848 	}
849 	inpsort[inplast++] = inp;
850 }
851 
852 /*
853  * Look up an inode cache structure.
854  */
855 struct inoinfo *
856 getinoinfo(fsck_ino_t inum)
857 {
858 	struct inoinfo *inp;
859 
860 	inp = search_cache(inphead[inum % numdirs], inum);
861 	return (inp);
862 }
863 
864 /*
865  * Determine whether inode is in cache.
866  */
867 int
868 inocached(fsck_ino_t inum)
869 {
870 	return (search_cache(inphead[inum % numdirs], inum) != NULL);
871 }
872 
873 /*
874  * Clean up all the inode cache structure.
875  */
876 void
877 inocleanup(void)
878 {
879 	struct inoinfo **inpp;
880 
881 	if (inphead == NULL)
882 		return;
883 	for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--) {
884 		free((void *)(*inpp));
885 	}
886 	free((void *)inphead);
887 	free((void *)inpsort);
888 	inphead = inpsort = NULL;
889 }
890 
891 /*
892  * Routines to maintain information about acl inodes.
893  * This is built during the first pass and used during the
894  * second and third passes.
895  *
896  * Enter acl inodes into the cache.
897  */
898 void
899 cacheacl(struct dinode *dp, fsck_ino_t inum)
900 {
901 	struct inoinfo *aclp;
902 	struct inoinfo **aclpp;
903 	uint_t blks;
904 
905 	blks = NDADDR + NIADDR;
906 	aclp = (struct inoinfo *)
907 		malloc(sizeof (*aclp) + (blks - 1) * sizeof (daddr32_t));
908 	if (aclp == NULL)
909 		return;
910 	aclpp = &aclphead[inum % numacls];
911 	aclp->i_nextlist = *aclpp;
912 	*aclpp = aclp;
913 	aclp->i_number = inum;
914 	aclp->i_isize = (offset_t)dp->di_size;
915 	aclp->i_blkssize = (size_t)(blks * sizeof (daddr32_t));
916 	(void) memmove(&aclp->i_blks[0], &dp->di_db[0], aclp->i_blkssize);
917 	if (aclplast == aclmax) {
918 		aclmax += 100;
919 		aclpsort = (struct inoinfo **)realloc((char *)aclpsort,
920 		    (unsigned)aclmax * sizeof (struct inoinfo *));
921 		if (aclpsort == NULL)
922 			errexit("cannot increase acl list");
923 	}
924 	aclpsort[aclplast++] = aclp;
925 }
926 
927 
928 /*
929  * Generic cache search function.
930  * ROOT is the first entry in a hash chain (the caller is expected
931  * to have done the initial bucket lookup).  KEY is what's being
932  * searched for.
933  *
934  * Returns a pointer to the entry if it is found, NULL otherwise.
935  */
936 static struct inoinfo *
937 search_cache(struct inoinfo *element, fsck_ino_t key)
938 {
939 	while (element != NULL) {
940 		if (element->i_number == key)
941 			break;
942 		element = element->i_nextlist;
943 	}
944 
945 	return (element);
946 }
947 
948 void
949 inodirty(void)
950 {
951 	dirty(pbp);
952 }
953 
954 static void
955 inoflush(void)
956 {
957 	if (pbp != NULL)
958 		flush(fswritefd, pbp);
959 }
960 
961 /*
962  * Interactive wrapper for freeino(), for those times when we're
963  * not sure if we should throw something away.
964  */
965 void
966 clri(struct inodesc *idesc, char *type, int verbose, int corrupting)
967 {
968 	int need_parent;
969 	struct dinode *dp;
970 
971 	if (statemap[idesc->id_number] == USTATE)
972 		return;
973 
974 	dp = ginode(idesc->id_number);
975 	if (verbose == CLRI_VERBOSE) {
976 		pwarn("%s %s", type, file_id(idesc->id_number, dp->di_mode));
977 		pinode(idesc->id_number);
978 	}
979 	if (preen || (reply("CLEAR") == 1)) {
980 		need_parent = (corrupting == CLRI_NOP_OK) ?
981 			TI_NOPARENT : TI_PARENT;
982 		freeino(idesc->id_number, need_parent);
983 		if (preen)
984 			(void) printf(" (CLEARED)\n");
985 		remove_orphan_dir(idesc->id_number);
986 	} else if (corrupting == CLRI_NOP_CORRUPT) {
987 		iscorrupt = 1;
988 	}
989 	(void) printf("\n");
990 }
991 
992 /*
993  * Find the directory entry for the inode noted in id_parent (which is
994  * not necessarily the parent of anything, we're just using a convenient
995  * field.
996  */
997 int
998 findname(struct inodesc *idesc)
999 {
1000 	struct direct *dirp = idesc->id_dirp;
1001 
1002 	if (dirp->d_ino != idesc->id_parent)
1003 		return (KEEPON);
1004 	(void) memmove(idesc->id_name, dirp->d_name,
1005 	    MIN(dirp->d_namlen, MAXNAMLEN) + 1);
1006 	return (STOP|FOUND);
1007 }
1008 
1009 /*
1010  * Find the inode number associated with the given name.
1011  */
1012 int
1013 findino(struct inodesc *idesc)
1014 {
1015 	struct direct *dirp = idesc->id_dirp;
1016 
1017 	if (dirp->d_ino == 0)
1018 		return (KEEPON);
1019 	if (strcmp(dirp->d_name, idesc->id_name) == 0 &&
1020 	    dirp->d_ino >= UFSROOTINO && dirp->d_ino <= maxino) {
1021 		idesc->id_parent = dirp->d_ino;
1022 		return (STOP|FOUND);
1023 	}
1024 	return (KEEPON);
1025 }
1026 
1027 int
1028 cleardirentry(fsck_ino_t parentdir, fsck_ino_t target)
1029 {
1030 	struct inodesc idesc;
1031 	struct dinode *dp;
1032 
1033 	dp = ginode(parentdir);
1034 	init_inodesc(&idesc);
1035 	idesc.id_func = clearanentry;
1036 	idesc.id_parent = target;
1037 	idesc.id_type = DATA;
1038 	idesc.id_fix = NOFIX;
1039 	return (ckinode(dp, &idesc, CKI_TRAVERSE));
1040 }
1041 
1042 static int
1043 clearanentry(struct inodesc *idesc)
1044 {
1045 	struct direct *dirp = idesc->id_dirp;
1046 
1047 	if (dirp->d_ino != idesc->id_parent || idesc->id_entryno < 2) {
1048 		idesc->id_entryno++;
1049 		return (KEEPON);
1050 	}
1051 	dirp->d_ino = 0;
1052 	return (STOP|FOUND|ALTERED);
1053 }
1054 
1055 void
1056 pinode(fsck_ino_t ino)
1057 {
1058 	struct dinode *dp;
1059 
1060 	(void) printf(" I=%lu ", (ulong_t)ino);
1061 	if (ino < UFSROOTINO || ino > maxino)
1062 		return;
1063 	dp = ginode(ino);
1064 	pdinode(dp);
1065 }
1066 
1067 static void
1068 pdinode(struct dinode *dp)
1069 {
1070 	char *p;
1071 	struct passwd *pw;
1072 	time_t t;
1073 
1074 	(void) printf(" OWNER=");
1075 	if ((pw = getpwuid((int)dp->di_uid)) != 0)
1076 		(void) printf("%s ", pw->pw_name);
1077 	else
1078 		(void) printf("%lu ", (ulong_t)dp->di_uid);
1079 	(void) printf("MODE=%o\n", dp->di_mode);
1080 	if (preen)
1081 		(void) printf("%s: ", devname);
1082 	(void) printf("SIZE=%lld ", (longlong_t)dp->di_size);
1083 
1084 	/* ctime() ignores LOCALE, so this is safe */
1085 	t = (time_t)dp->di_mtime;
1086 	p = ctime(&t);
1087 	(void) printf("MTIME=%12.12s %4.4s ", p + 4, p + 20);
1088 }
1089 
1090 void
1091 blkerror(fsck_ino_t ino, char *type, daddr32_t blk, daddr32_t lbn)
1092 {
1093 	pfatal("FRAGMENT %d %s I=%u LFN %d", blk, type, ino, lbn);
1094 	(void) printf("\n");
1095 
1096 	switch (statemap[ino] & ~INDELAYD) {
1097 
1098 	case FSTATE:
1099 	case FZLINK:
1100 		statemap[ino] = FCLEAR;
1101 		return;
1102 
1103 	case DFOUND:
1104 	case DSTATE:
1105 	case DZLINK:
1106 		statemap[ino] = DCLEAR;
1107 		add_orphan_dir(ino);
1108 		return;
1109 
1110 	case SSTATE:
1111 		statemap[ino] = SCLEAR;
1112 		return;
1113 
1114 	case FCLEAR:
1115 	case DCLEAR:
1116 	case SCLEAR:
1117 		return;
1118 
1119 	default:
1120 		errexit("BAD STATE 0x%x TO BLKERR\n", statemap[ino]);
1121 		/* NOTREACHED */
1122 	}
1123 }
1124 
1125 /*
1126  * allocate an unused inode
1127  */
1128 fsck_ino_t
1129 allocino(fsck_ino_t request, int type)
1130 {
1131 	fsck_ino_t ino;
1132 	struct dinode *dp;
1133 	struct cg *cgp = &cgrp;
1134 	int cg;
1135 	time_t t;
1136 	caddr_t err;
1137 
1138 	if (debug && (request != 0) && (request != UFSROOTINO))
1139 		errexit("assertion failed: allocino() asked for "
1140 			"inode %d instead of 0 or %d",
1141 			(int)request, (int)UFSROOTINO);
1142 
1143 	/*
1144 	 * We know that we're only going to get requests for UFSROOTINO
1145 	 * or 0.  If UFSROOTINO is wanted, then it better be available
1146 	 * because our caller is trying to recreate the root directory.
1147 	 * If we're asked for 0, then which one we return doesn't matter.
1148 	 * We know that inodes 0 and 1 are never valid to return, so we
1149 	 * the start at the lowest-legal inode number.
1150 	 *
1151 	 * If we got a request for UFSROOTINO, then request != 0, and
1152 	 * this pair of conditionals is the only place that treats
1153 	 * UFSROOTINO specially.
1154 	 */
1155 	if (request == 0)
1156 		request = UFSROOTINO;
1157 	else if (statemap[request] != USTATE)
1158 		return (0);
1159 
1160 	/*
1161 	 * Doesn't do wrapping, since we know we started at
1162 	 * the smallest inode.
1163 	 */
1164 	for (ino = request; ino < maxino; ino++)
1165 		if (statemap[ino] == USTATE)
1166 			break;
1167 	if (ino == maxino)
1168 		return (0);
1169 
1170 	/*
1171 	 * In pass5, we'll calculate the bitmaps and counts all again from
1172 	 * scratch and do a comparison, but for that to work the cg has
1173 	 * to know what in-memory changes we've made to it.  If we have
1174 	 * trouble reading the cg, cg_sanity() should kick it out so
1175 	 * we can skip explicit i/o error checking here.
1176 	 */
1177 	cg = itog(&sblock, ino);
1178 	(void) getblk(&cgblk, cgtod(&sblock, cg), (size_t)sblock.fs_cgsize);
1179 	err = cg_sanity(cgp, cg);
1180 	if (err != NULL) {
1181 		pfatal("CG %d: %s\n", cg, err);
1182 		free((void *)err);
1183 		if (reply("REPAIR") == 0)
1184 			errexit("Program terminated.");
1185 		fix_cg(cgp, cg);
1186 	}
1187 	setbit(cg_inosused(cgp), ino % sblock.fs_ipg);
1188 	cgp->cg_cs.cs_nifree--;
1189 	cgdirty();
1190 
1191 	if (lastino < ino)
1192 		lastino = ino;
1193 
1194 	/*
1195 	 * Don't currently support IFATTRDIR or any of the other
1196 	 * types, as they aren't needed.
1197 	 */
1198 	switch (type & IFMT) {
1199 	case IFDIR:
1200 		statemap[ino] = DSTATE;
1201 		cgp->cg_cs.cs_ndir++;
1202 		break;
1203 	case IFREG:
1204 	case IFLNK:
1205 		statemap[ino] = FSTATE;
1206 		break;
1207 	default:
1208 		/*
1209 		 * Pretend nothing ever happened.  This clears the
1210 		 * dirty flag, among other things.
1211 		 */
1212 		initbarea(&cgblk);
1213 		if (debug)
1214 			(void) printf("allocino: unknown type 0%o\n",
1215 			    type & IFMT);
1216 		return (0);
1217 	}
1218 
1219 	/*
1220 	 * We're allocating what should be a completely-unused inode,
1221 	 * so make sure we don't inherit anything from any previous
1222 	 * incarnations.
1223 	 */
1224 	dp = ginode(ino);
1225 	(void) memset((void *)dp, 0, sizeof (struct dinode));
1226 	dp->di_db[0] = allocblk(1);
1227 	if (dp->di_db[0] == 0) {
1228 		statemap[ino] = USTATE;
1229 		return (0);
1230 	}
1231 	dp->di_mode = (mode_t)type;
1232 	(void) time(&t);
1233 	dp->di_atime = (time32_t)t;
1234 	dp->di_ctime = dp->di_atime;
1235 	dp->di_mtime = dp->di_ctime;
1236 	dp->di_size = (u_offset_t)sblock.fs_fsize;
1237 	dp->di_blocks = btodb(sblock.fs_fsize);
1238 	n_files++;
1239 	inodirty();
1240 	return (ino);
1241 }
1242 
1243 /*
1244  * Release some or all of the blocks of an inode.
1245  * Only truncates down.  Assumes new_length is appropriately aligned
1246  * to a block boundary (or a directory block boundary, if it's a
1247  * directory).
1248  *
1249  * If this is a directory, discard all of its contents first, so
1250  * we don't create a bunch of orphans that would need another fsck
1251  * run to clean up.
1252  *
1253  * Even if truncating to zero length, the inode remains allocated.
1254  */
1255 void
1256 truncino(fsck_ino_t ino, offset_t new_length, int update)
1257 {
1258 	struct inodesc idesc;
1259 	struct inoinfo *iip;
1260 	struct dinode *dp;
1261 	fsck_ino_t parent;
1262 	mode_t mode;
1263 	caddr_t message;
1264 	int isdir;
1265 	int ilevel, dblk;
1266 
1267 	dp = ginode(ino);
1268 	mode = (dp->di_mode & IFMT);
1269 	isdir = (mode == IFDIR) || (mode == IFATTRDIR);
1270 
1271 	if (isdir) {
1272 		/*
1273 		 * Go with the parent we found by chasing references,
1274 		 * if we've gotten that far.  Otherwise, use what the
1275 		 * directory itself claims.  If there's no ``..'' entry
1276 		 * in it, give up trying to get the link counts right.
1277 		 */
1278 		if (update == TI_NOPARENT) {
1279 			parent = -1;
1280 		} else {
1281 			iip = getinoinfo(ino);
1282 			if (iip != NULL) {
1283 				parent = iip->i_parent;
1284 			} else {
1285 				parent = lookup_dotdot_ino(ino);
1286 				if (parent != 0) {
1287 					/*
1288 					 * Make sure that the claimed
1289 					 * parent actually has a
1290 					 * reference to us.
1291 					 */
1292 					dp = ginode(parent);
1293 					idesc.id_name = lfname;
1294 					idesc.id_type = DATA;
1295 					idesc.id_func = findino;
1296 					idesc.id_number = ino;
1297 					idesc.id_fix = DONTKNOW;
1298 					if ((ckinode(dp, &idesc,
1299 					    CKI_TRAVERSE) & FOUND) == 0)
1300 						parent = 0;
1301 				}
1302 			}
1303 		}
1304 
1305 		mark_delayed_inodes(ino, numfrags(&sblock, new_length));
1306 		if (parent > 0) {
1307 			dp = ginode(parent);
1308 			LINK_RANGE(message, dp->di_nlink, -1);
1309 			if (message != NULL) {
1310 				LINK_CLEAR(message, parent, dp->di_mode,
1311 				    &idesc);
1312 				if (statemap[parent] == USTATE)
1313 					goto no_parent_update;
1314 			}
1315 			TRACK_LNCNTP(parent, lncntp[parent]--);
1316 		} else if ((mode == IFDIR) && (parent == 0)) {
1317 			/*
1318 			 * Currently don't have a good way to
1319 			 * handle this, so throw up our hands.
1320 			 * However, we know that we can still
1321 			 * do some good if we continue, so
1322 			 * don't actually exit yet.
1323 			 *
1324 			 * We don't do it for attrdirs,
1325 			 * because there aren't link counts
1326 			 * between them and their parents.
1327 			 */
1328 			pwarn("Could not determine former parent of "
1329 			    "inode %d, link counts are possibly\n"
1330 			    "incorrect.  Please rerun fsck(1M) to "
1331 			    "correct this.\n",
1332 			    ino);
1333 			iscorrupt = 1;
1334 		}
1335 		/*
1336 		 * ...else if it's a directory with parent == -1, then
1337 		 * we've not gotten far enough to know connectivity,
1338 		 * and it'll get handled automatically later.
1339 		 */
1340 	}
1341 
1342 no_parent_update:
1343 	init_inodesc(&idesc);
1344 	idesc.id_type = ADDR;
1345 	idesc.id_func = pass4check;
1346 	idesc.id_number = ino;
1347 	idesc.id_fix = DONTKNOW;
1348 	idesc.id_truncto = howmany(new_length, sblock.fs_bsize);
1349 	dp = ginode(ino);
1350 	if (ckinode(dp, &idesc, CKI_TRUNCATE) & ALTERED)
1351 		inodirty();
1352 
1353 	/*
1354 	 * This has to be done after ckinode(), so that all of
1355 	 * the fragments get visited.  Note that we assume we're
1356 	 * always truncating to a block boundary, rather than a
1357 	 * fragment boundary.
1358 	 */
1359 	dp = ginode(ino);
1360 	dp->di_size = new_length;
1361 
1362 	/*
1363 	 * Clear now-obsolete pointers.
1364 	 */
1365 	for (dblk = idesc.id_truncto + 1; dblk < NDADDR; dblk++) {
1366 		dp->di_db[dblk] = 0;
1367 	}
1368 
1369 	ilevel = get_indir_offsets(-1, idesc.id_truncto, NULL, NULL);
1370 	for (ilevel++; ilevel < NIADDR; ilevel++) {
1371 		dp->di_ib[ilevel] = 0;
1372 	}
1373 
1374 	inodirty();
1375 }
1376 
1377 /*
1378  * Release an inode's resources, then release the inode itself.
1379  */
1380 void
1381 freeino(fsck_ino_t ino, int update_parent)
1382 {
1383 	int cg;
1384 	struct dinode *dp;
1385 	struct cg *cgp;
1386 
1387 	n_files--;
1388 	dp = ginode(ino);
1389 	if (dp->di_size > (u_offset_t)MAXOFF_T) {
1390 		largefile_count--;
1391 	}
1392 	truncino(ino, 0, update_parent);
1393 
1394 	dp = ginode(ino);
1395 	if ((dp->di_mode & IFMT) == IFATTRDIR) {
1396 		clearshadow(ino, &attrclientinfo);
1397 		dp = ginode(ino);
1398 	}
1399 
1400 	clearinode(dp);
1401 	inodirty();
1402 	statemap[ino] = USTATE;
1403 
1404 	/*
1405 	 * Keep the disk in sync with us so that pass5 doesn't get
1406 	 * upset about spurious inconsistencies.
1407 	 */
1408 	cg = itog(&sblock, ino);
1409 	(void) getblk(&cgblk, (diskaddr_t)cgtod(&sblock, cg),
1410 	    (size_t)sblock.fs_cgsize);
1411 	cgp = cgblk.b_un.b_cg;
1412 	clrbit(cg_inosused(cgp), ino % sblock.fs_ipg);
1413 	cgp->cg_cs.cs_nifree += 1;
1414 	cgdirty();
1415 	sblock.fs_cstotal.cs_nifree += 1;
1416 	sbdirty();
1417 }
1418 
1419 void
1420 init_inoinfo(struct inoinfo *inp, struct dinode *dp, fsck_ino_t inum)
1421 {
1422 	inp->i_parent = ((inum == UFSROOTINO) ? UFSROOTINO : (fsck_ino_t)0);
1423 	inp->i_dotdot = (fsck_ino_t)0;
1424 	inp->i_isize = (offset_t)dp->di_size;
1425 	inp->i_blkssize = (NDADDR + NIADDR) * sizeof (daddr32_t);
1426 	inp->i_extattr = dp->di_oeftflag;
1427 	(void) memmove((void *)&inp->i_blks[0], (void *)&dp->di_db[0],
1428 	    inp->i_blkssize);
1429 }
1430 
1431 /*
1432  * Return the inode number in the ".." entry of the provided
1433  * directory inode.
1434  */
1435 static int
1436 lookup_dotdot_ino(fsck_ino_t ino)
1437 {
1438 	struct inodesc idesc;
1439 
1440 	init_inodesc(&idesc);
1441 	idesc.id_type = DATA;
1442 	idesc.id_func = findino;
1443 	idesc.id_name = "..";
1444 	idesc.id_number = ino;
1445 	idesc.id_fix = NOFIX;
1446 
1447 	if ((ckinode(ginode(ino), &idesc, CKI_TRAVERSE) & FOUND) != 0) {
1448 		return (idesc.id_parent);
1449 	}
1450 
1451 	return (0);
1452 }
1453 
1454 /*
1455  * Convenience wrapper around ckinode(findino()).
1456  */
1457 int
1458 lookup_named_ino(fsck_ino_t dir, caddr_t name)
1459 {
1460 	struct inodesc idesc;
1461 
1462 	init_inodesc(&idesc);
1463 	idesc.id_type = DATA;
1464 	idesc.id_func = findino;
1465 	idesc.id_name = name;
1466 	idesc.id_number = dir;
1467 	idesc.id_fix = NOFIX;
1468 
1469 	if ((ckinode(ginode(dir), &idesc, CKI_TRAVERSE) & FOUND) != 0) {
1470 		return (idesc.id_parent);
1471 	}
1472 
1473 	return (0);
1474 }
1475 
1476 /*
1477  * Marks inodes that are being orphaned and might need to be reconnected
1478  * by pass4().  The inode we're traversing is the directory whose
1479  * contents will be reconnected later.  id_parent is the lfn at which
1480  * to start looking at said contents.
1481  */
1482 static int
1483 mark_a_delayed_inode(struct inodesc *idesc)
1484 {
1485 	struct direct *dirp = idesc->id_dirp;
1486 
1487 	if (idesc->id_lbn < idesc->id_parent) {
1488 		return (KEEPON);
1489 	}
1490 
1491 	if (dirp->d_ino != 0 &&
1492 	    strcmp(dirp->d_name, ".") != 0 &&
1493 	    strcmp(dirp->d_name, "..") != 0) {
1494 		statemap[dirp->d_ino] &= ~INFOUND;
1495 		statemap[dirp->d_ino] |= INDELAYD;
1496 	}
1497 
1498 	return (KEEPON);
1499 }
1500 
1501 static void
1502 mark_delayed_inodes(fsck_ino_t ino, daddr32_t first_lfn)
1503 {
1504 	struct dinode *dp;
1505 	struct inodesc idelayed;
1506 
1507 	init_inodesc(&idelayed);
1508 	idelayed.id_number = ino;
1509 	idelayed.id_type = DATA;
1510 	idelayed.id_fix = NOFIX;
1511 	idelayed.id_func = mark_a_delayed_inode;
1512 	idelayed.id_parent = first_lfn;
1513 	idelayed.id_entryno = 2;
1514 
1515 	dp = ginode(ino);
1516 	(void) ckinode(dp, &idelayed, CKI_TRAVERSE);
1517 }
1518 
1519 /*
1520  * Clear the i_oeftflag/extended attribute pointer from INO.
1521  */
1522 void
1523 clearattrref(fsck_ino_t ino)
1524 {
1525 	struct dinode *dp;
1526 
1527 	dp = ginode(ino);
1528 	if (debug) {
1529 		if (dp->di_oeftflag == 0)
1530 			(void) printf("clearattref: no attr to clear on %d\n",
1531 			    ino);
1532 	}
1533 
1534 	dp->di_oeftflag = 0;
1535 	inodirty();
1536 }
1537