xref: /original-bsd/sys/ufs/ffs/ufs_lookup.c (revision 753853ba)
1 /*
2  * Copyright (c) 1989 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  *	@(#)ufs_lookup.c	7.43 (Berkeley) 03/27/92
8  */
9 
10 #include <sys/param.h>
11 #include <sys/namei.h>
12 #include <sys/buf.h>
13 #include <sys/file.h>
14 #include <sys/mount.h>
15 #include <sys/vnode.h>
16 
17 #include <ufs/ufs/quota.h>
18 #include <ufs/ufs/inode.h>
19 #include <ufs/ufs/dir.h>
20 #include <ufs/ufs/ufsmount.h>
21 #include <ufs/ufs/ufs_extern.h>
22 
23 struct	nchstats nchstats;
24 #ifdef DIAGNOSTIC
25 int	dirchk = 1;
26 #else
27 int	dirchk = 0;
28 #endif
29 
30 /*
31  * Convert a component of a pathname into a pointer to a locked inode.
32  * This is a very central and rather complicated routine.
33  * If the file system is not maintained in a strict tree hierarchy,
34  * this can result in a deadlock situation (see comments in code below).
35  *
36  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
37  * on whether the name is to be looked up, created, renamed, or deleted.
38  * When CREATE, RENAME, or DELETE is specified, information usable in
39  * creating, renaming, or deleting a directory entry may be calculated.
40  * If flag has LOCKPARENT or'ed into it and the target of the pathname
41  * exists, lookup returns both the target and its parent directory locked.
42  * When creating or renaming and LOCKPARENT is specified, the target may
43  * not be ".".  When deleting and LOCKPARENT is specified, the target may
44  * be "."., but the caller must check to ensure it does an vrele and iput
45  * instead of two iputs.
46  *
47  * Overall outline of ufs_lookup:
48  *
49  *	check accessibility of directory
50  *	look for name in cache, if found, then if at end of path
51  *	  and deleting or creating, drop it, else return name
52  *	search for name in directory, to found or notfound
53  * notfound:
54  *	if creating, return locked directory, leaving info on available slots
55  *	else return error
56  * found:
57  *	if at end of path and deleting, return information to allow delete
58  *	if at end of path and rewriting (RENAME and LOCKPARENT), lock target
59  *	  inode and return info to allow rewrite
60  *	if not at end, add name to cache; if at end and neither creating
61  *	  nor deleting, add name to cache
62  *
63  * NOTE: (LOOKUP | LOCKPARENT) currently returns the parent inode unlocked.
64  */
65 int
66 ufs_lookup(dvp, vpp, cnp)
67 	struct vnode *dvp;
68 	struct vnode **vpp;
69 	struct componentname *cnp;
70 {
71 	register struct inode *dp;	/* the directory we are searching */
72 	struct buf *bp;			/* a buffer of directory entries */
73 	register struct direct *ep;	/* the current directory entry */
74 	int entryoffsetinblock;		/* offset of ep in bp's buffer */
75 	enum {NONE, COMPACT, FOUND} slotstatus;
76 	doff_t slotoffset;		/* offset of area with free space */
77 	int slotsize;			/* size of area at slotoffset */
78 	int slotfreespace;		/* amount of space free in slot */
79 	int slotneeded;			/* size of the entry we're seeking */
80 	int numdirpasses;		/* strategy for directory search */
81 	doff_t endsearch;		/* offset to end directory search */
82 	doff_t prevoff;			/* prev entry dp->i_offset */
83 	struct inode *pdp;		/* saved dp during symlink work */
84 	struct vnode *tdp;		/* returned by VOP_VGET */
85 	doff_t enduseful;		/* pointer past last used dir slot */
86 	u_long bmask;			/* block offset mask */
87 	int lockparent;			/* 1 => lockparent flag is set */
88 	int wantparent;			/* 1 => wantparent or lockparent flag */
89 	int error;
90 	struct vnode *vdp = dvp;	/* saved for one special case */
91 
92 	bp = NULL;
93 	slotoffset = -1;
94 	*vpp = NULL;
95 	dp = VTOI(dvp);
96 	lockparent = cnp->cn_flags & LOCKPARENT;
97 	wantparent = cnp->cn_flags & (LOCKPARENT|WANTPARENT);
98 
99 	/*
100 	 * Check accessiblity of directory.
101 	 */
102 	if ((dp->i_mode & IFMT) != IFDIR)
103 		return (ENOTDIR);
104 	if (error = ufs_access(dvp, VEXEC, cnp->cn_cred, cnp->cn_proc))
105 		return (error);
106 
107 	/*
108 	 * We now have a segment name to search for, and a directory to search.
109 	 *
110 	 * Before tediously performing a linear scan of the directory,
111 	 * check the name cache to see if the directory/name pair
112 	 * we are looking for is known already.
113 	 */
114 	if (error = cache_lookup(dvp, vpp, cnp)) {
115 		int vpid;	/* capability number of vnode */
116 
117 		if (error == ENOENT)
118 			return (error);
119 #ifdef PARANOID
120 		if (dvp == ndp->ni_rdir && (cnp->cn_flags & ISDOTDOT))
121 			panic("ufs_lookup: .. through root");
122 #endif
123 		/*
124 		 * Get the next vnode in the path.
125 		 * See comment below starting `Step through' for
126 		 * an explaination of the locking protocol.
127 		 */
128 		/*
129 		 * The borrowing of variables
130 		 * here is somewhat confusing.  Usually, dvp/dp
131 		 * is the directory being searched.
132 		 * Here it's the target returned from the cache.
133 		 */
134 		pdp = dp;
135 		dp = VTOI(*vpp);
136 		dvp = *vpp;
137 		vpid = dvp->v_id;
138 		if (pdp == dp) {   /* lookup on "." */
139 			VREF(dvp);
140 			error = 0;
141 		} else if (cnp->cn_flags & ISDOTDOT) {
142 			IUNLOCK(pdp);
143 			error = vget(dvp);
144 			if (!error && lockparent && (cnp->cn_flags & ISLASTCN))
145 				ILOCK(pdp);
146 		} else {
147 			error = vget(dvp);
148 			if (!lockparent || error || !(cnp->cn_flags & ISLASTCN))
149 				IUNLOCK(pdp);
150 		}
151 		/*
152 		 * Check that the capability number did not change
153 		 * while we were waiting for the lock.
154 		 */
155 		if (!error) {
156 			if (vpid == dvp->v_id)
157 				return (0);
158 			ufs_iput(dp);
159 			if (lockparent && pdp != dp &&
160 			    (cnp->cn_flags & ISLASTCN))
161 				IUNLOCK(pdp);
162 		}
163 		ILOCK(pdp);
164 		dp = pdp;
165 		dvp = ITOV(dp);
166 		*vpp = NULL;
167 	}
168 
169 	/*
170 	 * Suppress search for slots unless creating
171 	 * file and at end of pathname, in which case
172 	 * we watch for a place to put the new file in
173 	 * case it doesn't already exist.
174 	 */
175 	slotstatus = FOUND;
176 	slotfreespace = slotsize = slotneeded = 0;
177 	if ((cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) &&
178 	    (cnp->cn_flags & ISLASTCN)) {
179 		slotstatus = NONE;
180 		slotneeded = (sizeof(struct direct) - MAXNAMLEN +
181 			cnp->cn_namelen + 3) &~ 3;
182 	}
183 
184 	/*
185 	 * If there is cached information on a previous search of
186 	 * this directory, pick up where we last left off.
187 	 * We cache only lookups as these are the most common
188 	 * and have the greatest payoff. Caching CREATE has little
189 	 * benefit as it usually must search the entire directory
190 	 * to determine that the entry does not exist. Caching the
191 	 * location of the last DELETE or RENAME has not reduced
192 	 * profiling time and hence has been removed in the interest
193 	 * of simplicity.
194 	 */
195 	bmask = VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
196 	if (cnp->cn_nameiop != LOOKUP || dp->i_diroff == 0 ||
197 	    dp->i_diroff > dp->i_size) {
198 		entryoffsetinblock = 0;
199 		dp->i_offset = 0;
200 		numdirpasses = 1;
201 	} else {
202 		dp->i_offset = dp->i_diroff;
203 		if ((entryoffsetinblock = dp->i_offset & bmask) &&
204 		    (error = VOP_BLKATOFF(dvp, (off_t)dp->i_offset, NULL, &bp)))
205 			return (error);
206 		numdirpasses = 2;
207 		nchstats.ncs_2passes++;
208 	}
209 	prevoff = dp->i_offset;
210 	endsearch = roundup(dp->i_size, DIRBLKSIZ);
211 	enduseful = 0;
212 
213 searchloop:
214 	while (dp->i_offset < endsearch) {
215 		/*
216 		 * If offset is on a block boundary, read the next directory
217 		 * block.  Release previous if it exists.
218 		 */
219 		if ((dp->i_offset & bmask) == 0) {
220 			if (bp != NULL)
221 				brelse(bp);
222 			if (error =
223 			    VOP_BLKATOFF(dvp, (off_t)dp->i_offset, NULL, &bp))
224 				return (error);
225 			entryoffsetinblock = 0;
226 		}
227 		/*
228 		 * If still looking for a slot, and at a DIRBLKSIZE
229 		 * boundary, have to start looking for free space again.
230 		 */
231 		if (slotstatus == NONE &&
232 		    (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
233 			slotoffset = -1;
234 			slotfreespace = 0;
235 		}
236 		/*
237 		 * Get pointer to next entry.
238 		 * Full validation checks are slow, so we only check
239 		 * enough to insure forward progress through the
240 		 * directory. Complete checks can be run by patching
241 		 * "dirchk" to be true.
242 		 */
243 		ep = (struct direct *)(bp->b_un.b_addr + entryoffsetinblock);
244 		if (ep->d_reclen == 0 ||
245 		    dirchk && ufs_dirbadentry(ep, entryoffsetinblock)) {
246 			int i;
247 
248 			ufs_dirbad(dp, dp->i_offset, "mangled entry");
249 			i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
250 			dp->i_offset += i;
251 			entryoffsetinblock += i;
252 			continue;
253 		}
254 
255 		/*
256 		 * If an appropriate sized slot has not yet been found,
257 		 * check to see if one is available. Also accumulate space
258 		 * in the current block so that we can determine if
259 		 * compaction is viable.
260 		 */
261 		if (slotstatus != FOUND) {
262 			int size = ep->d_reclen;
263 
264 			if (ep->d_ino != 0)
265 				size -= DIRSIZ(ep);
266 			if (size > 0) {
267 				if (size >= slotneeded) {
268 					slotstatus = FOUND;
269 					slotoffset = dp->i_offset;
270 					slotsize = ep->d_reclen;
271 				} else if (slotstatus == NONE) {
272 					slotfreespace += size;
273 					if (slotoffset == -1)
274 						slotoffset = dp->i_offset;
275 					if (slotfreespace >= slotneeded) {
276 						slotstatus = COMPACT;
277 						slotsize = dp->i_offset +
278 						      ep->d_reclen - slotoffset;
279 					}
280 				}
281 			}
282 		}
283 
284 		/*
285 		 * Check for a name match.
286 		 */
287 		if (ep->d_ino) {
288 			if (ep->d_namlen == cnp->cn_namelen &&
289 			    !bcmp(cnp->cn_nameptr, ep->d_name,
290 				(unsigned)ep->d_namlen)) {
291 				/*
292 				 * Save directory entry's inode number and
293 				 * reclen in ndp->ni_ufs area, and release
294 				 * directory buffer.
295 				 */
296 				dp->i_ino = ep->d_ino;
297 				dp->i_reclen = ep->d_reclen;
298 				brelse(bp);
299 				goto found;
300 			}
301 		}
302 		prevoff = dp->i_offset;
303 		dp->i_offset += ep->d_reclen;
304 		entryoffsetinblock += ep->d_reclen;
305 		if (ep->d_ino)
306 			enduseful = dp->i_offset;
307 	}
308 /* notfound: */
309 	/*
310 	 * If we started in the middle of the directory and failed
311 	 * to find our target, we must check the beginning as well.
312 	 */
313 	if (numdirpasses == 2) {
314 		numdirpasses--;
315 		dp->i_offset = 0;
316 		endsearch = dp->i_diroff;
317 		goto searchloop;
318 	}
319 	if (bp != NULL)
320 		brelse(bp);
321 	/*
322 	 * If creating, and at end of pathname and current
323 	 * directory has not been removed, then can consider
324 	 * allowing file to be created.
325 	 */
326 	if ((cnp->cn_nameiop == CREATE || cnp->cn_nameiop == RENAME) &&
327 	    (cnp->cn_flags & ISLASTCN) && dp->i_nlink != 0) {
328 		/*
329 		 * Access for write is interpreted as allowing
330 		 * creation of files in the directory.
331 		 */
332 		if (error = ufs_access(dvp, VWRITE, cnp->cn_cred, cnp->cn_proc))
333 			return (error);
334 		/*
335 		 * Return an indication of where the new directory
336 		 * entry should be put.  If we didn't find a slot,
337 		 * then set dp->i_count to 0 indicating
338 		 * that the new slot belongs at the end of the
339 		 * directory. If we found a slot, then the new entry
340 		 * can be put in the range from dp->i_offset to
341 		 * dp->i_offset + dp->i_count.
342 		 */
343 		if (slotstatus == NONE) {
344 			dp->i_offset = roundup(dp->i_size, DIRBLKSIZ);
345 			dp->i_count = 0;
346 			enduseful = dp->i_offset;
347 		} else {
348 			dp->i_offset = slotoffset;
349 			dp->i_count = slotsize;
350 			if (enduseful < slotoffset + slotsize)
351 				enduseful = slotoffset + slotsize;
352 		}
353 		dp->i_endoff = roundup(enduseful, DIRBLKSIZ);
354 		dp->i_flag |= IUPD|ICHG;
355 		/*
356 		 * We return with the directory locked, so that
357 		 * the parameters we set up above will still be
358 		 * valid if we actually decide to do a direnter().
359 		 * We return ni_vp == NULL to indicate that the entry
360 		 * does not currently exist; we leave a pointer to
361 		 * the (locked) directory inode in ndp->ni_dvp.
362 		 * The pathname buffer is saved so that the name
363 		 * can be obtained later.
364 		 *
365 		 * NB - if the directory is unlocked, then this
366 		 * information cannot be used.
367 		 */
368 		cnp->cn_flags |= SAVENAME;
369 		if (!lockparent)
370 			IUNLOCK(dp);
371 		return (EJUSTRETURN);
372 	}
373 	/*
374 	 * Insert name into cache (as non-existent) if appropriate.
375 	 */
376 	if ((cnp->cn_flags & MAKEENTRY) && cnp->cn_nameiop != CREATE)
377 		cache_enter(dvp, *vpp, cnp);
378 	return (ENOENT);
379 
380 found:
381 	if (numdirpasses == 2)
382 		nchstats.ncs_pass2++;
383 	/*
384 	 * Check that directory length properly reflects presence
385 	 * of this entry.
386 	 */
387 	if (entryoffsetinblock + DIRSIZ(ep) > dp->i_size) {
388 		ufs_dirbad(dp, dp->i_offset, "i_size too small");
389 		dp->i_size = entryoffsetinblock + DIRSIZ(ep);
390 		dp->i_flag |= IUPD|ICHG;
391 	}
392 
393 	/*
394 	 * Found component in pathname.
395 	 * If the final component of path name, save information
396 	 * in the cache as to where the entry was found.
397 	 */
398 	if ((cnp->cn_flags & ISLASTCN) && cnp->cn_nameiop == LOOKUP)
399 		dp->i_diroff = dp->i_offset &~ (DIRBLKSIZ - 1);
400 
401 	/*
402 	 * If deleting, and at end of pathname, return
403 	 * parameters which can be used to remove file.
404 	 * If the wantparent flag isn't set, we return only
405 	 * the directory (in ndp->ni_dvp), otherwise we go
406 	 * on and lock the inode, being careful with ".".
407 	 */
408 	if (cnp->cn_nameiop == DELETE && (cnp->cn_flags & ISLASTCN)) {
409 		/*
410 		 * Write access to directory required to delete files.
411 		 */
412 		if (error = ufs_access(dvp, VWRITE, cnp->cn_cred, cnp->cn_proc))
413 			return (error);
414 		/*
415 		 * Return pointer to current entry in dp->i_offset,
416 		 * and distance past previous entry (if there
417 		 * is a previous entry in this block) in dp->i_count.
418 		 * Save directory inode pointer in ndp->ni_dvp for dirremove().
419 		 */
420 		if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
421 			dp->i_count = 0;
422 		else
423 			dp->i_count = dp->i_offset - prevoff;
424 		if (dp->i_number == dp->i_ino) {
425 			VREF(vdp);
426 			*vpp = vdp;
427 			return (0);
428 		}
429 		if (error = VOP_VGET(dvp, dp->i_ino, &tdp))
430 			return (error);
431 		/*
432 		 * If directory is "sticky", then user must own
433 		 * the directory, or the file in it, else she
434 		 * may not delete it (unless she's root). This
435 		 * implements append-only directories.
436 		 */
437 		if ((dp->i_mode & ISVTX) &&
438 		    cnp->cn_cred->cr_uid != 0 &&
439 		    cnp->cn_cred->cr_uid != dp->i_uid &&
440 		    VTOI(tdp)->i_uid != cnp->cn_cred->cr_uid) {
441 			vput(tdp);
442 			return (EPERM);
443 		}
444 		*vpp = tdp;
445 		if (!lockparent)
446 			IUNLOCK(dp);
447 		return (0);
448 	}
449 
450 	/*
451 	 * If rewriting (RENAME), return the inode and the
452 	 * information required to rewrite the present directory
453 	 * Must get inode of directory entry to verify it's a
454 	 * regular file, or empty directory.
455 	 */
456 	if (cnp->cn_nameiop == RENAME && wantparent &&
457 	    (cnp->cn_flags & ISLASTCN)) {
458 		if (error = ufs_access(dvp, VWRITE, cnp->cn_cred, cnp->cn_proc))
459 			return (error);
460 		/*
461 		 * Careful about locking second inode.
462 		 * This can only occur if the target is ".".
463 		 */
464 		if (dp->i_number == dp->i_ino)
465 			return (EISDIR);
466 		if (error = VOP_VGET(dvp, dp->i_ino, &tdp))
467 			return (error);
468 		*vpp = tdp;
469 		cnp->cn_flags |= SAVENAME;
470 		if (!lockparent)
471 			IUNLOCK(dp);
472 		return (0);
473 	}
474 
475 	/*
476 	 * Step through the translation in the name.  We do not `iput' the
477 	 * directory because we may need it again if a symbolic link
478 	 * is relative to the current directory.  Instead we save it
479 	 * unlocked as "pdp".  We must get the target inode before unlocking
480 	 * the directory to insure that the inode will not be removed
481 	 * before we get it.  We prevent deadlock by always fetching
482 	 * inodes from the root, moving down the directory tree. Thus
483 	 * when following backward pointers ".." we must unlock the
484 	 * parent directory before getting the requested directory.
485 	 * There is a potential race condition here if both the current
486 	 * and parent directories are removed before the `iget' for the
487 	 * inode associated with ".." returns.  We hope that this occurs
488 	 * infrequently since we cannot avoid this race condition without
489 	 * implementing a sophisticated deadlock detection algorithm.
490 	 * Note also that this simple deadlock detection scheme will not
491 	 * work if the file system has any hard links other than ".."
492 	 * that point backwards in the directory structure.
493 	 */
494 	pdp = dp;
495 	if (cnp->cn_flags & ISDOTDOT) {
496 		IUNLOCK(pdp);	/* race to get the inode */
497 		if (error = VOP_VGET(dvp, dp->i_ino, &tdp)) {
498 			ILOCK(pdp);
499 			return (error);
500 		}
501 		if (lockparent && (cnp->cn_flags & ISLASTCN))
502 			ILOCK(pdp);
503 		*vpp = tdp;
504 	} else if (dp->i_number == dp->i_ino) {
505 		VREF(dvp);	/* we want ourself, ie "." */
506 		*vpp = dvp;
507 	} else {
508 		if (error = VOP_VGET(dvp, dp->i_ino, &tdp))
509 			return (error);
510 		if (!lockparent || !(cnp->cn_flags & ISLASTCN))
511 			IUNLOCK(pdp);
512 		*vpp = tdp;
513 	}
514 
515 	/*
516 	 * Insert name into cache if appropriate.
517 	 */
518 	if (cnp->cn_flags & MAKEENTRY)
519 		cache_enter(dvp, *vpp, cnp);
520 	return (0);
521 }
522 
523 void
524 ufs_dirbad(ip, offset, how)
525 	struct inode *ip;
526 	doff_t offset;
527 	char *how;
528 {
529 	struct mount *mp;
530 
531 	mp = ITOV(ip)->v_mount;
532 	(void)printf("%s: bad dir ino %d at offset %d: %s\n",
533 	    mp->mnt_stat.f_mntonname, ip->i_number, offset, how);
534 	if ((mp->mnt_stat.f_flags & MNT_RDONLY) == 0)
535 		panic("bad dir");
536 }
537 
538 /*
539  * Do consistency checking on a directory entry:
540  *	record length must be multiple of 4
541  *	entry must fit in rest of its DIRBLKSIZ block
542  *	record must be large enough to contain entry
543  *	name is not longer than MAXNAMLEN
544  *	name must be as long as advertised, and null terminated
545  */
546 int
547 ufs_dirbadentry(ep, entryoffsetinblock)
548 	register struct direct *ep;
549 	int entryoffsetinblock;
550 {
551 	register int i;
552 
553 	if ((ep->d_reclen & 0x3) != 0 ||
554 	    ep->d_reclen > DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
555 	    ep->d_reclen < DIRSIZ(ep) || ep->d_namlen > MAXNAMLEN) {
556 		/*return (1); */
557 		printf("First bad\n");
558 		goto bad;
559 	}
560 	for (i = 0; i < ep->d_namlen; i++)
561 		if (ep->d_name[i] == '\0') {
562 			/*return (1); */
563 			printf("Second bad\n");
564 			goto bad;
565 	}
566 	if (ep->d_name[i])
567 		goto bad;
568 	return (ep->d_name[i]);
569 bad:
570 	return(1);
571 }
572 
573 /*
574  * Write a directory entry after a call to namei, using the parameters
575  * that it left in nameidata.  The argument ip is the inode which the new
576  * directory entry will refer to.  Dvp is a pointer to the directory to
577  * be written, which was left locked by namei. Remaining parameters
578  * (dp->i_offset, dp->i_count) indicate how the space for the new
579  * entry is to be obtained.
580  */
581 int
582 ufs_direnter(ip, dvp, cnp)
583 	struct inode *ip;
584 	struct vnode *dvp;
585 	register struct componentname *cnp;
586 {
587 	register struct direct *ep, *nep;
588 	register struct inode *dp;
589 	struct buf *bp;
590 	struct direct newdir;
591 	struct iovec aiov;
592 	struct uio auio;
593 	u_int dsize;
594 	int error, loc, newentrysize, spacefree;
595 	char *dirbuf;
596 
597 #ifdef DIAGNOSTIC
598 	if ((cnp->cn_flags & SAVENAME) == 0)
599 		panic("direnter: missing name");
600 #endif
601 	dp = VTOI(dvp);
602 	newdir.d_ino = ip->i_number;
603 	newdir.d_namlen = cnp->cn_namelen;
604 	bcopy(cnp->cn_nameptr, newdir.d_name, (unsigned)cnp->cn_namelen + 1);
605 	newentrysize = DIRSIZ(&newdir);
606 	if (dp->i_count == 0) {
607 		/*
608 		 * If dp->i_count is 0, then namei could find no
609 		 * space in the directory. Here, dp->i_offset will
610 		 * be on a directory block boundary and we will write the
611 		 * new entry into a fresh block.
612 		 */
613 		if (dp->i_offset & (DIRBLKSIZ - 1))
614 			panic("wdir: newblk");
615 		auio.uio_offset = dp->i_offset;
616 		newdir.d_reclen = DIRBLKSIZ;
617 		auio.uio_resid = newentrysize;
618 		aiov.iov_len = newentrysize;
619 		aiov.iov_base = (caddr_t)&newdir;
620 		auio.uio_iov = &aiov;
621 		auio.uio_iovcnt = 1;
622 		auio.uio_rw = UIO_WRITE;
623 		auio.uio_segflg = UIO_SYSSPACE;
624 		auio.uio_procp = (struct proc *)0;
625 		error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
626 		if (DIRBLKSIZ >
627 		    VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
628 			/* XXX should grow with balloc() */
629 			panic("ufs_direnter: frag size");
630 		else if (!error) {
631 			dp->i_size = roundup(dp->i_size, DIRBLKSIZ);
632 			dp->i_flag |= ICHG;
633 		}
634 		return (error);
635 	}
636 
637 	/*
638 	 * If dp->i_count is non-zero, then namei found space
639 	 * for the new entry in the range dp->i_offset to
640 	 * dp->i_offset + dp->i_count in the directory.
641 	 * To use this space, we may have to compact the entries located
642 	 * there, by copying them together towards the beginning of the
643 	 * block, leaving the free space in one usable chunk at the end.
644 	 */
645 
646 	/*
647 	 * Increase size of directory if entry eats into new space.
648 	 * This should never push the size past a new multiple of
649 	 * DIRBLKSIZE.
650 	 *
651 	 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
652 	 */
653 	if (dp->i_offset + dp->i_count > dp->i_size)
654 		dp->i_size = dp->i_offset + dp->i_count;
655 	/*
656 	 * Get the block containing the space for the new directory entry.
657 	 */
658 	if (error = VOP_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp))
659 		return (error);
660 	/*
661 	 * Find space for the new entry. In the simple case, the entry at
662 	 * offset base will have the space. If it does not, then namei
663 	 * arranged that compacting the region dp->i_offset to
664 	 * dp->i_offset + dp->i_count would yield the
665 	 * space.
666 	 */
667 	ep = (struct direct *)dirbuf;
668 	dsize = DIRSIZ(ep);
669 	spacefree = ep->d_reclen - dsize;
670 	for (loc = ep->d_reclen; loc < dp->i_count; ) {
671 		nep = (struct direct *)(dirbuf + loc);
672 		if (ep->d_ino) {
673 			/* trim the existing slot */
674 			ep->d_reclen = dsize;
675 			ep = (struct direct *)((char *)ep + dsize);
676 		} else {
677 			/* overwrite; nothing there; header is ours */
678 			spacefree += dsize;
679 		}
680 		dsize = DIRSIZ(nep);
681 		spacefree += nep->d_reclen - dsize;
682 		loc += nep->d_reclen;
683 		bcopy((caddr_t)nep, (caddr_t)ep, dsize);
684 	}
685 	/*
686 	 * Update the pointer fields in the previous entry (if any),
687 	 * copy in the new entry, and write out the block.
688 	 */
689 	if (ep->d_ino == 0) {
690 		if (spacefree + dsize < newentrysize)
691 			panic("wdir: compact1");
692 		newdir.d_reclen = spacefree + dsize;
693 	} else {
694 		if (spacefree < newentrysize)
695 			panic("wdir: compact2");
696 		newdir.d_reclen = spacefree;
697 		ep->d_reclen = dsize;
698 		ep = (struct direct *)((char *)ep + dsize);
699 	}
700 	bcopy((caddr_t)&newdir, (caddr_t)ep, (u_int)newentrysize);
701 	error = VOP_BWRITE(bp);
702 	dp->i_flag |= IUPD|ICHG;
703 	if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
704 		error = VOP_TRUNCATE(dvp, (off_t)dp->i_endoff, IO_SYNC);
705 	return (error);
706 }
707 
708 /*
709  * Remove a directory entry after a call to namei, using
710  * the parameters which it left in nameidata. The entry
711  * dp->i_offset contains the offset into the directory of the
712  * entry to be eliminated.  The dp->i_count field contains the
713  * size of the previous record in the directory.  If this
714  * is 0, the first entry is being deleted, so we need only
715  * zero the inode number to mark the entry as free.  If the
716  * entry is not the first in the directory, we must reclaim
717  * the space of the now empty record by adding the record size
718  * to the size of the previous entry.
719  */
720 int
721 ufs_dirremove(dvp, cnp)
722 	struct vnode *dvp;
723 	struct componentname *cnp;
724 {
725 	register struct inode *dp;
726 	struct direct *ep;
727 	struct buf *bp;
728 	int error;
729 
730 	dp = VTOI(dvp);
731 	if (dp->i_count == 0) {
732 		/*
733 		 * First entry in block: set d_ino to zero.
734 		 */
735 		if (error =
736 		    VOP_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp))
737 			return (error);
738 		ep->d_ino = 0;
739 		error = VOP_BWRITE(bp);
740 		dp->i_flag |= IUPD|ICHG;
741 		return (error);
742 	}
743 	/*
744 	 * Collapse new free space into previous entry.
745 	 */
746 	if (error = VOP_BLKATOFF(dvp, (off_t)(dp->i_offset - dp->i_count),
747 	    (char **)&ep, &bp))
748 		return (error);
749 	ep->d_reclen += dp->i_reclen;
750 	error = VOP_BWRITE(bp);
751 	dp->i_flag |= IUPD|ICHG;
752 	return (error);
753 }
754 
755 /*
756  * Rewrite an existing directory entry to point at the inode
757  * supplied.  The parameters describing the directory entry are
758  * set up by a call to namei.
759  */
760 int
761 ufs_dirrewrite(dp, ip, cnp)
762 	struct inode *dp, *ip;
763 	struct componentname *cnp;
764 {
765 	struct buf *bp;
766 	struct direct *ep;
767 	int error;
768 
769 	if (error =
770 	    VOP_BLKATOFF(ITOV(dp), (off_t)dp->i_offset, (char **)&ep, &bp))
771 		return (error);
772 	ep->d_ino = ip->i_number;
773 	error = VOP_BWRITE(bp);
774 	dp->i_flag |= IUPD|ICHG;
775 	return (error);
776 }
777 
778 /*
779  * Check if a directory is empty or not.
780  * Inode supplied must be locked.
781  *
782  * Using a struct dirtemplate here is not precisely
783  * what we want, but better than using a struct direct.
784  *
785  * NB: does not handle corrupted directories.
786  */
787 int
788 ufs_dirempty(ip, parentino, cred)
789 	register struct inode *ip;
790 	ino_t parentino;
791 	struct ucred *cred;
792 {
793 	register off_t off;
794 	struct dirtemplate dbuf;
795 	register struct direct *dp = (struct direct *)&dbuf;
796 	int error, count;
797 #define	MINDIRSIZ (sizeof (struct dirtemplate) / 2)
798 
799 	for (off = 0; off < ip->i_size; off += dp->d_reclen) {
800 		error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ, off,
801 		   UIO_SYSSPACE, IO_NODELOCKED, cred, &count, (struct proc *)0);
802 		/*
803 		 * Since we read MINDIRSIZ, residual must
804 		 * be 0 unless we're at end of file.
805 		 */
806 		if (error || count != 0)
807 			return (0);
808 		/* avoid infinite loops */
809 		if (dp->d_reclen == 0)
810 			return (0);
811 		/* skip empty entries */
812 		if (dp->d_ino == 0)
813 			continue;
814 		/* accept only "." and ".." */
815 		if (dp->d_namlen > 2)
816 			return (0);
817 		if (dp->d_name[0] != '.')
818 			return (0);
819 		/*
820 		 * At this point d_namlen must be 1 or 2.
821 		 * 1 implies ".", 2 implies ".." if second
822 		 * char is also "."
823 		 */
824 		if (dp->d_namlen == 1)
825 			continue;
826 		if (dp->d_name[1] == '.' && dp->d_ino == parentino)
827 			continue;
828 		return (0);
829 	}
830 	return (1);
831 }
832 
833 /*
834  * Check if source directory is in the path of the target directory.
835  * Target is supplied locked, source is unlocked.
836  * The target is always iput before returning.
837  */
838 int
839 ufs_checkpath(source, target, cred)
840 	struct inode *source, *target;
841 	struct ucred *cred;
842 {
843 	struct dirtemplate dirbuf;
844 	register struct inode *ip;
845 	struct vnode *vp;
846 	int error, rootino;
847 
848 	ip = target;
849 	if (ip->i_number == source->i_number) {
850 		error = EEXIST;
851 		goto out;
852 	}
853 	rootino = ROOTINO;
854 	error = 0;
855 	if (ip->i_number == rootino)
856 		goto out;
857 
858 	for (;;) {
859 		if ((ip->i_mode & IFMT) != IFDIR) {
860 			error = ENOTDIR;
861 			break;
862 		}
863 		vp = ITOV(ip);
864 		error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
865 			sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
866 			IO_NODELOCKED, cred, (int *)0, (struct proc *)0);
867 		if (error != 0)
868 			break;
869 		if (dirbuf.dotdot_namlen != 2 ||
870 		    dirbuf.dotdot_name[0] != '.' ||
871 		    dirbuf.dotdot_name[1] != '.') {
872 			error = ENOTDIR;
873 			break;
874 		}
875 		if (dirbuf.dotdot_ino == source->i_number) {
876 			error = EINVAL;
877 			break;
878 		}
879 		if (dirbuf.dotdot_ino == rootino)
880 			break;
881 		ufs_iput(ip);
882 		if (error = VOP_VGET(vp, dirbuf.dotdot_ino, &vp))
883 			break;
884 		ip = VTOI(vp);
885 	}
886 
887 out:
888 	if (error == ENOTDIR)
889 		printf("checkpath: .. not a directory\n");
890 	if (ip != NULL)
891 		ufs_iput(ip);
892 	return (error);
893 }
894