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