xref: /freebsd/sys/fs/ext2fs/ext2_lookup.c (revision 2282756519d9337dec783509a432fd6ddfd06683)
1 /*-
2  *  modified for Lites 1.1
3  *
4  *  Aug 1995, Godmar Back (gback@cs.utah.edu)
5  *  University of Utah, Department of Computer Science
6  */
7 /*-
8  * SPDX-License-Identifier: BSD-3-Clause
9  *
10  * Copyright (c) 1989, 1993
11  *	The Regents of the University of California.  All rights reserved.
12  * (c) UNIX System Laboratories, Inc.
13  * All or some portions of this file are derived from material licensed
14  * to the University of California by American Telephone and Telegraph
15  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
16  * the permission of UNIX System Laboratories, Inc.
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  * 1. Redistributions of source code must retain the above copyright
22  *    notice, this list of conditions and the following disclaimer.
23  * 2. Redistributions in binary form must reproduce the above copyright
24  *    notice, this list of conditions and the following disclaimer in the
25  *    documentation and/or other materials provided with the distribution.
26  * 3. Neither the name of the University nor the names of its contributors
27  *    may be used to endorse or promote products derived from this software
28  *    without specific prior written permission.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40  * SUCH DAMAGE.
41  *
42  *	@(#)ufs_lookup.c	8.6 (Berkeley) 4/1/94
43  * $FreeBSD$
44  */
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/namei.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/endian.h>
52 #include <sys/mount.h>
53 #include <sys/vnode.h>
54 #include <sys/malloc.h>
55 #include <sys/dirent.h>
56 #include <sys/sysctl.h>
57 
58 #include <ufs/ufs/dir.h>
59 
60 #include <fs/ext2fs/fs.h>
61 #include <fs/ext2fs/inode.h>
62 #include <fs/ext2fs/ext2_mount.h>
63 #include <fs/ext2fs/ext2fs.h>
64 #include <fs/ext2fs/ext2_dinode.h>
65 #include <fs/ext2fs/ext2_dir.h>
66 #include <fs/ext2fs/ext2_extern.h>
67 #include <fs/ext2fs/fs.h>
68 
69 #ifdef INVARIANTS
70 static int dirchk = 1;
71 #else
72 static int dirchk = 0;
73 #endif
74 
75 static SYSCTL_NODE(_vfs, OID_AUTO, e2fs, CTLFLAG_RD, 0, "EXT2FS filesystem");
76 SYSCTL_INT(_vfs_e2fs, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
77 
78 /*
79    DIRBLKSIZE in ffs is DEV_BSIZE (in most cases 512)
80    while it is the native blocksize in ext2fs - thus, a #define
81    is no longer appropriate
82 */
83 #undef  DIRBLKSIZ
84 
85 static u_char ext2_ft_to_dt[] = {
86 	DT_UNKNOWN,		/* EXT2_FT_UNKNOWN */
87 	DT_REG,			/* EXT2_FT_REG_FILE */
88 	DT_DIR,			/* EXT2_FT_DIR */
89 	DT_CHR,			/* EXT2_FT_CHRDEV */
90 	DT_BLK,			/* EXT2_FT_BLKDEV */
91 	DT_FIFO,		/* EXT2_FT_FIFO */
92 	DT_SOCK,		/* EXT2_FT_SOCK */
93 	DT_LNK,			/* EXT2_FT_SYMLINK */
94 };
95 #define	FTTODT(ft) \
96     ((ft) < nitems(ext2_ft_to_dt) ? ext2_ft_to_dt[(ft)] : DT_UNKNOWN)
97 
98 static u_char dt_to_ext2_ft[] = {
99 	EXT2_FT_UNKNOWN,	/* DT_UNKNOWN */
100 	EXT2_FT_FIFO,		/* DT_FIFO */
101 	EXT2_FT_CHRDEV,		/* DT_CHR */
102 	EXT2_FT_UNKNOWN,	/* unused */
103 	EXT2_FT_DIR,		/* DT_DIR */
104 	EXT2_FT_UNKNOWN,	/* unused */
105 	EXT2_FT_BLKDEV,		/* DT_BLK */
106 	EXT2_FT_UNKNOWN,	/* unused */
107 	EXT2_FT_REG_FILE,	/* DT_REG */
108 	EXT2_FT_UNKNOWN,	/* unused */
109 	EXT2_FT_SYMLINK,	/* DT_LNK */
110 	EXT2_FT_UNKNOWN,	/* unused */
111 	EXT2_FT_SOCK,		/* DT_SOCK */
112 	EXT2_FT_UNKNOWN,	/* unused */
113 	EXT2_FT_UNKNOWN,	/* DT_WHT */
114 };
115 #define	DTTOFT(dt) \
116     ((dt) < nitems(dt_to_ext2_ft) ? dt_to_ext2_ft[(dt)] : EXT2_FT_UNKNOWN)
117 
118 static int	ext2_dirbadentry(struct vnode *dp, struct ext2fs_direct_2 *de,
119 		    int entryoffsetinblock);
120 static int	ext2_is_dot_entry(struct componentname *cnp);
121 static int	ext2_lookup_ino(struct vnode *vdp, struct vnode **vpp,
122 		    struct componentname *cnp, ino_t *dd_ino);
123 
124 static int
125 ext2_is_dot_entry(struct componentname *cnp)
126 {
127 	if (cnp->cn_namelen <= 2 && cnp->cn_nameptr[0] == '.' &&
128 	    (cnp->cn_nameptr[1] == '.' || cnp->cn_nameptr[1] == '\0'))
129 		return (1);
130 	return (0);
131 }
132 
133 /*
134  * Vnode op for reading directories.
135  */
136 int
137 ext2_readdir(struct vop_readdir_args *ap)
138 {
139 	struct vnode *vp = ap->a_vp;
140 	struct uio *uio = ap->a_uio;
141 	struct buf *bp;
142 	struct inode *ip;
143 	struct ext2fs_direct_2 *dp, *edp;
144 	u_long *cookies;
145 	struct dirent dstdp;
146 	off_t offset, startoffset;
147 	size_t readcnt, skipcnt;
148 	ssize_t startresid;
149 	u_int ncookies;
150 	int DIRBLKSIZ = VTOI(ap->a_vp)->i_e2fs->e2fs_bsize;
151 	int error;
152 
153 	if (uio->uio_offset < 0)
154 		return (EINVAL);
155 	ip = VTOI(vp);
156 	if (ap->a_ncookies != NULL) {
157 		if (uio->uio_resid < 0)
158 			ncookies = 0;
159 		else
160 			ncookies = uio->uio_resid;
161 		if (uio->uio_offset >= ip->i_size)
162 			ncookies = 0;
163 		else if (ip->i_size - uio->uio_offset < ncookies)
164 			ncookies = ip->i_size - uio->uio_offset;
165 		ncookies = ncookies / (offsetof(struct ext2fs_direct_2,
166 		    e2d_namlen) + 4) + 1;
167 		cookies = malloc(ncookies * sizeof(*cookies), M_TEMP, M_WAITOK);
168 		*ap->a_ncookies = ncookies;
169 		*ap->a_cookies = cookies;
170 	} else {
171 		ncookies = 0;
172 		cookies = NULL;
173 	}
174 	offset = startoffset = uio->uio_offset;
175 	startresid = uio->uio_resid;
176 	error = 0;
177 	while (error == 0 && uio->uio_resid > 0 &&
178 	    uio->uio_offset < ip->i_size) {
179 		error = ext2_blkatoff(vp, uio->uio_offset, NULL, &bp);
180 		if (error)
181 			break;
182 		if (bp->b_offset + bp->b_bcount > ip->i_size)
183 			readcnt = ip->i_size - bp->b_offset;
184 		else
185 			readcnt = bp->b_bcount;
186 		skipcnt = (size_t)(uio->uio_offset - bp->b_offset) &
187 		    ~(size_t)(DIRBLKSIZ - 1);
188 		offset = bp->b_offset + skipcnt;
189 		dp = (struct ext2fs_direct_2 *)&bp->b_data[skipcnt];
190 		edp = (struct ext2fs_direct_2 *)&bp->b_data[readcnt];
191 		while (error == 0 && uio->uio_resid > 0 && dp < edp) {
192 			if (dp->e2d_reclen <= offsetof(struct ext2fs_direct_2,
193 			    e2d_namlen) || (caddr_t)dp + dp->e2d_reclen >
194 			    (caddr_t)edp) {
195 				error = EIO;
196 				break;
197 			}
198 			/*-
199 			 * "New" ext2fs directory entries differ in 3 ways
200 			 * from ufs on-disk ones:
201 			 * - the name is not necessarily NUL-terminated.
202 			 * - the file type field always exists and always
203 			 *   follows the name length field.
204 			 * - the file type is encoded in a different way.
205 			 *
206 			 * "Old" ext2fs directory entries need no special
207 			 * conversions, since they are binary compatible
208 			 * with "new" entries having a file type of 0 (i.e.,
209 			 * EXT2_FT_UNKNOWN).  Splitting the old name length
210 			 * field didn't make a mess like it did in ufs,
211 			 * because ext2fs uses a machine-independent disk
212 			 * layout.
213 			 */
214 			dstdp.d_namlen = dp->e2d_namlen;
215 			dstdp.d_type = FTTODT(dp->e2d_type);
216 			if (offsetof(struct ext2fs_direct_2, e2d_namlen) +
217 			    dstdp.d_namlen > dp->e2d_reclen) {
218 				error = EIO;
219 				break;
220 			}
221 			if (offset < startoffset || dp->e2d_ino == 0)
222 				goto nextentry;
223 			dstdp.d_fileno = dp->e2d_ino;
224 			dstdp.d_reclen = GENERIC_DIRSIZ(&dstdp);
225 			bcopy(dp->e2d_name, dstdp.d_name, dstdp.d_namlen);
226 			dstdp.d_name[dstdp.d_namlen] = '\0';
227 			if (dstdp.d_reclen > uio->uio_resid) {
228 				if (uio->uio_resid == startresid)
229 					error = EINVAL;
230 				else
231 					error = EJUSTRETURN;
232 				break;
233 			}
234 			/* Advance dp. */
235 			error = uiomove((caddr_t)&dstdp, dstdp.d_reclen, uio);
236 			if (error)
237 				break;
238 			if (cookies != NULL) {
239 				KASSERT(ncookies > 0,
240 				    ("ext2_readdir: cookies buffer too small"));
241 				*cookies = offset + dp->e2d_reclen;
242 				cookies++;
243 				ncookies--;
244 			}
245 nextentry:
246 			offset += dp->e2d_reclen;
247 			dp = (struct ext2fs_direct_2 *)((caddr_t)dp +
248 			    dp->e2d_reclen);
249 		}
250 		bqrelse(bp);
251 		uio->uio_offset = offset;
252 	}
253 	/* We need to correct uio_offset. */
254 	uio->uio_offset = offset;
255 	if (error == EJUSTRETURN)
256 		error = 0;
257 	if (ap->a_ncookies != NULL) {
258 		if (error == 0) {
259 			ap->a_ncookies -= ncookies;
260 		} else {
261 			free(*ap->a_cookies, M_TEMP);
262 			*ap->a_ncookies = 0;
263 			*ap->a_cookies = NULL;
264 		}
265 	}
266 	if (error == 0 && ap->a_eofflag)
267 		*ap->a_eofflag = ip->i_size <= uio->uio_offset;
268 	return (error);
269 }
270 
271 /*
272  * Convert a component of a pathname into a pointer to a locked inode.
273  * This is a very central and rather complicated routine.
274  * If the file system is not maintained in a strict tree hierarchy,
275  * this can result in a deadlock situation (see comments in code below).
276  *
277  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
278  * on whether the name is to be looked up, created, renamed, or deleted.
279  * When CREATE, RENAME, or DELETE is specified, information usable in
280  * creating, renaming, or deleting a directory entry may be calculated.
281  * If flag has LOCKPARENT or'ed into it and the target of the pathname
282  * exists, lookup returns both the target and its parent directory locked.
283  * When creating or renaming and LOCKPARENT is specified, the target may
284  * not be ".".  When deleting and LOCKPARENT is specified, the target may
285  * be "."., but the caller must check to ensure it does an vrele and vput
286  * instead of two vputs.
287  *
288  * Overall outline of ext2_lookup:
289  *
290  *	search for name in directory, to found or notfound
291  * notfound:
292  *	if creating, return locked directory, leaving info on available slots
293  *	else return error
294  * found:
295  *	if at end of path and deleting, return information to allow delete
296  *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
297  *	  inode and return info to allow rewrite
298  *	if not at end, add name to cache; if at end and neither creating
299  *	  nor deleting, add name to cache
300  */
301 int
302 ext2_lookup(struct vop_cachedlookup_args *ap)
303 {
304 
305 	return (ext2_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
306 }
307 
308 static int
309 ext2_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
310     ino_t *dd_ino)
311 {
312 	struct inode *dp;		/* inode for directory being searched */
313 	struct buf *bp;			/* a buffer of directory entries */
314 	struct ext2fs_direct_2 *ep;	/* the current directory entry */
315 	int entryoffsetinblock;		/* offset of ep in bp's buffer */
316 	struct ext2fs_searchslot ss;
317 	doff_t i_diroff;		/* cached i_diroff value */
318 	doff_t i_offset;		/* cached i_offset value */
319 	int numdirpasses;		/* strategy for directory search */
320 	doff_t endsearch;		/* offset to end directory search */
321 	doff_t prevoff;			/* prev entry dp->i_offset */
322 	struct vnode *pdp;		/* saved dp during symlink work */
323 	struct vnode *tdp;		/* returned by VFS_VGET */
324 	doff_t enduseful;		/* pointer past last used dir slot */
325 	u_long bmask;			/* block offset mask */
326 	int error;
327 	struct ucred *cred = cnp->cn_cred;
328 	int flags = cnp->cn_flags;
329 	int nameiop = cnp->cn_nameiop;
330 	ino_t ino, ino1;
331 	int ltype;
332 	int entry_found = 0;
333 
334 	int DIRBLKSIZ = VTOI(vdp)->i_e2fs->e2fs_bsize;
335 
336 	if (vpp != NULL)
337 		*vpp = NULL;
338 
339 	dp = VTOI(vdp);
340 	bmask = VFSTOEXT2(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
341 restart:
342 	bp = NULL;
343 	ss.slotoffset = -1;
344 
345 	/*
346 	 * We now have a segment name to search for, and a directory to search.
347 	 *
348 	 * Suppress search for slots unless creating
349 	 * file and at end of pathname, in which case
350 	 * we watch for a place to put the new file in
351 	 * case it doesn't already exist.
352 	 */
353 	i_diroff = dp->i_diroff;
354 	ss.slotstatus = FOUND;
355 	ss.slotfreespace = ss.slotsize = ss.slotneeded = 0;
356 	if ((nameiop == CREATE || nameiop == RENAME) &&
357 	    (flags & ISLASTCN)) {
358 		ss.slotstatus = NONE;
359 		ss.slotneeded = EXT2_DIR_REC_LEN(cnp->cn_namelen);
360 		/*
361 		 * was ss.slotneeded = (sizeof(struct direct) - MAXNAMLEN +
362 		 * cnp->cn_namelen + 3) &~ 3;
363 		 */
364 	}
365 	/*
366 	 * Try to lookup dir entry using htree directory index.
367 	 *
368 	 * If we got an error or we want to find '.' or '..' entry,
369 	 * we will fall back to linear search.
370 	 */
371 	if (!ext2_is_dot_entry(cnp) && ext2_htree_has_idx(dp)) {
372 		numdirpasses = 1;
373 		entryoffsetinblock = 0;
374 		switch (ext2_htree_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
375 		    &bp, &entryoffsetinblock, &i_offset, &prevoff,
376 		    &enduseful, &ss)) {
377 		case 0:
378 			ep = (struct ext2fs_direct_2 *)((char *)bp->b_data +
379 			    (i_offset & bmask));
380 			goto foundentry;
381 		case ENOENT:
382 			i_offset = roundup2(dp->i_size, DIRBLKSIZ);
383 			goto notfound;
384 		default:
385 			/*
386 			 * Something failed; just fallback to do a linear
387 			 * search.
388 			 */
389 			break;
390 		}
391 	}
392 
393 	/*
394 	 * If there is cached information on a previous search of
395 	 * this directory, pick up where we last left off.
396 	 * We cache only lookups as these are the most common
397 	 * and have the greatest payoff. Caching CREATE has little
398 	 * benefit as it usually must search the entire directory
399 	 * to determine that the entry does not exist. Caching the
400 	 * location of the last DELETE or RENAME has not reduced
401 	 * profiling time and hence has been removed in the interest
402 	 * of simplicity.
403 	 */
404 	if (nameiop != LOOKUP || i_diroff == 0 ||
405 	    i_diroff > dp->i_size) {
406 		entryoffsetinblock = 0;
407 		i_offset = 0;
408 		numdirpasses = 1;
409 	} else {
410 		i_offset = i_diroff;
411 		if ((entryoffsetinblock = i_offset & bmask) &&
412 		    (error = ext2_blkatoff(vdp, (off_t)i_offset, NULL,
413 		    &bp)))
414 			return (error);
415 		numdirpasses = 2;
416 		nchstats.ncs_2passes++;
417 	}
418 	prevoff = i_offset;
419 	endsearch = roundup2(dp->i_size, DIRBLKSIZ);
420 	enduseful = 0;
421 
422 searchloop:
423 	while (i_offset < endsearch) {
424 		/*
425 		 * If necessary, get the next directory block.
426 		 */
427 		if (bp != NULL)
428 			brelse(bp);
429 		error = ext2_blkatoff(vdp, (off_t)i_offset, NULL, &bp);
430 		if (error != 0)
431 			return (error);
432 		entryoffsetinblock = 0;
433 		/*
434 		 * If still looking for a slot, and at a DIRBLKSIZE
435 		 * boundary, have to start looking for free space again.
436 		 */
437 		if (ss.slotstatus == NONE &&
438 		    (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
439 			ss.slotoffset = -1;
440 			ss.slotfreespace = 0;
441 		}
442 		error = ext2_search_dirblock(dp, bp->b_data, &entry_found,
443 		    cnp->cn_nameptr, cnp->cn_namelen,
444 		    &entryoffsetinblock, &i_offset, &prevoff,
445 		    &enduseful, &ss);
446 		if (error != 0) {
447 			brelse(bp);
448 			return (error);
449 		}
450 		if (entry_found) {
451 			ep = (struct ext2fs_direct_2 *)((char *)bp->b_data +
452 			    (entryoffsetinblock & bmask));
453 foundentry:
454 			ino = ep->e2d_ino;
455 			goto found;
456 		}
457 	}
458 notfound:
459 	/*
460 	 * If we started in the middle of the directory and failed
461 	 * to find our target, we must check the beginning as well.
462 	 */
463 	if (numdirpasses == 2) {
464 		numdirpasses--;
465 		i_offset = 0;
466 		endsearch = i_diroff;
467 		goto searchloop;
468 	}
469 	if (bp != NULL)
470 		brelse(bp);
471 	/*
472 	 * If creating, and at end of pathname and current
473 	 * directory has not been removed, then can consider
474 	 * allowing file to be created.
475 	 */
476 	if ((nameiop == CREATE || nameiop == RENAME) &&
477 	    (flags & ISLASTCN) && dp->i_nlink != 0) {
478 		/*
479 		 * Access for write is interpreted as allowing
480 		 * creation of files in the directory.
481 		 */
482 		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
483 			return (error);
484 		/*
485 		 * Return an indication of where the new directory
486 		 * entry should be put.  If we didn't find a slot,
487 		 * then set dp->i_count to 0 indicating
488 		 * that the new slot belongs at the end of the
489 		 * directory. If we found a slot, then the new entry
490 		 * can be put in the range from dp->i_offset to
491 		 * dp->i_offset + dp->i_count.
492 		 */
493 		if (ss.slotstatus == NONE) {
494 			dp->i_offset = roundup2(dp->i_size, DIRBLKSIZ);
495 			dp->i_count = 0;
496 			enduseful = dp->i_offset;
497 		} else {
498 			dp->i_offset = ss.slotoffset;
499 			dp->i_count = ss.slotsize;
500 			if (enduseful < ss.slotoffset + ss.slotsize)
501 				enduseful = ss.slotoffset + ss.slotsize;
502 		}
503 		dp->i_endoff = roundup2(enduseful, DIRBLKSIZ);
504 		/*
505 		 * We return with the directory locked, so that
506 		 * the parameters we set up above will still be
507 		 * valid if we actually decide to do a direnter().
508 		 * We return ni_vp == NULL to indicate that the entry
509 		 * does not currently exist; we leave a pointer to
510 		 * the (locked) directory inode in ndp->ni_dvp.
511 		 * The pathname buffer is saved so that the name
512 		 * can be obtained later.
513 		 *
514 		 * NB - if the directory is unlocked, then this
515 		 * information cannot be used.
516 		 */
517 		cnp->cn_flags |= SAVENAME;
518 		return (EJUSTRETURN);
519 	}
520 	/*
521 	 * Insert name into cache (as non-existent) if appropriate.
522 	 */
523 	if ((cnp->cn_flags & MAKEENTRY) != 0)
524 		cache_enter(vdp, NULL, cnp);
525 	return (ENOENT);
526 
527 found:
528 	if (dd_ino != NULL)
529 		*dd_ino = ino;
530 	if (numdirpasses == 2)
531 		nchstats.ncs_pass2++;
532 	/*
533 	 * Check that directory length properly reflects presence
534 	 * of this entry.
535 	 */
536 	if (entryoffsetinblock + EXT2_DIR_REC_LEN(ep->e2d_namlen)
537 	    > dp->i_size) {
538 		ext2_dirbad(dp, i_offset, "i_size too small");
539 		dp->i_size = entryoffsetinblock + EXT2_DIR_REC_LEN(ep->e2d_namlen);
540 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
541 	}
542 	brelse(bp);
543 
544 	/*
545 	 * Found component in pathname.
546 	 * If the final component of path name, save information
547 	 * in the cache as to where the entry was found.
548 	 */
549 	if ((flags & ISLASTCN) && nameiop == LOOKUP)
550 		dp->i_diroff = rounddown2(i_offset, DIRBLKSIZ);
551 	/*
552 	 * If deleting, and at end of pathname, return
553 	 * parameters which can be used to remove file.
554 	 */
555 	if (nameiop == DELETE && (flags & ISLASTCN)) {
556 		if (flags & LOCKPARENT)
557 			ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
558 		/*
559 		 * Write access to directory required to delete files.
560 		 */
561 		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
562 			return (error);
563 		/*
564 		 * Return pointer to current entry in dp->i_offset,
565 		 * and distance past previous entry (if there
566 		 * is a previous entry in this block) in dp->i_count.
567 		 * Save directory inode pointer in ndp->ni_dvp for dirremove().
568 		 *
569 		 * Technically we shouldn't be setting these in the
570 		 * WANTPARENT case (first lookup in rename()), but any
571 		 * lookups that will result in directory changes will
572 		 * overwrite these.
573 		 */
574 		dp->i_offset = i_offset;
575 		if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
576 			dp->i_count = 0;
577 		else
578 			dp->i_count = dp->i_offset - prevoff;
579 		if (dd_ino != NULL)
580 			return (0);
581 		if (dp->i_number == ino) {
582 			VREF(vdp);
583 			*vpp = vdp;
584 			return (0);
585 		}
586 		if ((error = VFS_VGET(vdp->v_mount, ino, LK_EXCLUSIVE,
587 		    &tdp)) != 0)
588 			return (error);
589 		/*
590 		 * If directory is "sticky", then user must own
591 		 * the directory, or the file in it, else she
592 		 * may not delete it (unless she's root). This
593 		 * implements append-only directories.
594 		 */
595 		if ((dp->i_mode & ISVTX) &&
596 		    cred->cr_uid != 0 &&
597 		    cred->cr_uid != dp->i_uid &&
598 		    VTOI(tdp)->i_uid != cred->cr_uid) {
599 			vput(tdp);
600 			return (EPERM);
601 		}
602 		*vpp = tdp;
603 		return (0);
604 	}
605 
606 	/*
607 	 * If rewriting (RENAME), return the inode and the
608 	 * information required to rewrite the present directory
609 	 * Must get inode of directory entry to verify it's a
610 	 * regular file, or empty directory.
611 	 */
612 	if (nameiop == RENAME && (flags & ISLASTCN)) {
613 		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
614 			return (error);
615 		/*
616 		 * Careful about locking second inode.
617 		 * This can only occur if the target is ".".
618 		 */
619 		dp->i_offset = i_offset;
620 		if (dp->i_number == ino)
621 			return (EISDIR);
622 		if (dd_ino != NULL)
623 			return (0);
624 		if ((error = VFS_VGET(vdp->v_mount, ino, LK_EXCLUSIVE,
625 		    &tdp)) != 0)
626 			return (error);
627 		*vpp = tdp;
628 		cnp->cn_flags |= SAVENAME;
629 		return (0);
630 	}
631 	if (dd_ino != NULL)
632 		return (0);
633 
634 	/*
635 	 * Step through the translation in the name.  We do not `vput' the
636 	 * directory because we may need it again if a symbolic link
637 	 * is relative to the current directory.  Instead we save it
638 	 * unlocked as "pdp".  We must get the target inode before unlocking
639 	 * the directory to insure that the inode will not be removed
640 	 * before we get it.  We prevent deadlock by always fetching
641 	 * inodes from the root, moving down the directory tree. Thus
642 	 * when following backward pointers ".." we must unlock the
643 	 * parent directory before getting the requested directory.
644 	 * There is a potential race condition here if both the current
645 	 * and parent directories are removed before the VFS_VGET for the
646 	 * inode associated with ".." returns.  We hope that this occurs
647 	 * infrequently since we cannot avoid this race condition without
648 	 * implementing a sophisticated deadlock detection algorithm.
649 	 * Note also that this simple deadlock detection scheme will not
650 	 * work if the file system has any hard links other than ".."
651 	 * that point backwards in the directory structure.
652 	 */
653 	pdp = vdp;
654 	if (flags & ISDOTDOT) {
655 		error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
656 		if (pdp->v_iflag & VI_DOOMED) {
657 			if (error == 0)
658 				vput(tdp);
659 			error = ENOENT;
660 		}
661 		if (error)
662 			return (error);
663 		/*
664 		 * Recheck that ".." entry in the vdp directory points
665 		 * to the inode we looked up before vdp lock was
666 		 * dropped.
667 		 */
668 		error = ext2_lookup_ino(pdp, NULL, cnp, &ino1);
669 		if (error) {
670 			vput(tdp);
671 			return (error);
672 		}
673 		if (ino1 != ino) {
674 			vput(tdp);
675 			goto restart;
676 		}
677 		*vpp = tdp;
678 	} else if (dp->i_number == ino) {
679 		VREF(vdp);	/* we want ourself, ie "." */
680 		/*
681 		 * When we lookup "." we still can be asked to lock it
682 		 * differently.
683 		 */
684 		ltype = cnp->cn_lkflags & LK_TYPE_MASK;
685 		if (ltype != VOP_ISLOCKED(vdp)) {
686 			if (ltype == LK_EXCLUSIVE)
687 				vn_lock(vdp, LK_UPGRADE | LK_RETRY);
688 			else	/* if (ltype == LK_SHARED) */
689 				vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
690 		}
691 		*vpp = vdp;
692 	} else {
693 		if ((error = VFS_VGET(vdp->v_mount, ino, cnp->cn_lkflags,
694 		    &tdp)) != 0)
695 			return (error);
696 		*vpp = tdp;
697 	}
698 
699 	/*
700 	 * Insert name into cache if appropriate.
701 	 */
702 	if (cnp->cn_flags & MAKEENTRY)
703 		cache_enter(vdp, *vpp, cnp);
704 	return (0);
705 }
706 
707 int
708 ext2_search_dirblock(struct inode *ip, void *data, int *foundp,
709     const char *name, int namelen, int *entryoffsetinblockp,
710     doff_t *offp, doff_t *prevoffp, doff_t *endusefulp,
711     struct ext2fs_searchslot *ssp)
712 {
713 	struct vnode *vdp;
714 	struct ext2fs_direct_2 *ep, *top;
715 	uint32_t bsize = ip->i_e2fs->e2fs_bsize;
716 	int offset = *entryoffsetinblockp;
717 	int namlen;
718 
719 	vdp = ITOV(ip);
720 
721 	ep = (struct ext2fs_direct_2 *)((char *)data + offset);
722 	top = (struct ext2fs_direct_2 *)((char *)data +
723 	    bsize - EXT2_DIR_REC_LEN(0));
724 
725 	while (ep < top) {
726 		/*
727 		 * Full validation checks are slow, so we only check
728 		 * enough to insure forward progress through the
729 		 * directory. Complete checks can be run by setting
730 		 * "vfs.e2fs.dirchk" to be true.
731 		 */
732 		if (ep->e2d_reclen == 0 ||
733 		    (dirchk && ext2_dirbadentry(vdp, ep, offset))) {
734 			int i;
735 
736 			ext2_dirbad(ip, *offp, "mangled entry");
737 			i = bsize - (offset & (bsize - 1));
738 			*offp += i;
739 			offset += i;
740 			continue;
741 		}
742 
743 		/*
744 		 * If an appropriate sized slot has not yet been found,
745 		 * check to see if one is available. Also accumulate space
746 		 * in the current block so that we can determine if
747 		 * compaction is viable.
748 		 */
749 		if (ssp->slotstatus != FOUND) {
750 			int size = ep->e2d_reclen;
751 
752 			if (ep->e2d_ino != 0)
753 				size -= EXT2_DIR_REC_LEN(ep->e2d_namlen);
754 			if (size > 0) {
755 				if (size >= ssp->slotneeded) {
756 					ssp->slotstatus = FOUND;
757 					ssp->slotoffset = *offp;
758 					ssp->slotsize = ep->e2d_reclen;
759 				} else if (ssp->slotstatus == NONE) {
760 					ssp->slotfreespace += size;
761 					if (ssp->slotoffset == -1)
762 						ssp->slotoffset = *offp;
763 					if (ssp->slotfreespace >= ssp->slotneeded) {
764 						ssp->slotstatus = COMPACT;
765 						ssp->slotsize = *offp +
766 						    ep->e2d_reclen -
767 						    ssp->slotoffset;
768 					}
769 				}
770 			}
771 		}
772 		/*
773 		 * Check for a name match.
774 		 */
775 		if (ep->e2d_ino) {
776 			namlen = ep->e2d_namlen;
777 			if (namlen == namelen &&
778 			    !bcmp(name, ep->e2d_name, (unsigned)namlen)) {
779 				/*
780 				 * Save directory entry's inode number and
781 				 * reclen in ndp->ni_ufs area, and release
782 				 * directory buffer.
783 				 */
784 				*foundp = 1;
785 				return (0);
786 			}
787 		}
788 		*prevoffp = *offp;
789 		*offp += ep->e2d_reclen;
790 		offset += ep->e2d_reclen;
791 		*entryoffsetinblockp = offset;
792 		if (ep->e2d_ino)
793 			*endusefulp = *offp;
794 		/*
795 		 * Get pointer to the next entry.
796 		 */
797 		ep = (struct ext2fs_direct_2 *)((char *)data + offset);
798 	}
799 
800 	return (0);
801 }
802 
803 void
804 ext2_dirbad(struct inode *ip, doff_t offset, char *how)
805 {
806 	struct mount *mp;
807 
808 	mp = ITOV(ip)->v_mount;
809 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
810 		panic("ext2_dirbad: %s: bad dir ino %ju at offset %ld: %s\n",
811 		    mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
812 		    (long)offset, how);
813 	else
814 		(void)printf("%s: bad dir ino %ju at offset %ld: %s\n",
815 		    mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
816 		    (long)offset, how);
817 
818 }
819 
820 /*
821  * Do consistency checking on a directory entry:
822  *	record length must be multiple of 4
823  *	entry must fit in rest of its DIRBLKSIZ block
824  *	record must be large enough to contain entry
825  *	name is not longer than MAXNAMLEN
826  *	name must be as long as advertised, and null terminated
827  */
828 /*
829  *	changed so that it confirms to ext2_check_dir_entry
830  */
831 static int
832 ext2_dirbadentry(struct vnode *dp, struct ext2fs_direct_2 *de,
833     int entryoffsetinblock)
834 {
835 	int DIRBLKSIZ = VTOI(dp)->i_e2fs->e2fs_bsize;
836 
837 	char *error_msg = NULL;
838 
839 	if (de->e2d_reclen < EXT2_DIR_REC_LEN(1))
840 		error_msg = "rec_len is smaller than minimal";
841 	else if (de->e2d_reclen % 4 != 0)
842 		error_msg = "rec_len % 4 != 0";
843 	else if (de->e2d_reclen < EXT2_DIR_REC_LEN(de->e2d_namlen))
844 		error_msg = "reclen is too small for name_len";
845 	else if (entryoffsetinblock + de->e2d_reclen > DIRBLKSIZ)
846 		error_msg = "directory entry across blocks";
847 	/* else LATER
848 	     if (de->inode > dir->i_sb->u.ext2_sb.s_es->s_inodes_count)
849 		error_msg = "inode out of bounds";
850 	*/
851 
852 	if (error_msg != NULL) {
853 		printf("bad directory entry: %s\n", error_msg);
854 		printf("offset=%d, inode=%lu, rec_len=%u, name_len=%u\n",
855 			entryoffsetinblock, (unsigned long)de->e2d_ino,
856 			de->e2d_reclen, de->e2d_namlen);
857 	}
858 	return error_msg == NULL ? 0 : 1;
859 }
860 
861 /*
862  * Insert an entry into the fresh directory block.
863  * Initialize entry tail if the metadata_csum feature is turned on.
864  */
865 static int
866 ext2_add_first_entry(struct vnode *dvp, struct ext2fs_direct_2 *entry,
867     struct componentname *cnp)
868 {
869 	struct inode *dp;
870 	struct iovec aiov;
871 	struct uio auio;
872 	char* buf = NULL;
873 	int dirblksize, error;
874 
875 	dp = VTOI(dvp);
876 	dirblksize = dp->i_e2fs->e2fs_bsize;
877 
878 	if (dp->i_offset & (dirblksize - 1))
879 		panic("ext2_add_first_entry: bad directory offset");
880 
881 	if (EXT2_HAS_RO_COMPAT_FEATURE(dp->i_e2fs,
882 	    EXT2F_ROCOMPAT_METADATA_CKSUM)) {
883 		entry->e2d_reclen = dirblksize - sizeof(struct ext2fs_direct_tail);
884 		buf = malloc(dirblksize, M_TEMP, M_WAITOK);
885 		if (!buf) {
886 			error = ENOMEM;
887 			goto out;
888 		}
889 		memcpy(buf, entry, EXT2_DIR_REC_LEN(entry->e2d_namlen));
890 		ext2_init_dirent_tail(EXT2_DIRENT_TAIL(buf, dirblksize));
891 		ext2_dirent_csum_set(dp, (struct ext2fs_direct_2 *)buf);
892 
893 		auio.uio_offset = dp->i_offset;
894 		auio.uio_resid = dirblksize;
895 		aiov.iov_len = auio.uio_resid;
896 		aiov.iov_base = (caddr_t)buf;
897 	} else {
898 		entry->e2d_reclen = dirblksize;
899 		auio.uio_offset = dp->i_offset;
900 		auio.uio_resid = EXT2_DIR_REC_LEN(entry->e2d_namlen);
901 		aiov.iov_len = auio.uio_resid;
902 		aiov.iov_base = (caddr_t)entry;
903 	}
904 
905 	auio.uio_iov = &aiov;
906 	auio.uio_iovcnt = 1;
907 	auio.uio_rw = UIO_WRITE;
908 	auio.uio_segflg = UIO_SYSSPACE;
909 	auio.uio_td = (struct thread *)0;
910 	error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
911 	if (error)
912 		goto out;
913 
914 	dp->i_size = roundup2(dp->i_size, dirblksize);
915 	dp->i_flag |= IN_CHANGE;
916 
917 out:
918 	free(buf, M_TEMP);
919 	return (error);
920 
921 }
922 
923 /*
924  * Write a directory entry after a call to namei, using the parameters
925  * that it left in nameidata.  The argument ip is the inode which the new
926  * directory entry will refer to.  Dvp is a pointer to the directory to
927  * be written, which was left locked by namei. Remaining parameters
928  * (dp->i_offset, dp->i_count) indicate how the space for the new
929  * entry is to be obtained.
930  */
931 int
932 ext2_direnter(struct inode *ip, struct vnode *dvp, struct componentname *cnp)
933 {
934 	struct inode *dp;
935 	struct ext2fs_direct_2 newdir;
936 	int DIRBLKSIZ = ip->i_e2fs->e2fs_bsize;
937 	int error;
938 
939 
940 #ifdef INVARIANTS
941 	if ((cnp->cn_flags & SAVENAME) == 0)
942 		panic("ext2_direnter: missing name");
943 #endif
944 	dp = VTOI(dvp);
945 	newdir.e2d_ino = ip->i_number;
946 	newdir.e2d_namlen = cnp->cn_namelen;
947 	if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs,
948 	    EXT2F_INCOMPAT_FTYPE))
949 		newdir.e2d_type = DTTOFT(IFTODT(ip->i_mode));
950 	else
951 		newdir.e2d_type = EXT2_FT_UNKNOWN;
952 	bcopy(cnp->cn_nameptr, newdir.e2d_name, (unsigned)cnp->cn_namelen + 1);
953 
954 	if (ext2_htree_has_idx(dp)) {
955 		error = ext2_htree_add_entry(dvp, &newdir, cnp);
956 		if (error) {
957 			dp->i_flag &= ~IN_E3INDEX;
958 			dp->i_flag |= IN_CHANGE | IN_UPDATE;
959 		}
960 		return (error);
961 	}
962 
963 	if (EXT2_HAS_COMPAT_FEATURE(ip->i_e2fs, EXT2F_COMPAT_DIRHASHINDEX) &&
964 	    !ext2_htree_has_idx(dp)) {
965 		if ((dp->i_size / DIRBLKSIZ) == 1 &&
966 		    dp->i_offset == DIRBLKSIZ) {
967 			/*
968 			 * Making indexed directory when one block is not
969 			 * enough to save all entries.
970 			 */
971 			return ext2_htree_create_index(dvp, cnp, &newdir);
972 		}
973 	}
974 
975 	/*
976 	 * If dp->i_count is 0, then namei could find no
977 	 * space in the directory. Here, dp->i_offset will
978 	 * be on a directory block boundary and we will write the
979 	 * new entry into a fresh block.
980 	 */
981 	if (dp->i_count == 0)
982 		return ext2_add_first_entry(dvp, &newdir, cnp);
983 
984 	error = ext2_add_entry(dvp, &newdir);
985 	if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
986 		error = ext2_truncate(dvp, (off_t)dp->i_endoff, IO_SYNC,
987 		    cnp->cn_cred, cnp->cn_thread);
988 	return (error);
989 }
990 
991 /*
992  * Insert an entry into the directory block.
993  * Compact the contents.
994  */
995 int
996 ext2_add_entry(struct vnode *dvp, struct ext2fs_direct_2 *entry)
997 {
998 	struct ext2fs_direct_2 *ep, *nep;
999 	struct inode *dp;
1000 	struct buf *bp;
1001 	u_int dsize;
1002 	int error, loc, newentrysize, spacefree;
1003 	char *dirbuf;
1004 
1005 	dp = VTOI(dvp);
1006 
1007 	/*
1008 	 * If dp->i_count is non-zero, then namei found space
1009 	 * for the new entry in the range dp->i_offset to
1010 	 * dp->i_offset + dp->i_count in the directory.
1011 	 * To use this space, we may have to compact the entries located
1012 	 * there, by copying them together towards the beginning of the
1013 	 * block, leaving the free space in one usable chunk at the end.
1014 	 */
1015 
1016 	/*
1017 	 * Increase size of directory if entry eats into new space.
1018 	 * This should never push the size past a new multiple of
1019 	 * DIRBLKSIZE.
1020 	 *
1021 	 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
1022 	 */
1023 	if (dp->i_offset + dp->i_count > dp->i_size)
1024 		dp->i_size = dp->i_offset + dp->i_count;
1025 	/*
1026 	 * Get the block containing the space for the new directory entry.
1027 	 */
1028 	if ((error = ext2_blkatoff(dvp, (off_t)dp->i_offset, &dirbuf,
1029 	    &bp)) != 0)
1030 		return (error);
1031 	/*
1032 	 * Find space for the new entry. In the simple case, the entry at
1033 	 * offset base will have the space. If it does not, then namei
1034 	 * arranged that compacting the region dp->i_offset to
1035 	 * dp->i_offset + dp->i_count would yield the
1036 	 * space.
1037 	 */
1038 	newentrysize = EXT2_DIR_REC_LEN(entry->e2d_namlen);
1039 	ep = (struct ext2fs_direct_2 *)dirbuf;
1040 	dsize = EXT2_DIR_REC_LEN(ep->e2d_namlen);
1041 	spacefree = ep->e2d_reclen - dsize;
1042 	for (loc = ep->e2d_reclen; loc < dp->i_count; ) {
1043 		nep = (struct ext2fs_direct_2 *)(dirbuf + loc);
1044 		if (ep->e2d_ino) {
1045 			/* trim the existing slot */
1046 			ep->e2d_reclen = dsize;
1047 			ep = (struct ext2fs_direct_2 *)((char *)ep + dsize);
1048 		} else {
1049 			/* overwrite; nothing there; header is ours */
1050 			spacefree += dsize;
1051 		}
1052 		dsize = EXT2_DIR_REC_LEN(nep->e2d_namlen);
1053 		spacefree += nep->e2d_reclen - dsize;
1054 		loc += nep->e2d_reclen;
1055 		bcopy((caddr_t)nep, (caddr_t)ep, dsize);
1056 	}
1057 	/*
1058 	 * Update the pointer fields in the previous entry (if any),
1059 	 * copy in the new entry, and write out the block.
1060 	 */
1061 	if (ep->e2d_ino == 0) {
1062 		if (spacefree + dsize < newentrysize)
1063 			panic("ext2_direnter: compact1");
1064 		entry->e2d_reclen = spacefree + dsize;
1065 	} else {
1066 		if (spacefree < newentrysize)
1067 			panic("ext2_direnter: compact2");
1068 		entry->e2d_reclen = spacefree;
1069 		ep->e2d_reclen = dsize;
1070 		ep = (struct ext2fs_direct_2 *)((char *)ep + dsize);
1071 	}
1072 	bcopy((caddr_t)entry, (caddr_t)ep, (u_int)newentrysize);
1073 	ext2_dirent_csum_set(dp, (struct ext2fs_direct_2 *)bp->b_data);
1074 	if (DOINGASYNC(dvp)) {
1075 		bdwrite(bp);
1076 		error = 0;
1077 	} else {
1078 		error = bwrite(bp);
1079 	}
1080 	dp->i_flag |= IN_CHANGE | IN_UPDATE;
1081 	return (error);
1082 }
1083 
1084 /*
1085  * Remove a directory entry after a call to namei, using
1086  * the parameters which it left in nameidata. The entry
1087  * dp->i_offset contains the offset into the directory of the
1088  * entry to be eliminated.  The dp->i_count field contains the
1089  * size of the previous record in the directory.  If this
1090  * is 0, the first entry is being deleted, so we need only
1091  * zero the inode number to mark the entry as free.  If the
1092  * entry is not the first in the directory, we must reclaim
1093  * the space of the now empty record by adding the record size
1094  * to the size of the previous entry.
1095  */
1096 int
1097 ext2_dirremove(struct vnode *dvp, struct componentname *cnp)
1098 {
1099 	struct inode *dp;
1100 	struct ext2fs_direct_2 *ep, *rep;
1101 	struct buf *bp;
1102 	int error;
1103 
1104 	dp = VTOI(dvp);
1105 	if (dp->i_count == 0) {
1106 		/*
1107 		 * First entry in block: set d_ino to zero.
1108 		 */
1109 		if ((error =
1110 		    ext2_blkatoff(dvp, (off_t)dp->i_offset, (char **)&ep,
1111 		    &bp)) != 0)
1112 			return (error);
1113 		ep->e2d_ino = 0;
1114 		ext2_dirent_csum_set(dp, (struct ext2fs_direct_2 *)bp->b_data);
1115 		error = bwrite(bp);
1116 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
1117 		return (error);
1118 	}
1119 	/*
1120 	 * Collapse new free space into previous entry.
1121 	 */
1122 	if ((error = ext2_blkatoff(dvp, (off_t)(dp->i_offset - dp->i_count),
1123 	    (char **)&ep, &bp)) != 0)
1124 		return (error);
1125 
1126 	/* Set 'rep' to the entry being removed. */
1127 	if (dp->i_count == 0)
1128 		rep = ep;
1129 	else
1130 		rep = (struct ext2fs_direct_2 *)((char *)ep + ep->e2d_reclen);
1131 	ep->e2d_reclen += rep->e2d_reclen;
1132 	ext2_dirent_csum_set(dp, (struct ext2fs_direct_2 *)bp->b_data);
1133 	if (DOINGASYNC(dvp) && dp->i_count != 0)
1134 		bdwrite(bp);
1135 	else
1136 		error = bwrite(bp);
1137 	dp->i_flag |= IN_CHANGE | IN_UPDATE;
1138 	return (error);
1139 }
1140 
1141 /*
1142  * Rewrite an existing directory entry to point at the inode
1143  * supplied.  The parameters describing the directory entry are
1144  * set up by a call to namei.
1145  */
1146 int
1147 ext2_dirrewrite(struct inode *dp, struct inode *ip, struct componentname *cnp)
1148 {
1149 	struct buf *bp;
1150 	struct ext2fs_direct_2 *ep;
1151 	struct vnode *vdp = ITOV(dp);
1152 	int error;
1153 
1154 	if ((error = ext2_blkatoff(vdp, (off_t)dp->i_offset, (char **)&ep,
1155 	    &bp)) != 0)
1156 		return (error);
1157 	ep->e2d_ino = ip->i_number;
1158 	if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs,
1159 	    EXT2F_INCOMPAT_FTYPE))
1160 		ep->e2d_type = DTTOFT(IFTODT(ip->i_mode));
1161 	else
1162 		ep->e2d_type = EXT2_FT_UNKNOWN;
1163 	ext2_dirent_csum_set(dp, (struct ext2fs_direct_2 *)bp->b_data);
1164 	error = bwrite(bp);
1165 	dp->i_flag |= IN_CHANGE | IN_UPDATE;
1166 	return (error);
1167 }
1168 
1169 /*
1170  * Check if a directory is empty or not.
1171  * Inode supplied must be locked.
1172  *
1173  * Using a struct dirtemplate here is not precisely
1174  * what we want, but better than using a struct direct.
1175  *
1176  * NB: does not handle corrupted directories.
1177  */
1178 int
1179 ext2_dirempty(struct inode *ip, ino_t parentino, struct ucred *cred)
1180 {
1181 	off_t off;
1182 	struct dirtemplate dbuf;
1183 	struct ext2fs_direct_2 *dp = (struct ext2fs_direct_2 *)&dbuf;
1184 	int error, namlen;
1185 	ssize_t count;
1186 #define	MINDIRSIZ (sizeof(struct dirtemplate) / 2)
1187 
1188 	for (off = 0; off < ip->i_size; off += dp->e2d_reclen) {
1189 		error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1190 		    off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1191 		    NOCRED, &count, (struct thread *)0);
1192 		/*
1193 		 * Since we read MINDIRSIZ, residual must
1194 		 * be 0 unless we're at end of file.
1195 		 */
1196 		if (error || count != 0)
1197 			return (0);
1198 		/* avoid infinite loops */
1199 		if (dp->e2d_reclen == 0)
1200 			return (0);
1201 		/* skip empty entries */
1202 		if (dp->e2d_ino == 0)
1203 			continue;
1204 		/* accept only "." and ".." */
1205 		namlen = dp->e2d_namlen;
1206 		if (namlen > 2)
1207 			return (0);
1208 		if (dp->e2d_name[0] != '.')
1209 			return (0);
1210 		/*
1211 		 * At this point namlen must be 1 or 2.
1212 		 * 1 implies ".", 2 implies ".." if second
1213 		 * char is also "."
1214 		 */
1215 		if (namlen == 1)
1216 			continue;
1217 		if (dp->e2d_name[1] == '.' && dp->e2d_ino == parentino)
1218 			continue;
1219 		return (0);
1220 	}
1221 	return (1);
1222 }
1223 
1224 /*
1225  * Check if source directory is in the path of the target directory.
1226  * Target is supplied locked, source is unlocked.
1227  * The target is always vput before returning.
1228  */
1229 int
1230 ext2_checkpath(struct inode *source, struct inode *target, struct ucred *cred)
1231 {
1232 	struct vnode *vp;
1233 	int error, namlen;
1234 	struct dirtemplate dirbuf;
1235 
1236 	vp = ITOV(target);
1237 	if (target->i_number == source->i_number) {
1238 		error = EEXIST;
1239 		goto out;
1240 	}
1241 	if (target->i_number == EXT2_ROOTINO) {
1242 		error = 0;
1243 		goto out;
1244 	}
1245 
1246 	for (;;) {
1247 		if (vp->v_type != VDIR) {
1248 			error = ENOTDIR;
1249 			break;
1250 		}
1251 		error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1252 		    sizeof(struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1253 		    IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL,
1254 		    NULL);
1255 		if (error != 0)
1256 			break;
1257 		namlen = dirbuf.dotdot_type;	/* like ufs little-endian */
1258 		if (namlen != 2 ||
1259 		    dirbuf.dotdot_name[0] != '.' ||
1260 		    dirbuf.dotdot_name[1] != '.') {
1261 			error = ENOTDIR;
1262 			break;
1263 		}
1264 		if (dirbuf.dotdot_ino == source->i_number) {
1265 			error = EINVAL;
1266 			break;
1267 		}
1268 		if (dirbuf.dotdot_ino == EXT2_ROOTINO)
1269 			break;
1270 		vput(vp);
1271 		if ((error = VFS_VGET(vp->v_mount, dirbuf.dotdot_ino,
1272 		    LK_EXCLUSIVE, &vp)) != 0) {
1273 			vp = NULL;
1274 			break;
1275 		}
1276 	}
1277 
1278 out:
1279 	if (error == ENOTDIR)
1280 		printf("checkpath: .. not a directory\n");
1281 	if (vp != NULL)
1282 		vput(vp);
1283 	return (error);
1284 }
1285