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