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