1139778Simp/*-
212115Sdyson *  modified for Lites 1.1
312115Sdyson *
412115Sdyson *  Aug 1995, Godmar Back (gback@cs.utah.edu)
512115Sdyson *  University of Utah, Department of Computer Science
612115Sdyson */
7139778Simp/*-
812115Sdyson * Copyright (c) 1989, 1993
912115Sdyson *	The Regents of the University of California.  All rights reserved.
1012115Sdyson * (c) UNIX System Laboratories, Inc.
1112115Sdyson * All or some portions of this file are derived from material licensed
1212115Sdyson * to the University of California by American Telephone and Telegraph
1312115Sdyson * Co. or Unix System Laboratories, Inc. and are reproduced herein with
1412115Sdyson * the permission of UNIX System Laboratories, Inc.
1512115Sdyson *
1612115Sdyson * Redistribution and use in source and binary forms, with or without
1712115Sdyson * modification, are permitted provided that the following conditions
1812115Sdyson * are met:
1912115Sdyson * 1. Redistributions of source code must retain the above copyright
2012115Sdyson *    notice, this list of conditions and the following disclaimer.
2112115Sdyson * 2. Redistributions in binary form must reproduce the above copyright
2212115Sdyson *    notice, this list of conditions and the following disclaimer in the
2312115Sdyson *    documentation and/or other materials provided with the distribution.
2412115Sdyson * 4. Neither the name of the University nor the names of its contributors
2512115Sdyson *    may be used to endorse or promote products derived from this software
2612115Sdyson *    without specific prior written permission.
2712115Sdyson *
2812115Sdyson * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2912115Sdyson * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
3012115Sdyson * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
3112115Sdyson * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
3212115Sdyson * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
3312115Sdyson * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
3412115Sdyson * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
3512115Sdyson * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3612115Sdyson * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3712115Sdyson * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3812115Sdyson * SUCH DAMAGE.
3912115Sdyson *
4012115Sdyson *	@(#)ufs_lookup.c	8.6 (Berkeley) 4/1/94
4193016Sbde * $FreeBSD$
4212115Sdyson */
4312115Sdyson
4412115Sdyson#include <sys/param.h>
4512159Sbde#include <sys/systm.h>
4612115Sdyson#include <sys/namei.h>
4760041Sphk#include <sys/bio.h>
4812115Sdyson#include <sys/buf.h>
49193377Sstas#include <sys/endian.h>
5012115Sdyson#include <sys/mount.h>
5112115Sdyson#include <sys/vnode.h>
5212115Sdyson#include <sys/malloc.h>
5312115Sdyson#include <sys/dirent.h>
5496753Siedowse#include <sys/sysctl.h>
5512115Sdyson
5612115Sdyson#include <ufs/ufs/dir.h>
5712115Sdyson
58202283Slulf#include <fs/ext2fs/inode.h>
59202283Slulf#include <fs/ext2fs/ext2_mount.h>
60202283Slulf#include <fs/ext2fs/ext2fs.h>
61221128Sjhb#include <fs/ext2fs/ext2_dinode.h>
62202283Slulf#include <fs/ext2fs/ext2_dir.h>
63221128Sjhb#include <fs/ext2fs/ext2_extern.h>
6412115Sdyson
65252008Spfg#ifdef INVARIANTS
6696753Siedowsestatic int dirchk = 1;
6796753Siedowse#else
6896753Siedowsestatic int dirchk = 0;
6996753Siedowse#endif
7096753Siedowse
71141633Sphkstatic SYSCTL_NODE(_vfs, OID_AUTO, e2fs, CTLFLAG_RD, 0, "EXT2FS filesystem");
7296753SiedowseSYSCTL_INT(_vfs_e2fs, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
7396753Siedowse
74111742Sdes/*
7512115Sdyson   DIRBLKSIZE in ffs is DEV_BSIZE (in most cases 512)
7612115Sdyson   while it is the native blocksize in ext2fs - thus, a #define
7712115Sdyson   is no longer appropriate
7812115Sdyson*/
7912115Sdyson#undef  DIRBLKSIZ
8012115Sdyson
8155477Sbdestatic u_char ext2_ft_to_dt[] = {
8255477Sbde	DT_UNKNOWN,		/* EXT2_FT_UNKNOWN */
8355477Sbde	DT_REG,			/* EXT2_FT_REG_FILE */
8455477Sbde	DT_DIR,			/* EXT2_FT_DIR */
8555477Sbde	DT_CHR,			/* EXT2_FT_CHRDEV */
8655477Sbde	DT_BLK,			/* EXT2_FT_BLKDEV */
8755477Sbde	DT_FIFO,		/* EXT2_FT_FIFO */
8855477Sbde	DT_SOCK,		/* EXT2_FT_SOCK */
8955477Sbde	DT_LNK,			/* EXT2_FT_SYMLINK */
9055477Sbde};
91247055Spfg#define	FTTODT(ft) \
92247055Spfg    ((ft) < nitems(ext2_ft_to_dt) ? ext2_ft_to_dt[(ft)] : DT_UNKNOWN)
9355477Sbde
9455477Sbdestatic u_char dt_to_ext2_ft[] = {
9555477Sbde	EXT2_FT_UNKNOWN,	/* DT_UNKNOWN */
9655477Sbde	EXT2_FT_FIFO,		/* DT_FIFO */
9755477Sbde	EXT2_FT_CHRDEV,		/* DT_CHR */
9855477Sbde	EXT2_FT_UNKNOWN,	/* unused */
9955477Sbde	EXT2_FT_DIR,		/* DT_DIR */
10055477Sbde	EXT2_FT_UNKNOWN,	/* unused */
10155477Sbde	EXT2_FT_BLKDEV,		/* DT_BLK */
10255477Sbde	EXT2_FT_UNKNOWN,	/* unused */
10355477Sbde	EXT2_FT_REG_FILE,	/* DT_REG */
10455477Sbde	EXT2_FT_UNKNOWN,	/* unused */
10555477Sbde	EXT2_FT_SYMLINK,	/* DT_LNK */
10655477Sbde	EXT2_FT_UNKNOWN,	/* unused */
10755477Sbde	EXT2_FT_SOCK,		/* DT_SOCK */
10855477Sbde	EXT2_FT_UNKNOWN,	/* unused */
10955477Sbde	EXT2_FT_UNKNOWN,	/* DT_WHT */
11055477Sbde};
111247055Spfg#define	DTTOFT(dt) \
112247055Spfg    ((dt) < nitems(dt_to_ext2_ft) ? dt_to_ext2_ft[(dt)] : EXT2_FT_UNKNOWN)
11355477Sbde
114202283Slulfstatic int	ext2_dirbadentry(struct vnode *dp, struct ext2fs_direct_2 *de,
11593014Sbde		    int entryoffsetinblock);
116254205Spfgstatic int	ext2_is_dot_entry(struct componentname *cnp);
117235820Spfgstatic int	ext2_lookup_ino(struct vnode *vdp, struct vnode **vpp,
118235820Spfg		    struct componentname *cnp, ino_t *dd_ino);
11912159Sbde
120254205Spfgstatic int
121254205Spfgext2_is_dot_entry(struct componentname *cnp)
122254205Spfg{
123254205Spfg	if (cnp->cn_namelen <= 2 && cnp->cn_nameptr[0] == '.' &&
124254205Spfg	    (cnp->cn_nameptr[1] == '.' || cnp->cn_nameptr[1] == '0'))
125254205Spfg		return (1);
126254205Spfg	return (0);
127254205Spfg}
128254205Spfg
12912115Sdyson/*
13012115Sdyson * Vnode op for reading directories.
13112115Sdyson */
13212115Sdysonint
133247209Spfgext2_readdir(struct vop_readdir_args *ap)
13412115Sdyson{
135254801Spfg	struct vnode *vp = ap->a_vp;
136111742Sdes	struct uio *uio = ap->a_uio;
137254801Spfg	struct buf *bp;
138254801Spfg	struct inode *ip;
139254801Spfg	struct ext2fs_direct_2 *dp, *edp;
140254801Spfg	u_long *cookies;
141254801Spfg	struct dirent dstdp;
142254801Spfg	off_t offset, startoffset;
143254801Spfg	size_t readcnt, skipcnt;
144254801Spfg	ssize_t startresid;
14524649Sdfr	int ncookies;
146202283Slulf	int DIRBLKSIZ = VTOI(ap->a_vp)->i_e2fs->e2fs_bsize;
147254801Spfg	int error;
14812115Sdyson
149254801Spfg	if (uio->uio_offset < 0)
150254801Spfg		return (EINVAL);
151254801Spfg	ip = VTOI(vp);
152254801Spfg	if (ap->a_ncookies != NULL) {
153254801Spfg		ncookies = uio->uio_resid;
154254801Spfg		if (uio->uio_offset >= ip->i_size)
155254801Spfg			ncookies = 0;
156254801Spfg		else if (ip->i_size - uio->uio_offset < ncookies)
157254801Spfg			ncookies = ip->i_size - uio->uio_offset;
158254801Spfg		ncookies = ncookies / (offsetof(struct ext2fs_direct_2,
159254801Spfg		    e2d_namlen) + 4) + 1;
160254801Spfg		cookies = malloc(ncookies * sizeof(*cookies), M_TEMP, M_WAITOK);
161254801Spfg		*ap->a_ncookies = ncookies;
162254801Spfg		*ap->a_cookies = cookies;
163254801Spfg	} else {
16424649Sdfr		ncookies = 0;
165254801Spfg		cookies = NULL;
166254801Spfg	}
167254801Spfg	offset = startoffset = uio->uio_offset;
168254801Spfg	startresid = uio->uio_resid;
169254801Spfg	error = 0;
170254801Spfg	while (error == 0 && uio->uio_resid > 0 &&
171254801Spfg	    uio->uio_offset < ip->i_size) {
172254801Spfg		error = ext2_blkatoff(vp, uio->uio_offset, NULL, &bp);
173254801Spfg		if (error)
174254801Spfg			break;
175254801Spfg		if (bp->b_offset + bp->b_bcount > ip->i_size)
176254801Spfg			readcnt = ip->i_size - bp->b_offset;
177254801Spfg		else
178254801Spfg			readcnt = bp->b_bcount;
179254801Spfg		skipcnt = (size_t)(uio->uio_offset - bp->b_offset) &
180254801Spfg		    ~(size_t)(DIRBLKSIZ - 1);
181254801Spfg		offset = bp->b_offset + skipcnt;
182254801Spfg		dp = (struct ext2fs_direct_2 *)&bp->b_data[skipcnt];
183254801Spfg		edp = (struct ext2fs_direct_2 *)&bp->b_data[readcnt];
184254801Spfg		while (error == 0 && uio->uio_resid > 0 && dp < edp) {
185254801Spfg			if (dp->e2d_reclen <= offsetof(struct ext2fs_direct_2,
186254801Spfg			    e2d_namlen) || (caddr_t)dp + dp->e2d_reclen >
187254801Spfg			    (caddr_t)edp) {
188254801Spfg				error = EIO;
189254801Spfg				break;
190254801Spfg			}
19155477Sbde			/*-
19255477Sbde			 * "New" ext2fs directory entries differ in 3 ways
19355477Sbde			 * from ufs on-disk ones:
19455477Sbde			 * - the name is not necessarily NUL-terminated.
19555477Sbde			 * - the file type field always exists and always
196125843Sbde			 *   follows the name length field.
19755477Sbde			 * - the file type is encoded in a different way.
19855477Sbde			 *
19955477Sbde			 * "Old" ext2fs directory entries need no special
200125843Sbde			 * conversions, since they are binary compatible
201125843Sbde			 * with "new" entries having a file type of 0 (i.e.,
20255477Sbde			 * EXT2_FT_UNKNOWN).  Splitting the old name length
20355477Sbde			 * field didn't make a mess like it did in ufs,
204125843Sbde			 * because ext2fs uses a machine-independent disk
20555477Sbde			 * layout.
20655477Sbde			 */
207254801Spfg			dstdp.d_namlen = dp->e2d_namlen;
208254801Spfg			dstdp.d_type = FTTODT(dp->e2d_type);
209254801Spfg			if (offsetof(struct ext2fs_direct_2, e2d_namlen) +
210254801Spfg			    dstdp.d_namlen > dp->e2d_reclen) {
211254801Spfg				error = EIO;
212254801Spfg				break;
213254801Spfg			}
214254801Spfg			if (offset < startoffset || dp->e2d_ino == 0)
215254801Spfg				goto nextentry;
216202283Slulf			dstdp.d_fileno = dp->e2d_ino;
21755477Sbde			dstdp.d_reclen = GENERIC_DIRSIZ(&dstdp);
218202283Slulf			bcopy(dp->e2d_name, dstdp.d_name, dstdp.d_namlen);
219254801Spfg			dstdp.d_name[dstdp.d_namlen] = '\0';
220254801Spfg			if (dstdp.d_reclen > uio->uio_resid) {
221254801Spfg				if (uio->uio_resid == startresid)
222254801Spfg					error = EINVAL;
223254801Spfg				else
224254801Spfg					error = EJUSTRETURN;
22512115Sdyson				break;
22612115Sdyson			}
227254801Spfg			/* Advance dp. */
228254801Spfg			error = uiomove((caddr_t)&dstdp, dstdp.d_reclen, uio);
229254801Spfg			if (error)
230254801Spfg				break;
231254801Spfg			if (cookies != NULL) {
232254801Spfg				KASSERT(ncookies > 0,
233254801Spfg				    ("ext2_readdir: cookies buffer too small"));
234254801Spfg				*cookies = offset + dp->e2d_reclen;
235254801Spfg				cookies++;
236254801Spfg				ncookies--;
23724649Sdfr			}
238254801Spfgnextentry:
239254801Spfg			offset += dp->e2d_reclen;
240254801Spfg			dp = (struct ext2fs_direct_2 *)((caddr_t)dp +
241254801Spfg			   dp->e2d_reclen);
24224649Sdfr		}
243254801Spfg		bqrelse(bp);
244254801Spfg		uio->uio_offset = offset;
24512115Sdyson	}
246254801Spfg	/* We need to correct uio_offset. */
247254801Spfg	uio->uio_offset = offset;
248254801Spfg	if (error == EJUSTRETURN)
249254801Spfg		error = 0;
250254801Spfg	if (ap->a_ncookies != NULL) {
251254801Spfg		if (error == 0) {
252254801Spfg			ap->a_ncookies -= ncookies;
253254801Spfg		} else {
254254801Spfg			free(*ap->a_cookies, M_TEMP);
255254801Spfg			*ap->a_ncookies = 0;
256254801Spfg			*ap->a_cookies = NULL;
257254801Spfg		}
258254801Spfg	}
259254801Spfg	if (error == 0 && ap->a_eofflag)
260254801Spfg		*ap->a_eofflag = ip->i_size <= uio->uio_offset;
261111742Sdes	return (error);
26212115Sdyson}
26312115Sdyson
26412115Sdyson/*
26512115Sdyson * Convert a component of a pathname into a pointer to a locked inode.
26612115Sdyson * This is a very central and rather complicated routine.
26712115Sdyson * If the file system is not maintained in a strict tree hierarchy,
26812115Sdyson * this can result in a deadlock situation (see comments in code below).
26912115Sdyson *
27012115Sdyson * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
27112115Sdyson * on whether the name is to be looked up, created, renamed, or deleted.
27212115Sdyson * When CREATE, RENAME, or DELETE is specified, information usable in
27312115Sdyson * creating, renaming, or deleting a directory entry may be calculated.
27412115Sdyson * If flag has LOCKPARENT or'ed into it and the target of the pathname
27512115Sdyson * exists, lookup returns both the target and its parent directory locked.
27612115Sdyson * When creating or renaming and LOCKPARENT is specified, the target may
27712115Sdyson * not be ".".  When deleting and LOCKPARENT is specified, the target may
27812115Sdyson * be "."., but the caller must check to ensure it does an vrele and vput
27912115Sdyson * instead of two vputs.
28012115Sdyson *
281125843Sbde * Overall outline of ext2_lookup:
28212115Sdyson *
28312115Sdyson *	search for name in directory, to found or notfound
28412115Sdyson * notfound:
28512115Sdyson *	if creating, return locked directory, leaving info on available slots
28612115Sdyson *	else return error
28712115Sdyson * found:
28812115Sdyson *	if at end of path and deleting, return information to allow delete
28912115Sdyson *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
29012115Sdyson *	  inode and return info to allow rewrite
29112115Sdyson *	if not at end, add name to cache; if at end and neither creating
29212115Sdyson *	  nor deleting, add name to cache
29312115Sdyson */
29412115Sdysonint
295247209Spfgext2_lookup(struct vop_cachedlookup_args *ap)
29612115Sdyson{
297235820Spfg
298235820Spfg	return (ext2_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
299235820Spfg}
300235820Spfg
301235820Spfgstatic int
302235820Spfgext2_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
303235820Spfg    ino_t *dd_ino)
304235820Spfg{
30596752Siedowse	struct inode *dp;		/* inode for directory being searched */
30612115Sdyson	struct buf *bp;			/* a buffer of directory entries */
307202283Slulf	struct ext2fs_direct_2 *ep;	/* the current directory entry */
30812115Sdyson	int entryoffsetinblock;		/* offset of ep in bp's buffer */
309254205Spfg	struct ext2fs_searchslot ss;
310202283Slulf	doff_t i_diroff;		/* cached i_diroff value */
311202283Slulf	doff_t i_offset;		/* cached i_offset value */
31212115Sdyson	int numdirpasses;		/* strategy for directory search */
31312115Sdyson	doff_t endsearch;		/* offset to end directory search */
31412115Sdyson	doff_t prevoff;			/* prev entry dp->i_offset */
31512115Sdyson	struct vnode *pdp;		/* saved dp during symlink work */
31612115Sdyson	struct vnode *tdp;		/* returned by VFS_VGET */
31712115Sdyson	doff_t enduseful;		/* pointer past last used dir slot */
31812115Sdyson	u_long bmask;			/* block offset mask */
319254205Spfg	int error;
32012115Sdyson	struct ucred *cred = cnp->cn_cred;
32112115Sdyson	int flags = cnp->cn_flags;
32212115Sdyson	int nameiop = cnp->cn_nameiop;
323235820Spfg	ino_t ino, ino1;
324202283Slulf	int ltype;
325254205Spfg	int entry_found = 0;
32612115Sdyson
327235820Spfg	int	DIRBLKSIZ = VTOI(vdp)->i_e2fs->e2fs_bsize;
32812115Sdyson
329235820Spfg	if (vpp != NULL)
330235820Spfg		*vpp = NULL;
331235820Spfg
332235820Spfg	dp = VTOI(vdp);
333235820Spfg	bmask = VFSTOEXT2(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
334235820Spfgrestart:
33512115Sdyson	bp = NULL;
336254205Spfg	ss.slotoffset = -1;
337217584Sjhb
33812115Sdyson	/*
33912115Sdyson	 * We now have a segment name to search for, and a directory to search.
340254205Spfg	 *
34112115Sdyson	 * Suppress search for slots unless creating
34212115Sdyson	 * file and at end of pathname, in which case
34312115Sdyson	 * we watch for a place to put the new file in
34412115Sdyson	 * case it doesn't already exist.
34512115Sdyson	 */
346202283Slulf	ino = 0;
347202283Slulf	i_diroff = dp->i_diroff;
348254205Spfg	ss.slotstatus = FOUND;
349254205Spfg	ss.slotfreespace = ss.slotsize = ss.slotneeded = 0;
35012115Sdyson	if ((nameiop == CREATE || nameiop == RENAME) &&
35112115Sdyson	    (flags & ISLASTCN)) {
352254205Spfg		ss.slotstatus = NONE;
353254205Spfg		ss.slotneeded = EXT2_DIR_REC_LEN(cnp->cn_namelen);
35412115Sdyson		/* was
355254205Spfg		ss.slotneeded = (sizeof(struct direct) - MAXNAMLEN +
35612115Sdyson			cnp->cn_namelen + 3) &~ 3; */
35712115Sdyson	}
35812115Sdyson
35912115Sdyson	/*
360254205Spfg	 * Try to lookup dir entry using htree directory index.
361254205Spfg	 *
362254205Spfg	 * If we got an error or we want to find '.' or '..' entry,
363254205Spfg	 * we will fall back to linear search.
364254205Spfg	 */
365254205Spfg	if (!ext2_is_dot_entry(cnp) && ext2_htree_has_idx(dp)) {
366254205Spfg		numdirpasses = 1;
367254205Spfg		entryoffsetinblock = 0;
368254205Spfg		switch (ext2_htree_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
369254205Spfg				&bp, &entryoffsetinblock, &i_offset, &prevoff,
370254205Spfg				&enduseful, &ss)) {
371254205Spfg		case 0:
372254205Spfg			ep = (struct ext2fs_direct_2 *)((char *)bp->b_data +
373254205Spfg				(i_offset & bmask));
374254205Spfg			goto foundentry;
375254205Spfg		case ENOENT:
376254205Spfg			i_offset = roundup2(dp->i_size, DIRBLKSIZ);
377254205Spfg			goto notfound;
378254205Spfg		default:
379254205Spfg			/*
380254205Spfg			 * Something failed; just fallback to do a linear
381254205Spfg			 * search.
382254205Spfg			 */
383254205Spfg			break;
384254205Spfg		}
385254205Spfg	}
386254205Spfg
387254205Spfg	/*
38812115Sdyson	 * If there is cached information on a previous search of
38912115Sdyson	 * this directory, pick up where we last left off.
39012115Sdyson	 * We cache only lookups as these are the most common
39112115Sdyson	 * and have the greatest payoff. Caching CREATE has little
39212115Sdyson	 * benefit as it usually must search the entire directory
39312115Sdyson	 * to determine that the entry does not exist. Caching the
39412115Sdyson	 * location of the last DELETE or RENAME has not reduced
39512115Sdyson	 * profiling time and hence has been removed in the interest
39612115Sdyson	 * of simplicity.
39712115Sdyson	 */
398202283Slulf	if (nameiop != LOOKUP || i_diroff == 0 ||
399202283Slulf	    i_diroff > dp->i_size) {
40012115Sdyson		entryoffsetinblock = 0;
401202283Slulf		i_offset = 0;
40212115Sdyson		numdirpasses = 1;
40312115Sdyson	} else {
404202283Slulf		i_offset = i_diroff;
405202283Slulf		if ((entryoffsetinblock = i_offset & bmask) &&
406202283Slulf		    (error = ext2_blkatoff(vdp, (off_t)i_offset, NULL,
40796749Siedowse		    &bp)))
40812115Sdyson			return (error);
40912115Sdyson		numdirpasses = 2;
41012115Sdyson		nchstats.ncs_2passes++;
41112115Sdyson	}
412202283Slulf	prevoff = i_offset;
413202283Slulf	endsearch = roundup2(dp->i_size, DIRBLKSIZ);
41412115Sdyson	enduseful = 0;
41512115Sdyson
41612115Sdysonsearchloop:
417202283Slulf	while (i_offset < endsearch) {
41812115Sdyson		/*
41912115Sdyson		 * If necessary, get the next directory block.
42012115Sdyson		 */
421254205Spfg		if (bp != NULL)
422254205Spfg			brelse(bp);
423254205Spfg		error = ext2_blkatoff(vdp, (off_t)i_offset, NULL, &bp);
424254205Spfg		if (error != 0)
425254205Spfg			return (error);
426254205Spfg		entryoffsetinblock = 0;
42712115Sdyson		/*
42812115Sdyson		 * If still looking for a slot, and at a DIRBLKSIZE
42912115Sdyson		 * boundary, have to start looking for free space again.
43012115Sdyson		 */
431254205Spfg		if (ss.slotstatus == NONE &&
43212115Sdyson		    (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
433254205Spfg			ss.slotoffset = -1;
434254205Spfg			ss.slotfreespace = 0;
43512115Sdyson		}
436254205Spfg		error = ext2_search_dirblock(dp, bp->b_data, &entry_found,
437254205Spfg				cnp->cn_nameptr, cnp->cn_namelen,
438254205Spfg				&entryoffsetinblock, &i_offset, &prevoff,
439254205Spfg				&enduseful, &ss);
440254205Spfg		if (error != 0) {
441254205Spfg			brelse(bp);
442254205Spfg			return (error);
44312115Sdyson		}
444254205Spfg		if (entry_found) {
445254205Spfg			ep = (struct ext2fs_direct_2 *)((char *)bp->b_data +
446254205Spfg				(entryoffsetinblock & bmask));
447254205Spfgfoundentry:
448254205Spfg			ino = ep->e2d_ino;
449254205Spfg			goto found;
45012115Sdyson		}
45112115Sdyson	}
452254205Spfgnotfound:
45312115Sdyson	/*
45412115Sdyson	 * If we started in the middle of the directory and failed
45512115Sdyson	 * to find our target, we must check the beginning as well.
45612115Sdyson	 */
45712115Sdyson	if (numdirpasses == 2) {
45812115Sdyson		numdirpasses--;
459202283Slulf		i_offset = 0;
460202283Slulf		endsearch = i_diroff;
46112115Sdyson		goto searchloop;
46212115Sdyson	}
46312115Sdyson	if (bp != NULL)
46412115Sdyson		brelse(bp);
46512115Sdyson	/*
46612115Sdyson	 * If creating, and at end of pathname and current
46712115Sdyson	 * directory has not been removed, then can consider
46812115Sdyson	 * allowing file to be created.
46912115Sdyson	 */
47012115Sdyson	if ((nameiop == CREATE || nameiop == RENAME) &&
47112115Sdyson	    (flags & ISLASTCN) && dp->i_nlink != 0) {
47212115Sdyson		/*
47312115Sdyson		 * Access for write is interpreted as allowing
47412115Sdyson		 * creation of files in the directory.
47512115Sdyson		 */
47683366Sjulian		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
47712115Sdyson			return (error);
47812115Sdyson		/*
47912115Sdyson		 * Return an indication of where the new directory
48012115Sdyson		 * entry should be put.  If we didn't find a slot,
48112115Sdyson		 * then set dp->i_count to 0 indicating
48212115Sdyson		 * that the new slot belongs at the end of the
48312115Sdyson		 * directory. If we found a slot, then the new entry
48412115Sdyson		 * can be put in the range from dp->i_offset to
48512115Sdyson		 * dp->i_offset + dp->i_count.
48612115Sdyson		 */
487254205Spfg		if (ss.slotstatus == NONE) {
488202283Slulf			dp->i_offset = roundup2(dp->i_size, DIRBLKSIZ);
48912115Sdyson			dp->i_count = 0;
49012115Sdyson			enduseful = dp->i_offset;
49112115Sdyson		} else {
492254205Spfg			dp->i_offset = ss.slotoffset;
493254205Spfg			dp->i_count = ss.slotsize;
494254205Spfg			if (enduseful < ss.slotoffset + ss.slotsize)
495254205Spfg				enduseful = ss.slotoffset + ss.slotsize;
49612115Sdyson		}
497202283Slulf		dp->i_endoff = roundup2(enduseful, DIRBLKSIZ);
49812115Sdyson		/*
49912115Sdyson		 * We return with the directory locked, so that
50012115Sdyson		 * the parameters we set up above will still be
50112115Sdyson		 * valid if we actually decide to do a direnter().
50212115Sdyson		 * We return ni_vp == NULL to indicate that the entry
50312115Sdyson		 * does not currently exist; we leave a pointer to
50412115Sdyson		 * the (locked) directory inode in ndp->ni_dvp.
50512115Sdyson		 * The pathname buffer is saved so that the name
50612115Sdyson		 * can be obtained later.
50712115Sdyson		 *
50812115Sdyson		 * NB - if the directory is unlocked, then this
50912115Sdyson		 * information cannot be used.
51012115Sdyson		 */
51112115Sdyson		cnp->cn_flags |= SAVENAME;
51212115Sdyson		return (EJUSTRETURN);
51312115Sdyson	}
51412115Sdyson	/*
51512115Sdyson	 * Insert name into cache (as non-existent) if appropriate.
51612115Sdyson	 */
51712115Sdyson	if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
518235820Spfg		cache_enter(vdp, NULL, cnp);
51912115Sdyson	return (ENOENT);
52012115Sdyson
52112115Sdysonfound:
522235820Spfg	if (dd_ino != NULL)
523235820Spfg		*dd_ino = ino;
52412115Sdyson	if (numdirpasses == 2)
52512115Sdyson		nchstats.ncs_pass2++;
52612115Sdyson	/*
52712115Sdyson	 * Check that directory length properly reflects presence
52812115Sdyson	 * of this entry.
52912115Sdyson	 */
530202283Slulf	if (entryoffsetinblock + EXT2_DIR_REC_LEN(ep->e2d_namlen)
53112115Sdyson		> dp->i_size) {
532202283Slulf		ext2_dirbad(dp, i_offset, "i_size too small");
533202283Slulf		dp->i_size = entryoffsetinblock+EXT2_DIR_REC_LEN(ep->e2d_namlen);
53412115Sdyson		dp->i_flag |= IN_CHANGE | IN_UPDATE;
53512115Sdyson	}
536105420Sbde	brelse(bp);
53712115Sdyson
53812115Sdyson	/*
53912115Sdyson	 * Found component in pathname.
54012115Sdyson	 * If the final component of path name, save information
54112115Sdyson	 * in the cache as to where the entry was found.
54212115Sdyson	 */
54312115Sdyson	if ((flags & ISLASTCN) && nameiop == LOOKUP)
544202283Slulf		dp->i_diroff = i_offset &~ (DIRBLKSIZ - 1);
54512115Sdyson	/*
54612115Sdyson	 * If deleting, and at end of pathname, return
54712115Sdyson	 * parameters which can be used to remove file.
54812115Sdyson	 */
54912115Sdyson	if (nameiop == DELETE && (flags & ISLASTCN)) {
550252677Spfg		if (flags & LOCKPARENT)
551252677Spfg			ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
55212115Sdyson		/*
55312115Sdyson		 * Write access to directory required to delete files.
55412115Sdyson		 */
55583366Sjulian		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
55612115Sdyson			return (error);
55712115Sdyson		/*
55812115Sdyson		 * Return pointer to current entry in dp->i_offset,
55912115Sdyson		 * and distance past previous entry (if there
56012115Sdyson		 * is a previous entry in this block) in dp->i_count.
56112115Sdyson		 * Save directory inode pointer in ndp->ni_dvp for dirremove().
562252677Spfg		 *
563252677Spfg		 * Technically we shouldn't be setting these in the
564252677Spfg		 * WANTPARENT case (first lookup in rename()), but any
565252677Spfg		 * lookups that will result in directory changes will
566252677Spfg		 * overwrite these.
56712115Sdyson		 */
568252677Spfg		dp->i_offset = i_offset;
56912115Sdyson		if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
57012115Sdyson			dp->i_count = 0;
57112115Sdyson		else
57212115Sdyson			dp->i_count = dp->i_offset - prevoff;
573235820Spfg		if (dd_ino != NULL)
574235820Spfg			return (0);
575202283Slulf		if (dp->i_number == ino) {
57612115Sdyson			VREF(vdp);
57712115Sdyson			*vpp = vdp;
57812115Sdyson			return (0);
57912115Sdyson		}
580202283Slulf		if ((error = VFS_VGET(vdp->v_mount, ino, LK_EXCLUSIVE,
58192462Smckusick		    &tdp)) != 0)
58212115Sdyson			return (error);
58312115Sdyson		/*
58412115Sdyson		 * If directory is "sticky", then user must own
58512115Sdyson		 * the directory, or the file in it, else she
58612115Sdyson		 * may not delete it (unless she's root). This
58712115Sdyson		 * implements append-only directories.
58812115Sdyson		 */
58912115Sdyson		if ((dp->i_mode & ISVTX) &&
59012115Sdyson		    cred->cr_uid != 0 &&
59112115Sdyson		    cred->cr_uid != dp->i_uid &&
59212115Sdyson		    VTOI(tdp)->i_uid != cred->cr_uid) {
59312115Sdyson			vput(tdp);
59412115Sdyson			return (EPERM);
59512115Sdyson		}
59612115Sdyson		*vpp = tdp;
59712115Sdyson		return (0);
59812115Sdyson	}
59912115Sdyson
60012115Sdyson	/*
60112115Sdyson	 * If rewriting (RENAME), return the inode and the
60212115Sdyson	 * information required to rewrite the present directory
60312115Sdyson	 * Must get inode of directory entry to verify it's a
60412115Sdyson	 * regular file, or empty directory.
60512115Sdyson	 */
606144299Sjeff	if (nameiop == RENAME && (flags & ISLASTCN)) {
60783366Sjulian		if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)) != 0)
60812115Sdyson			return (error);
60912115Sdyson		/*
61012115Sdyson		 * Careful about locking second inode.
61112115Sdyson		 * This can only occur if the target is ".".
61212115Sdyson		 */
613252677Spfg		dp->i_offset = i_offset;
614202283Slulf		if (dp->i_number == ino)
61512115Sdyson			return (EISDIR);
616235820Spfg		if (dd_ino != NULL)
617235820Spfg			return (0);
618202283Slulf		if ((error = VFS_VGET(vdp->v_mount, ino, LK_EXCLUSIVE,
61992462Smckusick		    &tdp)) != 0)
62012115Sdyson			return (error);
62112115Sdyson		*vpp = tdp;
62212115Sdyson		cnp->cn_flags |= SAVENAME;
62312115Sdyson		return (0);
62412115Sdyson	}
625235820Spfg	if (dd_ino != NULL)
626235820Spfg		return (0);
62712115Sdyson
62812115Sdyson	/*
62912115Sdyson	 * Step through the translation in the name.  We do not `vput' the
63012115Sdyson	 * directory because we may need it again if a symbolic link
63112115Sdyson	 * is relative to the current directory.  Instead we save it
63212115Sdyson	 * unlocked as "pdp".  We must get the target inode before unlocking
63312115Sdyson	 * the directory to insure that the inode will not be removed
63412115Sdyson	 * before we get it.  We prevent deadlock by always fetching
63512115Sdyson	 * inodes from the root, moving down the directory tree. Thus
63612115Sdyson	 * when following backward pointers ".." we must unlock the
63712115Sdyson	 * parent directory before getting the requested directory.
63812115Sdyson	 * There is a potential race condition here if both the current
63912115Sdyson	 * and parent directories are removed before the VFS_VGET for the
64012115Sdyson	 * inode associated with ".." returns.  We hope that this occurs
64112115Sdyson	 * infrequently since we cannot avoid this race condition without
64212115Sdyson	 * implementing a sophisticated deadlock detection algorithm.
64312115Sdyson	 * Note also that this simple deadlock detection scheme will not
64412115Sdyson	 * work if the file system has any hard links other than ".."
64512115Sdyson	 * that point backwards in the directory structure.
64612115Sdyson	 */
64712115Sdyson	pdp = vdp;
64812115Sdyson	if (flags & ISDOTDOT) {
649252677Spfg		error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
650235820Spfg		if (pdp->v_iflag & VI_DOOMED) {
651235820Spfg			if (error == 0)
652235820Spfg				vput(tdp);
653235820Spfg			error = ENOENT;
654235820Spfg		}
655235820Spfg		if (error)
65612115Sdyson			return (error);
657235820Spfg		/*
658235820Spfg		 * Recheck that ".." entry in the vdp directory points
659235820Spfg		 * to the inode we looked up before vdp lock was
660235820Spfg		 * dropped.
661235820Spfg		 */
662235820Spfg		error = ext2_lookup_ino(pdp, NULL, cnp, &ino1);
663235820Spfg		if (error) {
664235820Spfg			vput(tdp);
665235820Spfg			return (error);
666235820Spfg		}
667235820Spfg		if (ino1 != ino) {
668235820Spfg			vput(tdp);
669235820Spfg			goto restart;
670235820Spfg		}
67112115Sdyson		*vpp = tdp;
672202283Slulf	} else if (dp->i_number == ino) {
67312115Sdyson		VREF(vdp);	/* we want ourself, ie "." */
674202283Slulf		/*
675202283Slulf		 * When we lookup "." we still can be asked to lock it
676202283Slulf		 * differently.
677202283Slulf		 */
678202283Slulf		ltype = cnp->cn_lkflags & LK_TYPE_MASK;
679202283Slulf		if (ltype != VOP_ISLOCKED(vdp)) {
680202283Slulf			if (ltype == LK_EXCLUSIVE)
681202283Slulf				vn_lock(vdp, LK_UPGRADE | LK_RETRY);
682202283Slulf			else /* if (ltype == LK_SHARED) */
683202283Slulf				vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
684202283Slulf		}
68512115Sdyson		*vpp = vdp;
68612115Sdyson	} else {
687202283Slulf		if ((error = VFS_VGET(vdp->v_mount, ino, cnp->cn_lkflags,
68892462Smckusick		    &tdp)) != 0)
68912115Sdyson			return (error);
69012115Sdyson		*vpp = tdp;
69112115Sdyson	}
69212115Sdyson
69312115Sdyson	/*
69412115Sdyson	 * Insert name into cache if appropriate.
69512115Sdyson	 */
69612115Sdyson	if (cnp->cn_flags & MAKEENTRY)
69712115Sdyson		cache_enter(vdp, *vpp, cnp);
69812115Sdyson	return (0);
69912115Sdyson}
70012115Sdyson
701254205Spfgint
702254205Spfgext2_search_dirblock(struct inode *ip, void *data, int *foundp,
703254205Spfg	const char *name, int namelen, int *entryoffsetinblockp,
704254205Spfg	doff_t *offp, doff_t *prevoffp, doff_t *endusefulp,
705254205Spfg	struct ext2fs_searchslot *ssp)
706254205Spfg{
707254205Spfg	struct vnode *vdp;
708254205Spfg	struct ext2fs_direct_2 *ep, *top;
709254205Spfg	uint32_t bsize = ip->i_e2fs->e2fs_bsize;
710254205Spfg	int offset = *entryoffsetinblockp;
711254205Spfg	int namlen;
712254205Spfg
713254205Spfg	vdp = ITOV(ip);
714254205Spfg
715254205Spfg	ep = (struct ext2fs_direct_2 *)((char *)data + offset);
716254205Spfg	top = (struct ext2fs_direct_2 *)((char *)data +
717254205Spfg		bsize - EXT2_DIR_REC_LEN(0));
718254205Spfg
719254205Spfg	while (ep < top) {
720254205Spfg		/*
721254205Spfg		 * Full validation checks are slow, so we only check
722254205Spfg		 * enough to insure forward progress through the
723254205Spfg		 * directory. Complete checks can be run by setting
724254205Spfg		 * "vfs.e2fs.dirchk" to be true.
725254205Spfg		 */
726254205Spfg		if (ep->e2d_reclen == 0 ||
727254205Spfg		    (dirchk && ext2_dirbadentry(vdp, ep, offset))) {
728254205Spfg			int i;
729254205Spfg			ext2_dirbad(ip, *offp, "mangled entry");
730254205Spfg			i = bsize - (offset & (bsize - 1));
731254205Spfg			*offp += i;
732254205Spfg			offset += i;
733254205Spfg			continue;
734254205Spfg		}
735254205Spfg
736254205Spfg		/*
737254205Spfg		 * If an appropriate sized slot has not yet been found,
738254205Spfg		 * check to see if one is available. Also accumulate space
739254205Spfg		 * in the current block so that we can determine if
740254205Spfg		 * compaction is viable.
741254205Spfg		 */
742254205Spfg		if (ssp->slotstatus != FOUND) {
743254205Spfg			int size = ep->e2d_reclen;
744254205Spfg
745254205Spfg			if (ep->e2d_ino != 0)
746254205Spfg				size -= EXT2_DIR_REC_LEN(ep->e2d_namlen);
747254205Spfg			if (size > 0) {
748254205Spfg				if (size >= ssp->slotneeded) {
749254205Spfg					ssp->slotstatus = FOUND;
750254205Spfg					ssp->slotoffset = *offp;
751254205Spfg					ssp->slotsize = ep->e2d_reclen;
752254205Spfg				} else if (ssp->slotstatus == NONE) {
753254205Spfg					ssp->slotfreespace += size;
754254205Spfg					if (ssp->slotoffset == -1)
755254205Spfg						ssp->slotoffset = *offp;
756254205Spfg					if (ssp->slotfreespace >= ssp->slotneeded) {
757254205Spfg						ssp->slotstatus = COMPACT;
758254205Spfg						ssp->slotsize = *offp +
759254205Spfg							ep->e2d_reclen -
760254205Spfg							ssp->slotoffset;
761254205Spfg					}
762254205Spfg				}
763254205Spfg			}
764254205Spfg		}
765254205Spfg
766254205Spfg		/*
767254205Spfg		 * Check for a name match.
768254205Spfg		 */
769254205Spfg		if (ep->e2d_ino) {
770254205Spfg			namlen = ep->e2d_namlen;
771254205Spfg			if (namlen == namelen &&
772254205Spfg			    !bcmp(name, ep->e2d_name, (unsigned)namlen)) {
773254205Spfg				/*
774254205Spfg				 * Save directory entry's inode number and
775254205Spfg				 * reclen in ndp->ni_ufs area, and release
776254205Spfg				 * directory buffer.
777254205Spfg				 */
778254205Spfg				*foundp = 1;
779254205Spfg				return (0);
780254205Spfg			}
781254205Spfg		}
782254205Spfg		*prevoffp = *offp;
783254205Spfg		*offp += ep->e2d_reclen;
784254205Spfg		offset += ep->e2d_reclen;
785254205Spfg		*entryoffsetinblockp = offset;
786254205Spfg		if (ep->e2d_ino)
787254205Spfg			*endusefulp = *offp;
788254205Spfg		/*
789254205Spfg		 * Get pointer to the next entry.
790254205Spfg		 */
791254205Spfg		ep = (struct ext2fs_direct_2 *)((char *)data + offset);
792254205Spfg	}
793254205Spfg
794254205Spfg	return (0);
795254205Spfg}
796254205Spfg
79796749Siedowsevoid
798247209Spfgext2_dirbad(struct inode *ip, doff_t offset, char *how)
79996749Siedowse{
80096749Siedowse	struct mount *mp;
80196749Siedowse
80296749Siedowse	mp = ITOV(ip)->v_mount;
803202283Slulf	if ((mp->mnt_flag & MNT_RDONLY) == 0)
804202283Slulf		panic("ext2_dirbad: %s: bad dir ino %lu at offset %ld: %s\n",
805202283Slulf			mp->mnt_stat.f_mntonname, (u_long)ip->i_number,(long)offset, how);
806202283Slulf	else
80796749Siedowse	(void)printf("%s: bad dir ino %lu at offset %ld: %s\n",
808262724Spfg	    mp->mnt_stat.f_mntonname, (u_long)ip->i_number, (long)offset, how);
809202283Slulf
81096749Siedowse}
81196749Siedowse
81212115Sdyson/*
81312115Sdyson * Do consistency checking on a directory entry:
81412115Sdyson *	record length must be multiple of 4
81512115Sdyson *	entry must fit in rest of its DIRBLKSIZ block
81612115Sdyson *	record must be large enough to contain entry
81712115Sdyson *	name is not longer than MAXNAMLEN
81812115Sdyson *	name must be as long as advertised, and null terminated
81912115Sdyson */
82012115Sdyson/*
82112115Sdyson *	changed so that it confirms to ext2_check_dir_entry
82212115Sdyson */
82312159Sbdestatic int
824247209Spfgext2_dirbadentry(struct vnode *dp, struct ext2fs_direct_2 *de,
825247209Spfg    int entryoffsetinblock)
82612115Sdyson{
827202283Slulf	int	DIRBLKSIZ = VTOI(dp)->i_e2fs->e2fs_bsize;
82812115Sdyson
829111742Sdes	char * error_msg = NULL;
83012115Sdyson
831202283Slulf	if (de->e2d_reclen < EXT2_DIR_REC_LEN(1))
832111742Sdes		error_msg = "rec_len is smaller than minimal";
833202283Slulf	else if (de->e2d_reclen % 4 != 0)
834111742Sdes		error_msg = "rec_len % 4 != 0";
835202283Slulf	else if (de->e2d_reclen < EXT2_DIR_REC_LEN(de->e2d_namlen))
836111742Sdes		error_msg = "reclen is too small for name_len";
837202283Slulf	else if (entryoffsetinblock + de->e2d_reclen > DIRBLKSIZ)
838111742Sdes		error_msg = "directory entry across blocks";
839111742Sdes	/* else LATER
84012115Sdyson	     if (de->inode > dir->i_sb->u.ext2_sb.s_es->s_inodes_count)
841111742Sdes		error_msg = "inode out of bounds";
84212115Sdyson	*/
84312115Sdyson
844111742Sdes	if (error_msg != NULL) {
845111742Sdes		printf("bad directory entry: %s\n", error_msg);
846111742Sdes		printf("offset=%d, inode=%lu, rec_len=%u, name_len=%u\n",
847202283Slulf			entryoffsetinblock, (unsigned long)de->e2d_ino,
848202283Slulf			de->e2d_reclen, de->e2d_namlen);
849111742Sdes	}
850111742Sdes	return error_msg == NULL ? 0 : 1;
85112115Sdyson}
85212115Sdyson
85312115Sdyson/*
85412115Sdyson * Write a directory entry after a call to namei, using the parameters
85512115Sdyson * that it left in nameidata.  The argument ip is the inode which the new
85612115Sdyson * directory entry will refer to.  Dvp is a pointer to the directory to
85712115Sdyson * be written, which was left locked by namei. Remaining parameters
85812115Sdyson * (dp->i_offset, dp->i_count) indicate how the space for the new
85912115Sdyson * entry is to be obtained.
86012115Sdyson */
86112115Sdysonint
862247209Spfgext2_direnter(struct inode *ip, struct vnode *dvp, struct componentname *cnp)
86312115Sdyson{
86496752Siedowse	struct inode *dp;
865202283Slulf	struct ext2fs_direct_2 newdir;
86612115Sdyson	struct iovec aiov;
86712115Sdyson	struct uio auio;
868254205Spfg	int error, newentrysize;
869254205Spfg	int DIRBLKSIZ = ip->i_e2fs->e2fs_bsize;
87012115Sdyson
87112115Sdyson
872252008Spfg#ifdef INVARIANTS
87312115Sdyson	if ((cnp->cn_flags & SAVENAME) == 0)
874246892Spfg		panic("ext2_direnter: missing name");
87512115Sdyson#endif
87612115Sdyson	dp = VTOI(dvp);
877202283Slulf	newdir.e2d_ino = ip->i_number;
878202283Slulf	newdir.e2d_namlen = cnp->cn_namelen;
879193377Sstas	if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs,
880202283Slulf	    EXT2F_INCOMPAT_FTYPE))
881202283Slulf		newdir.e2d_type = DTTOFT(IFTODT(ip->i_mode));
88255477Sbde	else
883202283Slulf		newdir.e2d_type = EXT2_FT_UNKNOWN;
884202283Slulf	bcopy(cnp->cn_nameptr, newdir.e2d_name, (unsigned)cnp->cn_namelen + 1);
885202283Slulf	newentrysize = EXT2_DIR_REC_LEN(newdir.e2d_namlen);
886254205Spfg
887254205Spfg	if (ext2_htree_has_idx(dp)) {
888254205Spfg		error = ext2_htree_add_entry(dvp, &newdir, cnp);
889254205Spfg		if (error) {
890261312Spfg			dp->i_flag &= ~IN_E4INDEX;
891261312Spfg			dp->i_flag |= IN_CHANGE | IN_UPDATE;
892254205Spfg		}
893254205Spfg		return (error);
894254205Spfg	}
895254205Spfg
896254205Spfg	if (EXT2_HAS_COMPAT_FEATURE(ip->i_e2fs, EXT2F_COMPAT_DIRHASHINDEX) &&
897254205Spfg	    !ext2_htree_has_idx(dp)) {
898254205Spfg		if ((dp->i_size / DIRBLKSIZ) == 1 &&
899254205Spfg		    dp->i_offset == DIRBLKSIZ) {
900254205Spfg			/*
901254205Spfg			 * Making indexed directory when one block is not
902254205Spfg			 * enough to save all entries.
903254205Spfg			 */
904254205Spfg			return ext2_htree_create_index(dvp, cnp, &newdir);
905254205Spfg		}
906254205Spfg	}
907254205Spfg
90812115Sdyson	if (dp->i_count == 0) {
90912115Sdyson		/*
91012115Sdyson		 * If dp->i_count is 0, then namei could find no
91112115Sdyson		 * space in the directory. Here, dp->i_offset will
91212115Sdyson		 * be on a directory block boundary and we will write the
91312115Sdyson		 * new entry into a fresh block.
91412115Sdyson		 */
91512115Sdyson		if (dp->i_offset & (DIRBLKSIZ - 1))
91612115Sdyson			panic("ext2_direnter: newblk");
91712115Sdyson		auio.uio_offset = dp->i_offset;
918202283Slulf		newdir.e2d_reclen = DIRBLKSIZ;
91912115Sdyson		auio.uio_resid = newentrysize;
92012115Sdyson		aiov.iov_len = newentrysize;
92112115Sdyson		aiov.iov_base = (caddr_t)&newdir;
92212115Sdyson		auio.uio_iov = &aiov;
92312115Sdyson		auio.uio_iovcnt = 1;
92412115Sdyson		auio.uio_rw = UIO_WRITE;
92512115Sdyson		auio.uio_segflg = UIO_SYSSPACE;
92683366Sjulian		auio.uio_td = (struct thread *)0;
92712115Sdyson		error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
92812115Sdyson		if (DIRBLKSIZ >
92996749Siedowse		    VFSTOEXT2(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
93012115Sdyson			/* XXX should grow with balloc() */
93112115Sdyson			panic("ext2_direnter: frag size");
93212115Sdyson		else if (!error) {
933202283Slulf			dp->i_size = roundup2(dp->i_size, DIRBLKSIZ);
93412115Sdyson			dp->i_flag |= IN_CHANGE;
93512115Sdyson		}
93612115Sdyson		return (error);
93712115Sdyson	}
93812115Sdyson
939254205Spfg	error = ext2_add_entry(dvp, &newdir);
940254205Spfg	if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
941254205Spfg		error = ext2_truncate(dvp, (off_t)dp->i_endoff, IO_SYNC,
942254205Spfg		    cnp->cn_cred, cnp->cn_thread);
943254205Spfg	return (error);
944254205Spfg}
945254205Spfg
946254205Spfg/*
947254205Spfg * Insert an entry into the directory block.
948254205Spfg * Compact the contents.
949254205Spfg */
950254205Spfgint
951254205Spfgext2_add_entry(struct vnode *dvp, struct ext2fs_direct_2 *entry)
952254205Spfg{
953254205Spfg	struct ext2fs_direct_2 *ep, *nep;
954254205Spfg	struct inode *dp;
955254205Spfg	struct buf *bp;
956254205Spfg	u_int dsize;
957254205Spfg	int error, loc, newentrysize, spacefree;
958254205Spfg	char *dirbuf;
959254205Spfg
960254205Spfg	dp = VTOI(dvp);
961254205Spfg
96212115Sdyson	/*
96312115Sdyson	 * If dp->i_count is non-zero, then namei found space
96412115Sdyson	 * for the new entry in the range dp->i_offset to
96512115Sdyson	 * dp->i_offset + dp->i_count in the directory.
96612115Sdyson	 * To use this space, we may have to compact the entries located
96712115Sdyson	 * there, by copying them together towards the beginning of the
96812115Sdyson	 * block, leaving the free space in one usable chunk at the end.
96912115Sdyson	 */
97012115Sdyson
97112115Sdyson	/*
97212115Sdyson	 * Increase size of directory if entry eats into new space.
97312115Sdyson	 * This should never push the size past a new multiple of
97412115Sdyson	 * DIRBLKSIZE.
97512115Sdyson	 *
97612115Sdyson	 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
97712115Sdyson	 */
97812115Sdyson	if (dp->i_offset + dp->i_count > dp->i_size)
97912115Sdyson		dp->i_size = dp->i_offset + dp->i_count;
98012115Sdyson	/*
98112115Sdyson	 * Get the block containing the space for the new directory entry.
98212115Sdyson	 */
98396749Siedowse	if ((error = ext2_blkatoff(dvp, (off_t)dp->i_offset, &dirbuf,
98496749Siedowse	    &bp)) != 0)
98512115Sdyson		return (error);
98612115Sdyson	/*
98712115Sdyson	 * Find space for the new entry. In the simple case, the entry at
98812115Sdyson	 * offset base will have the space. If it does not, then namei
98912115Sdyson	 * arranged that compacting the region dp->i_offset to
99012115Sdyson	 * dp->i_offset + dp->i_count would yield the
99112115Sdyson	 * space.
99212115Sdyson	 */
993254205Spfg	newentrysize = EXT2_DIR_REC_LEN(entry->e2d_namlen);
994202283Slulf	ep = (struct ext2fs_direct_2 *)dirbuf;
995202283Slulf	dsize = EXT2_DIR_REC_LEN(ep->e2d_namlen);
996202283Slulf	spacefree = ep->e2d_reclen - dsize;
997202283Slulf	for (loc = ep->e2d_reclen; loc < dp->i_count; ) {
998202283Slulf		nep = (struct ext2fs_direct_2 *)(dirbuf + loc);
999202283Slulf		if (ep->e2d_ino) {
100012115Sdyson			/* trim the existing slot */
1001202283Slulf			ep->e2d_reclen = dsize;
1002202283Slulf			ep = (struct ext2fs_direct_2 *)((char *)ep + dsize);
100312115Sdyson		} else {
100412115Sdyson			/* overwrite; nothing there; header is ours */
100512115Sdyson			spacefree += dsize;
100612115Sdyson		}
1007202283Slulf		dsize = EXT2_DIR_REC_LEN(nep->e2d_namlen);
1008202283Slulf		spacefree += nep->e2d_reclen - dsize;
1009202283Slulf		loc += nep->e2d_reclen;
101012115Sdyson		bcopy((caddr_t)nep, (caddr_t)ep, dsize);
101112115Sdyson	}
101212115Sdyson	/*
101312115Sdyson	 * Update the pointer fields in the previous entry (if any),
101412115Sdyson	 * copy in the new entry, and write out the block.
101512115Sdyson	 */
1016202283Slulf	if (ep->e2d_ino == 0) {
101712115Sdyson		if (spacefree + dsize < newentrysize)
101812115Sdyson			panic("ext2_direnter: compact1");
1019254205Spfg		entry->e2d_reclen = spacefree + dsize;
102012115Sdyson	} else {
102112115Sdyson		if (spacefree < newentrysize)
102212115Sdyson			panic("ext2_direnter: compact2");
1023254205Spfg		entry->e2d_reclen = spacefree;
1024202283Slulf		ep->e2d_reclen = dsize;
1025202283Slulf		ep = (struct ext2fs_direct_2 *)((char *)ep + dsize);
102612115Sdyson	}
1027254205Spfg	bcopy((caddr_t)entry, (caddr_t)ep, (u_int)newentrysize);
1028221166Sjhb	if (DOINGASYNC(dvp)) {
1029221166Sjhb		bdwrite(bp);
1030221166Sjhb		error = 0;
1031221166Sjhb	} else {
1032221166Sjhb		error = bwrite(bp);
1033221166Sjhb	}
103412115Sdyson	dp->i_flag |= IN_CHANGE | IN_UPDATE;
103512115Sdyson	return (error);
103612115Sdyson}
103712115Sdyson
103812115Sdyson/*
103912115Sdyson * Remove a directory entry after a call to namei, using
104012115Sdyson * the parameters which it left in nameidata. The entry
104112115Sdyson * dp->i_offset contains the offset into the directory of the
104212115Sdyson * entry to be eliminated.  The dp->i_count field contains the
104312115Sdyson * size of the previous record in the directory.  If this
104412115Sdyson * is 0, the first entry is being deleted, so we need only
104512115Sdyson * zero the inode number to mark the entry as free.  If the
104612115Sdyson * entry is not the first in the directory, we must reclaim
104712115Sdyson * the space of the now empty record by adding the record size
104812115Sdyson * to the size of the previous entry.
104912115Sdyson */
105012115Sdysonint
1051247209Spfgext2_dirremove(struct vnode *dvp, struct componentname *cnp)
105212115Sdyson{
105396752Siedowse	struct inode *dp;
1054202283Slulf	struct ext2fs_direct_2 *ep, *rep;
105512115Sdyson	struct buf *bp;
105612115Sdyson	int error;
1057111742Sdes
105812115Sdyson	dp = VTOI(dvp);
105912115Sdyson	if (dp->i_count == 0) {
106012115Sdyson		/*
106112115Sdyson		 * First entry in block: set d_ino to zero.
106212115Sdyson		 */
106343301Sdillon		if ((error =
106496749Siedowse		    ext2_blkatoff(dvp, (off_t)dp->i_offset, (char **)&ep,
106596749Siedowse		    &bp)) != 0)
106612115Sdyson			return (error);
1067202283Slulf		ep->e2d_ino = 0;
1068126853Sphk		error = bwrite(bp);
106912115Sdyson		dp->i_flag |= IN_CHANGE | IN_UPDATE;
107012115Sdyson		return (error);
107112115Sdyson	}
107212115Sdyson	/*
107312115Sdyson	 * Collapse new free space into previous entry.
107412115Sdyson	 */
107596749Siedowse	if ((error = ext2_blkatoff(dvp, (off_t)(dp->i_offset - dp->i_count),
107643301Sdillon	    (char **)&ep, &bp)) != 0)
107712115Sdyson		return (error);
1078202283Slulf
1079202283Slulf	/* Set 'rep' to the entry being removed. */
1080202283Slulf	if (dp->i_count == 0)
1081202283Slulf		rep = ep;
1082202283Slulf	else
1083202283Slulf		rep = (struct ext2fs_direct_2 *)((char *)ep + ep->e2d_reclen);
1084202283Slulf	ep->e2d_reclen += rep->e2d_reclen;
1085221166Sjhb	if (DOINGASYNC(dvp) && dp->i_count != 0)
1086221166Sjhb		bdwrite(bp);
1087221166Sjhb	else
1088221166Sjhb		error = bwrite(bp);
108912115Sdyson	dp->i_flag |= IN_CHANGE | IN_UPDATE;
109012115Sdyson	return (error);
109112115Sdyson}
109212115Sdyson
109312115Sdyson/*
109412115Sdyson * Rewrite an existing directory entry to point at the inode
109512115Sdyson * supplied.  The parameters describing the directory entry are
109612115Sdyson * set up by a call to namei.
109712115Sdyson */
109812115Sdysonint
1099247209Spfgext2_dirrewrite(struct inode *dp, struct inode *ip, struct componentname *cnp)
110012115Sdyson{
110112115Sdyson	struct buf *bp;
1102202283Slulf	struct ext2fs_direct_2 *ep;
110312115Sdyson	struct vnode *vdp = ITOV(dp);
110412115Sdyson	int error;
110512115Sdyson
110696749Siedowse	if ((error = ext2_blkatoff(vdp, (off_t)dp->i_offset, (char **)&ep,
110796749Siedowse	    &bp)) != 0)
110812115Sdyson		return (error);
1109202283Slulf	ep->e2d_ino = ip->i_number;
1110193377Sstas	if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs,
1111202283Slulf	    EXT2F_INCOMPAT_FTYPE))
1112202283Slulf		ep->e2d_type = DTTOFT(IFTODT(ip->i_mode));
111355477Sbde	else
1114202283Slulf		ep->e2d_type = EXT2_FT_UNKNOWN;
1115126853Sphk	error = bwrite(bp);
111612115Sdyson	dp->i_flag |= IN_CHANGE | IN_UPDATE;
111712115Sdyson	return (error);
111812115Sdyson}
111912115Sdyson
112012115Sdyson/*
112112115Sdyson * Check if a directory is empty or not.
112212115Sdyson * Inode supplied must be locked.
112312115Sdyson *
112412115Sdyson * Using a struct dirtemplate here is not precisely
112512115Sdyson * what we want, but better than using a struct direct.
112612115Sdyson *
112712115Sdyson * NB: does not handle corrupted directories.
112812115Sdyson */
112912115Sdysonint
1130247209Spfgext2_dirempty(struct inode *ip, ino_t parentino, struct ucred *cred)
113112115Sdyson{
113296752Siedowse	off_t off;
113312115Sdyson	struct dirtemplate dbuf;
1134202283Slulf	struct ext2fs_direct_2 *dp = (struct ext2fs_direct_2 *)&dbuf;
1135233353Skib	int error, namlen;
1136233353Skib	ssize_t count;
1137229549Spfg#define	MINDIRSIZ (sizeof(struct dirtemplate) / 2)
113812115Sdyson
1139202283Slulf	for (off = 0; off < ip->i_size; off += dp->e2d_reclen) {
1140101744Srwatson		error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1141101744Srwatson		    off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1142101941Srwatson		    NOCRED, &count, (struct thread *)0);
114312115Sdyson		/*
114412115Sdyson		 * Since we read MINDIRSIZ, residual must
114512115Sdyson		 * be 0 unless we're at end of file.
114612115Sdyson		 */
114712115Sdyson		if (error || count != 0)
114812115Sdyson			return (0);
114912115Sdyson		/* avoid infinite loops */
1150202283Slulf		if (dp->e2d_reclen == 0)
115112115Sdyson			return (0);
115212115Sdyson		/* skip empty entries */
1153202283Slulf		if (dp->e2d_ino == 0)
115412115Sdyson			continue;
115512115Sdyson		/* accept only "." and ".." */
1156202283Slulf		namlen = dp->e2d_namlen;
115712115Sdyson		if (namlen > 2)
115812115Sdyson			return (0);
1159202283Slulf		if (dp->e2d_name[0] != '.')
116012115Sdyson			return (0);
116112115Sdyson		/*
116212115Sdyson		 * At this point namlen must be 1 or 2.
116312115Sdyson		 * 1 implies ".", 2 implies ".." if second
116412115Sdyson		 * char is also "."
116512115Sdyson		 */
116612115Sdyson		if (namlen == 1)
116712115Sdyson			continue;
1168202283Slulf		if (dp->e2d_name[1] == '.' && dp->e2d_ino == parentino)
116912115Sdyson			continue;
117012115Sdyson		return (0);
117112115Sdyson	}
117212115Sdyson	return (1);
117312115Sdyson}
117412115Sdyson
117512115Sdyson/*
117612115Sdyson * Check if source directory is in the path of the target directory.
117712115Sdyson * Target is supplied locked, source is unlocked.
117812115Sdyson * The target is always vput before returning.
117912115Sdyson */
118012115Sdysonint
1181247209Spfgext2_checkpath(struct inode *source, struct inode *target, struct ucred *cred)
118212115Sdyson{
118312115Sdyson	struct vnode *vp;
1184247055Spfg	int error, namlen;
118512115Sdyson	struct dirtemplate dirbuf;
118612115Sdyson
118712115Sdyson	vp = ITOV(target);
118812115Sdyson	if (target->i_number == source->i_number) {
118912115Sdyson		error = EEXIST;
119012115Sdyson		goto out;
119112115Sdyson	}
1192247055Spfg	if (target->i_number == EXT2_ROOTINO) {
1193247055Spfg		error = 0;
119412115Sdyson		goto out;
1195247055Spfg	}
119612115Sdyson
119712115Sdyson	for (;;) {
119812115Sdyson		if (vp->v_type != VDIR) {
119912115Sdyson			error = ENOTDIR;
120012115Sdyson			break;
120112115Sdyson		}
120212115Sdyson		error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1203229549Spfg			sizeof(struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1204194296Skib			IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL,
1205194296Skib			NULL);
120612115Sdyson		if (error != 0)
120712115Sdyson			break;
120857710Sbde		namlen = dirbuf.dotdot_type;	/* like ufs little-endian */
120912115Sdyson		if (namlen != 2 ||
121012115Sdyson		    dirbuf.dotdot_name[0] != '.' ||
121112115Sdyson		    dirbuf.dotdot_name[1] != '.') {
121212115Sdyson			error = ENOTDIR;
121312115Sdyson			break;
121412115Sdyson		}
121512115Sdyson		if (dirbuf.dotdot_ino == source->i_number) {
121612115Sdyson			error = EINVAL;
121712115Sdyson			break;
121812115Sdyson		}
1219247055Spfg		if (dirbuf.dotdot_ino == EXT2_ROOTINO)
122012115Sdyson			break;
122112115Sdyson		vput(vp);
122292462Smckusick		if ((error = VFS_VGET(vp->v_mount, dirbuf.dotdot_ino,
122392462Smckusick		    LK_EXCLUSIVE, &vp)) != 0) {
122412115Sdyson			vp = NULL;
122512115Sdyson			break;
122612115Sdyson		}
122712115Sdyson	}
122812115Sdyson
122912115Sdysonout:
123012115Sdyson	if (error == ENOTDIR)
123112115Sdyson		printf("checkpath: .. not a directory\n");
123212115Sdyson	if (vp != NULL)
123312115Sdyson		vput(vp);
123412115Sdyson	return (error);
123512115Sdyson}
1236