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