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