]> CyberLeo.Net >> Repos - FreeBSD/releng/8.0.git/blob - sys/ufs/ufs/ufs_lookup.c
Adjust to reflect 8.0-RELEASE.
[FreeBSD/releng/8.0.git] / sys / ufs / ufs / ufs_lookup.c
1 /*-
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.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
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.
21  *
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
32  * SUCH DAMAGE.
33  *
34  *      @(#)ufs_lookup.c        8.15 (Berkeley) 6/16/95
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 #include "opt_ffs_broken_fixme.h"
41 #include "opt_ufs.h"
42 #include "opt_quota.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kernel.h>
47 #include <sys/namei.h>
48 #include <sys/bio.h>
49 #include <sys/buf.h>
50 #include <sys/proc.h>
51 #include <sys/stat.h>
52 #include <sys/mount.h>
53 #include <sys/vnode.h>
54 #include <sys/sysctl.h>
55
56 #include <vm/vm.h>
57 #include <vm/vm_extern.h>
58
59 #include <ufs/ufs/extattr.h>
60 #include <ufs/ufs/quota.h>
61 #include <ufs/ufs/inode.h>
62 #include <ufs/ufs/dir.h>
63 #ifdef UFS_DIRHASH
64 #include <ufs/ufs/dirhash.h>
65 #endif
66 #include <ufs/ufs/ufsmount.h>
67 #include <ufs/ufs/ufs_extern.h>
68
69 #ifdef DIAGNOSTIC
70 static int      dirchk = 1;
71 #else
72 static int      dirchk = 0;
73 #endif
74
75 SYSCTL_INT(_debug, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
76
77 /* true if old FS format...*/
78 #define OFSFMT(vp)      ((vp)->v_mount->mnt_maxsymlinklen <= 0)
79
80 static int ufs_lookup_(struct vnode *, struct vnode **, struct componentname *,
81     ino_t *);
82
83 /*
84  * Convert a component of a pathname into a pointer to a locked inode.
85  * This is a very central and rather complicated routine.
86  * If the filesystem is not maintained in a strict tree hierarchy,
87  * this can result in a deadlock situation (see comments in code below).
88  *
89  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
90  * on whether the name is to be looked up, created, renamed, or deleted.
91  * When CREATE, RENAME, or DELETE is specified, information usable in
92  * creating, renaming, or deleting a directory entry may be calculated.
93  * If flag has LOCKPARENT or'ed into it and the target of the pathname
94  * exists, lookup returns both the target and its parent directory locked.
95  * When creating or renaming and LOCKPARENT is specified, the target may
96  * not be ".".  When deleting and LOCKPARENT is specified, the target may
97  * be "."., but the caller must check to ensure it does an vrele and vput
98  * instead of two vputs.
99  *
100  * This routine is actually used as VOP_CACHEDLOOKUP method, and the
101  * filesystem employs the generic vfs_cache_lookup() as VOP_LOOKUP
102  * method.
103  *
104  * vfs_cache_lookup() performs the following for us:
105  *      check that it is a directory
106  *      check accessibility of directory
107  *      check for modification attempts on read-only mounts
108  *      if name found in cache
109  *          if at end of path and deleting or creating
110  *              drop it
111  *           else
112  *              return name.
113  *      return VOP_CACHEDLOOKUP()
114  *
115  * Overall outline of ufs_lookup:
116  *
117  *      search for name in directory, to found or notfound
118  * notfound:
119  *      if creating, return locked directory, leaving info on available slots
120  *      else return error
121  * found:
122  *      if at end of path and deleting, return information to allow delete
123  *      if at end of path and rewriting (RENAME and LOCKPARENT), lock target
124  *        inode and return info to allow rewrite
125  *      if not at end, add name to cache; if at end and neither creating
126  *        nor deleting, add name to cache
127  */
128 int
129 ufs_lookup(ap)
130         struct vop_cachedlookup_args /* {
131                 struct vnode *a_dvp;
132                 struct vnode **a_vpp;
133                 struct componentname *a_cnp;
134         } */ *ap;
135 {
136
137         return (ufs_lookup_(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
138 }
139
140 static int
141 ufs_lookup_(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
142     ino_t *dd_ino)
143 {
144         struct inode *dp;               /* inode for directory being searched */
145         struct buf *bp;                 /* a buffer of directory entries */
146         struct direct *ep;              /* the current directory entry */
147         int entryoffsetinblock;         /* offset of ep in bp's buffer */
148         enum {NONE, COMPACT, FOUND} slotstatus;
149         doff_t slotoffset;              /* offset of area with free space */
150         doff_t i_diroff;                /* cached i_diroff value. */
151         doff_t i_offset;                /* cached i_offset value. */
152         int slotsize;                   /* size of area at slotoffset */
153         int slotfreespace;              /* amount of space free in slot */
154         int slotneeded;                 /* size of the entry we're seeking */
155         int numdirpasses;               /* strategy for directory search */
156         doff_t endsearch;               /* offset to end directory search */
157         doff_t prevoff;                 /* prev entry dp->i_offset */
158         struct vnode *pdp;              /* saved dp during symlink work */
159         struct vnode *tdp;              /* returned by VFS_VGET */
160         doff_t enduseful;               /* pointer past last used dir slot */
161         u_long bmask;                   /* block offset mask */
162         int namlen, error;
163         struct ucred *cred = cnp->cn_cred;
164         int flags = cnp->cn_flags;
165         int nameiop = cnp->cn_nameiop;
166         ino_t ino, ino1;
167         int ltype;
168
169         if (vpp != NULL)
170                 *vpp = NULL;
171
172         dp = VTOI(vdp);
173
174         /*
175          * Create a vm object if vmiodirenable is enabled.
176          * Alternatively we could call vnode_create_vobject
177          * in VFS_VGET but we could end up creating objects
178          * that are never used.
179          */
180         vnode_create_vobject(vdp, DIP(dp, i_size), cnp->cn_thread);
181
182         bmask = VFSTOUFS(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
183
184 restart:
185         bp = NULL;
186         slotoffset = -1;
187
188         /*
189          * We now have a segment name to search for, and a directory to search.
190          *
191          * Suppress search for slots unless creating
192          * file and at end of pathname, in which case
193          * we watch for a place to put the new file in
194          * case it doesn't already exist.
195          */
196         ino = 0;
197         i_diroff = dp->i_diroff;
198         slotstatus = FOUND;
199         slotfreespace = slotsize = slotneeded = 0;
200         if ((nameiop == CREATE || nameiop == RENAME) &&
201             (flags & ISLASTCN)) {
202                 slotstatus = NONE;
203                 slotneeded = DIRECTSIZ(cnp->cn_namelen);
204         }
205
206 #ifdef UFS_DIRHASH
207         /*
208          * Use dirhash for fast operations on large directories. The logic
209          * to determine whether to hash the directory is contained within
210          * ufsdirhash_build(); a zero return means that it decided to hash
211          * this directory and it successfully built up the hash table.
212          */
213         if (ufsdirhash_build(dp) == 0) {
214                 /* Look for a free slot if needed. */
215                 enduseful = dp->i_size;
216                 if (slotstatus != FOUND) {
217                         slotoffset = ufsdirhash_findfree(dp, slotneeded,
218                             &slotsize);
219                         if (slotoffset >= 0) {
220                                 slotstatus = COMPACT;
221                                 enduseful = ufsdirhash_enduseful(dp);
222                                 if (enduseful < 0)
223                                         enduseful = dp->i_size;
224                         }
225                 }
226                 /* Look up the component. */
227                 numdirpasses = 1;
228                 entryoffsetinblock = 0; /* silence compiler warning */
229                 switch (ufsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
230                     &i_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
231                 case 0:
232                         ep = (struct direct *)((char *)bp->b_data +
233                             (i_offset & bmask));
234                         goto foundentry;
235                 case ENOENT:
236                         i_offset = roundup2(dp->i_size, DIRBLKSIZ);
237                         goto notfound;
238                 default:
239                         /* Something failed; just do a linear search. */
240                         break;
241                 }
242         }
243 #endif /* UFS_DIRHASH */
244         /*
245          * If there is cached information on a previous search of
246          * this directory, pick up where we last left off.
247          * We cache only lookups as these are the most common
248          * and have the greatest payoff. Caching CREATE has little
249          * benefit as it usually must search the entire directory
250          * to determine that the entry does not exist. Caching the
251          * location of the last DELETE or RENAME has not reduced
252          * profiling time and hence has been removed in the interest
253          * of simplicity.
254          */
255         if (nameiop != LOOKUP || i_diroff == 0 || i_diroff >= dp->i_size) {
256                 entryoffsetinblock = 0;
257                 i_offset = 0;
258                 numdirpasses = 1;
259         } else {
260                 i_offset = i_diroff;
261                 if ((entryoffsetinblock = i_offset & bmask) &&
262                     (error = UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp)))
263                         return (error);
264                 numdirpasses = 2;
265                 nchstats.ncs_2passes++;
266         }
267         prevoff = i_offset;
268         endsearch = roundup2(dp->i_size, DIRBLKSIZ);
269         enduseful = 0;
270
271 searchloop:
272         while (i_offset < endsearch) {
273                 /*
274                  * If necessary, get the next directory block.
275                  */
276                 if ((i_offset & bmask) == 0) {
277                         if (bp != NULL)
278                                 brelse(bp);
279                         error =
280                             UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp);
281                         if (error)
282                                 return (error);
283                         entryoffsetinblock = 0;
284                 }
285                 /*
286                  * If still looking for a slot, and at a DIRBLKSIZE
287                  * boundary, have to start looking for free space again.
288                  */
289                 if (slotstatus == NONE &&
290                     (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
291                         slotoffset = -1;
292                         slotfreespace = 0;
293                 }
294                 /*
295                  * Get pointer to next entry.
296                  * Full validation checks are slow, so we only check
297                  * enough to insure forward progress through the
298                  * directory. Complete checks can be run by patching
299                  * "dirchk" to be true.
300                  */
301                 ep = (struct direct *)((char *)bp->b_data + entryoffsetinblock);
302                 if (ep->d_reclen == 0 || ep->d_reclen >
303                     DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
304                     (dirchk && ufs_dirbadentry(vdp, ep, entryoffsetinblock))) {
305                         int i;
306
307                         ufs_dirbad(dp, i_offset, "mangled entry");
308                         i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
309                         i_offset += i;
310                         entryoffsetinblock += i;
311                         continue;
312                 }
313
314                 /*
315                  * If an appropriate sized slot has not yet been found,
316                  * check to see if one is available. Also accumulate space
317                  * in the current block so that we can determine if
318                  * compaction is viable.
319                  */
320                 if (slotstatus != FOUND) {
321                         int size = ep->d_reclen;
322
323                         if (ep->d_ino != 0)
324                                 size -= DIRSIZ(OFSFMT(vdp), ep);
325                         if (size > 0) {
326                                 if (size >= slotneeded) {
327                                         slotstatus = FOUND;
328                                         slotoffset = i_offset;
329                                         slotsize = ep->d_reclen;
330                                 } else if (slotstatus == NONE) {
331                                         slotfreespace += size;
332                                         if (slotoffset == -1)
333                                                 slotoffset = i_offset;
334                                         if (slotfreespace >= slotneeded) {
335                                                 slotstatus = COMPACT;
336                                                 slotsize = i_offset +
337                                                       ep->d_reclen - slotoffset;
338                                         }
339                                 }
340                         }
341                 }
342
343                 /*
344                  * Check for a name match.
345                  */
346                 if (ep->d_ino) {
347 #                       if (BYTE_ORDER == LITTLE_ENDIAN)
348                                 if (OFSFMT(vdp))
349                                         namlen = ep->d_type;
350                                 else
351                                         namlen = ep->d_namlen;
352 #                       else
353                                 namlen = ep->d_namlen;
354 #                       endif
355                         if (namlen == cnp->cn_namelen &&
356                                 (cnp->cn_nameptr[0] == ep->d_name[0]) &&
357                             !bcmp(cnp->cn_nameptr, ep->d_name,
358                                 (unsigned)namlen)) {
359 #ifdef UFS_DIRHASH
360 foundentry:
361 #endif
362                                 /*
363                                  * Save directory entry's inode number and
364                                  * reclen in ndp->ni_ufs area, and release
365                                  * directory buffer.
366                                  */
367                                 if (vdp->v_mount->mnt_maxsymlinklen > 0 &&
368                                     ep->d_type == DT_WHT) {
369                                         slotstatus = FOUND;
370                                         slotoffset = i_offset;
371                                         slotsize = ep->d_reclen;
372                                         enduseful = dp->i_size;
373                                         cnp->cn_flags |= ISWHITEOUT;
374                                         numdirpasses--;
375                                         goto notfound;
376                                 }
377                                 ino = ep->d_ino;
378                                 goto found;
379                         }
380                 }
381                 prevoff = i_offset;
382                 i_offset += ep->d_reclen;
383                 entryoffsetinblock += ep->d_reclen;
384                 if (ep->d_ino)
385                         enduseful = i_offset;
386         }
387 notfound:
388         /*
389          * If we started in the middle of the directory and failed
390          * to find our target, we must check the beginning as well.
391          */
392         if (numdirpasses == 2) {
393                 numdirpasses--;
394                 i_offset = 0;
395                 endsearch = i_diroff;
396                 goto searchloop;
397         }
398         if (bp != NULL)
399                 brelse(bp);
400         /*
401          * If creating, and at end of pathname and current
402          * directory has not been removed, then can consider
403          * allowing file to be created.
404          */
405         if ((nameiop == CREATE || nameiop == RENAME ||
406              (nameiop == DELETE &&
407               (cnp->cn_flags & DOWHITEOUT) &&
408               (cnp->cn_flags & ISWHITEOUT))) &&
409             (flags & ISLASTCN) && dp->i_effnlink != 0) {
410                 /*
411                  * Access for write is interpreted as allowing
412                  * creation of files in the directory.
413                  */
414                 error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
415                 if (error)
416                         return (error);
417                 /*
418                  * Return an indication of where the new directory
419                  * entry should be put.  If we didn't find a slot,
420                  * then set dp->i_count to 0 indicating
421                  * that the new slot belongs at the end of the
422                  * directory. If we found a slot, then the new entry
423                  * can be put in the range from dp->i_offset to
424                  * dp->i_offset + dp->i_count.
425                  */
426                 if (slotstatus == NONE) {
427                         dp->i_offset = roundup2(dp->i_size, DIRBLKSIZ);
428                         dp->i_count = 0;
429                         enduseful = dp->i_offset;
430                 } else if (nameiop == DELETE) {
431                         dp->i_offset = slotoffset;
432                         if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
433                                 dp->i_count = 0;
434                         else
435                                 dp->i_count = dp->i_offset - prevoff;
436                 } else {
437                         dp->i_offset = slotoffset;
438                         dp->i_count = slotsize;
439                         if (enduseful < slotoffset + slotsize)
440                                 enduseful = slotoffset + slotsize;
441                 }
442                 dp->i_endoff = roundup2(enduseful, DIRBLKSIZ);
443                 /*
444                  * We return with the directory locked, so that
445                  * the parameters we set up above will still be
446                  * valid if we actually decide to do a direnter().
447                  * We return ni_vp == NULL to indicate that the entry
448                  * does not currently exist; we leave a pointer to
449                  * the (locked) directory inode in ndp->ni_dvp.
450                  * The pathname buffer is saved so that the name
451                  * can be obtained later.
452                  *
453                  * NB - if the directory is unlocked, then this
454                  * information cannot be used.
455                  */
456                 cnp->cn_flags |= SAVENAME;
457                 return (EJUSTRETURN);
458         }
459         /*
460          * Insert name into cache (as non-existent) if appropriate.
461          */
462         if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
463                 cache_enter(vdp, NULL, cnp);
464         return (ENOENT);
465
466 found:
467         if (numdirpasses == 2)
468                 nchstats.ncs_pass2++;
469         /*
470          * Check that directory length properly reflects presence
471          * of this entry.
472          */
473         if (i_offset + DIRSIZ(OFSFMT(vdp), ep) > dp->i_size) {
474                 ufs_dirbad(dp, i_offset, "i_size too small");
475                 dp->i_size = i_offset + DIRSIZ(OFSFMT(vdp), ep);
476                 DIP_SET(dp, i_size, dp->i_size);
477                 dp->i_flag |= IN_CHANGE | IN_UPDATE;
478         }
479         brelse(bp);
480
481         /*
482          * Found component in pathname.
483          * If the final component of path name, save information
484          * in the cache as to where the entry was found.
485          */
486         if ((flags & ISLASTCN) && nameiop == LOOKUP)
487                 dp->i_diroff = i_offset &~ (DIRBLKSIZ - 1);
488
489         if (dd_ino != NULL) {
490                 *dd_ino = ino;
491                 return (0);
492         }
493
494         /*
495          * If deleting, and at end of pathname, return
496          * parameters which can be used to remove file.
497          */
498         if (nameiop == DELETE && (flags & ISLASTCN)) {
499                 if (flags & LOCKPARENT)
500                         ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
501                 /*
502                  * Write access to directory required to delete files.
503                  */
504                 error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
505                 if (error)
506                         return (error);
507                 /*
508                  * Return pointer to current entry in dp->i_offset,
509                  * and distance past previous entry (if there
510                  * is a previous entry in this block) in dp->i_count.
511                  * Save directory inode pointer in ndp->ni_dvp for dirremove().
512                  *
513                  * Technically we shouldn't be setting these in the
514                  * WANTPARENT case (first lookup in rename()), but any
515                  * lookups that will result in directory changes will
516                  * overwrite these.
517                  */
518                 dp->i_offset = i_offset;
519                 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
520                         dp->i_count = 0;
521                 else
522                         dp->i_count = dp->i_offset - prevoff;
523                 if (dp->i_number == ino) {
524                         VREF(vdp);
525                         *vpp = vdp;
526                         return (0);
527                 }
528                 if ((error = VFS_VGET(vdp->v_mount, ino,
529                     LK_EXCLUSIVE, &tdp)) != 0)
530                         return (error);
531                 /*
532                  * If directory is "sticky", then user must own
533                  * the directory, or the file in it, else she
534                  * may not delete it (unless she's root). This
535                  * implements append-only directories.
536                  */
537                 if ((dp->i_mode & ISVTX) &&
538                     VOP_ACCESS(vdp, VADMIN, cred, cnp->cn_thread) &&
539                     VOP_ACCESS(tdp, VADMIN, cred, cnp->cn_thread)) {
540                         vput(tdp);
541                         return (EPERM);
542                 }
543                 *vpp = tdp;
544                 return (0);
545         }
546
547         /*
548          * If rewriting (RENAME), return the inode and the
549          * information required to rewrite the present directory
550          * Must get inode of directory entry to verify it's a
551          * regular file, or empty directory.
552          */
553         if (nameiop == RENAME && (flags & ISLASTCN)) {
554                 if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread)))
555                         return (error);
556                 /*
557                  * Careful about locking second inode.
558                  * This can only occur if the target is ".".
559                  */
560                 dp->i_offset = i_offset;
561                 if (dp->i_number == ino)
562                         return (EISDIR);
563                 if ((error = VFS_VGET(vdp->v_mount, ino,
564                     LK_EXCLUSIVE, &tdp)) != 0)
565                         return (error);
566                 *vpp = tdp;
567                 cnp->cn_flags |= SAVENAME;
568                 return (0);
569         }
570
571         /*
572          * Step through the translation in the name.  We do not `vput' the
573          * directory because we may need it again if a symbolic link
574          * is relative to the current directory.  Instead we save it
575          * unlocked as "pdp".  We must get the target inode before unlocking
576          * the directory to insure that the inode will not be removed
577          * before we get it.  We prevent deadlock by always fetching
578          * inodes from the root, moving down the directory tree. Thus
579          * when following backward pointers ".." we must unlock the
580          * parent directory before getting the requested directory.
581          * There is a potential race condition here if both the current
582          * and parent directories are removed before the VFS_VGET for the
583          * inode associated with ".." returns.  We hope that this occurs
584          * infrequently since we cannot avoid this race condition without
585          * implementing a sophisticated deadlock detection algorithm.
586          * Note also that this simple deadlock detection scheme will not
587          * work if the filesystem has any hard links other than ".."
588          * that point backwards in the directory structure.
589          */
590         pdp = vdp;
591         if (flags & ISDOTDOT) {
592                 error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
593                 if (error)
594                         return (error);
595
596                 /*
597                  * Recheck that ".." entry in the vdp directory points
598                  * to the inode we looked up before vdp lock was
599                  * dropped.
600                  */
601                 error = ufs_lookup_(pdp, NULL, cnp, &ino1);
602                 if (error) {
603                         vput(tdp);
604                         return (error);
605                 }
606                 if (ino1 != ino) {
607                         vput(tdp);
608                         goto restart;
609                 }
610
611                 *vpp = tdp;
612         } else if (dp->i_number == ino) {
613                 VREF(vdp);      /* we want ourself, ie "." */
614                 /*
615                  * When we lookup "." we still can be asked to lock it
616                  * differently.
617                  */
618                 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
619                 if (ltype != VOP_ISLOCKED(vdp)) {
620                         if (ltype == LK_EXCLUSIVE)
621                                 vn_lock(vdp, LK_UPGRADE | LK_RETRY);
622                         else /* if (ltype == LK_SHARED) */
623                                 vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
624                 }
625                 *vpp = vdp;
626         } else {
627                 error = VFS_VGET(pdp->v_mount, ino, cnp->cn_lkflags, &tdp);
628                 if (error)
629                         return (error);
630                 *vpp = tdp;
631         }
632
633         /*
634          * Insert name into cache if appropriate.
635          */
636         if (cnp->cn_flags & MAKEENTRY)
637                 cache_enter(vdp, *vpp, cnp);
638         return (0);
639 }
640
641 void
642 ufs_dirbad(ip, offset, how)
643         struct inode *ip;
644         doff_t offset;
645         char *how;
646 {
647         struct mount *mp;
648
649         mp = ITOV(ip)->v_mount;
650         if ((mp->mnt_flag & MNT_RDONLY) == 0)
651                 panic("ufs_dirbad: %s: bad dir ino %lu at offset %ld: %s",
652                     mp->mnt_stat.f_mntonname, (u_long)ip->i_number, (long)offset, how);
653         else
654                 (void)printf("%s: bad dir ino %lu at offset %ld: %s\n",
655                     mp->mnt_stat.f_mntonname, (u_long)ip->i_number, (long)offset, how);
656 }
657
658 /*
659  * Do consistency checking on a directory entry:
660  *      record length must be multiple of 4
661  *      entry must fit in rest of its DIRBLKSIZ block
662  *      record must be large enough to contain entry
663  *      name is not longer than MAXNAMLEN
664  *      name must be as long as advertised, and null terminated
665  */
666 int
667 ufs_dirbadentry(dp, ep, entryoffsetinblock)
668         struct vnode *dp;
669         struct direct *ep;
670         int entryoffsetinblock;
671 {
672         int i, namlen;
673
674 #       if (BYTE_ORDER == LITTLE_ENDIAN)
675                 if (OFSFMT(dp))
676                         namlen = ep->d_type;
677                 else
678                         namlen = ep->d_namlen;
679 #       else
680                 namlen = ep->d_namlen;
681 #       endif
682         if ((ep->d_reclen & 0x3) != 0 ||
683             ep->d_reclen > DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
684             ep->d_reclen < DIRSIZ(OFSFMT(dp), ep) || namlen > MAXNAMLEN) {
685                 /*return (1); */
686                 printf("First bad\n");
687                 goto bad;
688         }
689         if (ep->d_ino == 0)
690                 return (0);
691         for (i = 0; i < namlen; i++)
692                 if (ep->d_name[i] == '\0') {
693                         /*return (1); */
694                         printf("Second bad\n");
695                         goto bad;
696                 }
697         if (ep->d_name[i])
698                 goto bad;
699         return (0);
700 bad:
701         return (1);
702 }
703
704 /*
705  * Construct a new directory entry after a call to namei, using the
706  * parameters that it left in the componentname argument cnp. The
707  * argument ip is the inode to which the new directory entry will refer.
708  */
709 void
710 ufs_makedirentry(ip, cnp, newdirp)
711         struct inode *ip;
712         struct componentname *cnp;
713         struct direct *newdirp;
714 {
715
716 #ifdef INVARIANTS
717         if ((cnp->cn_flags & SAVENAME) == 0)
718                 panic("ufs_makedirentry: missing name");
719 #endif
720         newdirp->d_ino = ip->i_number;
721         newdirp->d_namlen = cnp->cn_namelen;
722         bcopy(cnp->cn_nameptr, newdirp->d_name, (unsigned)cnp->cn_namelen + 1);
723         if (ITOV(ip)->v_mount->mnt_maxsymlinklen > 0)
724                 newdirp->d_type = IFTODT(ip->i_mode);
725         else {
726                 newdirp->d_type = 0;
727 #               if (BYTE_ORDER == LITTLE_ENDIAN)
728                         { u_char tmp = newdirp->d_namlen;
729                         newdirp->d_namlen = newdirp->d_type;
730                         newdirp->d_type = tmp; }
731 #               endif
732         }
733 }
734
735 /*
736  * Write a directory entry after a call to namei, using the parameters
737  * that it left in nameidata. The argument dirp is the new directory
738  * entry contents. Dvp is a pointer to the directory to be written,
739  * which was left locked by namei. Remaining parameters (dp->i_offset, 
740  * dp->i_count) indicate how the space for the new entry is to be obtained.
741  * Non-null bp indicates that a directory is being created (for the
742  * soft dependency code).
743  */
744 int
745 ufs_direnter(dvp, tvp, dirp, cnp, newdirbp)
746         struct vnode *dvp;
747         struct vnode *tvp;
748         struct direct *dirp;
749         struct componentname *cnp;
750         struct buf *newdirbp;
751 {
752         struct ucred *cr;
753         struct thread *td;
754         int newentrysize;
755         struct inode *dp;
756         struct buf *bp;
757         u_int dsize;
758         struct direct *ep, *nep;
759         int error, ret, blkoff, loc, spacefree, flags, namlen;
760         char *dirbuf;
761
762         td = curthread; /* XXX */
763         cr = td->td_ucred;
764
765         dp = VTOI(dvp);
766         newentrysize = DIRSIZ(OFSFMT(dvp), dirp);
767
768         if (dp->i_count == 0) {
769                 /*
770                  * If dp->i_count is 0, then namei could find no
771                  * space in the directory. Here, dp->i_offset will
772                  * be on a directory block boundary and we will write the
773                  * new entry into a fresh block.
774                  */
775                 if (dp->i_offset & (DIRBLKSIZ - 1))
776                         panic("ufs_direnter: newblk");
777                 flags = BA_CLRBUF;
778                 if (!DOINGSOFTDEP(dvp) && !DOINGASYNC(dvp))
779                         flags |= IO_SYNC;
780 #ifdef QUOTA
781                 if ((error = getinoquota(dp)) != 0) {
782                         if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
783                                 bdwrite(newdirbp);
784                         return (error);
785                 }
786 #endif
787                 if ((error = UFS_BALLOC(dvp, (off_t)dp->i_offset, DIRBLKSIZ,
788                     cr, flags, &bp)) != 0) {
789                         if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
790                                 bdwrite(newdirbp);
791                         return (error);
792                 }
793                 dp->i_size = dp->i_offset + DIRBLKSIZ;
794                 DIP_SET(dp, i_size, dp->i_size);
795                 dp->i_flag |= IN_CHANGE | IN_UPDATE;
796                 vnode_pager_setsize(dvp, (u_long)dp->i_size);
797                 dirp->d_reclen = DIRBLKSIZ;
798                 blkoff = dp->i_offset &
799                     (VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_iosize - 1);
800                 bcopy((caddr_t)dirp, (caddr_t)bp->b_data + blkoff,newentrysize);
801 #ifdef UFS_DIRHASH
802                 if (dp->i_dirhash != NULL) {
803                         ufsdirhash_newblk(dp, dp->i_offset);
804                         ufsdirhash_add(dp, dirp, dp->i_offset);
805                         ufsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
806                             dp->i_offset);
807                 }
808 #endif
809                 if (DOINGSOFTDEP(dvp)) {
810                         /*
811                          * Ensure that the entire newly allocated block is a
812                          * valid directory so that future growth within the
813                          * block does not have to ensure that the block is
814                          * written before the inode.
815                          */
816                         blkoff += DIRBLKSIZ;
817                         while (blkoff < bp->b_bcount) {
818                                 ((struct direct *)
819                                    (bp->b_data + blkoff))->d_reclen = DIRBLKSIZ;
820                                 blkoff += DIRBLKSIZ;
821                         }
822                         if (softdep_setup_directory_add(bp, dp, dp->i_offset,
823                             dirp->d_ino, newdirbp, 1) == 0) {
824                                 bdwrite(bp);
825                                 return (UFS_UPDATE(dvp, 0));
826                         }
827                         /* We have just allocated a directory block in an
828                          * indirect block. Rather than tracking when it gets
829                          * claimed by the inode, we simply do a VOP_FSYNC
830                          * now to ensure that it is there (in case the user
831                          * does a future fsync). Note that we have to unlock
832                          * the inode for the entry that we just entered, as
833                          * the VOP_FSYNC may need to lock other inodes which
834                          * can lead to deadlock if we also hold a lock on
835                          * the newly entered node.
836                          */
837                         if ((error = bwrite(bp)))
838                                 return (error);
839                         if (tvp != NULL)
840                                 VOP_UNLOCK(tvp, 0);
841                         error = VOP_FSYNC(dvp, MNT_WAIT, td);
842                         if (tvp != NULL)
843                                 vn_lock(tvp, LK_EXCLUSIVE | LK_RETRY);
844                         return (error);
845                 }
846                 if (DOINGASYNC(dvp)) {
847                         bdwrite(bp);
848                         return (UFS_UPDATE(dvp, 0));
849                 }
850                 error = bwrite(bp);
851                 ret = UFS_UPDATE(dvp, 1);
852                 if (error == 0)
853                         return (ret);
854                 return (error);
855         }
856
857         /*
858          * If dp->i_count is non-zero, then namei found space for the new
859          * entry in the range dp->i_offset to dp->i_offset + dp->i_count
860          * in the directory. To use this space, we may have to compact
861          * the entries located there, by copying them together towards the
862          * beginning of the block, leaving the free space in one usable
863          * chunk at the end.
864          */
865
866         /*
867          * Increase size of directory if entry eats into new space.
868          * This should never push the size past a new multiple of
869          * DIRBLKSIZE.
870          *
871          * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
872          */
873         if (dp->i_offset + dp->i_count > dp->i_size) {
874                 dp->i_size = dp->i_offset + dp->i_count;
875                 DIP_SET(dp, i_size, dp->i_size);
876         }
877         /*
878          * Get the block containing the space for the new directory entry.
879          */
880         error = UFS_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp);
881         if (error) {
882                 if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
883                         bdwrite(newdirbp);
884                 return (error);
885         }
886         /*
887          * Find space for the new entry. In the simple case, the entry at
888          * offset base will have the space. If it does not, then namei
889          * arranged that compacting the region dp->i_offset to
890          * dp->i_offset + dp->i_count would yield the space.
891          */
892         ep = (struct direct *)dirbuf;
893         dsize = ep->d_ino ? DIRSIZ(OFSFMT(dvp), ep) : 0;
894         spacefree = ep->d_reclen - dsize;
895         for (loc = ep->d_reclen; loc < dp->i_count; ) {
896                 nep = (struct direct *)(dirbuf + loc);
897
898                 /* Trim the existing slot (NB: dsize may be zero). */
899                 ep->d_reclen = dsize;
900                 ep = (struct direct *)((char *)ep + dsize);
901
902                 /* Read nep->d_reclen now as the bcopy() may clobber it. */
903                 loc += nep->d_reclen;
904                 if (nep->d_ino == 0) {
905                         /*
906                          * A mid-block unused entry. Such entries are
907                          * never created by the kernel, but fsck_ffs
908                          * can create them (and it doesn't fix them).
909                          *
910                          * Add up the free space, and initialise the
911                          * relocated entry since we don't bcopy it.
912                          */
913                         spacefree += nep->d_reclen;
914                         ep->d_ino = 0;
915                         dsize = 0;
916                         continue;
917                 }
918                 dsize = DIRSIZ(OFSFMT(dvp), nep);
919                 spacefree += nep->d_reclen - dsize;
920 #ifdef UFS_DIRHASH
921                 if (dp->i_dirhash != NULL)
922                         ufsdirhash_move(dp, nep,
923                             dp->i_offset + ((char *)nep - dirbuf),
924                             dp->i_offset + ((char *)ep - dirbuf));
925 #endif
926                 if (DOINGSOFTDEP(dvp))
927                         softdep_change_directoryentry_offset(dp, dirbuf,
928                             (caddr_t)nep, (caddr_t)ep, dsize); 
929                 else
930                         bcopy((caddr_t)nep, (caddr_t)ep, dsize);
931         }
932         /*
933          * Here, `ep' points to a directory entry containing `dsize' in-use
934          * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
935          * then the entry is completely unused (dsize == 0). The value
936          * of ep->d_reclen is always indeterminate.
937          *
938          * Update the pointer fields in the previous entry (if any),
939          * copy in the new entry, and write out the block.
940          */
941 #       if (BYTE_ORDER == LITTLE_ENDIAN)
942                 if (OFSFMT(dvp))
943                         namlen = ep->d_type;
944                 else
945                         namlen = ep->d_namlen;
946 #       else
947                 namlen = ep->d_namlen;
948 #       endif
949         if (ep->d_ino == 0 ||
950             (ep->d_ino == WINO && namlen == dirp->d_namlen &&
951              bcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
952                 if (spacefree + dsize < newentrysize)
953                         panic("ufs_direnter: compact1");
954                 dirp->d_reclen = spacefree + dsize;
955         } else {
956                 if (spacefree < newentrysize)
957                         panic("ufs_direnter: compact2");
958                 dirp->d_reclen = spacefree;
959                 ep->d_reclen = dsize;
960                 ep = (struct direct *)((char *)ep + dsize);
961         }
962 #ifdef UFS_DIRHASH
963         if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
964             dirp->d_reclen == spacefree))
965                 ufsdirhash_add(dp, dirp, dp->i_offset + ((char *)ep - dirbuf));
966 #endif
967         bcopy((caddr_t)dirp, (caddr_t)ep, (u_int)newentrysize);
968 #ifdef UFS_DIRHASH
969         if (dp->i_dirhash != NULL)
970                 ufsdirhash_checkblock(dp, dirbuf -
971                     (dp->i_offset & (DIRBLKSIZ - 1)),
972                     dp->i_offset & ~(DIRBLKSIZ - 1));
973 #endif
974
975         if (DOINGSOFTDEP(dvp)) {
976                 (void) softdep_setup_directory_add(bp, dp,
977                     dp->i_offset + (caddr_t)ep - dirbuf,
978                     dirp->d_ino, newdirbp, 0);
979                 bdwrite(bp);
980         } else {
981                 if (DOINGASYNC(dvp)) {
982                         bdwrite(bp);
983                         error = 0;
984                 } else {
985                         error = bwrite(bp);
986                 }
987         }
988         dp->i_flag |= IN_CHANGE | IN_UPDATE;
989         /*
990          * If all went well, and the directory can be shortened, proceed
991          * with the truncation. Note that we have to unlock the inode for
992          * the entry that we just entered, as the truncation may need to
993          * lock other inodes which can lead to deadlock if we also hold a
994          * lock on the newly entered node.
995          */
996         if (error == 0 && dp->i_endoff && dp->i_endoff < dp->i_size) {
997                 if (tvp != NULL)
998                         VOP_UNLOCK(tvp, 0);
999 #ifdef UFS_DIRHASH
1000                 if (dp->i_dirhash != NULL)
1001                         ufsdirhash_dirtrunc(dp, dp->i_endoff);
1002 #endif
1003                 (void) UFS_TRUNCATE(dvp, (off_t)dp->i_endoff,
1004                     IO_NORMAL | IO_SYNC, cr, td);
1005                 if (tvp != NULL)
1006                         vn_lock(tvp, LK_EXCLUSIVE | LK_RETRY);
1007         }
1008         return (error);
1009 }
1010
1011 /*
1012  * Remove a directory entry after a call to namei, using
1013  * the parameters which it left in nameidata. The entry
1014  * dp->i_offset contains the offset into the directory of the
1015  * entry to be eliminated.  The dp->i_count field contains the
1016  * size of the previous record in the directory.  If this
1017  * is 0, the first entry is being deleted, so we need only
1018  * zero the inode number to mark the entry as free.  If the
1019  * entry is not the first in the directory, we must reclaim
1020  * the space of the now empty record by adding the record size
1021  * to the size of the previous entry.
1022  */
1023 int
1024 ufs_dirremove(dvp, ip, flags, isrmdir)
1025         struct vnode *dvp;
1026         struct inode *ip;
1027         int flags;
1028         int isrmdir;
1029 {
1030         struct inode *dp;
1031         struct direct *ep, *rep;
1032         struct buf *bp;
1033         int error;
1034
1035         dp = VTOI(dvp);
1036
1037         if (flags & DOWHITEOUT) {
1038                 /*
1039                  * Whiteout entry: set d_ino to WINO.
1040                  */
1041                 if ((error =
1042                     UFS_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
1043                         return (error);
1044                 ep->d_ino = WINO;
1045                 ep->d_type = DT_WHT;
1046                 goto out;
1047         }
1048
1049         if ((error = UFS_BLKATOFF(dvp,
1050             (off_t)(dp->i_offset - dp->i_count), (char **)&ep, &bp)) != 0)
1051                 return (error);
1052
1053         /* Set 'rep' to the entry being removed. */
1054         if (dp->i_count == 0)
1055                 rep = ep;
1056         else
1057                 rep = (struct direct *)((char *)ep + ep->d_reclen);
1058 #ifdef UFS_DIRHASH
1059         /*
1060          * Remove the dirhash entry. This is complicated by the fact
1061          * that `ep' is the previous entry when dp->i_count != 0.
1062          */
1063         if (dp->i_dirhash != NULL)
1064                 ufsdirhash_remove(dp, rep, dp->i_offset);
1065 #endif
1066         if (dp->i_count == 0) {
1067                 /*
1068                  * First entry in block: set d_ino to zero.
1069                  */
1070                 ep->d_ino = 0;
1071         } else {
1072                 /*
1073                  * Collapse new free space into previous entry.
1074                  */
1075                 ep->d_reclen += rep->d_reclen;
1076         }
1077 #ifdef UFS_DIRHASH
1078         if (dp->i_dirhash != NULL)
1079                 ufsdirhash_checkblock(dp, (char *)ep -
1080                     ((dp->i_offset - dp->i_count) & (DIRBLKSIZ - 1)),
1081                     dp->i_offset & ~(DIRBLKSIZ - 1));
1082 #endif
1083 out:
1084         if (DOINGSOFTDEP(dvp)) {
1085                 if (ip) {
1086                         ip->i_effnlink--;
1087                         softdep_change_linkcnt(ip);
1088                         softdep_setup_remove(bp, dp, ip, isrmdir);
1089                 }
1090                 if (softdep_slowdown(dvp)) {
1091                         error = bwrite(bp);
1092                 } else {
1093                         bdwrite(bp);
1094                         error = 0;
1095                 }
1096         } else {
1097                 if (ip) {
1098                         ip->i_effnlink--;
1099                         ip->i_nlink--;
1100                         DIP_SET(ip, i_nlink, ip->i_nlink);
1101                         ip->i_flag |= IN_CHANGE;
1102                 }
1103                 if (flags & DOWHITEOUT)
1104                         error = bwrite(bp);
1105                 else if (DOINGASYNC(dvp) && dp->i_count != 0) {
1106                         bdwrite(bp);
1107                         error = 0;
1108                 } else
1109                         error = bwrite(bp);
1110         }
1111         dp->i_flag |= IN_CHANGE | IN_UPDATE;
1112         /*
1113          * If the last named reference to a snapshot goes away,
1114          * drop its snapshot reference so that it will be reclaimed
1115          * when last open reference goes away.
1116          */
1117 #if defined(FFS) || defined(IFS)
1118         if (ip != 0 && (ip->i_flags & SF_SNAPSHOT) != 0 && ip->i_effnlink == 0)
1119                 ffs_snapgone(ip);
1120 #endif
1121         return (error);
1122 }
1123
1124 /*
1125  * Rewrite an existing directory entry to point at the inode
1126  * supplied.  The parameters describing the directory entry are
1127  * set up by a call to namei.
1128  */
1129 int
1130 ufs_dirrewrite(dp, oip, newinum, newtype, isrmdir)
1131         struct inode *dp, *oip;
1132         ino_t newinum;
1133         int newtype;
1134         int isrmdir;
1135 {
1136         struct buf *bp;
1137         struct direct *ep;
1138         struct vnode *vdp = ITOV(dp);
1139         int error;
1140
1141         error = UFS_BLKATOFF(vdp, (off_t)dp->i_offset, (char **)&ep, &bp);
1142         if (error)
1143                 return (error);
1144         ep->d_ino = newinum;
1145         if (!OFSFMT(vdp))
1146                 ep->d_type = newtype;
1147         oip->i_effnlink--;
1148         if (DOINGSOFTDEP(vdp)) {
1149                 softdep_change_linkcnt(oip);
1150                 softdep_setup_directory_change(bp, dp, oip, newinum, isrmdir);
1151                 bdwrite(bp);
1152         } else {
1153                 oip->i_nlink--;
1154                 DIP_SET(oip, i_nlink, oip->i_nlink);
1155                 oip->i_flag |= IN_CHANGE;
1156                 if (DOINGASYNC(vdp)) {
1157                         bdwrite(bp);
1158                         error = 0;
1159                 } else {
1160                         error = bwrite(bp);
1161                 }
1162         }
1163         dp->i_flag |= IN_CHANGE | IN_UPDATE;
1164         /*
1165          * If the last named reference to a snapshot goes away,
1166          * drop its snapshot reference so that it will be reclaimed
1167          * when last open reference goes away.
1168          */
1169 #if defined(FFS) || defined(IFS)
1170         if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_effnlink == 0)
1171                 ffs_snapgone(oip);
1172 #endif
1173         return (error);
1174 }
1175
1176 /*
1177  * Check if a directory is empty or not.
1178  * Inode supplied must be locked.
1179  *
1180  * Using a struct dirtemplate here is not precisely
1181  * what we want, but better than using a struct direct.
1182  *
1183  * NB: does not handle corrupted directories.
1184  */
1185 int
1186 ufs_dirempty(ip, parentino, cred)
1187         struct inode *ip;
1188         ino_t parentino;
1189         struct ucred *cred;
1190 {
1191         doff_t off;
1192         struct dirtemplate dbuf;
1193         struct direct *dp = (struct direct *)&dbuf;
1194         int error, count, namlen;
1195 #define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
1196
1197         for (off = 0; off < ip->i_size; off += dp->d_reclen) {
1198                 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1199                     off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1200                     NOCRED, &count, (struct thread *)0);
1201                 /*
1202                  * Since we read MINDIRSIZ, residual must
1203                  * be 0 unless we're at end of file.
1204                  */
1205                 if (error || count != 0)
1206                         return (0);
1207                 /* avoid infinite loops */
1208                 if (dp->d_reclen == 0)
1209                         return (0);
1210                 /* skip empty entries */
1211                 if (dp->d_ino == 0 || dp->d_ino == WINO)
1212                         continue;
1213                 /* accept only "." and ".." */
1214 #               if (BYTE_ORDER == LITTLE_ENDIAN)
1215                         if (OFSFMT(ITOV(ip)))
1216                                 namlen = dp->d_type;
1217                         else
1218                                 namlen = dp->d_namlen;
1219 #               else
1220                         namlen = dp->d_namlen;
1221 #               endif
1222                 if (namlen > 2)
1223                         return (0);
1224                 if (dp->d_name[0] != '.')
1225                         return (0);
1226                 /*
1227                  * At this point namlen must be 1 or 2.
1228                  * 1 implies ".", 2 implies ".." if second
1229                  * char is also "."
1230                  */
1231                 if (namlen == 1 && dp->d_ino == ip->i_number)
1232                         continue;
1233                 if (dp->d_name[1] == '.' && dp->d_ino == parentino)
1234                         continue;
1235                 return (0);
1236         }
1237         return (1);
1238 }
1239
1240 static int
1241 ufs_dir_dd_ino(struct vnode *vp, struct ucred *cred, ino_t *dd_ino)
1242 {
1243         struct dirtemplate dirbuf;
1244         int error, namlen;
1245
1246         if (vp->v_type != VDIR)
1247                 return (ENOTDIR);
1248         error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1249             sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1250             IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL, NULL);
1251         if (error != 0)
1252                 return (error);
1253 #if (BYTE_ORDER == LITTLE_ENDIAN)
1254         if (OFSFMT(vp))
1255                 namlen = dirbuf.dotdot_type;
1256         else
1257                 namlen = dirbuf.dotdot_namlen;
1258 #else
1259         namlen = dirbuf.dotdot_namlen;
1260 #endif
1261         if (namlen != 2 || dirbuf.dotdot_name[0] != '.' ||
1262             dirbuf.dotdot_name[1] != '.')
1263                 return (ENOTDIR);
1264         *dd_ino = dirbuf.dotdot_ino;
1265         return (0);
1266 }
1267
1268 /*
1269  * Check if source directory is in the path of the target directory.
1270  * Target is supplied locked, source is unlocked.
1271  * The target is always vput before returning.
1272  */
1273 int
1274 ufs_checkpath(ino_t source_ino, struct inode *target, struct ucred *cred)
1275 {
1276         struct vnode *vp, *vp1;
1277         int error;
1278         ino_t dd_ino;
1279
1280         vp = ITOV(target);
1281         if (target->i_number == source_ino) {
1282                 error = EEXIST;
1283                 goto out;
1284         }
1285         error = 0;
1286         if (target->i_number == ROOTINO)
1287                 goto out;
1288
1289         for (;;) {
1290                 error = ufs_dir_dd_ino(vp, cred, &dd_ino);
1291                 if (error != 0)
1292                         break;
1293                 if (dd_ino == source_ino) {
1294                         error = EINVAL;
1295                         break;
1296                 }
1297                 if (dd_ino == ROOTINO)
1298                         break;
1299                 error = vn_vget_ino(vp, dd_ino, LK_EXCLUSIVE, &vp1);
1300                 if (error != 0)
1301                         break;
1302                 /* Recheck that ".." still points to vp1 after relock of vp */
1303                 error = ufs_dir_dd_ino(vp, cred, &dd_ino);
1304                 if (error != 0) {
1305                         vput(vp1);
1306                         break;
1307                 }
1308                 /* Redo the check of ".." if directory was reparented */
1309                 if (dd_ino != VTOI(vp1)->i_number) {
1310                         vput(vp1);
1311                         continue;
1312                 }
1313                 vput(vp);
1314                 vp = vp1;
1315         }
1316
1317 out:
1318         if (error == ENOTDIR)
1319                 printf("checkpath: .. not a directory\n");
1320         if (vp != NULL)
1321                 vput(vp);
1322         return (error);
1323 }