2 * Copyright (c) 1989, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)ufs_lookup.c 8.15 (Berkeley) 6/16/95
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
41 #include "opt_quota.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/namei.h>
51 #include <sys/mount.h>
52 #include <sys/vnode.h>
53 #include <sys/sysctl.h>
56 #include <vm/vm_extern.h>
58 #include <ufs/ufs/extattr.h>
59 #include <ufs/ufs/quota.h>
60 #include <ufs/ufs/inode.h>
61 #include <ufs/ufs/dir.h>
63 #include <ufs/ufs/dirhash.h>
65 #include <ufs/ufs/ufsmount.h>
66 #include <ufs/ufs/ufs_extern.h>
69 static int dirchk = 1;
71 static int dirchk = 0;
74 SYSCTL_INT(_debug, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
76 /* true if old FS format...*/
77 #define OFSFMT(vp) ((vp)->v_mount->mnt_maxsymlinklen <= 0)
80 ufs_delete_denied(struct vnode *vdp, struct vnode *tdp, struct ucred *cred,
87 * NFSv4 Minor Version 1, draft-ietf-nfsv4-minorversion1-03.txt
89 * 3.16.2.1. ACE4_DELETE vs. ACE4_DELETE_CHILD
93 * XXX: Is this check required?
95 error = VOP_ACCESS(vdp, VEXEC, cred, td);
99 error = VOP_ACCESSX(tdp, VDELETE, cred, td);
103 error = VOP_ACCESSX(vdp, VDELETE_CHILD, cred, td);
107 error = VOP_ACCESSX(vdp, VEXPLICIT_DENY | VDELETE_CHILD, cred, td);
111 #endif /* !UFS_ACL */
114 * Standard Unix access control - delete access requires VWRITE.
116 error = VOP_ACCESS(vdp, VWRITE, cred, td);
121 * If directory is "sticky", then user must own
122 * the directory, or the file in it, else she
123 * may not delete it (unless she's root). This
124 * implements append-only directories.
126 if ((VTOI(vdp)->i_mode & ISVTX) &&
127 VOP_ACCESS(vdp, VADMIN, cred, td) &&
128 VOP_ACCESS(tdp, VADMIN, cred, td))
135 * Convert a component of a pathname into a pointer to a locked inode.
136 * This is a very central and rather complicated routine.
137 * If the filesystem is not maintained in a strict tree hierarchy,
138 * this can result in a deadlock situation (see comments in code below).
140 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
141 * on whether the name is to be looked up, created, renamed, or deleted.
142 * When CREATE, RENAME, or DELETE is specified, information usable in
143 * creating, renaming, or deleting a directory entry may be calculated.
144 * If flag has LOCKPARENT or'ed into it and the target of the pathname
145 * exists, lookup returns both the target and its parent directory locked.
146 * When creating or renaming and LOCKPARENT is specified, the target may
147 * not be ".". When deleting and LOCKPARENT is specified, the target may
148 * be "."., but the caller must check to ensure it does an vrele and vput
149 * instead of two vputs.
151 * This routine is actually used as VOP_CACHEDLOOKUP method, and the
152 * filesystem employs the generic vfs_cache_lookup() as VOP_LOOKUP
155 * vfs_cache_lookup() performs the following for us:
156 * check that it is a directory
157 * check accessibility of directory
158 * check for modification attempts on read-only mounts
159 * if name found in cache
160 * if at end of path and deleting or creating
164 * return VOP_CACHEDLOOKUP()
166 * Overall outline of ufs_lookup:
168 * search for name in directory, to found or notfound
170 * if creating, return locked directory, leaving info on available slots
173 * if at end of path and deleting, return information to allow delete
174 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
175 * inode and return info to allow rewrite
176 * if not at end, add name to cache; if at end and neither creating
177 * nor deleting, add name to cache
181 struct vop_cachedlookup_args /* {
183 struct vnode **a_vpp;
184 struct componentname *a_cnp;
188 return (ufs_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
192 ufs_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
195 struct inode *dp; /* inode for directory being searched */
196 struct buf *bp; /* a buffer of directory entries */
197 struct direct *ep; /* the current directory entry */
198 int entryoffsetinblock; /* offset of ep in bp's buffer */
199 enum {NONE, COMPACT, FOUND} slotstatus;
200 doff_t slotoffset; /* offset of area with free space */
201 doff_t i_diroff; /* cached i_diroff value. */
202 doff_t i_offset; /* cached i_offset value. */
203 int slotsize; /* size of area at slotoffset */
204 int slotfreespace; /* amount of space free in slot */
205 int slotneeded; /* size of the entry we're seeking */
206 int numdirpasses; /* strategy for directory search */
207 doff_t endsearch; /* offset to end directory search */
208 doff_t prevoff; /* prev entry dp->i_offset */
209 struct vnode *pdp; /* saved dp during symlink work */
210 struct vnode *tdp; /* returned by VFS_VGET */
211 doff_t enduseful; /* pointer past last used dir slot */
212 u_long bmask; /* block offset mask */
214 struct ucred *cred = cnp->cn_cred;
215 int flags = cnp->cn_flags;
216 int nameiop = cnp->cn_nameiop;
224 if (dp->i_effnlink == 0)
228 * Create a vm object if vmiodirenable is enabled.
229 * Alternatively we could call vnode_create_vobject
230 * in VFS_VGET but we could end up creating objects
231 * that are never used.
233 vnode_create_vobject(vdp, DIP(dp, i_size), cnp->cn_thread);
235 bmask = VFSTOUFS(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
237 #ifdef DEBUG_VFS_LOCKS
239 * Assert that the directory vnode is locked, and locked
240 * exclusively for the last component lookup for modifying
243 * The directory-modifying operations need to save
244 * intermediate state in the inode between namei() call and
245 * actual directory manipulations. See fields in the struct
246 * inode marked as 'used during directory lookup'. We must
247 * ensure that upgrade in namei() does not happen, since
248 * upgrade might need to unlock vdp. If quotas are enabled,
249 * getinoquota() also requires exclusive lock to modify inode.
251 ASSERT_VOP_LOCKED(vdp, "ufs_lookup1");
252 if ((nameiop == CREATE || nameiop == DELETE || nameiop == RENAME) &&
253 (flags & (LOCKPARENT | ISLASTCN)) == (LOCKPARENT | ISLASTCN))
254 ASSERT_VOP_ELOCKED(vdp, "ufs_lookup2");
262 * We now have a segment name to search for, and a directory to search.
264 * Suppress search for slots unless creating
265 * file and at end of pathname, in which case
266 * we watch for a place to put the new file in
267 * case it doesn't already exist.
270 i_diroff = dp->i_diroff;
272 slotfreespace = slotsize = slotneeded = 0;
273 if ((nameiop == CREATE || nameiop == RENAME) &&
274 (flags & ISLASTCN)) {
276 slotneeded = DIRECTSIZ(cnp->cn_namelen);
281 * Use dirhash for fast operations on large directories. The logic
282 * to determine whether to hash the directory is contained within
283 * ufsdirhash_build(); a zero return means that it decided to hash
284 * this directory and it successfully built up the hash table.
286 if (ufsdirhash_build(dp) == 0) {
287 /* Look for a free slot if needed. */
288 enduseful = dp->i_size;
289 if (slotstatus != FOUND) {
290 slotoffset = ufsdirhash_findfree(dp, slotneeded,
292 if (slotoffset >= 0) {
293 slotstatus = COMPACT;
294 enduseful = ufsdirhash_enduseful(dp);
296 enduseful = dp->i_size;
299 /* Look up the component. */
301 entryoffsetinblock = 0; /* silence compiler warning */
302 switch (ufsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
303 &i_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
305 ep = (struct direct *)((char *)bp->b_data +
309 i_offset = roundup2(dp->i_size, DIRBLKSIZ);
312 /* Something failed; just do a linear search. */
316 #endif /* UFS_DIRHASH */
318 * If there is cached information on a previous search of
319 * this directory, pick up where we last left off.
320 * We cache only lookups as these are the most common
321 * and have the greatest payoff. Caching CREATE has little
322 * benefit as it usually must search the entire directory
323 * to determine that the entry does not exist. Caching the
324 * location of the last DELETE or RENAME has not reduced
325 * profiling time and hence has been removed in the interest
328 if (nameiop != LOOKUP || i_diroff == 0 || i_diroff >= dp->i_size) {
329 entryoffsetinblock = 0;
334 if ((entryoffsetinblock = i_offset & bmask) &&
335 (error = UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp)))
338 nchstats.ncs_2passes++;
341 endsearch = roundup2(dp->i_size, DIRBLKSIZ);
345 while (i_offset < endsearch) {
347 * If necessary, get the next directory block.
349 if ((i_offset & bmask) == 0) {
353 UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp);
356 entryoffsetinblock = 0;
359 * If still looking for a slot, and at a DIRBLKSIZE
360 * boundary, have to start looking for free space again.
362 if (slotstatus == NONE &&
363 (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
368 * Get pointer to next entry.
369 * Full validation checks are slow, so we only check
370 * enough to insure forward progress through the
371 * directory. Complete checks can be run by patching
372 * "dirchk" to be true.
374 ep = (struct direct *)((char *)bp->b_data + entryoffsetinblock);
375 if (ep->d_reclen == 0 || ep->d_reclen >
376 DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
377 (dirchk && ufs_dirbadentry(vdp, ep, entryoffsetinblock))) {
380 ufs_dirbad(dp, i_offset, "mangled entry");
381 i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
383 entryoffsetinblock += i;
388 * If an appropriate sized slot has not yet been found,
389 * check to see if one is available. Also accumulate space
390 * in the current block so that we can determine if
391 * compaction is viable.
393 if (slotstatus != FOUND) {
394 int size = ep->d_reclen;
397 size -= DIRSIZ(OFSFMT(vdp), ep);
399 if (size >= slotneeded) {
401 slotoffset = i_offset;
402 slotsize = ep->d_reclen;
403 } else if (slotstatus == NONE) {
404 slotfreespace += size;
405 if (slotoffset == -1)
406 slotoffset = i_offset;
407 if (slotfreespace >= slotneeded) {
408 slotstatus = COMPACT;
409 slotsize = i_offset +
410 ep->d_reclen - slotoffset;
417 * Check for a name match.
420 # if (BYTE_ORDER == LITTLE_ENDIAN)
424 namlen = ep->d_namlen;
426 namlen = ep->d_namlen;
428 if (namlen == cnp->cn_namelen &&
429 (cnp->cn_nameptr[0] == ep->d_name[0]) &&
430 !bcmp(cnp->cn_nameptr, ep->d_name,
436 * Save directory entry's inode number and
437 * reclen in ndp->ni_ufs area, and release
440 if (vdp->v_mount->mnt_maxsymlinklen > 0 &&
441 ep->d_type == DT_WHT) {
443 slotoffset = i_offset;
444 slotsize = ep->d_reclen;
445 enduseful = dp->i_size;
446 cnp->cn_flags |= ISWHITEOUT;
455 i_offset += ep->d_reclen;
456 entryoffsetinblock += ep->d_reclen;
458 enduseful = i_offset;
462 * If we started in the middle of the directory and failed
463 * to find our target, we must check the beginning as well.
465 if (numdirpasses == 2) {
468 endsearch = i_diroff;
474 * If creating, and at end of pathname and current
475 * directory has not been removed, then can consider
476 * allowing file to be created.
478 if ((nameiop == CREATE || nameiop == RENAME ||
479 (nameiop == DELETE &&
480 (cnp->cn_flags & DOWHITEOUT) &&
481 (cnp->cn_flags & ISWHITEOUT))) &&
482 (flags & ISLASTCN) && dp->i_effnlink != 0) {
484 * Access for write is interpreted as allowing
485 * creation of files in the directory.
487 * XXX: Fix the comment above.
489 if (flags & WILLBEDIR)
490 error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
492 error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
496 * Return an indication of where the new directory
497 * entry should be put. If we didn't find a slot,
498 * then set dp->i_count to 0 indicating
499 * that the new slot belongs at the end of the
500 * directory. If we found a slot, then the new entry
501 * can be put in the range from dp->i_offset to
502 * dp->i_offset + dp->i_count.
504 if (slotstatus == NONE) {
505 dp->i_offset = roundup2(dp->i_size, DIRBLKSIZ);
507 enduseful = dp->i_offset;
508 } else if (nameiop == DELETE) {
509 dp->i_offset = slotoffset;
510 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
513 dp->i_count = dp->i_offset - prevoff;
515 dp->i_offset = slotoffset;
516 dp->i_count = slotsize;
517 if (enduseful < slotoffset + slotsize)
518 enduseful = slotoffset + slotsize;
520 dp->i_endoff = roundup2(enduseful, DIRBLKSIZ);
522 * We return with the directory locked, so that
523 * the parameters we set up above will still be
524 * valid if we actually decide to do a direnter().
525 * We return ni_vp == NULL to indicate that the entry
526 * does not currently exist; we leave a pointer to
527 * the (locked) directory inode in ndp->ni_dvp.
528 * The pathname buffer is saved so that the name
529 * can be obtained later.
531 * NB - if the directory is unlocked, then this
532 * information cannot be used.
534 cnp->cn_flags |= SAVENAME;
535 return (EJUSTRETURN);
538 * Insert name into cache (as non-existent) if appropriate.
540 if ((cnp->cn_flags & MAKEENTRY) != 0)
541 cache_enter(vdp, NULL, cnp);
547 if (numdirpasses == 2)
548 nchstats.ncs_pass2++;
550 * Check that directory length properly reflects presence
553 if (i_offset + DIRSIZ(OFSFMT(vdp), ep) > dp->i_size) {
554 ufs_dirbad(dp, i_offset, "i_size too small");
555 dp->i_size = i_offset + DIRSIZ(OFSFMT(vdp), ep);
556 DIP_SET(dp, i_size, dp->i_size);
557 dp->i_flag |= IN_CHANGE | IN_UPDATE;
562 * Found component in pathname.
563 * If the final component of path name, save information
564 * in the cache as to where the entry was found.
566 if ((flags & ISLASTCN) && nameiop == LOOKUP)
567 dp->i_diroff = rounddown2(i_offset, DIRBLKSIZ);
570 * If deleting, and at end of pathname, return
571 * parameters which can be used to remove file.
573 if (nameiop == DELETE && (flags & ISLASTCN)) {
574 if (flags & LOCKPARENT)
575 ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
577 * Return pointer to current entry in dp->i_offset,
578 * and distance past previous entry (if there
579 * is a previous entry in this block) in dp->i_count.
580 * Save directory inode pointer in ndp->ni_dvp for dirremove().
582 * Technically we shouldn't be setting these in the
583 * WANTPARENT case (first lookup in rename()), but any
584 * lookups that will result in directory changes will
587 dp->i_offset = i_offset;
588 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
591 dp->i_count = dp->i_offset - prevoff;
594 if ((error = VFS_VGET(vdp->v_mount, ino,
595 LK_EXCLUSIVE, &tdp)) != 0)
597 error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
602 if (dp->i_number == ino) {
614 * If rewriting (RENAME), return the inode and the
615 * information required to rewrite the present directory
616 * Must get inode of directory entry to verify it's a
617 * regular file, or empty directory.
619 if (nameiop == RENAME && (flags & ISLASTCN)) {
620 if (flags & WILLBEDIR)
621 error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
623 error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
627 * Careful about locking second inode.
628 * This can only occur if the target is ".".
630 dp->i_offset = i_offset;
631 if (dp->i_number == ino)
635 if ((error = VFS_VGET(vdp->v_mount, ino,
636 LK_EXCLUSIVE, &tdp)) != 0)
639 error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
645 #ifdef SunOS_doesnt_do_that
647 * The only purpose of this check is to return the correct
648 * error. Assume that we want to rename directory "a"
649 * to a file "b", and that we have no ACL_WRITE_DATA on
650 * a containing directory, but we _do_ have ACL_APPEND_DATA.
651 * In that case, the VOP_ACCESS check above will return 0,
652 * and the operation will fail with ENOTDIR instead
655 if (tdp->v_type == VDIR)
656 error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
658 error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
666 cnp->cn_flags |= SAVENAME;
673 * Step through the translation in the name. We do not `vput' the
674 * directory because we may need it again if a symbolic link
675 * is relative to the current directory. Instead we save it
676 * unlocked as "pdp". We must get the target inode before unlocking
677 * the directory to insure that the inode will not be removed
678 * before we get it. We prevent deadlock by always fetching
679 * inodes from the root, moving down the directory tree. Thus
680 * when following backward pointers ".." we must unlock the
681 * parent directory before getting the requested directory.
682 * There is a potential race condition here if both the current
683 * and parent directories are removed before the VFS_VGET for the
684 * inode associated with ".." returns. We hope that this occurs
685 * infrequently since we cannot avoid this race condition without
686 * implementing a sophisticated deadlock detection algorithm.
687 * Note also that this simple deadlock detection scheme will not
688 * work if the filesystem has any hard links other than ".."
689 * that point backwards in the directory structure.
692 if (flags & ISDOTDOT) {
693 error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
698 * Recheck that ".." entry in the vdp directory points
699 * to the inode we looked up before vdp lock was
702 error = ufs_lookup_ino(pdp, NULL, cnp, &ino1);
713 } else if (dp->i_number == ino) {
714 VREF(vdp); /* we want ourself, ie "." */
716 * When we lookup "." we still can be asked to lock it
719 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
720 if (ltype != VOP_ISLOCKED(vdp)) {
721 if (ltype == LK_EXCLUSIVE)
722 vn_lock(vdp, LK_UPGRADE | LK_RETRY);
723 else /* if (ltype == LK_SHARED) */
724 vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
726 * Relock for the "." case may left us with
729 if (vdp->v_iflag & VI_DOOMED) {
736 error = VFS_VGET(pdp->v_mount, ino, cnp->cn_lkflags, &tdp);
743 * Insert name into cache if appropriate.
745 if (cnp->cn_flags & MAKEENTRY)
746 cache_enter(vdp, *vpp, cnp);
751 ufs_dirbad(ip, offset, how)
758 mp = ITOV(ip)->v_mount;
759 if ((mp->mnt_flag & MNT_RDONLY) == 0)
760 panic("ufs_dirbad: %s: bad dir ino %ju at offset %ld: %s",
761 mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
764 (void)printf("%s: bad dir ino %ju at offset %ld: %s\n",
765 mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
770 * Do consistency checking on a directory entry:
771 * record length must be multiple of 4
772 * entry must fit in rest of its DIRBLKSIZ block
773 * record must be large enough to contain entry
774 * name is not longer than MAXNAMLEN
775 * name must be as long as advertised, and null terminated
778 ufs_dirbadentry(dp, ep, entryoffsetinblock)
781 int entryoffsetinblock;
785 # if (BYTE_ORDER == LITTLE_ENDIAN)
789 namlen = ep->d_namlen;
791 namlen = ep->d_namlen;
793 if ((ep->d_reclen & 0x3) != 0 ||
794 ep->d_reclen > DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
795 ep->d_reclen < DIRSIZ(OFSFMT(dp), ep) || namlen > MAXNAMLEN) {
797 printf("First bad\n");
802 for (i = 0; i < namlen; i++)
803 if (ep->d_name[i] == '\0') {
805 printf("Second bad\n");
816 * Construct a new directory entry after a call to namei, using the
817 * parameters that it left in the componentname argument cnp. The
818 * argument ip is the inode to which the new directory entry will refer.
821 ufs_makedirentry(ip, cnp, newdirp)
823 struct componentname *cnp;
824 struct direct *newdirp;
828 if ((cnp->cn_flags & SAVENAME) == 0)
829 panic("ufs_makedirentry: missing name");
831 newdirp->d_ino = ip->i_number;
832 newdirp->d_namlen = cnp->cn_namelen;
833 bcopy(cnp->cn_nameptr, newdirp->d_name, (unsigned)cnp->cn_namelen + 1);
834 if (ITOV(ip)->v_mount->mnt_maxsymlinklen > 0)
835 newdirp->d_type = IFTODT(ip->i_mode);
838 # if (BYTE_ORDER == LITTLE_ENDIAN)
839 { u_char tmp = newdirp->d_namlen;
840 newdirp->d_namlen = newdirp->d_type;
841 newdirp->d_type = tmp; }
847 * Write a directory entry after a call to namei, using the parameters
848 * that it left in nameidata. The argument dirp is the new directory
849 * entry contents. Dvp is a pointer to the directory to be written,
850 * which was left locked by namei. Remaining parameters (dp->i_offset,
851 * dp->i_count) indicate how the space for the new entry is to be obtained.
852 * Non-null bp indicates that a directory is being created (for the
853 * soft dependency code).
856 ufs_direnter(dvp, tvp, dirp, cnp, newdirbp, isrename)
860 struct componentname *cnp;
861 struct buf *newdirbp;
870 struct direct *ep, *nep;
872 int error, ret, blkoff, loc, spacefree, flags, namlen;
875 td = curthread; /* XXX */
879 newentrysize = DIRSIZ(OFSFMT(dvp), dirp);
881 if (dp->i_count == 0) {
883 * If dp->i_count is 0, then namei could find no
884 * space in the directory. Here, dp->i_offset will
885 * be on a directory block boundary and we will write the
886 * new entry into a fresh block.
888 if (dp->i_offset & (DIRBLKSIZ - 1))
889 panic("ufs_direnter: newblk");
891 if (!DOINGSOFTDEP(dvp) && !DOINGASYNC(dvp))
894 if ((error = getinoquota(dp)) != 0) {
895 if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
900 old_isize = dp->i_size;
901 vnode_pager_setsize(dvp, (u_long)dp->i_offset + DIRBLKSIZ);
902 if ((error = UFS_BALLOC(dvp, (off_t)dp->i_offset, DIRBLKSIZ,
903 cr, flags, &bp)) != 0) {
904 if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
906 vnode_pager_setsize(dvp, (u_long)old_isize);
909 dp->i_size = dp->i_offset + DIRBLKSIZ;
910 DIP_SET(dp, i_size, dp->i_size);
911 dp->i_endoff = dp->i_size;
912 dp->i_flag |= IN_CHANGE | IN_UPDATE;
913 dirp->d_reclen = DIRBLKSIZ;
914 blkoff = dp->i_offset &
915 (VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_iosize - 1);
916 bcopy((caddr_t)dirp, (caddr_t)bp->b_data + blkoff,newentrysize);
918 if (dp->i_dirhash != NULL) {
919 ufsdirhash_newblk(dp, dp->i_offset);
920 ufsdirhash_add(dp, dirp, dp->i_offset);
921 ufsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
925 if (DOINGSOFTDEP(dvp)) {
927 * Ensure that the entire newly allocated block is a
928 * valid directory so that future growth within the
929 * block does not have to ensure that the block is
930 * written before the inode.
933 while (blkoff < bp->b_bcount) {
935 (bp->b_data + blkoff))->d_reclen = DIRBLKSIZ;
938 if (softdep_setup_directory_add(bp, dp, dp->i_offset,
939 dirp->d_ino, newdirbp, 1))
940 dp->i_flag |= IN_NEEDSYNC;
944 if ((dp->i_flag & IN_NEEDSYNC) == 0)
945 return (UFS_UPDATE(dvp, 0));
947 * We have just allocated a directory block in an
948 * indirect block. We must prevent holes in the
949 * directory created if directory entries are
950 * written out of order. To accomplish this we
951 * fsync when we extend a directory into indirects.
952 * During rename it's not safe to drop the tvp lock
953 * so sync must be delayed until it is.
955 * This synchronous step could be removed if fsck and
956 * the kernel were taught to fill in sparse
957 * directories rather than panic.
963 (void) VOP_FSYNC(dvp, MNT_WAIT, td);
965 vn_lock(tvp, LK_EXCLUSIVE | LK_RETRY);
968 if (DOINGASYNC(dvp)) {
970 return (UFS_UPDATE(dvp, 0));
973 ret = UFS_UPDATE(dvp, 1);
980 * If dp->i_count is non-zero, then namei found space for the new
981 * entry in the range dp->i_offset to dp->i_offset + dp->i_count
982 * in the directory. To use this space, we may have to compact
983 * the entries located there, by copying them together towards the
984 * beginning of the block, leaving the free space in one usable
989 * Increase size of directory if entry eats into new space.
990 * This should never push the size past a new multiple of
993 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
995 if (dp->i_offset + dp->i_count > dp->i_size) {
996 dp->i_size = dp->i_offset + dp->i_count;
997 DIP_SET(dp, i_size, dp->i_size);
1000 * Get the block containing the space for the new directory entry.
1002 error = UFS_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp);
1004 if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
1009 * Find space for the new entry. In the simple case, the entry at
1010 * offset base will have the space. If it does not, then namei
1011 * arranged that compacting the region dp->i_offset to
1012 * dp->i_offset + dp->i_count would yield the space.
1014 ep = (struct direct *)dirbuf;
1015 dsize = ep->d_ino ? DIRSIZ(OFSFMT(dvp), ep) : 0;
1016 spacefree = ep->d_reclen - dsize;
1017 for (loc = ep->d_reclen; loc < dp->i_count; ) {
1018 nep = (struct direct *)(dirbuf + loc);
1020 /* Trim the existing slot (NB: dsize may be zero). */
1021 ep->d_reclen = dsize;
1022 ep = (struct direct *)((char *)ep + dsize);
1024 /* Read nep->d_reclen now as the bcopy() may clobber it. */
1025 loc += nep->d_reclen;
1026 if (nep->d_ino == 0) {
1028 * A mid-block unused entry. Such entries are
1029 * never created by the kernel, but fsck_ffs
1030 * can create them (and it doesn't fix them).
1032 * Add up the free space, and initialise the
1033 * relocated entry since we don't bcopy it.
1035 spacefree += nep->d_reclen;
1040 dsize = DIRSIZ(OFSFMT(dvp), nep);
1041 spacefree += nep->d_reclen - dsize;
1043 if (dp->i_dirhash != NULL)
1044 ufsdirhash_move(dp, nep,
1045 dp->i_offset + ((char *)nep - dirbuf),
1046 dp->i_offset + ((char *)ep - dirbuf));
1048 if (DOINGSOFTDEP(dvp))
1049 softdep_change_directoryentry_offset(bp, dp, dirbuf,
1050 (caddr_t)nep, (caddr_t)ep, dsize);
1052 bcopy((caddr_t)nep, (caddr_t)ep, dsize);
1055 * Here, `ep' points to a directory entry containing `dsize' in-use
1056 * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
1057 * then the entry is completely unused (dsize == 0). The value
1058 * of ep->d_reclen is always indeterminate.
1060 * Update the pointer fields in the previous entry (if any),
1061 * copy in the new entry, and write out the block.
1063 # if (BYTE_ORDER == LITTLE_ENDIAN)
1065 namlen = ep->d_type;
1067 namlen = ep->d_namlen;
1069 namlen = ep->d_namlen;
1071 if (ep->d_ino == 0 ||
1072 (ep->d_ino == WINO && namlen == dirp->d_namlen &&
1073 bcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
1074 if (spacefree + dsize < newentrysize)
1075 panic("ufs_direnter: compact1");
1076 dirp->d_reclen = spacefree + dsize;
1078 if (spacefree < newentrysize)
1079 panic("ufs_direnter: compact2");
1080 dirp->d_reclen = spacefree;
1081 ep->d_reclen = dsize;
1082 ep = (struct direct *)((char *)ep + dsize);
1085 if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
1086 dirp->d_reclen == spacefree))
1087 ufsdirhash_add(dp, dirp, dp->i_offset + ((char *)ep - dirbuf));
1089 bcopy((caddr_t)dirp, (caddr_t)ep, (u_int)newentrysize);
1091 if (dp->i_dirhash != NULL)
1092 ufsdirhash_checkblock(dp, dirbuf -
1093 (dp->i_offset & (DIRBLKSIZ - 1)),
1094 rounddown2(dp->i_offset, DIRBLKSIZ));
1097 if (DOINGSOFTDEP(dvp)) {
1098 (void) softdep_setup_directory_add(bp, dp,
1099 dp->i_offset + (caddr_t)ep - dirbuf,
1100 dirp->d_ino, newdirbp, 0);
1101 if (newdirbp != NULL)
1105 if (DOINGASYNC(dvp)) {
1112 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1114 * If all went well, and the directory can be shortened, proceed
1115 * with the truncation. Note that we have to unlock the inode for
1116 * the entry that we just entered, as the truncation may need to
1117 * lock other inodes which can lead to deadlock if we also hold a
1118 * lock on the newly entered node.
1120 if (isrename == 0 && error == 0 &&
1121 dp->i_endoff && dp->i_endoff < dp->i_size) {
1124 error = UFS_TRUNCATE(dvp, (off_t)dp->i_endoff,
1125 IO_NORMAL | (DOINGASYNC(dvp) ? 0 : IO_SYNC), cr);
1127 vn_printf(dvp, "ufs_direnter: failed to truncate ");
1129 if (error == 0 && dp->i_dirhash != NULL)
1130 ufsdirhash_dirtrunc(dp, dp->i_endoff);
1134 vn_lock(tvp, LK_EXCLUSIVE | LK_RETRY);
1140 * Remove a directory entry after a call to namei, using
1141 * the parameters which it left in nameidata. The entry
1142 * dp->i_offset contains the offset into the directory of the
1143 * entry to be eliminated. The dp->i_count field contains the
1144 * size of the previous record in the directory. If this
1145 * is 0, the first entry is being deleted, so we need only
1146 * zero the inode number to mark the entry as free. If the
1147 * entry is not the first in the directory, we must reclaim
1148 * the space of the now empty record by adding the record size
1149 * to the size of the previous entry.
1152 ufs_dirremove(dvp, ip, flags, isrmdir)
1159 struct direct *ep, *rep;
1166 * Adjust the link count early so softdep can block if necessary.
1170 if (DOINGSOFTDEP(dvp)) {
1171 softdep_setup_unlink(dp, ip);
1174 DIP_SET(ip, i_nlink, ip->i_nlink);
1175 ip->i_flag |= IN_CHANGE;
1178 if (flags & DOWHITEOUT) {
1180 * Whiteout entry: set d_ino to WINO.
1183 UFS_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
1186 ep->d_type = DT_WHT;
1190 if ((error = UFS_BLKATOFF(dvp,
1191 (off_t)(dp->i_offset - dp->i_count), (char **)&ep, &bp)) != 0)
1194 /* Set 'rep' to the entry being removed. */
1195 if (dp->i_count == 0)
1198 rep = (struct direct *)((char *)ep + ep->d_reclen);
1201 * Remove the dirhash entry. This is complicated by the fact
1202 * that `ep' is the previous entry when dp->i_count != 0.
1204 if (dp->i_dirhash != NULL)
1205 ufsdirhash_remove(dp, rep, dp->i_offset);
1207 if (ip && rep->d_ino != ip->i_number)
1208 panic("ufs_dirremove: ip %ju does not match dirent ino %ju\n",
1209 (uintmax_t)ip->i_number, (uintmax_t)rep->d_ino);
1210 if (dp->i_count == 0) {
1212 * First entry in block: set d_ino to zero.
1217 * Collapse new free space into previous entry.
1219 ep->d_reclen += rep->d_reclen;
1222 if (dp->i_dirhash != NULL)
1223 ufsdirhash_checkblock(dp, (char *)ep -
1224 ((dp->i_offset - dp->i_count) & (DIRBLKSIZ - 1)),
1225 rounddown2(dp->i_offset, DIRBLKSIZ));
1229 if (DOINGSOFTDEP(dvp)) {
1231 softdep_setup_remove(bp, dp, ip, isrmdir);
1232 if (softdep_slowdown(dvp))
1237 if (flags & DOWHITEOUT)
1239 else if (DOINGASYNC(dvp) && dp->i_count != 0)
1244 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1246 * If the last named reference to a snapshot goes away,
1247 * drop its snapshot reference so that it will be reclaimed
1248 * when last open reference goes away.
1250 if (ip != NULL && (ip->i_flags & SF_SNAPSHOT) != 0 &&
1251 ip->i_effnlink == 0)
1257 * Rewrite an existing directory entry to point at the inode
1258 * supplied. The parameters describing the directory entry are
1259 * set up by a call to namei.
1262 ufs_dirrewrite(dp, oip, newinum, newtype, isrmdir)
1263 struct inode *dp, *oip;
1270 struct vnode *vdp = ITOV(dp);
1274 * Drop the link before we lock the buf so softdep can block if
1278 if (DOINGSOFTDEP(vdp)) {
1279 softdep_setup_unlink(dp, oip);
1282 DIP_SET(oip, i_nlink, oip->i_nlink);
1283 oip->i_flag |= IN_CHANGE;
1286 error = UFS_BLKATOFF(vdp, (off_t)dp->i_offset, (char **)&ep, &bp);
1289 if (ep->d_namlen == 2 && ep->d_name[1] == '.' && ep->d_name[0] == '.' &&
1290 ep->d_ino != oip->i_number) {
1294 ep->d_ino = newinum;
1296 ep->d_type = newtype;
1297 if (DOINGSOFTDEP(vdp)) {
1298 softdep_setup_directory_change(bp, dp, oip, newinum, isrmdir);
1301 if (DOINGASYNC(vdp)) {
1308 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1310 * If the last named reference to a snapshot goes away,
1311 * drop its snapshot reference so that it will be reclaimed
1312 * when last open reference goes away.
1314 if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_effnlink == 0)
1320 * Check if a directory is empty or not.
1321 * Inode supplied must be locked.
1323 * Using a struct dirtemplate here is not precisely
1324 * what we want, but better than using a struct direct.
1326 * NB: does not handle corrupted directories.
1329 ufs_dirempty(ip, parentino, cred)
1335 struct dirtemplate dbuf;
1336 struct direct *dp = (struct direct *)&dbuf;
1339 #define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
1341 for (off = 0; off < ip->i_size; off += dp->d_reclen) {
1342 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1343 off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1344 NOCRED, &count, (struct thread *)0);
1346 * Since we read MINDIRSIZ, residual must
1347 * be 0 unless we're at end of file.
1349 if (error || count != 0)
1351 /* avoid infinite loops */
1352 if (dp->d_reclen == 0)
1354 /* skip empty entries */
1355 if (dp->d_ino == 0 || dp->d_ino == WINO)
1357 /* accept only "." and ".." */
1358 # if (BYTE_ORDER == LITTLE_ENDIAN)
1359 if (OFSFMT(ITOV(ip)))
1360 namlen = dp->d_type;
1362 namlen = dp->d_namlen;
1364 namlen = dp->d_namlen;
1368 if (dp->d_name[0] != '.')
1371 * At this point namlen must be 1 or 2.
1372 * 1 implies ".", 2 implies ".." if second
1375 if (namlen == 1 && dp->d_ino == ip->i_number)
1377 if (dp->d_name[1] == '.' && dp->d_ino == parentino)
1385 ufs_dir_dd_ino(struct vnode *vp, struct ucred *cred, ino_t *dd_ino,
1386 struct vnode **dd_vp)
1388 struct dirtemplate dirbuf;
1392 ASSERT_VOP_LOCKED(vp, "ufs_dir_dd_ino");
1393 if (vp->v_type != VDIR)
1396 * First check to see if we have it in the name cache.
1398 if ((ddvp = vn_dir_dd_ino(vp)) != NULL) {
1399 KASSERT(ddvp->v_mount == vp->v_mount,
1400 ("ufs_dir_dd_ino: Unexpected mount point crossing"));
1401 *dd_ino = VTOI(ddvp)->i_number;
1406 * Have to read the directory.
1408 error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1409 sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1410 IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL, NULL);
1413 #if (BYTE_ORDER == LITTLE_ENDIAN)
1415 namlen = dirbuf.dotdot_type;
1417 namlen = dirbuf.dotdot_namlen;
1419 namlen = dirbuf.dotdot_namlen;
1421 if (namlen != 2 || dirbuf.dotdot_name[0] != '.' ||
1422 dirbuf.dotdot_name[1] != '.')
1424 *dd_ino = dirbuf.dotdot_ino;
1430 * Check if source directory is in the path of the target directory.
1433 ufs_checkpath(ino_t source_ino, ino_t parent_ino, struct inode *target, struct ucred *cred, ino_t *wait_ino)
1436 struct vnode *tvp, *vp, *vp1;
1440 vp = tvp = ITOV(target);
1443 if (target->i_number == source_ino)
1445 if (target->i_number == parent_ino)
1447 if (target->i_number == ROOTINO)
1450 error = ufs_dir_dd_ino(vp, cred, &dd_ino, &vp1);
1453 if (dd_ino == source_ino) {
1457 if (dd_ino == ROOTINO)
1459 if (dd_ino == parent_ino)
1462 error = VFS_VGET(mp, dd_ino, LK_SHARED | LK_NOWAIT,
1469 KASSERT(dd_ino == VTOI(vp1)->i_number,
1470 ("directory %ju reparented\n",
1471 (uintmax_t)VTOI(vp1)->i_number));
1477 if (error == ENOTDIR)
1478 panic("checkpath: .. not a directory\n");