xref: /freebsd/sys/ufs/ufs/ufs_lookup.c (revision 16038816)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)ufs_lookup.c	8.15 (Berkeley) 6/16/95
37  */
38 
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41 
42 #include "opt_ufs.h"
43 #include "opt_quota.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/namei.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/proc.h>
52 #include <sys/stat.h>
53 #include <sys/mount.h>
54 #include <sys/vnode.h>
55 #include <sys/sysctl.h>
56 
57 #include <vm/vm.h>
58 #include <vm/vm_extern.h>
59 
60 #include <ufs/ufs/extattr.h>
61 #include <ufs/ufs/quota.h>
62 #include <ufs/ufs/inode.h>
63 #include <ufs/ufs/dir.h>
64 #ifdef UFS_DIRHASH
65 #include <ufs/ufs/dirhash.h>
66 #endif
67 #include <ufs/ufs/ufsmount.h>
68 #include <ufs/ufs/ufs_extern.h>
69 #include <ufs/ffs/ffs_extern.h>
70 
71 #ifdef DIAGNOSTIC
72 static int	dirchk = 1;
73 #else
74 static int	dirchk = 0;
75 #endif
76 
77 SYSCTL_INT(_debug, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
78 
79 static int
80 ufs_delete_denied(struct vnode *vdp, struct vnode *tdp, struct ucred *cred,
81     struct thread *td)
82 {
83 	int error;
84 
85 #ifdef UFS_ACL
86 	/*
87 	 * NFSv4 Minor Version 1, draft-ietf-nfsv4-minorversion1-03.txt
88 	 *
89 	 * 3.16.2.1. ACE4_DELETE vs. ACE4_DELETE_CHILD
90 	 */
91 
92 	/*
93 	 * XXX: Is this check required?
94 	 */
95 	error = VOP_ACCESS(vdp, VEXEC, cred, td);
96 	if (error)
97 		return (error);
98 
99 	error = VOP_ACCESSX(tdp, VDELETE, cred, td);
100 	if (error == 0)
101 		return (0);
102 
103 	error = VOP_ACCESSX(vdp, VDELETE_CHILD, cred, td);
104 	if (error == 0)
105 		return (0);
106 
107 	error = VOP_ACCESSX(vdp, VEXPLICIT_DENY | VDELETE_CHILD, cred, td);
108 	if (error)
109 		return (error);
110 
111 #endif /* !UFS_ACL */
112 
113 	/*
114 	 * Standard Unix access control - delete access requires VWRITE.
115 	 */
116 	error = VOP_ACCESS(vdp, VWRITE, cred, td);
117 	if (error)
118 		return (error);
119 
120 	/*
121 	 * If directory is "sticky", then user must own
122 	 * the directory, or the file in it, else she
123 	 * may not delete it (unless she's root). This
124 	 * implements append-only directories.
125 	 */
126 	if ((VTOI(vdp)->i_mode & ISVTX) &&
127 	    VOP_ACCESS(vdp, VADMIN, cred, td) &&
128 	    VOP_ACCESS(tdp, VADMIN, cred, td))
129 		return (EPERM);
130 
131 	return (0);
132 }
133 
134 /*
135  * Convert a component of a pathname into a pointer to a locked inode.
136  * This is a very central and rather complicated routine.
137  * If the filesystem is not maintained in a strict tree hierarchy,
138  * this can result in a deadlock situation (see comments in code below).
139  *
140  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
141  * on whether the name is to be looked up, created, renamed, or deleted.
142  * When CREATE, RENAME, or DELETE is specified, information usable in
143  * creating, renaming, or deleting a directory entry may be calculated.
144  * If flag has LOCKPARENT or'ed into it and the target of the pathname
145  * exists, lookup returns both the target and its parent directory locked.
146  * When creating or renaming and LOCKPARENT is specified, the target may
147  * not be ".".  When deleting and LOCKPARENT is specified, the target may
148  * be "."., but the caller must check to ensure it does an vrele and vput
149  * instead of two vputs.
150  *
151  * This routine is actually used as VOP_CACHEDLOOKUP method, and the
152  * filesystem employs the generic vfs_cache_lookup() as VOP_LOOKUP
153  * method.
154  *
155  * vfs_cache_lookup() performs the following for us:
156  *	check that it is a directory
157  *	check accessibility of directory
158  *	check for modification attempts on read-only mounts
159  *	if name found in cache
160  *	    if at end of path and deleting or creating
161  *		drop it
162  *	     else
163  *		return name.
164  *	return VOP_CACHEDLOOKUP()
165  *
166  * Overall outline of ufs_lookup:
167  *
168  *	search for name in directory, to found or notfound
169  * notfound:
170  *	if creating, return locked directory, leaving info on available slots
171  *	else return error
172  * found:
173  *	if at end of path and deleting, return information to allow delete
174  *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
175  *	  inode and return info to allow rewrite
176  *	if not at end, add name to cache; if at end and neither creating
177  *	  nor deleting, add name to cache
178  */
179 int
180 ufs_lookup(ap)
181 	struct vop_cachedlookup_args /* {
182 		struct vnode *a_dvp;
183 		struct vnode **a_vpp;
184 		struct componentname *a_cnp;
185 	} */ *ap;
186 {
187 
188 	return (ufs_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
189 }
190 
191 int
192 ufs_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
193     ino_t *dd_ino)
194 {
195 	struct inode *dp;		/* inode for directory being searched */
196 	struct buf *bp;			/* a buffer of directory entries */
197 	struct direct *ep;		/* the current directory entry */
198 	int entryoffsetinblock;		/* offset of ep in bp's buffer */
199 	enum {NONE, COMPACT, FOUND} slotstatus;
200 	doff_t slotoffset;		/* offset of area with free space */
201 	doff_t i_diroff;		/* cached i_diroff value. */
202 	doff_t i_offset;		/* cached i_offset value. */
203 	int slotsize;			/* size of area at slotoffset */
204 	int slotfreespace;		/* amount of space free in slot */
205 	int slotneeded;			/* size of the entry we're seeking */
206 	int numdirpasses;		/* strategy for directory search */
207 	doff_t endsearch;		/* offset to end directory search */
208 	doff_t prevoff;			/* prev entry dp->i_offset */
209 	struct vnode *pdp;		/* saved dp during symlink work */
210 	struct vnode *tdp;		/* returned by VFS_VGET */
211 	doff_t enduseful;		/* pointer past last used dir slot */
212 	u_long bmask;			/* block offset mask */
213 	int namlen, error;
214 	struct ucred *cred = cnp->cn_cred;
215 	int flags = cnp->cn_flags;
216 	int nameiop = cnp->cn_nameiop;
217 	ino_t ino, ino1;
218 	int ltype;
219 
220 	if (vpp != NULL)
221 		*vpp = NULL;
222 
223 	dp = VTOI(vdp);
224 	if (dp->i_effnlink == 0)
225 		return (ENOENT);
226 
227 	/*
228 	 * Create a vm object if vmiodirenable is enabled.
229 	 * Alternatively we could call vnode_create_vobject
230 	 * in VFS_VGET but we could end up creating objects
231 	 * that are never used.
232 	 */
233 	vnode_create_vobject(vdp, DIP(dp, i_size), cnp->cn_thread);
234 
235 	bmask = VFSTOUFS(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
236 
237 #ifdef DEBUG_VFS_LOCKS
238 	/*
239 	 * Assert that the directory vnode is locked, and locked
240 	 * exclusively for the last component lookup for modifying
241 	 * operations.
242 	 *
243 	 * The directory-modifying operations need to save
244 	 * intermediate state in the inode between namei() call and
245 	 * actual directory manipulations.  See fields in the struct
246 	 * inode marked as 'used during directory lookup'.  We must
247 	 * ensure that upgrade in namei() does not happen, since
248 	 * upgrade might need to unlock vdp.  If quotas are enabled,
249 	 * getinoquota() also requires exclusive lock to modify inode.
250 	 */
251 	ASSERT_VOP_LOCKED(vdp, "ufs_lookup1");
252 	if ((nameiop == CREATE || nameiop == DELETE || nameiop == RENAME) &&
253 	    (flags & (LOCKPARENT | ISLASTCN)) == (LOCKPARENT | ISLASTCN))
254 		ASSERT_VOP_ELOCKED(vdp, "ufs_lookup2");
255 #endif
256 
257 restart:
258 	bp = NULL;
259 	slotoffset = -1;
260 
261 	/*
262 	 * We now have a segment name to search for, and a directory to search.
263 	 *
264 	 * Suppress search for slots unless creating
265 	 * file and at end of pathname, in which case
266 	 * we watch for a place to put the new file in
267 	 * case it doesn't already exist.
268 	 */
269 	ino = 0;
270 	i_diroff = dp->i_diroff;
271 	slotstatus = FOUND;
272 	slotfreespace = slotsize = slotneeded = 0;
273 	if ((nameiop == CREATE || nameiop == RENAME) &&
274 	    (flags & ISLASTCN)) {
275 		slotstatus = NONE;
276 		slotneeded = DIRECTSIZ(cnp->cn_namelen);
277 	}
278 
279 #ifdef UFS_DIRHASH
280 	/*
281 	 * Use dirhash for fast operations on large directories. The logic
282 	 * to determine whether to hash the directory is contained within
283 	 * ufsdirhash_build(); a zero return means that it decided to hash
284 	 * this directory and it successfully built up the hash table.
285 	 */
286 	if (ufsdirhash_build(dp) == 0) {
287 		/* Look for a free slot if needed. */
288 		enduseful = dp->i_size;
289 		if (slotstatus != FOUND) {
290 			slotoffset = ufsdirhash_findfree(dp, slotneeded,
291 			    &slotsize);
292 			if (slotoffset >= 0) {
293 				slotstatus = COMPACT;
294 				enduseful = ufsdirhash_enduseful(dp);
295 				if (enduseful < 0)
296 					enduseful = dp->i_size;
297 			}
298 		}
299 		/* Look up the component. */
300 		numdirpasses = 1;
301 		entryoffsetinblock = 0; /* silence compiler warning */
302 		switch (ufsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
303 		    &i_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
304 		case 0:
305 			ep = (struct direct *)((char *)bp->b_data +
306 			    (i_offset & bmask));
307 			goto foundentry;
308 		case ENOENT:
309 			i_offset = roundup2(dp->i_size, DIRBLKSIZ);
310 			goto notfound;
311 		default:
312 			/* Something failed; just do a linear search. */
313 			break;
314 		}
315 	}
316 #endif /* UFS_DIRHASH */
317 	/*
318 	 * If there is cached information on a previous search of
319 	 * this directory, pick up where we last left off.
320 	 * We cache only lookups as these are the most common
321 	 * and have the greatest payoff. Caching CREATE has little
322 	 * benefit as it usually must search the entire directory
323 	 * to determine that the entry does not exist. Caching the
324 	 * location of the last DELETE or RENAME has not reduced
325 	 * profiling time and hence has been removed in the interest
326 	 * of simplicity.
327 	 */
328 	if (nameiop != LOOKUP || i_diroff == 0 || i_diroff >= dp->i_size) {
329 		entryoffsetinblock = 0;
330 		i_offset = 0;
331 		numdirpasses = 1;
332 	} else {
333 		i_offset = i_diroff;
334 		if ((entryoffsetinblock = i_offset & bmask) &&
335 		    (error = UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp)))
336 			return (error);
337 		numdirpasses = 2;
338 		nchstats.ncs_2passes++;
339 	}
340 	prevoff = i_offset;
341 	endsearch = roundup2(dp->i_size, DIRBLKSIZ);
342 	enduseful = 0;
343 
344 searchloop:
345 	while (i_offset < endsearch) {
346 		/*
347 		 * If necessary, get the next directory block.
348 		 */
349 		if ((i_offset & bmask) == 0) {
350 			if (bp != NULL)
351 				brelse(bp);
352 			error =
353 			    UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp);
354 			if (error)
355 				return (error);
356 			entryoffsetinblock = 0;
357 		}
358 		/*
359 		 * If still looking for a slot, and at a DIRBLKSIZE
360 		 * boundary, have to start looking for free space again.
361 		 */
362 		if (slotstatus == NONE &&
363 		    (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
364 			slotoffset = -1;
365 			slotfreespace = 0;
366 		}
367 		/*
368 		 * Get pointer to next entry.
369 		 * Full validation checks are slow, so we only check
370 		 * enough to insure forward progress through the
371 		 * directory. Complete checks can be run by patching
372 		 * "dirchk" to be true.
373 		 */
374 		ep = (struct direct *)((char *)bp->b_data + entryoffsetinblock);
375 		if (ep->d_reclen == 0 || ep->d_reclen >
376 		    DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
377 		    (dirchk && ufs_dirbadentry(vdp, ep, entryoffsetinblock))) {
378 			int i;
379 
380 			ufs_dirbad(dp, i_offset, "mangled entry");
381 			i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
382 			i_offset += i;
383 			entryoffsetinblock += i;
384 			continue;
385 		}
386 
387 		/*
388 		 * If an appropriate sized slot has not yet been found,
389 		 * check to see if one is available. Also accumulate space
390 		 * in the current block so that we can determine if
391 		 * compaction is viable.
392 		 */
393 		if (slotstatus != FOUND) {
394 			int size = ep->d_reclen;
395 
396 			if (ep->d_ino != 0)
397 				size -= DIRSIZ(OFSFMT(vdp), ep);
398 			if (size > 0) {
399 				if (size >= slotneeded) {
400 					slotstatus = FOUND;
401 					slotoffset = i_offset;
402 					slotsize = ep->d_reclen;
403 				} else if (slotstatus == NONE) {
404 					slotfreespace += size;
405 					if (slotoffset == -1)
406 						slotoffset = i_offset;
407 					if (slotfreespace >= slotneeded) {
408 						slotstatus = COMPACT;
409 						slotsize = i_offset +
410 						      ep->d_reclen - slotoffset;
411 					}
412 				}
413 			}
414 		}
415 
416 		/*
417 		 * Check for a name match.
418 		 */
419 		if (ep->d_ino) {
420 #			if (BYTE_ORDER == LITTLE_ENDIAN)
421 				if (OFSFMT(vdp))
422 					namlen = ep->d_type;
423 				else
424 					namlen = ep->d_namlen;
425 #			else
426 				namlen = ep->d_namlen;
427 #			endif
428 			if (namlen == cnp->cn_namelen &&
429 				(cnp->cn_nameptr[0] == ep->d_name[0]) &&
430 			    !bcmp(cnp->cn_nameptr, ep->d_name,
431 				(unsigned)namlen)) {
432 #ifdef UFS_DIRHASH
433 foundentry:
434 #endif
435 				/*
436 				 * Save directory entry's inode number and
437 				 * reclen in ndp->ni_ufs area, and release
438 				 * directory buffer.
439 				 */
440 				if (!OFSFMT(vdp) && ep->d_type == DT_WHT) {
441 					slotstatus = FOUND;
442 					slotoffset = i_offset;
443 					slotsize = ep->d_reclen;
444 					enduseful = dp->i_size;
445 					cnp->cn_flags |= ISWHITEOUT;
446 					numdirpasses--;
447 					goto notfound;
448 				}
449 				ino = ep->d_ino;
450 				goto found;
451 			}
452 		}
453 		prevoff = i_offset;
454 		i_offset += ep->d_reclen;
455 		entryoffsetinblock += ep->d_reclen;
456 		if (ep->d_ino)
457 			enduseful = i_offset;
458 	}
459 notfound:
460 	/*
461 	 * If we started in the middle of the directory and failed
462 	 * to find our target, we must check the beginning as well.
463 	 */
464 	if (numdirpasses == 2) {
465 		numdirpasses--;
466 		i_offset = 0;
467 		endsearch = i_diroff;
468 		goto searchloop;
469 	}
470 	if (bp != NULL)
471 		brelse(bp);
472 	/*
473 	 * If creating, and at end of pathname and current
474 	 * directory has not been removed, then can consider
475 	 * allowing file to be created.
476 	 */
477 	if ((nameiop == CREATE || nameiop == RENAME ||
478 	     (nameiop == DELETE &&
479 	      (cnp->cn_flags & DOWHITEOUT) &&
480 	      (cnp->cn_flags & ISWHITEOUT))) &&
481 	    (flags & ISLASTCN) && dp->i_effnlink != 0) {
482 		/*
483 		 * Access for write is interpreted as allowing
484 		 * creation of files in the directory.
485 		 *
486 		 * XXX: Fix the comment above.
487 		 */
488 		if (flags & WILLBEDIR)
489 			error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
490 		else
491 			error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
492 		if (error)
493 			return (error);
494 		/*
495 		 * Return an indication of where the new directory
496 		 * entry should be put.  If we didn't find a slot,
497 		 * then set dp->i_count to 0 indicating
498 		 * that the new slot belongs at the end of the
499 		 * directory. If we found a slot, then the new entry
500 		 * can be put in the range from dp->i_offset to
501 		 * dp->i_offset + dp->i_count.
502 		 */
503 		if (slotstatus == NONE) {
504 			SET_I_OFFSET(dp, roundup2(dp->i_size, DIRBLKSIZ));
505 			SET_I_COUNT(dp, 0);
506 			enduseful = I_OFFSET(dp);
507 		} else if (nameiop == DELETE) {
508 			SET_I_OFFSET(dp, slotoffset);
509 			if ((I_OFFSET(dp) & (DIRBLKSIZ - 1)) == 0)
510 				SET_I_COUNT(dp, 0);
511 			else
512 				SET_I_COUNT(dp, I_OFFSET(dp) - prevoff);
513 		} else {
514 			SET_I_OFFSET(dp, slotoffset);
515 			SET_I_COUNT(dp, slotsize);
516 			if (enduseful < slotoffset + slotsize)
517 				enduseful = slotoffset + slotsize;
518 		}
519 		SET_I_ENDOFF(dp, roundup2(enduseful, DIRBLKSIZ));
520 		/*
521 		 * We return with the directory locked, so that
522 		 * the parameters we set up above will still be
523 		 * valid if we actually decide to do a direnter().
524 		 * We return ni_vp == NULL to indicate that the entry
525 		 * does not currently exist; we leave a pointer to
526 		 * the (locked) directory inode in ndp->ni_dvp.
527 		 * The pathname buffer is saved so that the name
528 		 * can be obtained later.
529 		 *
530 		 * NB - if the directory is unlocked, then this
531 		 * information cannot be used.
532 		 */
533 		cnp->cn_flags |= SAVENAME;
534 		return (EJUSTRETURN);
535 	}
536 	/*
537 	 * Insert name into cache (as non-existent) if appropriate.
538 	 */
539 	if ((cnp->cn_flags & MAKEENTRY) != 0)
540 		cache_enter(vdp, NULL, cnp);
541 	return (ENOENT);
542 
543 found:
544 	if (dd_ino != NULL)
545 		*dd_ino = ino;
546 	if (numdirpasses == 2)
547 		nchstats.ncs_pass2++;
548 	/*
549 	 * Check that directory length properly reflects presence
550 	 * of this entry.
551 	 */
552 	if (i_offset + DIRSIZ(OFSFMT(vdp), ep) > dp->i_size) {
553 		ufs_dirbad(dp, i_offset, "i_size too small");
554 		dp->i_size = i_offset + DIRSIZ(OFSFMT(vdp), ep);
555 		DIP_SET(dp, i_size, dp->i_size);
556 		UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
557 	}
558 	brelse(bp);
559 
560 	/*
561 	 * Found component in pathname.
562 	 * If the final component of path name, save information
563 	 * in the cache as to where the entry was found.
564 	 */
565 	if ((flags & ISLASTCN) && nameiop == LOOKUP)
566 		dp->i_diroff = rounddown2(i_offset, DIRBLKSIZ);
567 
568 	/*
569 	 * If deleting, and at end of pathname, return
570 	 * parameters which can be used to remove file.
571 	 */
572 	if (nameiop == DELETE && (flags & ISLASTCN)) {
573 		if (flags & LOCKPARENT)
574 			ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
575 
576 		if (VOP_ISLOCKED(vdp) == LK_EXCLUSIVE) {
577 			/*
578 			 * Return pointer to current entry in
579 			 * dp->i_offset, and distance past previous
580 			 * entry (if there is a previous entry in this
581 			 * block) in dp->i_count.
582 			 *
583 			 * We shouldn't be setting these in the
584 			 * WANTPARENT case (first lookup in rename()), but any
585 			 * lookups that will result in directory changes will
586 			 * overwrite these.
587 			 */
588 			SET_I_OFFSET(dp, i_offset);
589 			if ((I_OFFSET(dp) & (DIRBLKSIZ - 1)) == 0)
590 				SET_I_COUNT(dp, 0);
591 			else
592 				SET_I_COUNT(dp, I_OFFSET(dp) - prevoff);
593 		}
594 		if (dd_ino != NULL)
595 			return (0);
596 
597 		/*
598 		 * Save directory inode pointer in ndp->ni_dvp for
599 		 * dirremove().
600 		 */
601 		if ((error = VFS_VGET(vdp->v_mount, ino,
602 		    LK_EXCLUSIVE, &tdp)) != 0)
603 			return (error);
604 		error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
605 		if (error) {
606 			vput(tdp);
607 			return (error);
608 		}
609 		if (dp->i_number == ino) {
610 			VREF(vdp);
611 			*vpp = vdp;
612 			vput(tdp);
613 			return (0);
614 		}
615 
616 		*vpp = tdp;
617 		return (0);
618 	}
619 
620 	/*
621 	 * If rewriting (RENAME), return the inode and the
622 	 * information required to rewrite the present directory
623 	 * Must get inode of directory entry to verify it's a
624 	 * regular file, or empty directory.
625 	 */
626 	if (nameiop == RENAME && (flags & ISLASTCN)) {
627 		if (flags & WILLBEDIR)
628 			error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
629 		else
630 			error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
631 		if (error)
632 			return (error);
633 		/*
634 		 * Careful about locking second inode.
635 		 * This can only occur if the target is ".".
636 		 */
637 		SET_I_OFFSET(dp, i_offset);
638 		if (dp->i_number == ino)
639 			return (EISDIR);
640 		if (dd_ino != NULL)
641 			return (0);
642 		if ((error = VFS_VGET(vdp->v_mount, ino,
643 		    LK_EXCLUSIVE, &tdp)) != 0)
644 			return (error);
645 
646 		error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
647 		if (error) {
648 			vput(tdp);
649 			return (error);
650 		}
651 
652 #ifdef SunOS_doesnt_do_that
653 		/*
654 		 * The only purpose of this check is to return the correct
655 		 * error.  Assume that we want to rename directory "a"
656 		 * to a file "b", and that we have no ACL_WRITE_DATA on
657 		 * a containing directory, but we _do_ have ACL_APPEND_DATA.
658 		 * In that case, the VOP_ACCESS check above will return 0,
659 		 * and the operation will fail with ENOTDIR instead
660 		 * of EACCESS.
661 		 */
662 		if (tdp->v_type == VDIR)
663 			error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
664 		else
665 			error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
666 		if (error) {
667 			vput(tdp);
668 			return (error);
669 		}
670 #endif
671 
672 		*vpp = tdp;
673 		cnp->cn_flags |= SAVENAME;
674 		return (0);
675 	}
676 	if (dd_ino != NULL)
677 		return (0);
678 
679 	/*
680 	 * Step through the translation in the name.  We do not `vput' the
681 	 * directory because we may need it again if a symbolic link
682 	 * is relative to the current directory.  Instead we save it
683 	 * unlocked as "pdp".  We must get the target inode before unlocking
684 	 * the directory to insure that the inode will not be removed
685 	 * before we get it.  We prevent deadlock by always fetching
686 	 * inodes from the root, moving down the directory tree. Thus
687 	 * when following backward pointers ".." we must unlock the
688 	 * parent directory before getting the requested directory.
689 	 * There is a potential race condition here if both the current
690 	 * and parent directories are removed before the VFS_VGET for the
691 	 * inode associated with ".." returns.  We hope that this occurs
692 	 * infrequently since we cannot avoid this race condition without
693 	 * implementing a sophisticated deadlock detection algorithm.
694 	 * Note also that this simple deadlock detection scheme will not
695 	 * work if the filesystem has any hard links other than ".."
696 	 * that point backwards in the directory structure.
697 	 */
698 	pdp = vdp;
699 	if (flags & ISDOTDOT) {
700 		error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
701 		if (error)
702 			return (error);
703 
704 		/*
705 		 * Recheck that ".." entry in the vdp directory points
706 		 * to the inode we looked up before vdp lock was
707 		 * dropped.
708 		 */
709 		error = ufs_lookup_ino(pdp, NULL, cnp, &ino1);
710 		if (error) {
711 			vput(tdp);
712 			return (error);
713 		}
714 		if (ino1 != ino) {
715 			vput(tdp);
716 			goto restart;
717 		}
718 
719 		*vpp = tdp;
720 	} else if (dp->i_number == ino) {
721 		VREF(vdp);	/* we want ourself, ie "." */
722 		/*
723 		 * When we lookup "." we still can be asked to lock it
724 		 * differently.
725 		 */
726 		ltype = cnp->cn_lkflags & LK_TYPE_MASK;
727 		if (ltype != VOP_ISLOCKED(vdp)) {
728 			if (ltype == LK_EXCLUSIVE)
729 				vn_lock(vdp, LK_UPGRADE | LK_RETRY);
730 			else /* if (ltype == LK_SHARED) */
731 				vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
732 			/*
733 			 * Relock for the "." case may left us with
734 			 * reclaimed vnode.
735 			 */
736 			if (VN_IS_DOOMED(vdp)) {
737 				vrele(vdp);
738 				return (ENOENT);
739 			}
740 		}
741 		*vpp = vdp;
742 	} else {
743 		error = VFS_VGET(pdp->v_mount, ino, cnp->cn_lkflags, &tdp);
744 		if (error == 0 && VTOI(tdp)->i_mode == 0) {
745 			vgone(tdp);
746 			vput(tdp);
747 			error = ENOENT;
748 		}
749 		if (error)
750 			return (error);
751 		*vpp = tdp;
752 	}
753 
754 	/*
755 	 * Insert name into cache if appropriate.
756 	 */
757 	if (cnp->cn_flags & MAKEENTRY)
758 		cache_enter(vdp, *vpp, cnp);
759 	return (0);
760 }
761 
762 void
763 ufs_dirbad(ip, offset, how)
764 	struct inode *ip;
765 	doff_t offset;
766 	char *how;
767 {
768 	struct mount *mp;
769 
770 	mp = ITOV(ip)->v_mount;
771 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
772 		panic("ufs_dirbad: %s: bad dir ino %ju at offset %ld: %s",
773 		    mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
774 		    (long)offset, how);
775 	else
776 		(void)printf("%s: bad dir ino %ju at offset %ld: %s\n",
777 		    mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
778 		    (long)offset, how);
779 }
780 
781 /*
782  * Do consistency checking on a directory entry:
783  *	record length must be multiple of 4
784  *	entry must fit in rest of its DIRBLKSIZ block
785  *	record must be large enough to contain entry
786  *	name is not longer than UFS_MAXNAMLEN
787  *	name must be as long as advertised, and null terminated
788  */
789 int
790 ufs_dirbadentry(dp, ep, entryoffsetinblock)
791 	struct vnode *dp;
792 	struct direct *ep;
793 	int entryoffsetinblock;
794 {
795 	int i, namlen;
796 
797 #	if (BYTE_ORDER == LITTLE_ENDIAN)
798 		if (OFSFMT(dp))
799 			namlen = ep->d_type;
800 		else
801 			namlen = ep->d_namlen;
802 #	else
803 		namlen = ep->d_namlen;
804 #	endif
805 	if ((ep->d_reclen & 0x3) != 0 ||
806 	    ep->d_reclen > DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
807 	    ep->d_reclen < DIRSIZ(OFSFMT(dp), ep) || namlen > UFS_MAXNAMLEN) {
808 		/*return (1); */
809 		printf("First bad\n");
810 		goto bad;
811 	}
812 	if (ep->d_ino == 0)
813 		return (0);
814 	for (i = 0; i < namlen; i++)
815 		if (ep->d_name[i] == '\0') {
816 			/*return (1); */
817 			printf("Second bad\n");
818 			goto bad;
819 		}
820 	if (ep->d_name[i])
821 		goto bad;
822 	return (0);
823 bad:
824 	return (1);
825 }
826 
827 /*
828  * Construct a new directory entry after a call to namei, using the
829  * parameters that it left in the componentname argument cnp. The
830  * argument ip is the inode to which the new directory entry will refer.
831  */
832 void
833 ufs_makedirentry(ip, cnp, newdirp)
834 	struct inode *ip;
835 	struct componentname *cnp;
836 	struct direct *newdirp;
837 {
838 	u_int namelen;
839 
840 	namelen = (unsigned)cnp->cn_namelen;
841 	KASSERT((cnp->cn_flags & SAVENAME) != 0,
842 		("ufs_makedirentry: missing name"));
843 	KASSERT(namelen <= UFS_MAXNAMLEN,
844 		("ufs_makedirentry: name too long"));
845 	newdirp->d_ino = ip->i_number;
846 	newdirp->d_namlen = namelen;
847 
848 	/* Zero out after-name padding */
849 	*(u_int32_t *)(&newdirp->d_name[namelen & ~(DIR_ROUNDUP - 1)]) = 0;
850 
851 	bcopy(cnp->cn_nameptr, newdirp->d_name, namelen);
852 
853 	if (!OFSFMT(ITOV(ip)))
854 		newdirp->d_type = IFTODT(ip->i_mode);
855 	else {
856 		newdirp->d_type = 0;
857 #		if (BYTE_ORDER == LITTLE_ENDIAN)
858 			{ u_char tmp = newdirp->d_namlen;
859 			newdirp->d_namlen = newdirp->d_type;
860 			newdirp->d_type = tmp; }
861 #		endif
862 	}
863 }
864 
865 /*
866  * Write a directory entry after a call to namei, using the parameters
867  * that it left in nameidata. The argument dirp is the new directory
868  * entry contents. Dvp is a pointer to the directory to be written,
869  * which was left locked by namei. Remaining parameters (dp->i_offset,
870  * dp->i_count) indicate how the space for the new entry is to be obtained.
871  * Non-null bp indicates that a directory is being created (for the
872  * soft dependency code).
873  */
874 int
875 ufs_direnter(dvp, tvp, dirp, cnp, newdirbp)
876 	struct vnode *dvp;
877 	struct vnode *tvp;
878 	struct direct *dirp;
879 	struct componentname *cnp;
880 	struct buf *newdirbp;
881 {
882 	struct ucred *cr;
883 	struct thread *td;
884 	int newentrysize;
885 	struct inode *dp;
886 	struct buf *bp;
887 	u_int dsize;
888 	struct direct *ep, *nep;
889 	u_int64_t old_isize;
890 	int error, ret, blkoff, loc, spacefree, flags, namlen;
891 	char *dirbuf;
892 
893 	td = curthread;	/* XXX */
894 	cr = td->td_ucred;
895 
896 	dp = VTOI(dvp);
897 	newentrysize = DIRSIZ(OFSFMT(dvp), dirp);
898 
899 	if (I_COUNT(dp) == 0) {
900 		/*
901 		 * If dp->i_count is 0, then namei could find no
902 		 * space in the directory. Here, dp->i_offset will
903 		 * be on a directory block boundary and we will write the
904 		 * new entry into a fresh block.
905 		 */
906 		if (I_OFFSET(dp) & (DIRBLKSIZ - 1))
907 			panic("ufs_direnter: newblk");
908 		flags = BA_CLRBUF;
909 		if (!DOINGSOFTDEP(dvp) && !DOINGASYNC(dvp))
910 			flags |= IO_SYNC;
911 #ifdef QUOTA
912 		if ((error = getinoquota(dp)) != 0) {
913 			if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
914 				bdwrite(newdirbp);
915 			return (error);
916 		}
917 #endif
918 		old_isize = dp->i_size;
919 		vnode_pager_setsize(dvp, (u_long)I_OFFSET(dp) + DIRBLKSIZ);
920 		if ((error = UFS_BALLOC(dvp, (off_t)I_OFFSET(dp), DIRBLKSIZ,
921 		    cr, flags, &bp)) != 0) {
922 			if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
923 				bdwrite(newdirbp);
924 			vnode_pager_setsize(dvp, (u_long)old_isize);
925 			return (error);
926 		}
927 		dp->i_size = I_OFFSET(dp) + DIRBLKSIZ;
928 		DIP_SET(dp, i_size, dp->i_size);
929 		SET_I_ENDOFF(dp, dp->i_size);
930 		UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
931 		dirp->d_reclen = DIRBLKSIZ;
932 		blkoff = I_OFFSET(dp) &
933 		    (VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_iosize - 1);
934 		bcopy((caddr_t)dirp, (caddr_t)bp->b_data + blkoff,newentrysize);
935 #ifdef UFS_DIRHASH
936 		if (dp->i_dirhash != NULL) {
937 			ufsdirhash_newblk(dp, I_OFFSET(dp));
938 			ufsdirhash_add(dp, dirp, I_OFFSET(dp));
939 			ufsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
940 			    I_OFFSET(dp));
941 		}
942 #endif
943 		if (DOINGSOFTDEP(dvp)) {
944 			/*
945 			 * Ensure that the entire newly allocated block is a
946 			 * valid directory so that future growth within the
947 			 * block does not have to ensure that the block is
948 			 * written before the inode.
949 			 */
950 			blkoff += DIRBLKSIZ;
951 			while (blkoff < bp->b_bcount) {
952 				((struct direct *)
953 				   (bp->b_data + blkoff))->d_reclen = DIRBLKSIZ;
954 				blkoff += DIRBLKSIZ;
955 			}
956 			if (softdep_setup_directory_add(bp, dp, I_OFFSET(dp),
957 			    dirp->d_ino, newdirbp, 1))
958 				UFS_INODE_SET_FLAG(dp, IN_NEEDSYNC);
959 			if (newdirbp)
960 				bdwrite(newdirbp);
961 			bdwrite(bp);
962 			return (UFS_UPDATE(dvp, 0));
963 		}
964 		if (DOINGASYNC(dvp)) {
965 			bdwrite(bp);
966 			return (UFS_UPDATE(dvp, 0));
967 		}
968 		error = bwrite(bp);
969 		ret = UFS_UPDATE(dvp, 1);
970 		if (error == 0)
971 			return (ret);
972 		return (error);
973 	}
974 
975 	/*
976 	 * If dp->i_count is non-zero, then namei found space for the new
977 	 * entry in the range dp->i_offset to dp->i_offset + dp->i_count
978 	 * in the directory. To use this space, we may have to compact
979 	 * the entries located there, by copying them together towards the
980 	 * beginning of the block, leaving the free space in one usable
981 	 * chunk at the end.
982 	 */
983 
984 	/*
985 	 * Increase size of directory if entry eats into new space.
986 	 * This should never push the size past a new multiple of
987 	 * DIRBLKSIZE.
988 	 *
989 	 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
990 	 */
991 	if (I_OFFSET(dp) + I_COUNT(dp) > dp->i_size) {
992 		dp->i_size = I_OFFSET(dp) + I_COUNT(dp);
993 		DIP_SET(dp, i_size, dp->i_size);
994 		UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_MODIFIED);
995 	}
996 	/*
997 	 * Get the block containing the space for the new directory entry.
998 	 */
999 	error = UFS_BLKATOFF(dvp, (off_t)I_OFFSET(dp), &dirbuf, &bp);
1000 	if (error) {
1001 		if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
1002 			bdwrite(newdirbp);
1003 		return (error);
1004 	}
1005 	/*
1006 	 * Find space for the new entry. In the simple case, the entry at
1007 	 * offset base will have the space. If it does not, then namei
1008 	 * arranged that compacting the region dp->i_offset to
1009 	 * dp->i_offset + dp->i_count would yield the space.
1010 	 */
1011 	ep = (struct direct *)dirbuf;
1012 	dsize = ep->d_ino ? DIRSIZ(OFSFMT(dvp), ep) : 0;
1013 	spacefree = ep->d_reclen - dsize;
1014 	for (loc = ep->d_reclen; loc < I_COUNT(dp); ) {
1015 		nep = (struct direct *)(dirbuf + loc);
1016 
1017 		/* Trim the existing slot (NB: dsize may be zero). */
1018 		ep->d_reclen = dsize;
1019 		ep = (struct direct *)((char *)ep + dsize);
1020 
1021 		/* Read nep->d_reclen now as the bcopy() may clobber it. */
1022 		loc += nep->d_reclen;
1023 		if (nep->d_ino == 0) {
1024 			/*
1025 			 * A mid-block unused entry. Such entries are
1026 			 * never created by the kernel, but fsck_ffs
1027 			 * can create them (and it doesn't fix them).
1028 			 *
1029 			 * Add up the free space, and initialise the
1030 			 * relocated entry since we don't bcopy it.
1031 			 */
1032 			spacefree += nep->d_reclen;
1033 			ep->d_ino = 0;
1034 			dsize = 0;
1035 			continue;
1036 		}
1037 		dsize = DIRSIZ(OFSFMT(dvp), nep);
1038 		spacefree += nep->d_reclen - dsize;
1039 #ifdef UFS_DIRHASH
1040 		if (dp->i_dirhash != NULL)
1041 			ufsdirhash_move(dp, nep,
1042 			    I_OFFSET(dp) + ((char *)nep - dirbuf),
1043 			    I_OFFSET(dp) + ((char *)ep - dirbuf));
1044 #endif
1045 		if (DOINGSOFTDEP(dvp))
1046 			softdep_change_directoryentry_offset(bp, dp, dirbuf,
1047 			    (caddr_t)nep, (caddr_t)ep, dsize);
1048 		else
1049 			bcopy((caddr_t)nep, (caddr_t)ep, dsize);
1050 	}
1051 	/*
1052 	 * Here, `ep' points to a directory entry containing `dsize' in-use
1053 	 * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
1054 	 * then the entry is completely unused (dsize == 0). The value
1055 	 * of ep->d_reclen is always indeterminate.
1056 	 *
1057 	 * Update the pointer fields in the previous entry (if any),
1058 	 * copy in the new entry, and write out the block.
1059 	 */
1060 #	if (BYTE_ORDER == LITTLE_ENDIAN)
1061 		if (OFSFMT(dvp))
1062 			namlen = ep->d_type;
1063 		else
1064 			namlen = ep->d_namlen;
1065 #	else
1066 		namlen = ep->d_namlen;
1067 #	endif
1068 	if (ep->d_ino == 0 ||
1069 	    (ep->d_ino == UFS_WINO && namlen == dirp->d_namlen &&
1070 	     bcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
1071 		if (spacefree + dsize < newentrysize)
1072 			panic("ufs_direnter: compact1");
1073 		dirp->d_reclen = spacefree + dsize;
1074 	} else {
1075 		if (spacefree < newentrysize)
1076 			panic("ufs_direnter: compact2");
1077 		dirp->d_reclen = spacefree;
1078 		ep->d_reclen = dsize;
1079 		ep = (struct direct *)((char *)ep + dsize);
1080 	}
1081 #ifdef UFS_DIRHASH
1082 	if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
1083 	    dirp->d_reclen == spacefree))
1084 		ufsdirhash_add(dp, dirp, I_OFFSET(dp) + ((char *)ep - dirbuf));
1085 #endif
1086 	bcopy((caddr_t)dirp, (caddr_t)ep, (u_int)newentrysize);
1087 #ifdef UFS_DIRHASH
1088 	if (dp->i_dirhash != NULL)
1089 		ufsdirhash_checkblock(dp, dirbuf -
1090 		    (I_OFFSET(dp) & (DIRBLKSIZ - 1)),
1091 		    rounddown2(I_OFFSET(dp), DIRBLKSIZ));
1092 #endif
1093 
1094 	if (DOINGSOFTDEP(dvp)) {
1095 		(void) softdep_setup_directory_add(bp, dp,
1096 		    I_OFFSET(dp) + (caddr_t)ep - dirbuf,
1097 		    dirp->d_ino, newdirbp, 0);
1098 		if (newdirbp != NULL)
1099 			bdwrite(newdirbp);
1100 		bdwrite(bp);
1101 	} else {
1102 		if (DOINGASYNC(dvp)) {
1103 			bdwrite(bp);
1104 			error = 0;
1105 		} else {
1106 			error = bwrite(bp);
1107 		}
1108 	}
1109 
1110 	/*
1111 	 * If all went well, and the directory can be shortened,
1112 	 * mark directory inode with the truncation request.
1113 	 */
1114 	UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE | (error == 0 &&
1115 	    I_ENDOFF(dp) != 0 && I_ENDOFF(dp) < dp->i_size ? IN_ENDOFF : 0));
1116 
1117 	return (error);
1118 }
1119 
1120 /*
1121  * Remove a directory entry after a call to namei, using
1122  * the parameters which it left in nameidata. The entry
1123  * dp->i_offset contains the offset into the directory of the
1124  * entry to be eliminated.  The dp->i_count field contains the
1125  * size of the previous record in the directory.  If this
1126  * is 0, the first entry is being deleted, so we need only
1127  * zero the inode number to mark the entry as free.  If the
1128  * entry is not the first in the directory, we must reclaim
1129  * the space of the now empty record by adding the record size
1130  * to the size of the previous entry.
1131  */
1132 int
1133 ufs_dirremove(dvp, ip, flags, isrmdir)
1134 	struct vnode *dvp;
1135 	struct inode *ip;
1136 	int flags;
1137 	int isrmdir;
1138 {
1139 	struct inode *dp;
1140 	struct direct *ep, *rep;
1141 	struct buf *bp;
1142 	off_t offset;
1143 	int error;
1144 
1145 	dp = VTOI(dvp);
1146 
1147 	/*
1148 	 * Adjust the link count early so softdep can block if necessary.
1149 	 */
1150 	if (ip) {
1151 		ip->i_effnlink--;
1152 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1153 		if (DOINGSOFTDEP(dvp)) {
1154 			softdep_setup_unlink(dp, ip);
1155 		} else {
1156 			ip->i_nlink--;
1157 			DIP_SET(ip, i_nlink, ip->i_nlink);
1158 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1159 		}
1160 	}
1161 	if (flags & DOWHITEOUT)
1162 		offset = I_OFFSET(dp);
1163 	else
1164 		offset = I_OFFSET(dp) - I_COUNT(dp);
1165 	if ((error = UFS_BLKATOFF(dvp, offset, (char **)&ep, &bp)) != 0) {
1166 		if (ip) {
1167 			ip->i_effnlink++;
1168 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1169 			if (DOINGSOFTDEP(dvp)) {
1170 				softdep_change_linkcnt(ip);
1171 			} else {
1172 				ip->i_nlink++;
1173 				DIP_SET(ip, i_nlink, ip->i_nlink);
1174 				UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1175 			}
1176 		}
1177 		return (error);
1178 	}
1179 	if (flags & DOWHITEOUT) {
1180 		/*
1181 		 * Whiteout entry: set d_ino to UFS_WINO.
1182 		 */
1183 		ep->d_ino = UFS_WINO;
1184 		ep->d_type = DT_WHT;
1185 		goto out;
1186 	}
1187 	/* Set 'rep' to the entry being removed. */
1188 	if (I_COUNT(dp) == 0)
1189 		rep = ep;
1190 	else
1191 		rep = (struct direct *)((char *)ep + ep->d_reclen);
1192 #ifdef UFS_DIRHASH
1193 	/*
1194 	 * Remove the dirhash entry. This is complicated by the fact
1195 	 * that `ep' is the previous entry when dp->i_count != 0.
1196 	 */
1197 	if (dp->i_dirhash != NULL)
1198 		ufsdirhash_remove(dp, rep, I_OFFSET(dp));
1199 #endif
1200 	if (ip && rep->d_ino != ip->i_number)
1201 		panic("ufs_dirremove: ip %ju does not match dirent ino %ju\n",
1202 		    (uintmax_t)ip->i_number, (uintmax_t)rep->d_ino);
1203 	/*
1204 	 * Zero out the file directory entry metadata to reduce disk
1205 	 * scavenging disclosure.
1206 	 */
1207 	bzero(&rep->d_name[0], rep->d_namlen);
1208 	rep->d_namlen = 0;
1209 	rep->d_type = 0;
1210 	rep->d_ino = 0;
1211 
1212 	if (I_COUNT(dp) != 0) {
1213 		/*
1214 		 * Collapse new free space into previous entry.
1215 		 */
1216 		ep->d_reclen += rep->d_reclen;
1217 		rep->d_reclen = 0;
1218 	}
1219 #ifdef UFS_DIRHASH
1220 	if (dp->i_dirhash != NULL)
1221 		ufsdirhash_checkblock(dp, (char *)ep -
1222 		    ((I_OFFSET(dp) - I_COUNT(dp)) & (DIRBLKSIZ - 1)),
1223 		    rounddown2(I_OFFSET(dp), DIRBLKSIZ));
1224 #endif
1225 out:
1226 	error = 0;
1227 	if (DOINGSOFTDEP(dvp)) {
1228 		if (ip)
1229 			softdep_setup_remove(bp, dp, ip, isrmdir);
1230 		if (softdep_slowdown(dvp))
1231 			error = bwrite(bp);
1232 		else
1233 			bdwrite(bp);
1234 	} else {
1235 		if (flags & DOWHITEOUT)
1236 			error = bwrite(bp);
1237 		else if (DOINGASYNC(dvp))
1238 			bdwrite(bp);
1239 		else
1240 			error = bwrite(bp);
1241 	}
1242 	UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE);
1243 	/*
1244 	 * If the last named reference to a snapshot goes away,
1245 	 * drop its snapshot reference so that it will be reclaimed
1246 	 * when last open reference goes away.
1247 	 */
1248 	if (ip != NULL && (ip->i_flags & SF_SNAPSHOT) != 0 &&
1249 	    ip->i_effnlink == 0)
1250 		UFS_SNAPGONE(ip);
1251 	return (error);
1252 }
1253 
1254 /*
1255  * Rewrite an existing directory entry to point at the inode
1256  * supplied.  The parameters describing the directory entry are
1257  * set up by a call to namei.
1258  */
1259 int
1260 ufs_dirrewrite(dp, oip, newinum, newtype, isrmdir)
1261 	struct inode *dp, *oip;
1262 	ino_t newinum;
1263 	int newtype;
1264 	int isrmdir;
1265 {
1266 	struct buf *bp;
1267 	struct direct *ep;
1268 	struct vnode *vdp = ITOV(dp);
1269 	int error;
1270 
1271 	/*
1272 	 * Drop the link before we lock the buf so softdep can block if
1273 	 * necessary.
1274 	 */
1275 	oip->i_effnlink--;
1276 	UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1277 	if (DOINGSOFTDEP(vdp)) {
1278 		softdep_setup_unlink(dp, oip);
1279 	} else {
1280 		oip->i_nlink--;
1281 		DIP_SET(oip, i_nlink, oip->i_nlink);
1282 		UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1283 	}
1284 
1285 	error = UFS_BLKATOFF(vdp, (off_t)I_OFFSET(dp), (char **)&ep, &bp);
1286 	if (error == 0 && ep->d_namlen == 2 && ep->d_name[1] == '.' &&
1287 	    ep->d_name[0] == '.' && ep->d_ino != oip->i_number) {
1288 		brelse(bp);
1289 		error = EIDRM;
1290 	}
1291 	if (error) {
1292 		oip->i_effnlink++;
1293 		UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1294 		if (DOINGSOFTDEP(vdp)) {
1295 			softdep_change_linkcnt(oip);
1296 		} else {
1297 			oip->i_nlink++;
1298 			DIP_SET(oip, i_nlink, oip->i_nlink);
1299 			UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1300 		}
1301 		return (error);
1302 	}
1303 	ep->d_ino = newinum;
1304 	if (!OFSFMT(vdp))
1305 		ep->d_type = newtype;
1306 	if (DOINGSOFTDEP(vdp)) {
1307 		softdep_setup_directory_change(bp, dp, oip, newinum, isrmdir);
1308 		bdwrite(bp);
1309 	} else {
1310 		if (DOINGASYNC(vdp)) {
1311 			bdwrite(bp);
1312 			error = 0;
1313 		} else {
1314 			error = bwrite(bp);
1315 		}
1316 	}
1317 	UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE);
1318 	/*
1319 	 * If the last named reference to a snapshot goes away,
1320 	 * drop its snapshot reference so that it will be reclaimed
1321 	 * when last open reference goes away.
1322 	 */
1323 	if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_effnlink == 0)
1324 		UFS_SNAPGONE(oip);
1325 	return (error);
1326 }
1327 
1328 /*
1329  * Check if a directory is empty or not.
1330  * Inode supplied must be locked.
1331  *
1332  * Using a struct dirtemplate here is not precisely
1333  * what we want, but better than using a struct direct.
1334  *
1335  * NB: does not handle corrupted directories.
1336  */
1337 int
1338 ufs_dirempty(ip, parentino, cred)
1339 	struct inode *ip;
1340 	ino_t parentino;
1341 	struct ucred *cred;
1342 {
1343 	doff_t off;
1344 	struct dirtemplate dbuf;
1345 	struct direct *dp = (struct direct *)&dbuf;
1346 	int error, namlen;
1347 	ssize_t count;
1348 #define	MINDIRSIZ (sizeof (struct dirtemplate) / 2)
1349 
1350 	for (off = 0; off < ip->i_size; off += dp->d_reclen) {
1351 		error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1352 		    off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1353 		    NOCRED, &count, (struct thread *)0);
1354 		/*
1355 		 * Since we read MINDIRSIZ, residual must
1356 		 * be 0 unless we're at end of file.
1357 		 */
1358 		if (error || count != 0)
1359 			return (0);
1360 		/* avoid infinite loops */
1361 		if (dp->d_reclen == 0)
1362 			return (0);
1363 		/* skip empty entries */
1364 		if (dp->d_ino == 0 || dp->d_ino == UFS_WINO)
1365 			continue;
1366 		/* accept only "." and ".." */
1367 #		if (BYTE_ORDER == LITTLE_ENDIAN)
1368 			if (OFSFMT(ITOV(ip)))
1369 				namlen = dp->d_type;
1370 			else
1371 				namlen = dp->d_namlen;
1372 #		else
1373 			namlen = dp->d_namlen;
1374 #		endif
1375 		if (namlen > 2)
1376 			return (0);
1377 		if (dp->d_name[0] != '.')
1378 			return (0);
1379 		/*
1380 		 * At this point namlen must be 1 or 2.
1381 		 * 1 implies ".", 2 implies ".." if second
1382 		 * char is also "."
1383 		 */
1384 		if (namlen == 1 && dp->d_ino == ip->i_number)
1385 			continue;
1386 		if (dp->d_name[1] == '.' && dp->d_ino == parentino)
1387 			continue;
1388 		return (0);
1389 	}
1390 	return (1);
1391 }
1392 
1393 static int
1394 ufs_dir_dd_ino(struct vnode *vp, struct ucred *cred, ino_t *dd_ino,
1395     struct vnode **dd_vp)
1396 {
1397 	struct dirtemplate dirbuf;
1398 	struct vnode *ddvp;
1399 	int error, namlen;
1400 
1401 	ASSERT_VOP_LOCKED(vp, "ufs_dir_dd_ino");
1402 	*dd_vp = NULL;
1403 	if (vp->v_type != VDIR)
1404 		return (ENOTDIR);
1405 	/*
1406 	 * First check to see if we have it in the name cache.
1407 	 */
1408 	if ((ddvp = vn_dir_dd_ino(vp)) != NULL) {
1409 		KASSERT(ddvp->v_mount == vp->v_mount,
1410 		    ("ufs_dir_dd_ino: Unexpected mount point crossing"));
1411 		*dd_ino = VTOI(ddvp)->i_number;
1412 		*dd_vp = ddvp;
1413 		return (0);
1414 	}
1415 	/*
1416 	 * Have to read the directory.
1417 	 */
1418 	error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1419 	    sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1420 	    IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL, NULL);
1421 	if (error != 0)
1422 		return (error);
1423 #if (BYTE_ORDER == LITTLE_ENDIAN)
1424 	if (OFSFMT(vp))
1425 		namlen = dirbuf.dotdot_type;
1426 	else
1427 		namlen = dirbuf.dotdot_namlen;
1428 #else
1429 	namlen = dirbuf.dotdot_namlen;
1430 #endif
1431 	if (namlen != 2 || dirbuf.dotdot_name[0] != '.' ||
1432 	    dirbuf.dotdot_name[1] != '.')
1433 		return (ENOTDIR);
1434 	*dd_ino = dirbuf.dotdot_ino;
1435 	return (0);
1436 }
1437 
1438 /*
1439  * Check if source directory is in the path of the target directory.
1440  */
1441 int
1442 ufs_checkpath(ino_t source_ino, ino_t parent_ino, struct inode *target, struct ucred *cred, ino_t *wait_ino)
1443 {
1444 	struct mount *mp;
1445 	struct vnode *tvp, *vp, *vp1;
1446 	int error;
1447 	ino_t dd_ino;
1448 
1449 	vp = tvp = ITOV(target);
1450 	mp = vp->v_mount;
1451 	*wait_ino = 0;
1452 	if (target->i_number == source_ino)
1453 		return (EEXIST);
1454 	if (target->i_number == parent_ino)
1455 		return (0);
1456 	if (target->i_number == UFS_ROOTINO)
1457 		return (0);
1458 	for (;;) {
1459 		error = ufs_dir_dd_ino(vp, cred, &dd_ino, &vp1);
1460 		if (error != 0)
1461 			break;
1462 		if (dd_ino == source_ino) {
1463 			error = EINVAL;
1464 			break;
1465 		}
1466 		if (dd_ino == UFS_ROOTINO)
1467 			break;
1468 		if (dd_ino == parent_ino)
1469 			break;
1470 		if (vp1 == NULL) {
1471 			error = VFS_VGET(mp, dd_ino, LK_SHARED | LK_NOWAIT,
1472 			    &vp1);
1473 			if (error != 0) {
1474 				*wait_ino = dd_ino;
1475 				break;
1476 			}
1477 		}
1478 		KASSERT(dd_ino == VTOI(vp1)->i_number,
1479 		    ("directory %ju reparented\n",
1480 		    (uintmax_t)VTOI(vp1)->i_number));
1481 		if (vp != tvp)
1482 			vput(vp);
1483 		vp = vp1;
1484 	}
1485 
1486 	if (error == ENOTDIR)
1487 		panic("checkpath: .. not a directory\n");
1488 	if (vp1 != NULL)
1489 		vput(vp1);
1490 	if (vp != tvp)
1491 		vput(vp);
1492 	return (error);
1493 }
1494 
1495 #ifdef DIAGNOSTIC
1496 static void
1497 ufs_assert_inode_offset_owner(struct inode *ip, struct iown_tracker *tr,
1498     const char *name, const char *file, int line)
1499 {
1500 	char msg[128];
1501 
1502 	snprintf(msg, sizeof(msg), "at %s@%d", file, line);
1503 	ASSERT_VOP_ELOCKED(ITOV(ip), msg);
1504 	MPASS((ip->i_mode & IFMT) == IFDIR);
1505 	if (curthread == tr->tr_owner && ip->i_lock_gen == tr->tr_gen)
1506 		return;
1507 	printf("locked at\n");
1508 	stack_print(&tr->tr_st);
1509 	printf("unlocked at\n");
1510 	stack_print(&tr->tr_unlock);
1511 	panic("%s ip %p %jd offset owner %p %d gen %d "
1512 	    "curthread %p %d gen %d at %s@%d\n",
1513 	    name, ip, (uintmax_t)ip->i_number, tr->tr_owner,
1514 	    tr->tr_owner->td_tid, tr->tr_gen,
1515 	    curthread, curthread->td_tid, ip->i_lock_gen,
1516 	    file, line);
1517 }
1518 
1519 static void
1520 ufs_set_inode_offset_owner(struct inode *ip, struct iown_tracker *tr,
1521     const char *file, int line)
1522 {
1523 	char msg[128];
1524 
1525 	snprintf(msg, sizeof(msg), "at %s@%d", file, line);
1526 	ASSERT_VOP_ELOCKED(ITOV(ip), msg);
1527 	MPASS((ip->i_mode & IFMT) == IFDIR);
1528 	tr->tr_owner = curthread;
1529 	tr->tr_gen = ip->i_lock_gen;
1530 	stack_save(&tr->tr_st);
1531 }
1532 
1533 static void
1534 ufs_init_one_tracker(struct iown_tracker *tr)
1535 {
1536 	tr->tr_owner = NULL;
1537 	stack_zero(&tr->tr_st);
1538 }
1539 
1540 void
1541 ufs_init_trackers(struct inode *ip)
1542 {
1543 	ufs_init_one_tracker(&ip->i_offset_tracker);
1544 	ufs_init_one_tracker(&ip->i_count_tracker);
1545 	ufs_init_one_tracker(&ip->i_endoff_tracker);
1546 }
1547 
1548 void
1549 ufs_unlock_tracker(struct inode *ip)
1550 {
1551 	if (ip->i_count_tracker.tr_gen == ip->i_lock_gen)
1552 		stack_save(&ip->i_count_tracker.tr_unlock);
1553 	if (ip->i_offset_tracker.tr_gen == ip->i_lock_gen)
1554 		stack_save(&ip->i_offset_tracker.tr_unlock);
1555 	if (ip->i_endoff_tracker.tr_gen == ip->i_lock_gen)
1556 		stack_save(&ip->i_endoff_tracker.tr_unlock);
1557 	ip->i_lock_gen++;
1558 }
1559 
1560 doff_t
1561 ufs_get_i_offset(struct inode *ip, const char *file, int line)
1562 {
1563 	ufs_assert_inode_offset_owner(ip, &ip->i_offset_tracker, "i_offset",
1564 	    file, line);
1565 	return (ip->i_offset);
1566 }
1567 
1568 void
1569 ufs_set_i_offset(struct inode *ip, doff_t off, const char *file, int line)
1570 {
1571 	ufs_set_inode_offset_owner(ip, &ip->i_offset_tracker, file, line);
1572 	ip->i_offset = off;
1573 }
1574 
1575 int32_t
1576 ufs_get_i_count(struct inode *ip, const char *file, int line)
1577 {
1578 	ufs_assert_inode_offset_owner(ip, &ip->i_count_tracker, "i_count",
1579 	    file, line);
1580 	return (ip->i_count);
1581 }
1582 
1583 void
1584 ufs_set_i_count(struct inode *ip, int32_t cnt, const char *file, int line)
1585 {
1586 	ufs_set_inode_offset_owner(ip, &ip->i_count_tracker, file, line);
1587 	ip->i_count = cnt;
1588 }
1589 
1590 doff_t
1591 ufs_get_i_endoff(struct inode *ip, const char *file, int line)
1592 {
1593 	ufs_assert_inode_offset_owner(ip, &ip->i_endoff_tracker, "i_endoff",
1594 	    file, line);
1595 	return (ip->i_endoff);
1596 }
1597 
1598 void
1599 ufs_set_i_endoff(struct inode *ip, doff_t off, const char *file, int line)
1600 {
1601 	ufs_set_inode_offset_owner(ip, &ip->i_endoff_tracker, file, line);
1602 	ip->i_endoff = off;
1603 }
1604 
1605 #endif
1606