xref: /freebsd/sbin/fsck_ffs/dir.c (revision d65c432aa693043a241e9061d040c4d2b3e86d96)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #if 0
33 #ifndef lint
34 static const char sccsid[] = "@(#)dir.c	8.8 (Berkeley) 4/28/95";
35 #endif /* not lint */
36 #endif
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include <sys/param.h>
41 #include <sys/time.h>
42 #include <sys/types.h>
43 #include <sys/sysctl.h>
44 
45 #include <ufs/ufs/dinode.h>
46 #include <ufs/ufs/dir.h>
47 #include <ufs/ffs/fs.h>
48 
49 #include <err.h>
50 #include <string.h>
51 
52 #include "fsck.h"
53 
54 static struct	dirtemplate emptydir = {
55 	0, DIRBLKSIZ, DT_UNKNOWN, 0, "",
56 	0, 0, DT_UNKNOWN, 0, ""
57 };
58 static struct	dirtemplate dirhead = {
59 	0, 12, DT_DIR, 1, ".",
60 	0, DIRBLKSIZ - 12, DT_DIR, 2, ".."
61 };
62 
63 static int chgino(struct inodesc *);
64 static int dircheck(struct inodesc *, struct bufarea *, struct direct *);
65 static int expanddir(union dinode *dp, char *name);
66 static void freedir(ino_t ino, ino_t parent);
67 static struct direct *fsck_readdir(struct inodesc *);
68 static struct bufarea *getdirblk(ufs2_daddr_t blkno, long size);
69 static int lftempname(char *bufp, ino_t ino);
70 static int mkentry(struct inodesc *);
71 
72 /*
73  * Propagate connected state through the tree.
74  */
75 void
76 propagate(void)
77 {
78 	struct inoinfo **inpp, *inp;
79 	struct inoinfo **inpend;
80 	long change;
81 
82 	inpend = &inpsort[inplast];
83 	do {
84 		change = 0;
85 		for (inpp = inpsort; inpp < inpend; inpp++) {
86 			inp = *inpp;
87 			if (inp->i_parent == 0)
88 				continue;
89 			if (inoinfo(inp->i_parent)->ino_state == DFOUND &&
90 			    INO_IS_DUNFOUND(inp->i_number)) {
91 				inoinfo(inp->i_number)->ino_state = DFOUND;
92 				change++;
93 			}
94 		}
95 	} while (change > 0);
96 }
97 
98 /*
99  * Scan each entry in a directory block.
100  */
101 int
102 dirscan(struct inodesc *idesc)
103 {
104 	struct direct *dp;
105 	struct bufarea *bp;
106 	u_int dsize, n;
107 	long blksiz;
108 	char dbuf[DIRBLKSIZ];
109 
110 	if (idesc->id_type != DATA)
111 		errx(EEXIT, "wrong type to dirscan %d", idesc->id_type);
112 	if (idesc->id_entryno == 0 &&
113 	    (idesc->id_filesize & (DIRBLKSIZ - 1)) != 0)
114 		idesc->id_filesize = roundup(idesc->id_filesize, DIRBLKSIZ);
115 	blksiz = idesc->id_numfrags * sblock.fs_fsize;
116 	if (chkrange(idesc->id_blkno, idesc->id_numfrags)) {
117 		idesc->id_filesize -= blksiz;
118 		return (SKIP);
119 	}
120 	idesc->id_loc = 0;
121 	for (dp = fsck_readdir(idesc); dp != NULL; dp = fsck_readdir(idesc)) {
122 		dsize = dp->d_reclen;
123 		if (dsize > sizeof(dbuf))
124 			dsize = sizeof(dbuf);
125 		memmove(dbuf, dp, (size_t)dsize);
126 		idesc->id_dirp = (struct direct *)dbuf;
127 		if ((n = (*idesc->id_func)(idesc)) & ALTERED) {
128 			bp = getdirblk(idesc->id_blkno, blksiz);
129 			memmove(bp->b_un.b_buf + idesc->id_loc - dsize, dbuf,
130 			    (size_t)dsize);
131 			dirty(bp);
132 			sbdirty();
133 			rerun = 1;
134 		}
135 		if (n & STOP)
136 			return (n);
137 	}
138 	return (idesc->id_filesize > 0 ? KEEPON : STOP);
139 }
140 
141 /*
142  * Get and verify the next entry in a directory.
143  * We also verify that if there is another entry in the block that it is
144  * valid, so if it is not valid it can be subsumed into the current entry.
145  */
146 static struct direct *
147 fsck_readdir(struct inodesc *idesc)
148 {
149 	struct direct *dp, *ndp;
150 	struct bufarea *bp;
151 	long size, blksiz, subsume_ndp;
152 
153 	subsume_ndp = 0;
154 	blksiz = idesc->id_numfrags * sblock.fs_fsize;
155 	if (idesc->id_filesize <= 0 || idesc->id_loc >= blksiz)
156 		return (NULL);
157 	bp = getdirblk(idesc->id_blkno, blksiz);
158 	dp = (struct direct *)(bp->b_un.b_buf + idesc->id_loc);
159 	/*
160 	 * Only need to check current entry if it is the first in the
161 	 * the block, as later entries will have been checked in the
162 	 * previous call to this function.
163 	 */
164 	if (idesc->id_loc % DIRBLKSIZ != 0 || dircheck(idesc, bp, dp) != 0) {
165 		/*
166 		 * Current entry is good, update to point at next.
167 		 */
168 		idesc->id_loc += dp->d_reclen;
169 		idesc->id_filesize -= dp->d_reclen;
170 		/*
171 		 * If at end of directory block, just return this entry.
172 		 */
173 		if (idesc->id_filesize <= 0 || idesc->id_loc >= blksiz ||
174 		    idesc->id_loc % DIRBLKSIZ == 0)
175 			return (dp);
176 		/*
177 		 * If the next entry good, return this entry.
178 		 */
179 		ndp = (struct direct *)(bp->b_un.b_buf + idesc->id_loc);
180 		if (dircheck(idesc, bp, ndp) != 0)
181 			return (dp);
182 		/*
183 		 * The next entry is bad, so subsume it and the remainder
184 		 * of this directory block into this entry.
185 		 */
186 		subsume_ndp = 1;
187 	}
188 	/*
189 	 * Current or next entry is bad. Zap current entry or
190 	 * subsume next entry into current entry as appropriate.
191 	 */
192 	size = DIRBLKSIZ - (idesc->id_loc % DIRBLKSIZ);
193 	idesc->id_loc += size;
194 	idesc->id_filesize -= size;
195 	if (idesc->id_fix == IGNORE)
196 		return (NULL);
197 	if (subsume_ndp) {
198 		memset(ndp, 0, size);
199 		dp->d_reclen += size;
200 	} else {
201 		memset(dp, 0, size);
202 		dp->d_reclen = size;
203 	}
204 	if (dofix(idesc, "DIRECTORY CORRUPTED"))
205 		dirty(bp);
206 	return (dp);
207 }
208 
209 /*
210  * Verify that a directory entry is valid.
211  * This is a superset of the checks made in the kernel.
212  * Also optionally clears padding and unused directory space.
213  *
214  * Returns 0 if the entry is bad, 1 if the entry is good.
215  */
216 static int
217 dircheck(struct inodesc *idesc, struct bufarea *bp, struct direct *dp)
218 {
219 	size_t size;
220 	char *cp;
221 	u_int8_t namlen;
222 	int spaceleft, modified, unused;
223 
224 	spaceleft = DIRBLKSIZ - (idesc->id_loc % DIRBLKSIZ);
225 	size = DIRSIZ(0, dp);
226 	if (dp->d_reclen == 0 ||
227 	    dp->d_reclen > spaceleft ||
228 	    dp->d_reclen < size ||
229 	    idesc->id_filesize < size ||
230 	    (dp->d_reclen & (DIR_ROUNDUP - 1)) != 0)
231 		goto bad;
232 	modified = 0;
233 	if (dp->d_ino == 0) {
234 		if (!zflag || fswritefd < 0)
235 			return (1);
236 		/*
237 		 * Special case of an unused directory entry. Normally only
238 		 * occurs at the beginning of a directory block when the block
239 		 * contains no entries. Other than the first entry in a
240 		 * directory block, the kernel coalesces unused space with
241 		 * the previous entry by extending its d_reclen. However,
242 		 * when cleaning up a directory, fsck may set d_ino to zero
243 		 * in the middle of a directory block. If we're clearing out
244 		 * directory cruft (-z flag), then make sure that all directory
245 		 * space in entries with d_ino == 0 gets fully cleared.
246 		 */
247 		if (dp->d_type != 0) {
248 			dp->d_type = 0;
249 			modified = 1;
250 		}
251 		if (dp->d_namlen != 0) {
252 			dp->d_namlen = 0;
253 			modified = 1;
254 		}
255 		unused = dp->d_reclen - __offsetof(struct direct, d_name);
256 		for (cp = dp->d_name; unused > 0; unused--, cp++) {
257 			if (*cp != '\0') {
258 				*cp = '\0';
259 				modified = 1;
260 			}
261 		}
262 		if (modified)
263 			dirty(bp);
264 		return (1);
265 	}
266 	/*
267 	 * The d_type field should not be tested here. A bad type is an error
268 	 * in the entry itself but is not a corruption of the directory
269 	 * structure itself. So blowing away all the remaining entries in the
270 	 * directory block is inappropriate. Rather the type error should be
271 	 * checked in pass1 and fixed there.
272 	 *
273 	 * The name validation should also be done in pass1 although the
274 	 * check to see if the name is longer than fits in the space
275 	 * allocated for it (i.e., the *cp != '\0' fails after exiting the
276 	 * loop below) then it really is a structural error that requires
277 	 * the stronger action taken here.
278 	 */
279 	namlen = dp->d_namlen;
280 	if (namlen == 0 || dp->d_type > 15)
281 		goto bad;
282 	for (cp = dp->d_name, size = 0; size < namlen; size++) {
283 		if (*cp == '\0' || *cp++ == '/')
284 			goto bad;
285 	}
286 	if (*cp != '\0')
287 		goto bad;
288 	if (zflag && fswritefd >= 0) {
289 		/*
290 		 * Clear unused directory entry space, including the d_name
291 		 * padding.
292 		 */
293 		/* First figure the number of pad bytes. */
294 		unused = roundup2(namlen + 1, DIR_ROUNDUP) - (namlen + 1);
295 
296 		/* Add in the free space to the end of the record. */
297 		unused += dp->d_reclen - DIRSIZ(0, dp);
298 
299 		/*
300 		 * Now clear out the unused space, keeping track if we actually
301 		 * changed anything.
302 		 */
303 		for (cp = &dp->d_name[namlen + 1]; unused > 0; unused--, cp++) {
304 			if (*cp != '\0') {
305 				*cp = '\0';
306 				modified = 1;
307 			}
308 		}
309 
310 		if (modified)
311 			dirty(bp);
312 	}
313 	return (1);
314 
315 bad:
316 	if (debug)
317 		printf("Bad dir: ino %d reclen %d namlen %d type %d name %s\n",
318 		    dp->d_ino, dp->d_reclen, dp->d_namlen, dp->d_type,
319 		    dp->d_name);
320 	return (0);
321 }
322 
323 void
324 direrror(ino_t ino, const char *errmesg)
325 {
326 
327 	fileerror(ino, ino, errmesg);
328 }
329 
330 void
331 fileerror(ino_t cwd, ino_t ino, const char *errmesg)
332 {
333 	union dinode *dp;
334 	char pathbuf[MAXPATHLEN + 1];
335 
336 	pwarn("%s ", errmesg);
337 	if (ino < UFS_ROOTINO || ino > maxino) {
338 		pfatal("out-of-range inode number %ju", (uintmax_t)ino);
339 		return;
340 	}
341 	dp = ginode(ino);
342 	prtinode(ino, dp);
343 	printf("\n");
344 	getpathname(pathbuf, cwd, ino);
345 	if (ftypeok(dp))
346 		pfatal("%s=%s\n",
347 		    (DIP(dp, di_mode) & IFMT) == IFDIR ? "DIR" : "FILE",
348 		    pathbuf);
349 	else
350 		pfatal("NAME=%s\n", pathbuf);
351 }
352 
353 void
354 adjust(struct inodesc *idesc, int lcnt)
355 {
356 	union dinode *dp;
357 	int saveresolved;
358 
359 	dp = ginode(idesc->id_number);
360 	if (DIP(dp, di_nlink) == lcnt) {
361 		/*
362 		 * If we have not hit any unresolved problems, are running
363 		 * in preen mode, and are on a file system using soft updates,
364 		 * then just toss any partially allocated files.
365 		 */
366 		if (resolved && (preen || bkgrdflag) && usedsoftdep) {
367 			clri(idesc, "UNREF", 1);
368 			return;
369 		} else {
370 			/*
371 			 * The file system can be marked clean even if
372 			 * a file is not linked up, but is cleared.
373 			 * Hence, resolved should not be cleared when
374 			 * linkup is answered no, but clri is answered yes.
375 			 */
376 			saveresolved = resolved;
377 			if (linkup(idesc->id_number, (ino_t)0, NULL) == 0) {
378 				resolved = saveresolved;
379 				clri(idesc, "UNREF", 0);
380 				return;
381 			}
382 			/*
383 			 * Account for the new reference created by linkup().
384 			 */
385 			dp = ginode(idesc->id_number);
386 			lcnt--;
387 		}
388 	}
389 	if (lcnt != 0) {
390 		pwarn("LINK COUNT %s", (lfdir == idesc->id_number) ? lfname :
391 			((DIP(dp, di_mode) & IFMT) == IFDIR ? "DIR" : "FILE"));
392 		prtinode(idesc->id_number, dp);
393 		printf(" COUNT %d SHOULD BE %d",
394 			DIP(dp, di_nlink), DIP(dp, di_nlink) - lcnt);
395 		if (preen || usedsoftdep) {
396 			if (lcnt < 0) {
397 				printf("\n");
398 				pfatal("LINK COUNT INCREASING");
399 			}
400 			if (preen)
401 				printf(" (ADJUSTED)\n");
402 		}
403 		if (preen || reply("ADJUST") == 1) {
404 			if (bkgrdflag == 0) {
405 				DIP_SET(dp, di_nlink, DIP(dp, di_nlink) - lcnt);
406 				inodirty(dp);
407 			} else {
408 				cmd.value = idesc->id_number;
409 				cmd.size = -lcnt;
410 				if (debug)
411 					printf("adjrefcnt ino %ld amt %lld\n",
412 					    (long)cmd.value,
413 					    (long long)cmd.size);
414 				if (sysctl(adjrefcnt, MIBSIZE, 0, 0,
415 				    &cmd, sizeof cmd) == -1)
416 					rwerror("ADJUST INODE", cmd.value);
417 			}
418 		}
419 	}
420 }
421 
422 static int
423 mkentry(struct inodesc *idesc)
424 {
425 	struct direct *dirp = idesc->id_dirp;
426 	struct direct newent;
427 	int newlen, oldlen;
428 
429 	newent.d_namlen = strlen(idesc->id_name);
430 	newlen = DIRSIZ(0, &newent);
431 	if (dirp->d_ino != 0)
432 		oldlen = DIRSIZ(0, dirp);
433 	else
434 		oldlen = 0;
435 	if (dirp->d_reclen - oldlen < newlen)
436 		return (KEEPON);
437 	newent.d_reclen = dirp->d_reclen - oldlen;
438 	dirp->d_reclen = oldlen;
439 	dirp = (struct direct *)(((char *)dirp) + oldlen);
440 	dirp->d_ino = idesc->id_parent;	/* ino to be entered is in id_parent */
441 	dirp->d_reclen = newent.d_reclen;
442 	dirp->d_type = inoinfo(idesc->id_parent)->ino_type;
443 	dirp->d_namlen = newent.d_namlen;
444 	memmove(dirp->d_name, idesc->id_name, (size_t)newent.d_namlen + 1);
445 	return (ALTERED|STOP);
446 }
447 
448 static int
449 chgino(struct inodesc *idesc)
450 {
451 	struct direct *dirp = idesc->id_dirp;
452 
453 	if (memcmp(dirp->d_name, idesc->id_name, (int)dirp->d_namlen + 1))
454 		return (KEEPON);
455 	dirp->d_ino = idesc->id_parent;
456 	dirp->d_type = inoinfo(idesc->id_parent)->ino_type;
457 	return (ALTERED|STOP);
458 }
459 
460 int
461 linkup(ino_t orphan, ino_t parentdir, char *name)
462 {
463 	union dinode *dp;
464 	int lostdir;
465 	ino_t oldlfdir;
466 	struct inodesc idesc;
467 	char tempname[BUFSIZ];
468 
469 	memset(&idesc, 0, sizeof(struct inodesc));
470 	dp = ginode(orphan);
471 	lostdir = (DIP(dp, di_mode) & IFMT) == IFDIR;
472 	pwarn("UNREF %s ", lostdir ? "DIR" : "FILE");
473 	prtinode(orphan, dp);
474 	printf("\n");
475 	if (preen && DIP(dp, di_size) == 0)
476 		return (0);
477 	if (cursnapshot != 0) {
478 		pfatal("FILE LINKUP IN SNAPSHOT");
479 		return (0);
480 	}
481 	if (preen)
482 		printf(" (RECONNECTED)\n");
483 	else
484 		if (reply("RECONNECT") == 0)
485 			return (0);
486 	if (lfdir == 0) {
487 		dp = ginode(UFS_ROOTINO);
488 		idesc.id_name = strdup(lfname);
489 		idesc.id_type = DATA;
490 		idesc.id_func = findino;
491 		idesc.id_number = UFS_ROOTINO;
492 		if ((ckinode(dp, &idesc) & FOUND) != 0) {
493 			lfdir = idesc.id_parent;
494 		} else {
495 			pwarn("NO lost+found DIRECTORY");
496 			if (preen || reply("CREATE")) {
497 				lfdir = allocdir(UFS_ROOTINO, (ino_t)0, lfmode);
498 				if (lfdir != 0) {
499 					if (makeentry(UFS_ROOTINO, lfdir,
500 					    lfname) != 0) {
501 						numdirs++;
502 						if (preen)
503 							printf(" (CREATED)\n");
504 					} else {
505 						freedir(lfdir, UFS_ROOTINO);
506 						lfdir = 0;
507 						if (preen)
508 							printf("\n");
509 					}
510 				}
511 			}
512 		}
513 		if (lfdir == 0) {
514 			pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY");
515 			printf("\n\n");
516 			return (0);
517 		}
518 	}
519 	dp = ginode(lfdir);
520 	if ((DIP(dp, di_mode) & IFMT) != IFDIR) {
521 		pfatal("lost+found IS NOT A DIRECTORY");
522 		if (reply("REALLOCATE") == 0)
523 			return (0);
524 		oldlfdir = lfdir;
525 		if ((lfdir = allocdir(UFS_ROOTINO, (ino_t)0, lfmode)) == 0) {
526 			pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n");
527 			return (0);
528 		}
529 		if ((changeino(UFS_ROOTINO, lfname, lfdir) & ALTERED) == 0) {
530 			pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n");
531 			return (0);
532 		}
533 		inodirty(dp);
534 		idesc.id_type = ADDR;
535 		idesc.id_func = pass4check;
536 		idesc.id_number = oldlfdir;
537 		adjust(&idesc, inoinfo(oldlfdir)->ino_linkcnt + 1);
538 		inoinfo(oldlfdir)->ino_linkcnt = 0;
539 		dp = ginode(lfdir);
540 	}
541 	if (inoinfo(lfdir)->ino_state != DFOUND) {
542 		pfatal("SORRY. NO lost+found DIRECTORY\n\n");
543 		return (0);
544 	}
545 	(void)lftempname(tempname, orphan);
546 	if (makeentry(lfdir, orphan, (name ? name : tempname)) == 0) {
547 		pfatal("SORRY. NO SPACE IN lost+found DIRECTORY");
548 		printf("\n\n");
549 		return (0);
550 	}
551 	inoinfo(orphan)->ino_linkcnt--;
552 	if (lostdir) {
553 		if ((changeino(orphan, "..", lfdir) & ALTERED) == 0 &&
554 		    parentdir != (ino_t)-1)
555 			(void)makeentry(orphan, lfdir, "..");
556 		dp = ginode(lfdir);
557 		DIP_SET(dp, di_nlink, DIP(dp, di_nlink) + 1);
558 		inodirty(dp);
559 		inoinfo(lfdir)->ino_linkcnt++;
560 		pwarn("DIR I=%lu CONNECTED. ", (u_long)orphan);
561 		if (parentdir != (ino_t)-1) {
562 			printf("PARENT WAS I=%lu\n", (u_long)parentdir);
563 			/*
564 			 * The parent directory, because of the ordering
565 			 * guarantees, has had the link count incremented
566 			 * for the child, but no entry was made.  This
567 			 * fixes the parent link count so that fsck does
568 			 * not need to be rerun.
569 			 */
570 			inoinfo(parentdir)->ino_linkcnt++;
571 		}
572 		if (preen == 0)
573 			printf("\n");
574 	}
575 	return (1);
576 }
577 
578 /*
579  * fix an entry in a directory.
580  */
581 int
582 changeino(ino_t dir, const char *name, ino_t newnum)
583 {
584 	struct inodesc idesc;
585 
586 	memset(&idesc, 0, sizeof(struct inodesc));
587 	idesc.id_type = DATA;
588 	idesc.id_func = chgino;
589 	idesc.id_number = dir;
590 	idesc.id_fix = DONTKNOW;
591 	idesc.id_name = strdup(name);
592 	idesc.id_parent = newnum;	/* new value for name */
593 	return (ckinode(ginode(dir), &idesc));
594 }
595 
596 /*
597  * make an entry in a directory
598  */
599 int
600 makeentry(ino_t parent, ino_t ino, const char *name)
601 {
602 	union dinode *dp;
603 	struct inodesc idesc;
604 	char pathbuf[MAXPATHLEN + 1];
605 
606 	if (parent < UFS_ROOTINO || parent >= maxino ||
607 	    ino < UFS_ROOTINO || ino >= maxino)
608 		return (0);
609 	memset(&idesc, 0, sizeof(struct inodesc));
610 	idesc.id_type = DATA;
611 	idesc.id_func = mkentry;
612 	idesc.id_number = parent;
613 	idesc.id_parent = ino;	/* this is the inode to enter */
614 	idesc.id_fix = DONTKNOW;
615 	idesc.id_name = strdup(name);
616 	dp = ginode(parent);
617 	if (DIP(dp, di_size) % DIRBLKSIZ) {
618 		DIP_SET(dp, di_size, roundup(DIP(dp, di_size), DIRBLKSIZ));
619 		inodirty(dp);
620 	}
621 	if ((ckinode(dp, &idesc) & ALTERED) != 0)
622 		return (1);
623 	getpathname(pathbuf, parent, parent);
624 	dp = ginode(parent);
625 	if (expanddir(dp, pathbuf) == 0)
626 		return (0);
627 	return (ckinode(dp, &idesc) & ALTERED);
628 }
629 
630 /*
631  * Attempt to expand the size of a directory
632  */
633 static int
634 expanddir(union dinode *dp, char *name)
635 {
636 	ufs2_daddr_t lastbn, newblk;
637 	struct bufarea *bp;
638 	char *cp, firstblk[DIRBLKSIZ];
639 
640 	lastbn = lblkno(&sblock, DIP(dp, di_size));
641 	if (lastbn >= UFS_NDADDR - 1 || DIP(dp, di_db[lastbn]) == 0 ||
642 	    DIP(dp, di_size) == 0)
643 		return (0);
644 	if ((newblk = allocblk(sblock.fs_frag)) == 0)
645 		return (0);
646 	DIP_SET(dp, di_db[lastbn + 1], DIP(dp, di_db[lastbn]));
647 	DIP_SET(dp, di_db[lastbn], newblk);
648 	DIP_SET(dp, di_size, DIP(dp, di_size) + sblock.fs_bsize);
649 	DIP_SET(dp, di_blocks, DIP(dp, di_blocks) + btodb(sblock.fs_bsize));
650 	bp = getdirblk(DIP(dp, di_db[lastbn + 1]),
651 		sblksize(&sblock, DIP(dp, di_size), lastbn + 1));
652 	if (bp->b_errs)
653 		goto bad;
654 	memmove(firstblk, bp->b_un.b_buf, DIRBLKSIZ);
655 	bp = getdirblk(newblk, sblock.fs_bsize);
656 	if (bp->b_errs)
657 		goto bad;
658 	memmove(bp->b_un.b_buf, firstblk, DIRBLKSIZ);
659 	for (cp = &bp->b_un.b_buf[DIRBLKSIZ];
660 	     cp < &bp->b_un.b_buf[sblock.fs_bsize];
661 	     cp += DIRBLKSIZ)
662 		memmove(cp, &emptydir, sizeof emptydir);
663 	dirty(bp);
664 	bp = getdirblk(DIP(dp, di_db[lastbn + 1]),
665 		sblksize(&sblock, DIP(dp, di_size), lastbn + 1));
666 	if (bp->b_errs)
667 		goto bad;
668 	memmove(bp->b_un.b_buf, &emptydir, sizeof emptydir);
669 	pwarn("NO SPACE LEFT IN %s", name);
670 	if (preen)
671 		printf(" (EXPANDED)\n");
672 	else if (reply("EXPAND") == 0)
673 		goto bad;
674 	dirty(bp);
675 	inodirty(dp);
676 	return (1);
677 bad:
678 	DIP_SET(dp, di_db[lastbn], DIP(dp, di_db[lastbn + 1]));
679 	DIP_SET(dp, di_db[lastbn + 1], 0);
680 	DIP_SET(dp, di_size, DIP(dp, di_size) - sblock.fs_bsize);
681 	DIP_SET(dp, di_blocks, DIP(dp, di_blocks) - btodb(sblock.fs_bsize));
682 	freeblk(newblk, sblock.fs_frag);
683 	return (0);
684 }
685 
686 /*
687  * allocate a new directory
688  */
689 ino_t
690 allocdir(ino_t parent, ino_t request, int mode)
691 {
692 	ino_t ino;
693 	char *cp;
694 	union dinode *dp;
695 	struct bufarea *bp;
696 	struct inoinfo *inp;
697 	struct dirtemplate *dirp;
698 
699 	ino = allocino(request, IFDIR|mode);
700 	dirp = &dirhead;
701 	dirp->dot_ino = ino;
702 	dirp->dotdot_ino = parent;
703 	dp = ginode(ino);
704 	bp = getdirblk(DIP(dp, di_db[0]), sblock.fs_fsize);
705 	if (bp->b_errs) {
706 		freeino(ino);
707 		return (0);
708 	}
709 	memmove(bp->b_un.b_buf, dirp, sizeof(struct dirtemplate));
710 	for (cp = &bp->b_un.b_buf[DIRBLKSIZ];
711 	     cp < &bp->b_un.b_buf[sblock.fs_fsize];
712 	     cp += DIRBLKSIZ)
713 		memmove(cp, &emptydir, sizeof emptydir);
714 	dirty(bp);
715 	DIP_SET(dp, di_nlink, 2);
716 	inodirty(dp);
717 	if (ino == UFS_ROOTINO) {
718 		inoinfo(ino)->ino_linkcnt = DIP(dp, di_nlink);
719 		cacheino(dp, ino);
720 		return(ino);
721 	}
722 	if (!INO_IS_DVALID(parent)) {
723 		freeino(ino);
724 		return (0);
725 	}
726 	cacheino(dp, ino);
727 	inp = getinoinfo(ino);
728 	inp->i_parent = parent;
729 	inp->i_dotdot = parent;
730 	inoinfo(ino)->ino_state = inoinfo(parent)->ino_state;
731 	if (inoinfo(ino)->ino_state == DSTATE) {
732 		inoinfo(ino)->ino_linkcnt = DIP(dp, di_nlink);
733 		inoinfo(parent)->ino_linkcnt++;
734 	}
735 	dp = ginode(parent);
736 	DIP_SET(dp, di_nlink, DIP(dp, di_nlink) + 1);
737 	inodirty(dp);
738 	return (ino);
739 }
740 
741 /*
742  * free a directory inode
743  */
744 static void
745 freedir(ino_t ino, ino_t parent)
746 {
747 	union dinode *dp;
748 
749 	if (ino != parent) {
750 		dp = ginode(parent);
751 		DIP_SET(dp, di_nlink, DIP(dp, di_nlink) - 1);
752 		inodirty(dp);
753 	}
754 	freeino(ino);
755 }
756 
757 /*
758  * generate a temporary name for the lost+found directory.
759  */
760 static int
761 lftempname(char *bufp, ino_t ino)
762 {
763 	ino_t in;
764 	char *cp;
765 	int namlen;
766 
767 	cp = bufp + 2;
768 	for (in = maxino; in > 0; in /= 10)
769 		cp++;
770 	*--cp = 0;
771 	namlen = cp - bufp;
772 	in = ino;
773 	while (cp > bufp) {
774 		*--cp = (in % 10) + '0';
775 		in /= 10;
776 	}
777 	*cp = '#';
778 	return (namlen);
779 }
780 
781 /*
782  * Get a directory block.
783  * Insure that it is held until another is requested.
784  */
785 static struct bufarea *
786 getdirblk(ufs2_daddr_t blkno, long size)
787 {
788 
789 	if (pdirbp != NULL)
790 		pdirbp->b_flags &= ~B_INUSE;
791 	pdirbp = getdatablk(blkno, size, BT_DIRDATA);
792 	return (pdirbp);
793 }
794