xref: /titanic_41/usr/src/cmd/fs.d/ufs/fsck/inode.c (revision 103b2b152ab1f30e081cd8f98b88e71e6cd6d2fc)
1 /*
2  * Copyright 2005 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, cg_fatal;
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, &cg_fatal);
1180 	if (err != NULL) {
1181 		pfatal("CG %d: %s\n", cg, err);
1182 		free((void *)err);
1183 		if (cg_fatal)
1184 			errexit(
1185 	    "Irreparable cylinder group header problem.  Program terminated.");
1186 		if (reply("REPAIR") == 0)
1187 			errexit("Program terminated.");
1188 		fix_cg(cgp, cg);
1189 	}
1190 	setbit(cg_inosused(cgp), ino % sblock.fs_ipg);
1191 	cgp->cg_cs.cs_nifree--;
1192 	cgdirty();
1193 
1194 	if (lastino < ino)
1195 		lastino = ino;
1196 
1197 	/*
1198 	 * Don't currently support IFATTRDIR or any of the other
1199 	 * types, as they aren't needed.
1200 	 */
1201 	switch (type & IFMT) {
1202 	case IFDIR:
1203 		statemap[ino] = DSTATE;
1204 		cgp->cg_cs.cs_ndir++;
1205 		break;
1206 	case IFREG:
1207 	case IFLNK:
1208 		statemap[ino] = FSTATE;
1209 		break;
1210 	default:
1211 		/*
1212 		 * Pretend nothing ever happened.  This clears the
1213 		 * dirty flag, among other things.
1214 		 */
1215 		initbarea(&cgblk);
1216 		if (debug)
1217 			(void) printf("allocino: unknown type 0%o\n",
1218 			    type & IFMT);
1219 		return (0);
1220 	}
1221 
1222 	/*
1223 	 * We're allocating what should be a completely-unused inode,
1224 	 * so make sure we don't inherit anything from any previous
1225 	 * incarnations.
1226 	 */
1227 	dp = ginode(ino);
1228 	(void) memset((void *)dp, 0, sizeof (struct dinode));
1229 	dp->di_db[0] = allocblk(1);
1230 	if (dp->di_db[0] == 0) {
1231 		statemap[ino] = USTATE;
1232 		return (0);
1233 	}
1234 	dp->di_mode = (mode_t)type;
1235 	(void) time(&t);
1236 	dp->di_atime = (time32_t)t;
1237 	dp->di_ctime = dp->di_atime;
1238 	dp->di_mtime = dp->di_ctime;
1239 	dp->di_size = (u_offset_t)sblock.fs_fsize;
1240 	dp->di_blocks = btodb(sblock.fs_fsize);
1241 	n_files++;
1242 	inodirty();
1243 	return (ino);
1244 }
1245 
1246 /*
1247  * Release some or all of the blocks of an inode.
1248  * Only truncates down.  Assumes new_length is appropriately aligned
1249  * to a block boundary (or a directory block boundary, if it's a
1250  * directory).
1251  *
1252  * If this is a directory, discard all of its contents first, so
1253  * we don't create a bunch of orphans that would need another fsck
1254  * run to clean up.
1255  *
1256  * Even if truncating to zero length, the inode remains allocated.
1257  */
1258 void
1259 truncino(fsck_ino_t ino, offset_t new_length, int update)
1260 {
1261 	struct inodesc idesc;
1262 	struct inoinfo *iip;
1263 	struct dinode *dp;
1264 	fsck_ino_t parent;
1265 	mode_t mode;
1266 	caddr_t message;
1267 	int isdir;
1268 	int ilevel, dblk;
1269 
1270 	dp = ginode(ino);
1271 	mode = (dp->di_mode & IFMT);
1272 	isdir = (mode == IFDIR) || (mode == IFATTRDIR);
1273 
1274 	if (isdir) {
1275 		/*
1276 		 * Go with the parent we found by chasing references,
1277 		 * if we've gotten that far.  Otherwise, use what the
1278 		 * directory itself claims.  If there's no ``..'' entry
1279 		 * in it, give up trying to get the link counts right.
1280 		 */
1281 		if (update == TI_NOPARENT) {
1282 			parent = -1;
1283 		} else {
1284 			iip = getinoinfo(ino);
1285 			if (iip != NULL) {
1286 				parent = iip->i_parent;
1287 			} else {
1288 				parent = lookup_dotdot_ino(ino);
1289 				if (parent != 0) {
1290 					/*
1291 					 * Make sure that the claimed
1292 					 * parent actually has a
1293 					 * reference to us.
1294 					 */
1295 					dp = ginode(parent);
1296 					idesc.id_name = lfname;
1297 					idesc.id_type = DATA;
1298 					idesc.id_func = findino;
1299 					idesc.id_number = ino;
1300 					idesc.id_fix = DONTKNOW;
1301 					if ((ckinode(dp, &idesc,
1302 					    CKI_TRAVERSE) & FOUND) == 0)
1303 						parent = 0;
1304 				}
1305 			}
1306 		}
1307 
1308 		mark_delayed_inodes(ino, numfrags(&sblock, new_length));
1309 		if (parent > 0) {
1310 			dp = ginode(parent);
1311 			LINK_RANGE(message, dp->di_nlink, -1);
1312 			if (message != NULL) {
1313 				LINK_CLEAR(message, parent, dp->di_mode,
1314 				    &idesc);
1315 				if (statemap[parent] == USTATE)
1316 					goto no_parent_update;
1317 			}
1318 			TRACK_LNCNTP(parent, lncntp[parent]--);
1319 		} else if ((mode == IFDIR) && (parent == 0)) {
1320 			/*
1321 			 * Currently don't have a good way to
1322 			 * handle this, so throw up our hands.
1323 			 * However, we know that we can still
1324 			 * do some good if we continue, so
1325 			 * don't actually exit yet.
1326 			 *
1327 			 * We don't do it for attrdirs,
1328 			 * because there aren't link counts
1329 			 * between them and their parents.
1330 			 */
1331 			pwarn("Could not determine former parent of "
1332 			    "inode %d, link counts are possibly\n"
1333 			    "incorrect.  Please rerun fsck(1M) to "
1334 			    "correct this.\n",
1335 			    ino);
1336 			iscorrupt = 1;
1337 		}
1338 		/*
1339 		 * ...else if it's a directory with parent == -1, then
1340 		 * we've not gotten far enough to know connectivity,
1341 		 * and it'll get handled automatically later.
1342 		 */
1343 	}
1344 
1345 no_parent_update:
1346 	init_inodesc(&idesc);
1347 	idesc.id_type = ADDR;
1348 	idesc.id_func = pass4check;
1349 	idesc.id_number = ino;
1350 	idesc.id_fix = DONTKNOW;
1351 	idesc.id_truncto = howmany(new_length, sblock.fs_bsize);
1352 	dp = ginode(ino);
1353 	if (ckinode(dp, &idesc, CKI_TRUNCATE) & ALTERED)
1354 		inodirty();
1355 
1356 	/*
1357 	 * This has to be done after ckinode(), so that all of
1358 	 * the fragments get visited.  Note that we assume we're
1359 	 * always truncating to a block boundary, rather than a
1360 	 * fragment boundary.
1361 	 */
1362 	dp = ginode(ino);
1363 	dp->di_size = new_length;
1364 
1365 	/*
1366 	 * Clear now-obsolete pointers.
1367 	 */
1368 	for (dblk = idesc.id_truncto + 1; dblk < NDADDR; dblk++) {
1369 		dp->di_db[dblk] = 0;
1370 	}
1371 
1372 	ilevel = get_indir_offsets(-1, idesc.id_truncto, NULL, NULL);
1373 	for (ilevel++; ilevel < NIADDR; ilevel++) {
1374 		dp->di_ib[ilevel] = 0;
1375 	}
1376 
1377 	inodirty();
1378 }
1379 
1380 /*
1381  * Release an inode's resources, then release the inode itself.
1382  */
1383 void
1384 freeino(fsck_ino_t ino, int update_parent)
1385 {
1386 	int cg;
1387 	struct dinode *dp;
1388 	struct cg *cgp;
1389 
1390 	n_files--;
1391 	dp = ginode(ino);
1392 	if (dp->di_size > (u_offset_t)MAXOFF_T) {
1393 		largefile_count--;
1394 	}
1395 	truncino(ino, 0, update_parent);
1396 
1397 	dp = ginode(ino);
1398 	if ((dp->di_mode & IFMT) == IFATTRDIR) {
1399 		clearshadow(ino, &attrclientinfo);
1400 		dp = ginode(ino);
1401 	}
1402 
1403 	clearinode(dp);
1404 	inodirty();
1405 	statemap[ino] = USTATE;
1406 
1407 	/*
1408 	 * Keep the disk in sync with us so that pass5 doesn't get
1409 	 * upset about spurious inconsistencies.
1410 	 */
1411 	cg = itog(&sblock, ino);
1412 	(void) getblk(&cgblk, (diskaddr_t)cgtod(&sblock, cg),
1413 	    (size_t)sblock.fs_cgsize);
1414 	cgp = cgblk.b_un.b_cg;
1415 	clrbit(cg_inosused(cgp), ino % sblock.fs_ipg);
1416 	cgp->cg_cs.cs_nifree += 1;
1417 	cgdirty();
1418 	sblock.fs_cstotal.cs_nifree += 1;
1419 	sbdirty();
1420 }
1421 
1422 void
1423 init_inoinfo(struct inoinfo *inp, struct dinode *dp, fsck_ino_t inum)
1424 {
1425 	inp->i_parent = ((inum == UFSROOTINO) ? UFSROOTINO : (fsck_ino_t)0);
1426 	inp->i_dotdot = (fsck_ino_t)0;
1427 	inp->i_isize = (offset_t)dp->di_size;
1428 	inp->i_blkssize = (NDADDR + NIADDR) * sizeof (daddr32_t);
1429 	inp->i_extattr = dp->di_oeftflag;
1430 	(void) memmove((void *)&inp->i_blks[0], (void *)&dp->di_db[0],
1431 	    inp->i_blkssize);
1432 }
1433 
1434 /*
1435  * Return the inode number in the ".." entry of the provided
1436  * directory inode.
1437  */
1438 static int
1439 lookup_dotdot_ino(fsck_ino_t ino)
1440 {
1441 	struct inodesc idesc;
1442 
1443 	init_inodesc(&idesc);
1444 	idesc.id_type = DATA;
1445 	idesc.id_func = findino;
1446 	idesc.id_name = "..";
1447 	idesc.id_number = ino;
1448 	idesc.id_fix = NOFIX;
1449 
1450 	if ((ckinode(ginode(ino), &idesc, CKI_TRAVERSE) & FOUND) != 0) {
1451 		return (idesc.id_parent);
1452 	}
1453 
1454 	return (0);
1455 }
1456 
1457 /*
1458  * Convenience wrapper around ckinode(findino()).
1459  */
1460 int
1461 lookup_named_ino(fsck_ino_t dir, caddr_t name)
1462 {
1463 	struct inodesc idesc;
1464 
1465 	init_inodesc(&idesc);
1466 	idesc.id_type = DATA;
1467 	idesc.id_func = findino;
1468 	idesc.id_name = name;
1469 	idesc.id_number = dir;
1470 	idesc.id_fix = NOFIX;
1471 
1472 	if ((ckinode(ginode(dir), &idesc, CKI_TRAVERSE) & FOUND) != 0) {
1473 		return (idesc.id_parent);
1474 	}
1475 
1476 	return (0);
1477 }
1478 
1479 /*
1480  * Marks inodes that are being orphaned and might need to be reconnected
1481  * by pass4().  The inode we're traversing is the directory whose
1482  * contents will be reconnected later.  id_parent is the lfn at which
1483  * to start looking at said contents.
1484  */
1485 static int
1486 mark_a_delayed_inode(struct inodesc *idesc)
1487 {
1488 	struct direct *dirp = idesc->id_dirp;
1489 
1490 	if (idesc->id_lbn < idesc->id_parent) {
1491 		return (KEEPON);
1492 	}
1493 
1494 	if (dirp->d_ino != 0 &&
1495 	    strcmp(dirp->d_name, ".") != 0 &&
1496 	    strcmp(dirp->d_name, "..") != 0) {
1497 		statemap[dirp->d_ino] &= ~INFOUND;
1498 		statemap[dirp->d_ino] |= INDELAYD;
1499 	}
1500 
1501 	return (KEEPON);
1502 }
1503 
1504 static void
1505 mark_delayed_inodes(fsck_ino_t ino, daddr32_t first_lfn)
1506 {
1507 	struct dinode *dp;
1508 	struct inodesc idelayed;
1509 
1510 	init_inodesc(&idelayed);
1511 	idelayed.id_number = ino;
1512 	idelayed.id_type = DATA;
1513 	idelayed.id_fix = NOFIX;
1514 	idelayed.id_func = mark_a_delayed_inode;
1515 	idelayed.id_parent = first_lfn;
1516 	idelayed.id_entryno = 2;
1517 
1518 	dp = ginode(ino);
1519 	(void) ckinode(dp, &idelayed, CKI_TRAVERSE);
1520 }
1521 
1522 /*
1523  * Clear the i_oeftflag/extended attribute pointer from INO.
1524  */
1525 void
1526 clearattrref(fsck_ino_t ino)
1527 {
1528 	struct dinode *dp;
1529 
1530 	dp = ginode(ino);
1531 	if (debug) {
1532 		if (dp->di_oeftflag == 0)
1533 			(void) printf("clearattref: no attr to clear on %d\n",
1534 			    ino);
1535 	}
1536 
1537 	dp->di_oeftflag = 0;
1538 	inodirty();
1539 }
1540