]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ufs/ufs_lookup.c
THIS BRANCH IS OBSOLETE, PLEASE READ:
[FreeBSD/FreeBSD.git] / sys / ufs / ufs / ufs_lookup.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1989, 1993
5  *      The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *      @(#)ufs_lookup.c        8.15 (Berkeley) 6/16/95
37  */
38
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
41
42 #include "opt_ufs.h"
43 #include "opt_quota.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/namei.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/proc.h>
52 #include <sys/stat.h>
53 #include <sys/mount.h>
54 #include <sys/vnode.h>
55 #include <sys/sysctl.h>
56
57 #include <vm/vm.h>
58 #include <vm/vm_extern.h>
59
60 #include <ufs/ufs/extattr.h>
61 #include <ufs/ufs/quota.h>
62 #include <ufs/ufs/inode.h>
63 #include <ufs/ufs/dir.h>
64 #ifdef UFS_DIRHASH
65 #include <ufs/ufs/dirhash.h>
66 #endif
67 #include <ufs/ufs/ufsmount.h>
68 #include <ufs/ufs/ufs_extern.h>
69 #include <ufs/ffs/ffs_extern.h>
70
71 #ifdef DIAGNOSTIC
72 static int      dirchk = 1;
73 #else
74 static int      dirchk = 0;
75 #endif
76
77 SYSCTL_INT(_debug, OID_AUTO, dircheck, CTLFLAG_RW, &dirchk, 0, "");
78
79 /* true if old FS format...*/
80 #define OFSFMT(vp)      ((vp)->v_mount->mnt_maxsymlinklen <= 0)
81
82 static int
83 ufs_delete_denied(struct vnode *vdp, struct vnode *tdp, struct ucred *cred,
84     struct thread *td)
85 {
86         int error;
87
88 #ifdef UFS_ACL
89         /*
90          * NFSv4 Minor Version 1, draft-ietf-nfsv4-minorversion1-03.txt
91          *
92          * 3.16.2.1. ACE4_DELETE vs. ACE4_DELETE_CHILD
93          */
94
95         /*
96          * XXX: Is this check required?
97          */
98         error = VOP_ACCESS(vdp, VEXEC, cred, td);
99         if (error)
100                 return (error);
101
102         error = VOP_ACCESSX(tdp, VDELETE, cred, td);
103         if (error == 0)
104                 return (0);
105
106         error = VOP_ACCESSX(vdp, VDELETE_CHILD, cred, td);
107         if (error == 0)
108                 return (0);
109
110         error = VOP_ACCESSX(vdp, VEXPLICIT_DENY | VDELETE_CHILD, cred, td);
111         if (error)
112                 return (error);
113
114 #endif /* !UFS_ACL */
115
116         /*
117          * Standard Unix access control - delete access requires VWRITE.
118          */
119         error = VOP_ACCESS(vdp, VWRITE, cred, td);
120         if (error)
121                 return (error);
122
123         /*
124          * If directory is "sticky", then user must own
125          * the directory, or the file in it, else she
126          * may not delete it (unless she's root). This
127          * implements append-only directories.
128          */
129         if ((VTOI(vdp)->i_mode & ISVTX) &&
130             VOP_ACCESS(vdp, VADMIN, cred, td) &&
131             VOP_ACCESS(tdp, VADMIN, cred, td))
132                 return (EPERM);
133
134         return (0);
135 }
136
137 /*
138  * Convert a component of a pathname into a pointer to a locked inode.
139  * This is a very central and rather complicated routine.
140  * If the filesystem is not maintained in a strict tree hierarchy,
141  * this can result in a deadlock situation (see comments in code below).
142  *
143  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
144  * on whether the name is to be looked up, created, renamed, or deleted.
145  * When CREATE, RENAME, or DELETE is specified, information usable in
146  * creating, renaming, or deleting a directory entry may be calculated.
147  * If flag has LOCKPARENT or'ed into it and the target of the pathname
148  * exists, lookup returns both the target and its parent directory locked.
149  * When creating or renaming and LOCKPARENT is specified, the target may
150  * not be ".".  When deleting and LOCKPARENT is specified, the target may
151  * be "."., but the caller must check to ensure it does an vrele and vput
152  * instead of two vputs.
153  *
154  * This routine is actually used as VOP_CACHEDLOOKUP method, and the
155  * filesystem employs the generic vfs_cache_lookup() as VOP_LOOKUP
156  * method.
157  *
158  * vfs_cache_lookup() performs the following for us:
159  *      check that it is a directory
160  *      check accessibility of directory
161  *      check for modification attempts on read-only mounts
162  *      if name found in cache
163  *          if at end of path and deleting or creating
164  *              drop it
165  *           else
166  *              return name.
167  *      return VOP_CACHEDLOOKUP()
168  *
169  * Overall outline of ufs_lookup:
170  *
171  *      search for name in directory, to found or notfound
172  * notfound:
173  *      if creating, return locked directory, leaving info on available slots
174  *      else return error
175  * found:
176  *      if at end of path and deleting, return information to allow delete
177  *      if at end of path and rewriting (RENAME and LOCKPARENT), lock target
178  *        inode and return info to allow rewrite
179  *      if not at end, add name to cache; if at end and neither creating
180  *        nor deleting, add name to cache
181  */
182 int
183 ufs_lookup(ap)
184         struct vop_cachedlookup_args /* {
185                 struct vnode *a_dvp;
186                 struct vnode **a_vpp;
187                 struct componentname *a_cnp;
188         } */ *ap;
189 {
190
191         return (ufs_lookup_ino(ap->a_dvp, ap->a_vpp, ap->a_cnp, NULL));
192 }
193
194 int
195 ufs_lookup_ino(struct vnode *vdp, struct vnode **vpp, struct componentname *cnp,
196     ino_t *dd_ino)
197 {
198         struct inode *dp;               /* inode for directory being searched */
199         struct buf *bp;                 /* a buffer of directory entries */
200         struct direct *ep;              /* the current directory entry */
201         int entryoffsetinblock;         /* offset of ep in bp's buffer */
202         enum {NONE, COMPACT, FOUND} slotstatus;
203         doff_t slotoffset;              /* offset of area with free space */
204         doff_t i_diroff;                /* cached i_diroff value. */
205         doff_t i_offset;                /* cached i_offset value. */
206         int slotsize;                   /* size of area at slotoffset */
207         int slotfreespace;              /* amount of space free in slot */
208         int slotneeded;                 /* size of the entry we're seeking */
209         int numdirpasses;               /* strategy for directory search */
210         doff_t endsearch;               /* offset to end directory search */
211         doff_t prevoff;                 /* prev entry dp->i_offset */
212         struct vnode *pdp;              /* saved dp during symlink work */
213         struct vnode *tdp;              /* returned by VFS_VGET */
214         doff_t enduseful;               /* pointer past last used dir slot */
215         u_long bmask;                   /* block offset mask */
216         int namlen, error;
217         struct ucred *cred = cnp->cn_cred;
218         int flags = cnp->cn_flags;
219         int nameiop = cnp->cn_nameiop;
220         ino_t ino, ino1;
221         int ltype;
222
223         if (vpp != NULL)
224                 *vpp = NULL;
225
226         dp = VTOI(vdp);
227         if (dp->i_effnlink == 0)
228                 return (ENOENT);
229
230         /*
231          * Create a vm object if vmiodirenable is enabled.
232          * Alternatively we could call vnode_create_vobject
233          * in VFS_VGET but we could end up creating objects
234          * that are never used.
235          */
236         vnode_create_vobject(vdp, DIP(dp, i_size), cnp->cn_thread);
237
238         bmask = VFSTOUFS(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
239
240 #ifdef DEBUG_VFS_LOCKS
241         /*
242          * Assert that the directory vnode is locked, and locked
243          * exclusively for the last component lookup for modifying
244          * operations.
245          *
246          * The directory-modifying operations need to save
247          * intermediate state in the inode between namei() call and
248          * actual directory manipulations.  See fields in the struct
249          * inode marked as 'used during directory lookup'.  We must
250          * ensure that upgrade in namei() does not happen, since
251          * upgrade might need to unlock vdp.  If quotas are enabled,
252          * getinoquota() also requires exclusive lock to modify inode.
253          */
254         ASSERT_VOP_LOCKED(vdp, "ufs_lookup1");
255         if ((nameiop == CREATE || nameiop == DELETE || nameiop == RENAME) &&
256             (flags & (LOCKPARENT | ISLASTCN)) == (LOCKPARENT | ISLASTCN))
257                 ASSERT_VOP_ELOCKED(vdp, "ufs_lookup2");
258 #endif
259
260 restart:
261         bp = NULL;
262         slotoffset = -1;
263
264         /*
265          * We now have a segment name to search for, and a directory to search.
266          *
267          * Suppress search for slots unless creating
268          * file and at end of pathname, in which case
269          * we watch for a place to put the new file in
270          * case it doesn't already exist.
271          */
272         ino = 0;
273         i_diroff = dp->i_diroff;
274         slotstatus = FOUND;
275         slotfreespace = slotsize = slotneeded = 0;
276         if ((nameiop == CREATE || nameiop == RENAME) &&
277             (flags & ISLASTCN)) {
278                 slotstatus = NONE;
279                 slotneeded = DIRECTSIZ(cnp->cn_namelen);
280         }
281
282 #ifdef UFS_DIRHASH
283         /*
284          * Use dirhash for fast operations on large directories. The logic
285          * to determine whether to hash the directory is contained within
286          * ufsdirhash_build(); a zero return means that it decided to hash
287          * this directory and it successfully built up the hash table.
288          */
289         if (ufsdirhash_build(dp) == 0) {
290                 /* Look for a free slot if needed. */
291                 enduseful = dp->i_size;
292                 if (slotstatus != FOUND) {
293                         slotoffset = ufsdirhash_findfree(dp, slotneeded,
294                             &slotsize);
295                         if (slotoffset >= 0) {
296                                 slotstatus = COMPACT;
297                                 enduseful = ufsdirhash_enduseful(dp);
298                                 if (enduseful < 0)
299                                         enduseful = dp->i_size;
300                         }
301                 }
302                 /* Look up the component. */
303                 numdirpasses = 1;
304                 entryoffsetinblock = 0; /* silence compiler warning */
305                 switch (ufsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
306                     &i_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
307                 case 0:
308                         ep = (struct direct *)((char *)bp->b_data +
309                             (i_offset & bmask));
310                         goto foundentry;
311                 case ENOENT:
312                         i_offset = roundup2(dp->i_size, DIRBLKSIZ);
313                         goto notfound;
314                 default:
315                         /* Something failed; just do a linear search. */
316                         break;
317                 }
318         }
319 #endif /* UFS_DIRHASH */
320         /*
321          * If there is cached information on a previous search of
322          * this directory, pick up where we last left off.
323          * We cache only lookups as these are the most common
324          * and have the greatest payoff. Caching CREATE has little
325          * benefit as it usually must search the entire directory
326          * to determine that the entry does not exist. Caching the
327          * location of the last DELETE or RENAME has not reduced
328          * profiling time and hence has been removed in the interest
329          * of simplicity.
330          */
331         if (nameiop != LOOKUP || i_diroff == 0 || i_diroff >= dp->i_size) {
332                 entryoffsetinblock = 0;
333                 i_offset = 0;
334                 numdirpasses = 1;
335         } else {
336                 i_offset = i_diroff;
337                 if ((entryoffsetinblock = i_offset & bmask) &&
338                     (error = UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp)))
339                         return (error);
340                 numdirpasses = 2;
341                 nchstats.ncs_2passes++;
342         }
343         prevoff = i_offset;
344         endsearch = roundup2(dp->i_size, DIRBLKSIZ);
345         enduseful = 0;
346
347 searchloop:
348         while (i_offset < endsearch) {
349                 /*
350                  * If necessary, get the next directory block.
351                  */
352                 if ((i_offset & bmask) == 0) {
353                         if (bp != NULL)
354                                 brelse(bp);
355                         error =
356                             UFS_BLKATOFF(vdp, (off_t)i_offset, NULL, &bp);
357                         if (error)
358                                 return (error);
359                         entryoffsetinblock = 0;
360                 }
361                 /*
362                  * If still looking for a slot, and at a DIRBLKSIZE
363                  * boundary, have to start looking for free space again.
364                  */
365                 if (slotstatus == NONE &&
366                     (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
367                         slotoffset = -1;
368                         slotfreespace = 0;
369                 }
370                 /*
371                  * Get pointer to next entry.
372                  * Full validation checks are slow, so we only check
373                  * enough to insure forward progress through the
374                  * directory. Complete checks can be run by patching
375                  * "dirchk" to be true.
376                  */
377                 ep = (struct direct *)((char *)bp->b_data + entryoffsetinblock);
378                 if (ep->d_reclen == 0 || ep->d_reclen >
379                     DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
380                     (dirchk && ufs_dirbadentry(vdp, ep, entryoffsetinblock))) {
381                         int i;
382
383                         ufs_dirbad(dp, i_offset, "mangled entry");
384                         i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
385                         i_offset += i;
386                         entryoffsetinblock += i;
387                         continue;
388                 }
389
390                 /*
391                  * If an appropriate sized slot has not yet been found,
392                  * check to see if one is available. Also accumulate space
393                  * in the current block so that we can determine if
394                  * compaction is viable.
395                  */
396                 if (slotstatus != FOUND) {
397                         int size = ep->d_reclen;
398
399                         if (ep->d_ino != 0)
400                                 size -= DIRSIZ(OFSFMT(vdp), ep);
401                         if (size > 0) {
402                                 if (size >= slotneeded) {
403                                         slotstatus = FOUND;
404                                         slotoffset = i_offset;
405                                         slotsize = ep->d_reclen;
406                                 } else if (slotstatus == NONE) {
407                                         slotfreespace += size;
408                                         if (slotoffset == -1)
409                                                 slotoffset = i_offset;
410                                         if (slotfreespace >= slotneeded) {
411                                                 slotstatus = COMPACT;
412                                                 slotsize = i_offset +
413                                                       ep->d_reclen - slotoffset;
414                                         }
415                                 }
416                         }
417                 }
418
419                 /*
420                  * Check for a name match.
421                  */
422                 if (ep->d_ino) {
423 #                       if (BYTE_ORDER == LITTLE_ENDIAN)
424                                 if (OFSFMT(vdp))
425                                         namlen = ep->d_type;
426                                 else
427                                         namlen = ep->d_namlen;
428 #                       else
429                                 namlen = ep->d_namlen;
430 #                       endif
431                         if (namlen == cnp->cn_namelen &&
432                                 (cnp->cn_nameptr[0] == ep->d_name[0]) &&
433                             !bcmp(cnp->cn_nameptr, ep->d_name,
434                                 (unsigned)namlen)) {
435 #ifdef UFS_DIRHASH
436 foundentry:
437 #endif
438                                 /*
439                                  * Save directory entry's inode number and
440                                  * reclen in ndp->ni_ufs area, and release
441                                  * directory buffer.
442                                  */
443                                 if (vdp->v_mount->mnt_maxsymlinklen > 0 &&
444                                     ep->d_type == DT_WHT) {
445                                         slotstatus = FOUND;
446                                         slotoffset = i_offset;
447                                         slotsize = ep->d_reclen;
448                                         enduseful = dp->i_size;
449                                         cnp->cn_flags |= ISWHITEOUT;
450                                         numdirpasses--;
451                                         goto notfound;
452                                 }
453                                 ino = ep->d_ino;
454                                 goto found;
455                         }
456                 }
457                 prevoff = i_offset;
458                 i_offset += ep->d_reclen;
459                 entryoffsetinblock += ep->d_reclen;
460                 if (ep->d_ino)
461                         enduseful = i_offset;
462         }
463 notfound:
464         /*
465          * If we started in the middle of the directory and failed
466          * to find our target, we must check the beginning as well.
467          */
468         if (numdirpasses == 2) {
469                 numdirpasses--;
470                 i_offset = 0;
471                 endsearch = i_diroff;
472                 goto searchloop;
473         }
474         if (bp != NULL)
475                 brelse(bp);
476         /*
477          * If creating, and at end of pathname and current
478          * directory has not been removed, then can consider
479          * allowing file to be created.
480          */
481         if ((nameiop == CREATE || nameiop == RENAME ||
482              (nameiop == DELETE &&
483               (cnp->cn_flags & DOWHITEOUT) &&
484               (cnp->cn_flags & ISWHITEOUT))) &&
485             (flags & ISLASTCN) && dp->i_effnlink != 0) {
486                 /*
487                  * Access for write is interpreted as allowing
488                  * creation of files in the directory.
489                  *
490                  * XXX: Fix the comment above.
491                  */
492                 if (flags & WILLBEDIR)
493                         error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
494                 else
495                         error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
496                 if (error)
497                         return (error);
498                 /*
499                  * Return an indication of where the new directory
500                  * entry should be put.  If we didn't find a slot,
501                  * then set dp->i_count to 0 indicating
502                  * that the new slot belongs at the end of the
503                  * directory. If we found a slot, then the new entry
504                  * can be put in the range from dp->i_offset to
505                  * dp->i_offset + dp->i_count.
506                  */
507                 if (slotstatus == NONE) {
508                         SET_I_OFFSET(dp, roundup2(dp->i_size, DIRBLKSIZ));
509                         SET_I_COUNT(dp, 0);
510                         enduseful = I_OFFSET(dp);
511                 } else if (nameiop == DELETE) {
512                         SET_I_OFFSET(dp, slotoffset);
513                         if ((I_OFFSET(dp) & (DIRBLKSIZ - 1)) == 0)
514                                 SET_I_COUNT(dp, 0);
515                         else
516                                 SET_I_COUNT(dp, I_OFFSET(dp) - prevoff);
517                 } else {
518                         SET_I_OFFSET(dp, slotoffset);
519                         SET_I_COUNT(dp, slotsize);
520                         if (enduseful < slotoffset + slotsize)
521                                 enduseful = slotoffset + slotsize;
522                 }
523                 SET_I_ENDOFF(dp, roundup2(enduseful, DIRBLKSIZ));
524                 /*
525                  * We return with the directory locked, so that
526                  * the parameters we set up above will still be
527                  * valid if we actually decide to do a direnter().
528                  * We return ni_vp == NULL to indicate that the entry
529                  * does not currently exist; we leave a pointer to
530                  * the (locked) directory inode in ndp->ni_dvp.
531                  * The pathname buffer is saved so that the name
532                  * can be obtained later.
533                  *
534                  * NB - if the directory is unlocked, then this
535                  * information cannot be used.
536                  */
537                 cnp->cn_flags |= SAVENAME;
538                 return (EJUSTRETURN);
539         }
540         /*
541          * Insert name into cache (as non-existent) if appropriate.
542          */
543         if ((cnp->cn_flags & MAKEENTRY) != 0)
544                 cache_enter(vdp, NULL, cnp);
545         return (ENOENT);
546
547 found:
548         if (dd_ino != NULL)
549                 *dd_ino = ino;
550         if (numdirpasses == 2)
551                 nchstats.ncs_pass2++;
552         /*
553          * Check that directory length properly reflects presence
554          * of this entry.
555          */
556         if (i_offset + DIRSIZ(OFSFMT(vdp), ep) > dp->i_size) {
557                 ufs_dirbad(dp, i_offset, "i_size too small");
558                 dp->i_size = i_offset + DIRSIZ(OFSFMT(vdp), ep);
559                 DIP_SET(dp, i_size, dp->i_size);
560                 UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
561         }
562         brelse(bp);
563
564         /*
565          * Found component in pathname.
566          * If the final component of path name, save information
567          * in the cache as to where the entry was found.
568          */
569         if ((flags & ISLASTCN) && nameiop == LOOKUP)
570                 dp->i_diroff = rounddown2(i_offset, DIRBLKSIZ);
571
572         /*
573          * If deleting, and at end of pathname, return
574          * parameters which can be used to remove file.
575          */
576         if (nameiop == DELETE && (flags & ISLASTCN)) {
577                 if (flags & LOCKPARENT)
578                         ASSERT_VOP_ELOCKED(vdp, __FUNCTION__);
579
580                 if (VOP_ISLOCKED(vdp) == LK_EXCLUSIVE) {
581                         /*
582                          * Return pointer to current entry in
583                          * dp->i_offset, and distance past previous
584                          * entry (if there is a previous entry in this
585                          * block) in dp->i_count.
586                          *
587                          * We shouldn't be setting these in the
588                          * WANTPARENT case (first lookup in rename()), but any
589                          * lookups that will result in directory changes will
590                          * overwrite these.
591                          */
592                         SET_I_OFFSET(dp, i_offset);
593                         if ((I_OFFSET(dp) & (DIRBLKSIZ - 1)) == 0)
594                                 SET_I_COUNT(dp, 0);
595                         else
596                                 SET_I_COUNT(dp, I_OFFSET(dp) - prevoff);
597                 }
598                 if (dd_ino != NULL)
599                         return (0);
600
601                 /*
602                  * Save directory inode pointer in ndp->ni_dvp for
603                  * dirremove().
604                  */
605                 if ((error = VFS_VGET(vdp->v_mount, ino,
606                     LK_EXCLUSIVE, &tdp)) != 0)
607                         return (error);
608                 error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
609                 if (error) {
610                         vput(tdp);
611                         return (error);
612                 }
613                 if (dp->i_number == ino) {
614                         VREF(vdp);
615                         *vpp = vdp;
616                         vput(tdp);
617                         return (0);
618                 }
619
620                 *vpp = tdp;
621                 return (0);
622         }
623
624         /*
625          * If rewriting (RENAME), return the inode and the
626          * information required to rewrite the present directory
627          * Must get inode of directory entry to verify it's a
628          * regular file, or empty directory.
629          */
630         if (nameiop == RENAME && (flags & ISLASTCN)) {
631                 if (flags & WILLBEDIR)
632                         error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
633                 else
634                         error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
635                 if (error)
636                         return (error);
637                 /*
638                  * Careful about locking second inode.
639                  * This can only occur if the target is ".".
640                  */
641                 SET_I_OFFSET(dp, i_offset);
642                 if (dp->i_number == ino)
643                         return (EISDIR);
644                 if (dd_ino != NULL)
645                         return (0);
646                 if ((error = VFS_VGET(vdp->v_mount, ino,
647                     LK_EXCLUSIVE, &tdp)) != 0)
648                         return (error);
649
650                 error = ufs_delete_denied(vdp, tdp, cred, cnp->cn_thread);
651                 if (error) {
652                         vput(tdp);
653                         return (error);
654                 }
655
656 #ifdef SunOS_doesnt_do_that
657                 /*
658                  * The only purpose of this check is to return the correct
659                  * error.  Assume that we want to rename directory "a"
660                  * to a file "b", and that we have no ACL_WRITE_DATA on
661                  * a containing directory, but we _do_ have ACL_APPEND_DATA. 
662                  * In that case, the VOP_ACCESS check above will return 0,
663                  * and the operation will fail with ENOTDIR instead
664                  * of EACCESS.
665                  */
666                 if (tdp->v_type == VDIR)
667                         error = VOP_ACCESSX(vdp, VWRITE | VAPPEND, cred, cnp->cn_thread);
668                 else
669                         error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_thread);
670                 if (error) {
671                         vput(tdp);
672                         return (error);
673                 }
674 #endif
675
676                 *vpp = tdp;
677                 cnp->cn_flags |= SAVENAME;
678                 return (0);
679         }
680         if (dd_ino != NULL)
681                 return (0);
682
683         /*
684          * Step through the translation in the name.  We do not `vput' the
685          * directory because we may need it again if a symbolic link
686          * is relative to the current directory.  Instead we save it
687          * unlocked as "pdp".  We must get the target inode before unlocking
688          * the directory to insure that the inode will not be removed
689          * before we get it.  We prevent deadlock by always fetching
690          * inodes from the root, moving down the directory tree. Thus
691          * when following backward pointers ".." we must unlock the
692          * parent directory before getting the requested directory.
693          * There is a potential race condition here if both the current
694          * and parent directories are removed before the VFS_VGET for the
695          * inode associated with ".." returns.  We hope that this occurs
696          * infrequently since we cannot avoid this race condition without
697          * implementing a sophisticated deadlock detection algorithm.
698          * Note also that this simple deadlock detection scheme will not
699          * work if the filesystem has any hard links other than ".."
700          * that point backwards in the directory structure.
701          */
702         pdp = vdp;
703         if (flags & ISDOTDOT) {
704                 error = vn_vget_ino(pdp, ino, cnp->cn_lkflags, &tdp);
705                 if (error)
706                         return (error);
707
708                 /*
709                  * Recheck that ".." entry in the vdp directory points
710                  * to the inode we looked up before vdp lock was
711                  * dropped.
712                  */
713                 error = ufs_lookup_ino(pdp, NULL, cnp, &ino1);
714                 if (error) {
715                         vput(tdp);
716                         return (error);
717                 }
718                 if (ino1 != ino) {
719                         vput(tdp);
720                         goto restart;
721                 }
722
723                 *vpp = tdp;
724         } else if (dp->i_number == ino) {
725                 VREF(vdp);      /* we want ourself, ie "." */
726                 /*
727                  * When we lookup "." we still can be asked to lock it
728                  * differently.
729                  */
730                 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
731                 if (ltype != VOP_ISLOCKED(vdp)) {
732                         if (ltype == LK_EXCLUSIVE)
733                                 vn_lock(vdp, LK_UPGRADE | LK_RETRY);
734                         else /* if (ltype == LK_SHARED) */
735                                 vn_lock(vdp, LK_DOWNGRADE | LK_RETRY);
736                         /*
737                          * Relock for the "." case may left us with
738                          * reclaimed vnode.
739                          */
740                         if (VN_IS_DOOMED(vdp)) {
741                                 vrele(vdp);
742                                 return (ENOENT);
743                         }
744                 }
745                 *vpp = vdp;
746         } else {
747                 error = VFS_VGET(pdp->v_mount, ino, cnp->cn_lkflags, &tdp);
748                 if (error == 0 && VTOI(tdp)->i_mode == 0) {
749                         vgone(tdp);
750                         vput(tdp);
751                         error = ENOENT;
752                 }
753                 if (error)
754                         return (error);
755                 *vpp = tdp;
756         }
757
758         /*
759          * Insert name into cache if appropriate.
760          */
761         if (cnp->cn_flags & MAKEENTRY)
762                 cache_enter(vdp, *vpp, cnp);
763         return (0);
764 }
765
766 void
767 ufs_dirbad(ip, offset, how)
768         struct inode *ip;
769         doff_t offset;
770         char *how;
771 {
772         struct mount *mp;
773
774         mp = ITOV(ip)->v_mount;
775         if ((mp->mnt_flag & MNT_RDONLY) == 0)
776                 panic("ufs_dirbad: %s: bad dir ino %ju at offset %ld: %s",
777                     mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
778                     (long)offset, how);
779         else
780                 (void)printf("%s: bad dir ino %ju at offset %ld: %s\n",
781                     mp->mnt_stat.f_mntonname, (uintmax_t)ip->i_number,
782                     (long)offset, how);
783 }
784
785 /*
786  * Do consistency checking on a directory entry:
787  *      record length must be multiple of 4
788  *      entry must fit in rest of its DIRBLKSIZ block
789  *      record must be large enough to contain entry
790  *      name is not longer than UFS_MAXNAMLEN
791  *      name must be as long as advertised, and null terminated
792  */
793 int
794 ufs_dirbadentry(dp, ep, entryoffsetinblock)
795         struct vnode *dp;
796         struct direct *ep;
797         int entryoffsetinblock;
798 {
799         int i, namlen;
800
801 #       if (BYTE_ORDER == LITTLE_ENDIAN)
802                 if (OFSFMT(dp))
803                         namlen = ep->d_type;
804                 else
805                         namlen = ep->d_namlen;
806 #       else
807                 namlen = ep->d_namlen;
808 #       endif
809         if ((ep->d_reclen & 0x3) != 0 ||
810             ep->d_reclen > DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1)) ||
811             ep->d_reclen < DIRSIZ(OFSFMT(dp), ep) || namlen > UFS_MAXNAMLEN) {
812                 /*return (1); */
813                 printf("First bad\n");
814                 goto bad;
815         }
816         if (ep->d_ino == 0)
817                 return (0);
818         for (i = 0; i < namlen; i++)
819                 if (ep->d_name[i] == '\0') {
820                         /*return (1); */
821                         printf("Second bad\n");
822                         goto bad;
823                 }
824         if (ep->d_name[i])
825                 goto bad;
826         return (0);
827 bad:
828         return (1);
829 }
830
831 /*
832  * Construct a new directory entry after a call to namei, using the
833  * parameters that it left in the componentname argument cnp. The
834  * argument ip is the inode to which the new directory entry will refer.
835  */
836 void
837 ufs_makedirentry(ip, cnp, newdirp)
838         struct inode *ip;
839         struct componentname *cnp;
840         struct direct *newdirp;
841 {
842         u_int namelen;
843
844         namelen = (unsigned)cnp->cn_namelen;
845         KASSERT((cnp->cn_flags & SAVENAME) != 0,
846                 ("ufs_makedirentry: missing name"));
847         KASSERT(namelen <= UFS_MAXNAMLEN,
848                 ("ufs_makedirentry: name too long"));
849         newdirp->d_ino = ip->i_number;
850         newdirp->d_namlen = namelen;
851
852         /* Zero out after-name padding */
853         *(u_int32_t *)(&newdirp->d_name[namelen & ~(DIR_ROUNDUP - 1)]) = 0;
854
855         bcopy(cnp->cn_nameptr, newdirp->d_name, namelen);
856
857         if (ITOV(ip)->v_mount->mnt_maxsymlinklen > 0)
858                 newdirp->d_type = IFTODT(ip->i_mode);
859         else {
860                 newdirp->d_type = 0;
861 #               if (BYTE_ORDER == LITTLE_ENDIAN)
862                         { u_char tmp = newdirp->d_namlen;
863                         newdirp->d_namlen = newdirp->d_type;
864                         newdirp->d_type = tmp; }
865 #               endif
866         }
867 }
868
869 /*
870  * Write a directory entry after a call to namei, using the parameters
871  * that it left in nameidata. The argument dirp is the new directory
872  * entry contents. Dvp is a pointer to the directory to be written,
873  * which was left locked by namei. Remaining parameters (dp->i_offset, 
874  * dp->i_count) indicate how the space for the new entry is to be obtained.
875  * Non-null bp indicates that a directory is being created (for the
876  * soft dependency code).
877  */
878 int
879 ufs_direnter(dvp, tvp, dirp, cnp, newdirbp, isrename)
880         struct vnode *dvp;
881         struct vnode *tvp;
882         struct direct *dirp;
883         struct componentname *cnp;
884         struct buf *newdirbp;
885         int isrename;
886 {
887         struct ucred *cr;
888         struct thread *td;
889         int newentrysize;
890         struct inode *dp;
891         struct buf *bp;
892         u_int dsize;
893         struct direct *ep, *nep;
894         u_int64_t old_isize;
895         int error, ret, blkoff, loc, spacefree, flags, namlen;
896         char *dirbuf;
897
898         td = curthread; /* XXX */
899         cr = td->td_ucred;
900
901         dp = VTOI(dvp);
902         newentrysize = DIRSIZ(OFSFMT(dvp), dirp);
903
904         if (I_COUNT(dp) == 0) {
905                 /*
906                  * If dp->i_count is 0, then namei could find no
907                  * space in the directory. Here, dp->i_offset will
908                  * be on a directory block boundary and we will write the
909                  * new entry into a fresh block.
910                  */
911                 if (I_OFFSET(dp) & (DIRBLKSIZ - 1))
912                         panic("ufs_direnter: newblk");
913                 flags = BA_CLRBUF;
914                 if (!DOINGSOFTDEP(dvp) && !DOINGASYNC(dvp))
915                         flags |= IO_SYNC;
916 #ifdef QUOTA
917                 if ((error = getinoquota(dp)) != 0) {
918                         if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
919                                 bdwrite(newdirbp);
920                         return (error);
921                 }
922 #endif
923                 old_isize = dp->i_size;
924                 vnode_pager_setsize(dvp, (u_long)I_OFFSET(dp) + DIRBLKSIZ);
925                 if ((error = UFS_BALLOC(dvp, (off_t)I_OFFSET(dp), DIRBLKSIZ,
926                     cr, flags, &bp)) != 0) {
927                         if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
928                                 bdwrite(newdirbp);
929                         vnode_pager_setsize(dvp, (u_long)old_isize);
930                         return (error);
931                 }
932                 dp->i_size = I_OFFSET(dp) + DIRBLKSIZ;
933                 DIP_SET(dp, i_size, dp->i_size);
934                 SET_I_ENDOFF(dp, dp->i_size);
935                 UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
936                 dirp->d_reclen = DIRBLKSIZ;
937                 blkoff = I_OFFSET(dp) &
938                     (VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_iosize - 1);
939                 bcopy((caddr_t)dirp, (caddr_t)bp->b_data + blkoff,newentrysize);
940 #ifdef UFS_DIRHASH
941                 if (dp->i_dirhash != NULL) {
942                         ufsdirhash_newblk(dp, I_OFFSET(dp));
943                         ufsdirhash_add(dp, dirp, I_OFFSET(dp));
944                         ufsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
945                             I_OFFSET(dp));
946                 }
947 #endif
948                 if (DOINGSOFTDEP(dvp)) {
949                         /*
950                          * Ensure that the entire newly allocated block is a
951                          * valid directory so that future growth within the
952                          * block does not have to ensure that the block is
953                          * written before the inode.
954                          */
955                         blkoff += DIRBLKSIZ;
956                         while (blkoff < bp->b_bcount) {
957                                 ((struct direct *)
958                                    (bp->b_data + blkoff))->d_reclen = DIRBLKSIZ;
959                                 blkoff += DIRBLKSIZ;
960                         }
961                         if (softdep_setup_directory_add(bp, dp, I_OFFSET(dp),
962                             dirp->d_ino, newdirbp, 1))
963                                 UFS_INODE_SET_FLAG(dp, IN_NEEDSYNC);
964                         if (newdirbp)
965                                 bdwrite(newdirbp);
966                         bdwrite(bp);
967                         if ((dp->i_flag & IN_NEEDSYNC) == 0)
968                                 return (UFS_UPDATE(dvp, 0));
969                         return (0);
970                 }
971                 if (DOINGASYNC(dvp)) {
972                         bdwrite(bp);
973                         return (UFS_UPDATE(dvp, 0));
974                 }
975                 error = bwrite(bp);
976                 ret = UFS_UPDATE(dvp, 1);
977                 if (error == 0)
978                         return (ret);
979                 return (error);
980         }
981
982         /*
983          * If dp->i_count is non-zero, then namei found space for the new
984          * entry in the range dp->i_offset to dp->i_offset + dp->i_count
985          * in the directory. To use this space, we may have to compact
986          * the entries located there, by copying them together towards the
987          * beginning of the block, leaving the free space in one usable
988          * chunk at the end.
989          */
990
991         /*
992          * Increase size of directory if entry eats into new space.
993          * This should never push the size past a new multiple of
994          * DIRBLKSIZE.
995          *
996          * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
997          */
998         if (I_OFFSET(dp) + I_COUNT(dp) > dp->i_size) {
999                 dp->i_size = I_OFFSET(dp) + I_COUNT(dp);
1000                 DIP_SET(dp, i_size, dp->i_size);
1001                 UFS_INODE_SET_FLAG(dp, IN_SIZEMOD | IN_MODIFIED);
1002         }
1003         /*
1004          * Get the block containing the space for the new directory entry.
1005          */
1006         error = UFS_BLKATOFF(dvp, (off_t)I_OFFSET(dp), &dirbuf, &bp);
1007         if (error) {
1008                 if (DOINGSOFTDEP(dvp) && newdirbp != NULL)
1009                         bdwrite(newdirbp);
1010                 return (error);
1011         }
1012         /*
1013          * Find space for the new entry. In the simple case, the entry at
1014          * offset base will have the space. If it does not, then namei
1015          * arranged that compacting the region dp->i_offset to
1016          * dp->i_offset + dp->i_count would yield the space.
1017          */
1018         ep = (struct direct *)dirbuf;
1019         dsize = ep->d_ino ? DIRSIZ(OFSFMT(dvp), ep) : 0;
1020         spacefree = ep->d_reclen - dsize;
1021         for (loc = ep->d_reclen; loc < I_COUNT(dp); ) {
1022                 nep = (struct direct *)(dirbuf + loc);
1023
1024                 /* Trim the existing slot (NB: dsize may be zero). */
1025                 ep->d_reclen = dsize;
1026                 ep = (struct direct *)((char *)ep + dsize);
1027
1028                 /* Read nep->d_reclen now as the bcopy() may clobber it. */
1029                 loc += nep->d_reclen;
1030                 if (nep->d_ino == 0) {
1031                         /*
1032                          * A mid-block unused entry. Such entries are
1033                          * never created by the kernel, but fsck_ffs
1034                          * can create them (and it doesn't fix them).
1035                          *
1036                          * Add up the free space, and initialise the
1037                          * relocated entry since we don't bcopy it.
1038                          */
1039                         spacefree += nep->d_reclen;
1040                         ep->d_ino = 0;
1041                         dsize = 0;
1042                         continue;
1043                 }
1044                 dsize = DIRSIZ(OFSFMT(dvp), nep);
1045                 spacefree += nep->d_reclen - dsize;
1046 #ifdef UFS_DIRHASH
1047                 if (dp->i_dirhash != NULL)
1048                         ufsdirhash_move(dp, nep,
1049                             I_OFFSET(dp) + ((char *)nep - dirbuf),
1050                             I_OFFSET(dp) + ((char *)ep - dirbuf));
1051 #endif
1052                 if (DOINGSOFTDEP(dvp))
1053                         softdep_change_directoryentry_offset(bp, dp, dirbuf,
1054                             (caddr_t)nep, (caddr_t)ep, dsize); 
1055                 else
1056                         bcopy((caddr_t)nep, (caddr_t)ep, dsize);
1057         }
1058         /*
1059          * Here, `ep' points to a directory entry containing `dsize' in-use
1060          * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
1061          * then the entry is completely unused (dsize == 0). The value
1062          * of ep->d_reclen is always indeterminate.
1063          *
1064          * Update the pointer fields in the previous entry (if any),
1065          * copy in the new entry, and write out the block.
1066          */
1067 #       if (BYTE_ORDER == LITTLE_ENDIAN)
1068                 if (OFSFMT(dvp))
1069                         namlen = ep->d_type;
1070                 else
1071                         namlen = ep->d_namlen;
1072 #       else
1073                 namlen = ep->d_namlen;
1074 #       endif
1075         if (ep->d_ino == 0 ||
1076             (ep->d_ino == UFS_WINO && namlen == dirp->d_namlen &&
1077              bcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
1078                 if (spacefree + dsize < newentrysize)
1079                         panic("ufs_direnter: compact1");
1080                 dirp->d_reclen = spacefree + dsize;
1081         } else {
1082                 if (spacefree < newentrysize)
1083                         panic("ufs_direnter: compact2");
1084                 dirp->d_reclen = spacefree;
1085                 ep->d_reclen = dsize;
1086                 ep = (struct direct *)((char *)ep + dsize);
1087         }
1088 #ifdef UFS_DIRHASH
1089         if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
1090             dirp->d_reclen == spacefree))
1091                 ufsdirhash_add(dp, dirp, I_OFFSET(dp) + ((char *)ep - dirbuf));
1092 #endif
1093         bcopy((caddr_t)dirp, (caddr_t)ep, (u_int)newentrysize);
1094 #ifdef UFS_DIRHASH
1095         if (dp->i_dirhash != NULL)
1096                 ufsdirhash_checkblock(dp, dirbuf -
1097                     (I_OFFSET(dp) & (DIRBLKSIZ - 1)),
1098                     rounddown2(I_OFFSET(dp), DIRBLKSIZ));
1099 #endif
1100
1101         if (DOINGSOFTDEP(dvp)) {
1102                 (void) softdep_setup_directory_add(bp, dp,
1103                     I_OFFSET(dp) + (caddr_t)ep - dirbuf,
1104                     dirp->d_ino, newdirbp, 0);
1105                 if (newdirbp != NULL)
1106                         bdwrite(newdirbp);
1107                 bdwrite(bp);
1108         } else {
1109                 if (DOINGASYNC(dvp)) {
1110                         bdwrite(bp);
1111                         error = 0;
1112                 } else {
1113                         error = bwrite(bp);
1114                 }
1115         }
1116         UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE);
1117         /*
1118          * If all went well, and the directory can be shortened, proceed
1119          * with the truncation. Note that we have to unlock the inode for
1120          * the entry that we just entered, as the truncation may need to
1121          * lock other inodes which can lead to deadlock if we also hold a
1122          * lock on the newly entered node.
1123          */
1124         if (isrename == 0 && error == 0 &&
1125             I_ENDOFF(dp) != 0 && I_ENDOFF(dp) < dp->i_size) {
1126                 if (tvp != NULL)
1127                         VOP_UNLOCK(tvp);
1128                 error = UFS_TRUNCATE(dvp, (off_t)I_ENDOFF(dp),
1129                     IO_NORMAL | (DOINGASYNC(dvp) ? 0 : IO_SYNC), cr);
1130                 if (error != 0)
1131                         vn_printf(dvp,
1132                             "ufs_direnter: failed to truncate, error %d\n",
1133                             error);
1134 #ifdef UFS_DIRHASH
1135                 if (error == 0 && dp->i_dirhash != NULL)
1136                         ufsdirhash_dirtrunc(dp, I_ENDOFF(dp));
1137 #endif
1138                 error = 0;
1139                 if (tvp != NULL)
1140                         vn_lock(tvp, LK_EXCLUSIVE | LK_RETRY);
1141         }
1142         return (error);
1143 }
1144
1145 /*
1146  * Remove a directory entry after a call to namei, using
1147  * the parameters which it left in nameidata. The entry
1148  * dp->i_offset contains the offset into the directory of the
1149  * entry to be eliminated.  The dp->i_count field contains the
1150  * size of the previous record in the directory.  If this
1151  * is 0, the first entry is being deleted, so we need only
1152  * zero the inode number to mark the entry as free.  If the
1153  * entry is not the first in the directory, we must reclaim
1154  * the space of the now empty record by adding the record size
1155  * to the size of the previous entry.
1156  */
1157 int
1158 ufs_dirremove(dvp, ip, flags, isrmdir)
1159         struct vnode *dvp;
1160         struct inode *ip;
1161         int flags;
1162         int isrmdir;
1163 {
1164         struct inode *dp;
1165         struct direct *ep, *rep;
1166         struct buf *bp;
1167         off_t offset;
1168         int error;
1169
1170         dp = VTOI(dvp);
1171
1172         /*
1173          * Adjust the link count early so softdep can block if necessary.
1174          */
1175         if (ip) {
1176                 ip->i_effnlink--;
1177                 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1178                 if (DOINGSOFTDEP(dvp)) {
1179                         softdep_setup_unlink(dp, ip);
1180                 } else {
1181                         ip->i_nlink--;
1182                         DIP_SET(ip, i_nlink, ip->i_nlink);
1183                         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1184                 }
1185         }
1186         if (flags & DOWHITEOUT)
1187                 offset = I_OFFSET(dp);
1188         else
1189                 offset = I_OFFSET(dp) - I_COUNT(dp);
1190         if ((error = UFS_BLKATOFF(dvp, offset, (char **)&ep, &bp)) != 0) {
1191                 if (ip) {
1192                         ip->i_effnlink++;
1193                         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1194                         if (DOINGSOFTDEP(dvp)) {
1195                                 softdep_change_linkcnt(ip);
1196                         } else {
1197                                 ip->i_nlink++;
1198                                 DIP_SET(ip, i_nlink, ip->i_nlink);
1199                                 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
1200                         }
1201                 }
1202                 return (error);
1203         }
1204         if (flags & DOWHITEOUT) {
1205                 /*
1206                  * Whiteout entry: set d_ino to UFS_WINO.
1207                  */
1208                 ep->d_ino = UFS_WINO;
1209                 ep->d_type = DT_WHT;
1210                 goto out;
1211         }
1212         /* Set 'rep' to the entry being removed. */
1213         if (I_COUNT(dp) == 0)
1214                 rep = ep;
1215         else
1216                 rep = (struct direct *)((char *)ep + ep->d_reclen);
1217 #ifdef UFS_DIRHASH
1218         /*
1219          * Remove the dirhash entry. This is complicated by the fact
1220          * that `ep' is the previous entry when dp->i_count != 0.
1221          */
1222         if (dp->i_dirhash != NULL)
1223                 ufsdirhash_remove(dp, rep, I_OFFSET(dp));
1224 #endif
1225         if (ip && rep->d_ino != ip->i_number)
1226                 panic("ufs_dirremove: ip %ju does not match dirent ino %ju\n",
1227                     (uintmax_t)ip->i_number, (uintmax_t)rep->d_ino);
1228         /*
1229          * Zero out the file directory entry metadata to reduce disk
1230          * scavenging disclosure.
1231          */
1232         bzero(&rep->d_name[0], rep->d_namlen);
1233         rep->d_namlen = 0;
1234         rep->d_type = 0;
1235         rep->d_ino = 0;
1236
1237         if (I_COUNT(dp) != 0) {
1238                 /*
1239                  * Collapse new free space into previous entry.
1240                  */
1241                 ep->d_reclen += rep->d_reclen;
1242                 rep->d_reclen = 0;
1243         }
1244 #ifdef UFS_DIRHASH
1245         if (dp->i_dirhash != NULL)
1246                 ufsdirhash_checkblock(dp, (char *)ep -
1247                     ((I_OFFSET(dp) - I_COUNT(dp)) & (DIRBLKSIZ - 1)),
1248                     rounddown2(I_OFFSET(dp), DIRBLKSIZ));
1249 #endif
1250 out:
1251         error = 0;
1252         if (DOINGSOFTDEP(dvp)) {
1253                 if (ip)
1254                         softdep_setup_remove(bp, dp, ip, isrmdir);
1255                 if (softdep_slowdown(dvp))
1256                         error = bwrite(bp);
1257                 else
1258                         bdwrite(bp);
1259         } else {
1260                 if (flags & DOWHITEOUT)
1261                         error = bwrite(bp);
1262                 else if (DOINGASYNC(dvp))
1263                         bdwrite(bp);
1264                 else
1265                         error = bwrite(bp);
1266         }
1267         UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE);
1268         /*
1269          * If the last named reference to a snapshot goes away,
1270          * drop its snapshot reference so that it will be reclaimed
1271          * when last open reference goes away.
1272          */
1273         if (ip != NULL && (ip->i_flags & SF_SNAPSHOT) != 0 &&
1274             ip->i_effnlink == 0)
1275                 UFS_SNAPGONE(ip);
1276         return (error);
1277 }
1278
1279 /*
1280  * Rewrite an existing directory entry to point at the inode
1281  * supplied.  The parameters describing the directory entry are
1282  * set up by a call to namei.
1283  */
1284 int
1285 ufs_dirrewrite(dp, oip, newinum, newtype, isrmdir)
1286         struct inode *dp, *oip;
1287         ino_t newinum;
1288         int newtype;
1289         int isrmdir;
1290 {
1291         struct buf *bp;
1292         struct direct *ep;
1293         struct vnode *vdp = ITOV(dp);
1294         int error;
1295
1296         /*
1297          * Drop the link before we lock the buf so softdep can block if
1298          * necessary.
1299          */
1300         oip->i_effnlink--;
1301         UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1302         if (DOINGSOFTDEP(vdp)) {
1303                 softdep_setup_unlink(dp, oip);
1304         } else {
1305                 oip->i_nlink--;
1306                 DIP_SET(oip, i_nlink, oip->i_nlink);
1307                 UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1308         }
1309
1310         error = UFS_BLKATOFF(vdp, (off_t)I_OFFSET(dp), (char **)&ep, &bp);
1311         if (error == 0 && ep->d_namlen == 2 && ep->d_name[1] == '.' &&
1312             ep->d_name[0] == '.' && ep->d_ino != oip->i_number) {
1313                 brelse(bp);
1314                 error = EIDRM;
1315         }
1316         if (error) {
1317                 oip->i_effnlink++;
1318                 UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1319                 if (DOINGSOFTDEP(vdp)) {
1320                         softdep_change_linkcnt(oip);
1321                 } else {
1322                         oip->i_nlink++;
1323                         DIP_SET(oip, i_nlink, oip->i_nlink);
1324                         UFS_INODE_SET_FLAG(oip, IN_CHANGE);
1325                 }
1326                 return (error);
1327         }
1328         ep->d_ino = newinum;
1329         if (!OFSFMT(vdp))
1330                 ep->d_type = newtype;
1331         if (DOINGSOFTDEP(vdp)) {
1332                 softdep_setup_directory_change(bp, dp, oip, newinum, isrmdir);
1333                 bdwrite(bp);
1334         } else {
1335                 if (DOINGASYNC(vdp)) {
1336                         bdwrite(bp);
1337                         error = 0;
1338                 } else {
1339                         error = bwrite(bp);
1340                 }
1341         }
1342         UFS_INODE_SET_FLAG(dp, IN_CHANGE | IN_UPDATE);
1343         /*
1344          * If the last named reference to a snapshot goes away,
1345          * drop its snapshot reference so that it will be reclaimed
1346          * when last open reference goes away.
1347          */
1348         if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_effnlink == 0)
1349                 UFS_SNAPGONE(oip);
1350         return (error);
1351 }
1352
1353 /*
1354  * Check if a directory is empty or not.
1355  * Inode supplied must be locked.
1356  *
1357  * Using a struct dirtemplate here is not precisely
1358  * what we want, but better than using a struct direct.
1359  *
1360  * NB: does not handle corrupted directories.
1361  */
1362 int
1363 ufs_dirempty(ip, parentino, cred)
1364         struct inode *ip;
1365         ino_t parentino;
1366         struct ucred *cred;
1367 {
1368         doff_t off;
1369         struct dirtemplate dbuf;
1370         struct direct *dp = (struct direct *)&dbuf;
1371         int error, namlen;
1372         ssize_t count;
1373 #define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
1374
1375         for (off = 0; off < ip->i_size; off += dp->d_reclen) {
1376                 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ,
1377                     off, UIO_SYSSPACE, IO_NODELOCKED | IO_NOMACCHECK, cred,
1378                     NOCRED, &count, (struct thread *)0);
1379                 /*
1380                  * Since we read MINDIRSIZ, residual must
1381                  * be 0 unless we're at end of file.
1382                  */
1383                 if (error || count != 0)
1384                         return (0);
1385                 /* avoid infinite loops */
1386                 if (dp->d_reclen == 0)
1387                         return (0);
1388                 /* skip empty entries */
1389                 if (dp->d_ino == 0 || dp->d_ino == UFS_WINO)
1390                         continue;
1391                 /* accept only "." and ".." */
1392 #               if (BYTE_ORDER == LITTLE_ENDIAN)
1393                         if (OFSFMT(ITOV(ip)))
1394                                 namlen = dp->d_type;
1395                         else
1396                                 namlen = dp->d_namlen;
1397 #               else
1398                         namlen = dp->d_namlen;
1399 #               endif
1400                 if (namlen > 2)
1401                         return (0);
1402                 if (dp->d_name[0] != '.')
1403                         return (0);
1404                 /*
1405                  * At this point namlen must be 1 or 2.
1406                  * 1 implies ".", 2 implies ".." if second
1407                  * char is also "."
1408                  */
1409                 if (namlen == 1 && dp->d_ino == ip->i_number)
1410                         continue;
1411                 if (dp->d_name[1] == '.' && dp->d_ino == parentino)
1412                         continue;
1413                 return (0);
1414         }
1415         return (1);
1416 }
1417
1418 static int
1419 ufs_dir_dd_ino(struct vnode *vp, struct ucred *cred, ino_t *dd_ino,
1420     struct vnode **dd_vp)
1421 {
1422         struct dirtemplate dirbuf;
1423         struct vnode *ddvp;
1424         int error, namlen;
1425
1426         ASSERT_VOP_LOCKED(vp, "ufs_dir_dd_ino");
1427         *dd_vp = NULL;
1428         if (vp->v_type != VDIR)
1429                 return (ENOTDIR);
1430         /*
1431          * First check to see if we have it in the name cache.
1432          */
1433         if ((ddvp = vn_dir_dd_ino(vp)) != NULL) {
1434                 KASSERT(ddvp->v_mount == vp->v_mount,
1435                     ("ufs_dir_dd_ino: Unexpected mount point crossing"));
1436                 *dd_ino = VTOI(ddvp)->i_number;
1437                 *dd_vp = ddvp;
1438                 return (0);
1439         }
1440         /*
1441          * Have to read the directory.
1442          */
1443         error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1444             sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1445             IO_NODELOCKED | IO_NOMACCHECK, cred, NOCRED, NULL, NULL);
1446         if (error != 0)
1447                 return (error);
1448 #if (BYTE_ORDER == LITTLE_ENDIAN)
1449         if (OFSFMT(vp))
1450                 namlen = dirbuf.dotdot_type;
1451         else
1452                 namlen = dirbuf.dotdot_namlen;
1453 #else
1454         namlen = dirbuf.dotdot_namlen;
1455 #endif
1456         if (namlen != 2 || dirbuf.dotdot_name[0] != '.' ||
1457             dirbuf.dotdot_name[1] != '.')
1458                 return (ENOTDIR);
1459         *dd_ino = dirbuf.dotdot_ino;
1460         return (0);
1461 }
1462
1463 /*
1464  * Check if source directory is in the path of the target directory.
1465  */
1466 int
1467 ufs_checkpath(ino_t source_ino, ino_t parent_ino, struct inode *target, struct ucred *cred, ino_t *wait_ino)
1468 {
1469         struct mount *mp;
1470         struct vnode *tvp, *vp, *vp1;
1471         int error;
1472         ino_t dd_ino;
1473
1474         vp = tvp = ITOV(target);
1475         mp = vp->v_mount;
1476         *wait_ino = 0;
1477         if (target->i_number == source_ino)
1478                 return (EEXIST);
1479         if (target->i_number == parent_ino)
1480                 return (0);
1481         if (target->i_number == UFS_ROOTINO)
1482                 return (0);
1483         for (;;) {
1484                 error = ufs_dir_dd_ino(vp, cred, &dd_ino, &vp1);
1485                 if (error != 0)
1486                         break;
1487                 if (dd_ino == source_ino) {
1488                         error = EINVAL;
1489                         break;
1490                 }
1491                 if (dd_ino == UFS_ROOTINO)
1492                         break;
1493                 if (dd_ino == parent_ino)
1494                         break;
1495                 if (vp1 == NULL) {
1496                         error = VFS_VGET(mp, dd_ino, LK_SHARED | LK_NOWAIT,
1497                             &vp1);
1498                         if (error != 0) {
1499                                 *wait_ino = dd_ino;
1500                                 break;
1501                         }
1502                 }
1503                 KASSERT(dd_ino == VTOI(vp1)->i_number,
1504                     ("directory %ju reparented\n",
1505                     (uintmax_t)VTOI(vp1)->i_number));
1506                 if (vp != tvp)
1507                         vput(vp);
1508                 vp = vp1;
1509         }
1510
1511         if (error == ENOTDIR)
1512                 panic("checkpath: .. not a directory\n");
1513         if (vp1 != NULL)
1514                 vput(vp1);
1515         if (vp != tvp)
1516                 vput(vp);
1517         return (error);
1518 }
1519
1520 #ifdef DIAGNOSTIC
1521 static void
1522 ufs_assert_inode_offset_owner(struct inode *ip, struct iown_tracker *tr,
1523     const char *name, const char *file, int line)
1524 {
1525         char msg[128];
1526
1527         snprintf(msg, sizeof(msg), "at %s@%d", file, line);
1528         ASSERT_VOP_ELOCKED(ITOV(ip), msg);
1529         MPASS((ip->i_mode & IFMT) == IFDIR);
1530         if (curthread == tr->tr_owner && ip->i_lock_gen == tr->tr_gen)
1531                 return;
1532         printf("locked at\n");
1533         stack_print(&tr->tr_st);
1534         printf("unlocked at\n");
1535         stack_print(&tr->tr_unlock);
1536         panic("%s ip %p %jd offset owner %p %d gen %d "
1537             "curthread %p %d gen %d at %s@%d\n",
1538             name, ip, (uintmax_t)ip->i_number, tr->tr_owner,
1539             tr->tr_owner->td_tid, tr->tr_gen,
1540             curthread, curthread->td_tid, ip->i_lock_gen,
1541             file, line);
1542 }
1543
1544 static void
1545 ufs_set_inode_offset_owner(struct inode *ip, struct iown_tracker *tr,
1546     const char *file, int line)
1547 {
1548         char msg[128];
1549
1550         snprintf(msg, sizeof(msg), "at %s@%d", file, line);
1551         ASSERT_VOP_ELOCKED(ITOV(ip), msg);
1552         MPASS((ip->i_mode & IFMT) == IFDIR);
1553         tr->tr_owner = curthread;
1554         tr->tr_gen = ip->i_lock_gen;
1555         stack_save(&tr->tr_st);
1556 }
1557
1558 static void
1559 ufs_init_one_tracker(struct iown_tracker *tr)
1560 {
1561         tr->tr_owner = NULL;
1562         stack_zero(&tr->tr_st);
1563 }
1564
1565 void
1566 ufs_init_trackers(struct inode *ip)
1567 {
1568         ufs_init_one_tracker(&ip->i_offset_tracker);
1569         ufs_init_one_tracker(&ip->i_count_tracker);
1570         ufs_init_one_tracker(&ip->i_endoff_tracker);
1571 }
1572
1573 void
1574 ufs_unlock_tracker(struct inode *ip)
1575 {
1576         if (ip->i_count_tracker.tr_gen == ip->i_lock_gen)
1577                 stack_save(&ip->i_count_tracker.tr_unlock);
1578         if (ip->i_offset_tracker.tr_gen == ip->i_lock_gen)
1579                 stack_save(&ip->i_offset_tracker.tr_unlock);
1580         if (ip->i_endoff_tracker.tr_gen == ip->i_lock_gen)
1581                 stack_save(&ip->i_endoff_tracker.tr_unlock);
1582         ip->i_lock_gen++;
1583 }
1584
1585 doff_t
1586 ufs_get_i_offset(struct inode *ip, const char *file, int line)
1587 {
1588         ufs_assert_inode_offset_owner(ip, &ip->i_offset_tracker, "i_offset",
1589             file, line);
1590         return (ip->i_offset);
1591 }
1592
1593 void
1594 ufs_set_i_offset(struct inode *ip, doff_t off, const char *file, int line)
1595 {
1596         ufs_set_inode_offset_owner(ip, &ip->i_offset_tracker, file, line);
1597         ip->i_offset = off;
1598 }
1599
1600 int32_t
1601 ufs_get_i_count(struct inode *ip, const char *file, int line)
1602 {
1603         ufs_assert_inode_offset_owner(ip, &ip->i_count_tracker, "i_count",
1604             file, line);
1605         return (ip->i_count);
1606 }
1607
1608 void
1609 ufs_set_i_count(struct inode *ip, int32_t cnt, const char *file, int line)
1610 {
1611         ufs_set_inode_offset_owner(ip, &ip->i_count_tracker, file, line);
1612         ip->i_count = cnt;
1613 }
1614
1615 doff_t
1616 ufs_get_i_endoff(struct inode *ip, const char *file, int line)
1617 {
1618         ufs_assert_inode_offset_owner(ip, &ip->i_endoff_tracker, "i_endoff",
1619             file, line);
1620         return (ip->i_endoff);
1621 }
1622
1623 void
1624 ufs_set_i_endoff(struct inode *ip, doff_t off, const char *file, int line)
1625 {
1626         ufs_set_inode_offset_owner(ip, &ip->i_endoff_tracker, file, line);
1627         ip->i_endoff = off;
1628 }
1629
1630 #endif