namecache work stage 1: namespace cleanups. Add a NAMEI_ prefix to
[dragonfly.git] / sys / vfs / gnu / ext2fs / ext2_lookup.c
1 /*
2  *  modified for Lites 1.1
3  *
4  *  Aug 1995, Godmar Back (gback@cs.utah.edu)
5  *  University of Utah, Department of Computer Science
6  *
7  * $FreeBSD: src/sys/gnu/ext2fs/ext2_lookup.c,v 1.21.2.3 2002/11/17 02:02:42 bde Exp $
8  * $DragonFly: src/sys/vfs/gnu/ext2fs/ext2_lookup.c,v 1.7 2003/09/23 05:03:52 dillon Exp $
9  */
10 /*
11  * Copyright (c) 1989, 1993
12  *      The Regents of the University of California.  All rights reserved.
13  * (c) UNIX System Laboratories, Inc.
14  * All or some portions of this file are derived from material licensed
15  * to the University of California by American Telephone and Telegraph
16  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
17  * the permission of UNIX System Laboratories, Inc.
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  * 3. All advertising materials mentioning features or use of this software
28  *    must display the following acknowledgement:
29  *      This product includes software developed by the University of
30  *      California, Berkeley and its contributors.
31  * 4. Neither the name of the University nor the names of its contributors
32  *    may be used to endorse or promote products derived from this software
33  *    without specific prior written permission.
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45  * SUCH DAMAGE.
46  *
47  *      @(#)ufs_lookup.c        8.6 (Berkeley) 4/1/94
48  */
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/namei.h>
53 #include <sys/buf.h>
54 #include <sys/mount.h>
55 #include <sys/vnode.h>
56 #include <sys/malloc.h>
57 #include <sys/dirent.h>
58
59 #include <vfs/ufs/quota.h>
60 #include <vfs/ufs/inode.h>
61 #include <vfs/ufs/dir.h>
62 #include <vfs/ufs/ufsmount.h>
63 #include <vfs/ufs/ufs_extern.h>
64
65 #include "ext2_extern.h"
66 #include "ext2_fs.h"
67 #include "ext2_fs_sb.h"
68
69 /* 
70    DIRBLKSIZE in ffs is DEV_BSIZE (in most cases 512)
71    while it is the native blocksize in ext2fs - thus, a #define
72    is no longer appropriate
73 */
74 #undef  DIRBLKSIZ
75
76 extern  int dirchk;
77
78 static u_char ext2_ft_to_dt[] = {
79         DT_UNKNOWN,             /* EXT2_FT_UNKNOWN */
80         DT_REG,                 /* EXT2_FT_REG_FILE */
81         DT_DIR,                 /* EXT2_FT_DIR */
82         DT_CHR,                 /* EXT2_FT_CHRDEV */
83         DT_BLK,                 /* EXT2_FT_BLKDEV */
84         DT_FIFO,                /* EXT2_FT_FIFO */
85         DT_SOCK,                /* EXT2_FT_SOCK */
86         DT_LNK,                 /* EXT2_FT_SYMLINK */
87 };
88 #define FTTODT(ft)                                              \
89     ((ft) > sizeof(ext2_ft_to_dt) / sizeof(ext2_ft_to_dt[0]) ?  \
90     DT_UNKNOWN : ext2_ft_to_dt[(ft)])
91
92 static u_char dt_to_ext2_ft[] = {
93         EXT2_FT_UNKNOWN,        /* DT_UNKNOWN */
94         EXT2_FT_FIFO,           /* DT_FIFO */
95         EXT2_FT_CHRDEV,         /* DT_CHR */
96         EXT2_FT_UNKNOWN,        /* unused */
97         EXT2_FT_DIR,            /* DT_DIR */
98         EXT2_FT_UNKNOWN,        /* unused */
99         EXT2_FT_BLKDEV,         /* DT_BLK */
100         EXT2_FT_UNKNOWN,        /* unused */
101         EXT2_FT_REG_FILE,       /* DT_REG */
102         EXT2_FT_UNKNOWN,        /* unused */
103         EXT2_FT_SYMLINK,        /* DT_LNK */
104         EXT2_FT_UNKNOWN,        /* unused */
105         EXT2_FT_SOCK,           /* DT_SOCK */
106         EXT2_FT_UNKNOWN,        /* unused */
107         EXT2_FT_UNKNOWN,        /* DT_WHT */
108 };
109 #define DTTOFT(dt)                                              \
110     ((dt) > sizeof(dt_to_ext2_ft) / sizeof(dt_to_ext2_ft[0]) ?  \
111     EXT2_FT_UNKNOWN : dt_to_ext2_ft[(dt)])
112
113 static int      ext2_dirbadentry (struct vnode *dp,
114                                       struct ext2_dir_entry_2 *de,
115                                       int entryoffsetinblock);
116
117 /*
118  * Vnode op for reading directories.
119  *
120  * The routine below assumes that the on-disk format of a directory
121  * is the same as that defined by <sys/dirent.h>. If the on-disk
122  * format changes, then it will be necessary to do a conversion
123  * from the on-disk format that read returns to the format defined
124  * by <sys/dirent.h>.
125  */
126 /*
127  * this is exactly what we do here - the problem is that the conversion
128  * will blow up some entries by four bytes, so it can't be done in place.
129  * This is too bad. Right now the conversion is done entry by entry, the
130  * converted entry is sent via uiomove. 
131  *
132  * XXX allocate a buffer, convert as many entries as possible, then send
133  * the whole buffer to uiomove
134  */
135 int
136 ext2_readdir(ap)
137         struct vop_readdir_args /* {
138                 struct vnode *a_vp;
139                 struct uio *a_uio;
140                 struct ucred *a_cred;
141         } */ *ap;
142 {
143         struct uio *uio = ap->a_uio;
144         int count, error;
145
146         struct ext2_dir_entry_2 *edp, *dp;
147         int ncookies;
148         struct dirent dstdp;
149         struct uio auio;
150         struct iovec aiov;
151         caddr_t dirbuf;
152         int DIRBLKSIZ = VTOI(ap->a_vp)->i_e2fs->s_blocksize;
153         int readcnt;
154         off_t startoffset = uio->uio_offset;
155
156         count = uio->uio_resid;
157         /*
158          * Avoid complications for partial directory entries by adjusting
159          * the i/o to end at a block boundary.  Don't give up (like ufs
160          * does) if the initial adjustment gives a negative count, since
161          * many callers don't supply a large enough buffer.  The correct
162          * size is a little larger than DIRBLKSIZ to allow for expansion
163          * of directory entries, but some callers just use 512.
164          */
165         count -= (uio->uio_offset + count) & (DIRBLKSIZ -1);
166         if (count <= 0)
167                 count += DIRBLKSIZ;
168
169 #ifdef EXT2FS_DEBUG
170         printf("ext2_readdir: uio_offset = %lld, uio_resid = %d, count = %d\n", 
171             uio->uio_offset, uio->uio_resid, count);
172 #endif
173
174         auio = *uio;
175         auio.uio_iov = &aiov;
176         auio.uio_iovcnt = 1;
177         auio.uio_resid = count;
178         auio.uio_segflg = UIO_SYSSPACE;
179         aiov.iov_len = count;
180         MALLOC(dirbuf, caddr_t, count, M_TEMP, M_WAITOK);
181         aiov.iov_base = dirbuf;
182         error = VOP_READ(ap->a_vp, &auio, 0, ap->a_cred);
183         if (error == 0) {
184                 readcnt = count - auio.uio_resid;
185                 edp = (struct ext2_dir_entry_2 *)&dirbuf[readcnt];
186                 ncookies = 0;
187                 bzero(&dstdp, offsetof(struct dirent, d_name));
188                 for (dp = (struct ext2_dir_entry_2 *)dirbuf; 
189                     !error && uio->uio_resid > 0 && dp < edp; ) {
190                         /*-
191                          * "New" ext2fs directory entries differ in 3 ways
192                          * from ufs on-disk ones:
193                          * - the name is not necessarily NUL-terminated.
194                          * - the file type field always exists and always
195                          * follows the name length field.
196                          * - the file type is encoded in a different way.
197                          *
198                          * "Old" ext2fs directory entries need no special
199                          * conversions, since they binary compatible with
200                          * "new" entries having a file type of 0 (i.e.,
201                          * EXT2_FT_UNKNOWN).  Splitting the old name length
202                          * field didn't make a mess like it did in ufs,
203                          * because ext2fs uses a machine-dependent disk
204                          * layout.
205                          */
206                         dstdp.d_fileno = dp->inode;
207                         dstdp.d_type = FTTODT(dp->file_type);
208                         dstdp.d_namlen = dp->name_len;
209                         dstdp.d_reclen = GENERIC_DIRSIZ(&dstdp);
210                         bcopy(dp->name, dstdp.d_name, dstdp.d_namlen);
211                         bzero(dstdp.d_name + dstdp.d_namlen,
212                             dstdp.d_reclen - offsetof(struct dirent, d_name) -
213                             dstdp.d_namlen);
214
215                         if (dp->rec_len > 0) {
216                                 if(dstdp.d_reclen <= uio->uio_resid) {
217                                         /* advance dp */
218                                         dp = (struct ext2_dir_entry_2 *)
219                                             ((char *)dp + dp->rec_len); 
220                                         error = 
221                                           uiomove((caddr_t)&dstdp,
222                                                   dstdp.d_reclen, uio);
223                                         if (!error)
224                                                 ncookies++;
225                                 } else
226                                         break;
227                         } else {
228                                 error = EIO;
229                                 break;
230                         }
231                 }
232                 /* we need to correct uio_offset */
233                 uio->uio_offset = startoffset + (caddr_t)dp - dirbuf;
234
235                 if (!error && ap->a_ncookies != NULL) {
236                         u_long *cookiep, *cookies, *ecookies;
237                         off_t off;
238
239                         if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
240                                 panic("ext2fs_readdir: unexpected uio from NFS server");
241                         MALLOC(cookies, u_long *, ncookies * sizeof(u_long), M_TEMP,
242                                M_WAITOK);
243                         off = startoffset;
244                         for (dp = (struct ext2_dir_entry_2 *)dirbuf,
245                              cookiep = cookies, ecookies = cookies + ncookies;
246                              cookiep < ecookies;
247                              dp = (struct ext2_dir_entry_2 *)((caddr_t) dp + dp->rec_len)) {
248                                 off += dp->rec_len;
249                                 *cookiep++ = (u_long) off;
250                         }
251                         *ap->a_ncookies = ncookies;
252                         *ap->a_cookies = cookies;
253                 }
254         }
255         FREE(dirbuf, M_TEMP);
256         if (ap->a_eofflag)
257                 *ap->a_eofflag = VTOI(ap->a_vp)->i_size <= uio->uio_offset;
258         return (error);
259 }
260
261 /*
262  * Convert a component of a pathname into a pointer to a locked inode.
263  * This is a very central and rather complicated routine.
264  * If the file system is not maintained in a strict tree hierarchy,
265  * this can result in a deadlock situation (see comments in code below).
266  *
267  * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
268  * on whether the name is to be looked up, created, renamed, or deleted.
269  * When CREATE, RENAME, or DELETE is specified, information usable in
270  * creating, renaming, or deleting a directory entry may be calculated.
271  * If flag has LOCKPARENT or'ed into it and the target of the pathname
272  * exists, lookup returns both the target and its parent directory locked.
273  * When creating or renaming and LOCKPARENT is specified, the target may
274  * not be ".".  When deleting and LOCKPARENT is specified, the target may
275  * be "."., but the caller must check to ensure it does an vrele and vput
276  * instead of two vputs.
277  *
278  * Overall outline of ufs_lookup:
279  *
280  *      search for name in directory, to found or notfound
281  * notfound:
282  *      if creating, return locked directory, leaving info on available slots
283  *      else return error
284  * found:
285  *      if at end of path and deleting, return information to allow delete
286  *      if at end of path and rewriting (RENAME and LOCKPARENT), lock target
287  *        inode and return info to allow rewrite
288  *      if not at end, add name to cache; if at end and neither creating
289  *        nor deleting, add name to cache
290  */
291 int
292 ext2_lookup(ap)
293         struct vop_cachedlookup_args /* {
294                 struct vnode *a_dvp;
295                 struct vnode **a_vpp;
296                 struct componentname *a_cnp;
297         } */ *ap;
298 {
299         struct vnode *vdp;      /* vnode for directory being searched */
300         struct inode *dp;       /* inode for directory being searched */
301         struct buf *bp;                 /* a buffer of directory entries */
302         struct ext2_dir_entry_2 *ep; /* the current directory entry */
303         int entryoffsetinblock;         /* offset of ep in bp's buffer */
304         enum {NONE, COMPACT, FOUND} slotstatus;
305         doff_t slotoffset;              /* offset of area with free space */
306         int slotsize;                   /* size of area at slotoffset */
307         int slotfreespace;              /* amount of space free in slot */
308         int slotneeded;                 /* size of the entry we're seeking */
309         int numdirpasses;               /* strategy for directory search */
310         doff_t endsearch;               /* offset to end directory search */
311         doff_t prevoff;                 /* prev entry dp->i_offset */
312         struct vnode *pdp;              /* saved dp during symlink work */
313         struct vnode *tdp;              /* returned by VFS_VGET */
314         doff_t enduseful;               /* pointer past last used dir slot */
315         u_long bmask;                   /* block offset mask */
316         int lockparent;                 /* 1 => lockparent flag is set */
317         int wantparent;                 /* 1 => wantparent or lockparent flag */
318         int namlen, error;
319         struct vnode **vpp = ap->a_vpp;
320         struct componentname *cnp = ap->a_cnp;
321         struct ucred *cred = cnp->cn_cred;
322         int flags = cnp->cn_flags;
323         int nameiop = cnp->cn_nameiop;
324         struct thread *td = cnp->cn_td;
325
326         int     DIRBLKSIZ = VTOI(ap->a_dvp)->i_e2fs->s_blocksize;
327
328         bp = NULL;
329         slotoffset = -1;
330         *vpp = NULL;
331         vdp = ap->a_dvp;
332         dp = VTOI(vdp);
333         lockparent = flags & CNP_LOCKPARENT;
334         wantparent = flags & (CNP_LOCKPARENT|CNP_WANTPARENT);
335
336         /*
337          * We now have a segment name to search for, and a directory to search.
338          */
339
340         /*
341          * Suppress search for slots unless creating
342          * file and at end of pathname, in which case
343          * we watch for a place to put the new file in
344          * case it doesn't already exist.
345          */
346         slotstatus = FOUND;
347         slotfreespace = slotsize = slotneeded = 0;
348         if ((nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) &&
349             (flags & CNP_ISLASTCN)) {
350                 slotstatus = NONE;
351                 slotneeded = EXT2_DIR_REC_LEN(cnp->cn_namelen); 
352                 /* was
353                 slotneeded = (sizeof(struct direct) - MAXNAMLEN +
354                         cnp->cn_namelen + 3) &~ 3; */
355         }
356
357         /*
358          * If there is cached information on a previous search of
359          * this directory, pick up where we last left off.
360          * We cache only lookups as these are the most common
361          * and have the greatest payoff. Caching CREATE has little
362          * benefit as it usually must search the entire directory
363          * to determine that the entry does not exist. Caching the
364          * location of the last DELETE or RENAME has not reduced
365          * profiling time and hence has been removed in the interest
366          * of simplicity.
367          */
368         bmask = VFSTOUFS(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
369         if (nameiop != NAMEI_LOOKUP || dp->i_diroff == 0 ||
370             dp->i_diroff > dp->i_size) {
371                 entryoffsetinblock = 0;
372                 dp->i_offset = 0;
373                 numdirpasses = 1;
374         } else {
375                 dp->i_offset = dp->i_diroff;
376                 if ((entryoffsetinblock = dp->i_offset & bmask) &&
377                     (error = UFS_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)))
378                         return (error);
379                 numdirpasses = 2;
380                 nchstats.ncs_2passes++;
381         }
382         prevoff = dp->i_offset;
383         endsearch = roundup(dp->i_size, DIRBLKSIZ);
384         enduseful = 0;
385
386 searchloop:
387         while (dp->i_offset < endsearch) {
388                 /*
389                  * If necessary, get the next directory block.
390                  */
391                 if ((dp->i_offset & bmask) == 0) {
392                         if (bp != NULL)
393                                 brelse(bp);
394                         if ((error =
395                             UFS_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)) != 0)
396                                 return (error);
397                         entryoffsetinblock = 0;
398                 }
399                 /*
400                  * If still looking for a slot, and at a DIRBLKSIZE
401                  * boundary, have to start looking for free space again.
402                  */
403                 if (slotstatus == NONE &&
404                     (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
405                         slotoffset = -1;
406                         slotfreespace = 0;
407                 }
408                 /*
409                  * Get pointer to next entry.
410                  * Full validation checks are slow, so we only check
411                  * enough to insure forward progress through the
412                  * directory. Complete checks can be run by patching
413                  * "dirchk" to be true.
414                  */
415                 ep = (struct ext2_dir_entry_2 *)
416                         ((char *)bp->b_data + entryoffsetinblock);
417                 if (ep->rec_len == 0 ||
418                     (dirchk && ext2_dirbadentry(vdp, ep, entryoffsetinblock))) {
419                         int i;
420                         ufs_dirbad(dp, dp->i_offset, "mangled entry");
421                         i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
422                         dp->i_offset += i;
423                         entryoffsetinblock += i;
424                         continue;
425                 }
426
427                 /*
428                  * If an appropriate sized slot has not yet been found,
429                  * check to see if one is available. Also accumulate space
430                  * in the current block so that we can determine if
431                  * compaction is viable.
432                  */
433                 if (slotstatus != FOUND) {
434                         int size = ep->rec_len;
435
436                         if (ep->inode != 0)
437                                 size -= EXT2_DIR_REC_LEN(ep->name_len);
438                         if (size > 0) {
439                                 if (size >= slotneeded) {
440                                         slotstatus = FOUND;
441                                         slotoffset = dp->i_offset;
442                                         slotsize = ep->rec_len;
443                                 } else if (slotstatus == NONE) {
444                                         slotfreespace += size;
445                                         if (slotoffset == -1)
446                                                 slotoffset = dp->i_offset;
447                                         if (slotfreespace >= slotneeded) {
448                                                 slotstatus = COMPACT;
449                                                 slotsize = dp->i_offset +
450                                                       ep->rec_len - slotoffset;
451                                         }
452                                 }
453                         }
454                 }
455
456                 /*
457                  * Check for a name match.
458                  */
459                 if (ep->inode) {
460                         namlen = ep->name_len;
461                         if (namlen == cnp->cn_namelen &&
462                             !bcmp(cnp->cn_nameptr, ep->name,
463                                 (unsigned)namlen)) {
464                                 /*
465                                  * Save directory entry's inode number and
466                                  * reclen in ndp->ni_ufs area, and release
467                                  * directory buffer.
468                                  */
469                                 dp->i_ino = ep->inode;
470                                 dp->i_reclen = ep->rec_len;
471                                 goto found;
472                         }
473                 }
474                 prevoff = dp->i_offset;
475                 dp->i_offset += ep->rec_len;
476                 entryoffsetinblock += ep->rec_len;
477                 if (ep->inode)
478                         enduseful = dp->i_offset;
479         }
480 /* notfound: */
481         /*
482          * If we started in the middle of the directory and failed
483          * to find our target, we must check the beginning as well.
484          */
485         if (numdirpasses == 2) {
486                 numdirpasses--;
487                 dp->i_offset = 0;
488                 endsearch = dp->i_diroff;
489                 goto searchloop;
490         }
491         if (bp != NULL)
492                 brelse(bp);
493         /*
494          * If creating, and at end of pathname and current
495          * directory has not been removed, then can consider
496          * allowing file to be created.
497          */
498         if ((nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) &&
499             (flags & CNP_ISLASTCN) && dp->i_nlink != 0) {
500                 /*
501                  * Access for write is interpreted as allowing
502                  * creation of files in the directory.
503                  */
504                 if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_td)) != 0)
505                         return (error);
506                 /*
507                  * Return an indication of where the new directory
508                  * entry should be put.  If we didn't find a slot,
509                  * then set dp->i_count to 0 indicating
510                  * that the new slot belongs at the end of the
511                  * directory. If we found a slot, then the new entry
512                  * can be put in the range from dp->i_offset to
513                  * dp->i_offset + dp->i_count.
514                  */
515                 if (slotstatus == NONE) {
516                         dp->i_offset = roundup(dp->i_size, DIRBLKSIZ);
517                         dp->i_count = 0;
518                         enduseful = dp->i_offset;
519                 } else {
520                         dp->i_offset = slotoffset;
521                         dp->i_count = slotsize;
522                         if (enduseful < slotoffset + slotsize)
523                                 enduseful = slotoffset + slotsize;
524                 }
525                 dp->i_endoff = roundup(enduseful, DIRBLKSIZ);
526                 dp->i_flag |= IN_CHANGE | IN_UPDATE;
527                 /*
528                  * We return with the directory locked, so that
529                  * the parameters we set up above will still be
530                  * valid if we actually decide to do a direnter().
531                  * We return ni_vp == NULL to indicate that the entry
532                  * does not currently exist; we leave a pointer to
533                  * the (locked) directory inode in ndp->ni_dvp.
534                  * The pathname buffer is saved so that the name
535                  * can be obtained later.
536                  *
537                  * NB - if the directory is unlocked, then this
538                  * information cannot be used.
539                  */
540                 cnp->cn_flags |= CNP_SAVENAME;
541                 if (!lockparent)
542                         VOP_UNLOCK(vdp, 0, td);
543                 return (EJUSTRETURN);
544         }
545         /*
546          * Insert name into cache (as non-existent) if appropriate.
547          */
548         if ((cnp->cn_flags & CNP_MAKEENTRY) && nameiop != NAMEI_CREATE)
549                 cache_enter(vdp, *vpp, cnp);
550         return (ENOENT);
551
552 found:
553         if (numdirpasses == 2)
554                 nchstats.ncs_pass2++;
555         /*
556          * Check that directory length properly reflects presence
557          * of this entry.
558          */
559         if (entryoffsetinblock + EXT2_DIR_REC_LEN(ep->name_len)
560                 > dp->i_size) {
561                 ufs_dirbad(dp, dp->i_offset, "i_size too small");
562                 dp->i_size = entryoffsetinblock+EXT2_DIR_REC_LEN(ep->name_len);
563                 dp->i_flag |= IN_CHANGE | IN_UPDATE;
564         }
565         brelse(bp);
566
567         /*
568          * Found component in pathname.
569          * If the final component of path name, save information
570          * in the cache as to where the entry was found.
571          */
572         if ((flags & CNP_ISLASTCN) && nameiop == NAMEI_LOOKUP)
573                 dp->i_diroff = dp->i_offset &~ (DIRBLKSIZ - 1);
574
575         /*
576          * If deleting, and at end of pathname, return
577          * parameters which can be used to remove file.
578          * If the wantparent flag isn't set, we return only
579          * the directory (in ndp->ni_dvp), otherwise we go
580          * on and lock the inode, being careful with ".".
581          */
582         if (nameiop == NAMEI_DELETE && (flags & CNP_ISLASTCN)) {
583                 /*
584                  * Write access to directory required to delete files.
585                  */
586                 if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_td)) != 0)
587                         return (error);
588                 /*
589                  * Return pointer to current entry in dp->i_offset,
590                  * and distance past previous entry (if there
591                  * is a previous entry in this block) in dp->i_count.
592                  * Save directory inode pointer in ndp->ni_dvp for dirremove().
593                  */
594                 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
595                         dp->i_count = 0;
596                 else
597                         dp->i_count = dp->i_offset - prevoff;
598                 if (dp->i_number == dp->i_ino) {
599                         VREF(vdp);
600                         *vpp = vdp;
601                         return (0);
602                 }
603                 if ((error = VFS_VGET(vdp->v_mount, dp->i_ino, &tdp)) != 0)
604                         return (error);
605                 /*
606                  * If directory is "sticky", then user must own
607                  * the directory, or the file in it, else she
608                  * may not delete it (unless she's root). This
609                  * implements append-only directories.
610                  */
611                 if ((dp->i_mode & ISVTX) &&
612                     cred->cr_uid != 0 &&
613                     cred->cr_uid != dp->i_uid &&
614                     VTOI(tdp)->i_uid != cred->cr_uid) {
615                         vput(tdp);
616                         return (EPERM);
617                 }
618                 *vpp = tdp;
619                 if (!lockparent)
620                         VOP_UNLOCK(vdp, 0, td);
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 == NAMEI_RENAME && wantparent &&
631             (flags & CNP_ISLASTCN)) {
632                 if ((error = VOP_ACCESS(vdp, VWRITE, cred, cnp->cn_td)) != 0)
633                         return (error);
634                 /*
635                  * Careful about locking second inode.
636                  * This can only occur if the target is ".".
637                  */
638                 if (dp->i_number == dp->i_ino)
639                         return (EISDIR);
640                 if ((error = VFS_VGET(vdp->v_mount, dp->i_ino, &tdp)) != 0)
641                         return (error);
642                 *vpp = tdp;
643                 cnp->cn_flags |= CNP_SAVENAME;
644                 if (!lockparent)
645                         VOP_UNLOCK(vdp, 0, td);
646                 return (0);
647         }
648
649         /*
650          * Step through the translation in the name.  We do not `vput' the
651          * directory because we may need it again if a symbolic link
652          * is relative to the current directory.  Instead we save it
653          * unlocked as "pdp".  We must get the target inode before unlocking
654          * the directory to insure that the inode will not be removed
655          * before we get it.  We prevent deadlock by always fetching
656          * inodes from the root, moving down the directory tree. Thus
657          * when following backward pointers ".." we must unlock the
658          * parent directory before getting the requested directory.
659          * There is a potential race condition here if both the current
660          * and parent directories are removed before the VFS_VGET for the
661          * inode associated with ".." returns.  We hope that this occurs
662          * infrequently since we cannot avoid this race condition without
663          * implementing a sophisticated deadlock detection algorithm.
664          * Note also that this simple deadlock detection scheme will not
665          * work if the file system has any hard links other than ".."
666          * that point backwards in the directory structure.
667          */
668         pdp = vdp;
669         if (flags & CNP_ISDOTDOT) {
670                 VOP_UNLOCK(pdp, 0, td); /* race to get the inode */
671                 if ((error = VFS_VGET(vdp->v_mount, dp->i_ino, &tdp)) != 0) {
672                         vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY, td);
673                         return (error);
674                 }
675                 if (lockparent && (flags & CNP_ISLASTCN) &&
676                     (error = vn_lock(pdp, LK_EXCLUSIVE, td))) {
677                         vput(tdp);
678                         return (error);
679                 }
680                 *vpp = tdp;
681         } else if (dp->i_number == dp->i_ino) {
682                 VREF(vdp);      /* we want ourself, ie "." */
683                 *vpp = vdp;
684         } else {
685                 if ((error = VFS_VGET(vdp->v_mount, dp->i_ino, &tdp)) != 0)
686                         return (error);
687                 if (!lockparent || !(flags & CNP_ISLASTCN))
688                         VOP_UNLOCK(pdp, 0, td);
689                 *vpp = tdp;
690         }
691
692         /*
693          * Insert name into cache if appropriate.
694          */
695         if (cnp->cn_flags & CNP_MAKEENTRY)
696                 cache_enter(vdp, *vpp, cnp);
697         return (0);
698 }
699
700 /*
701  * Do consistency checking on a directory entry:
702  *      record length must be multiple of 4
703  *      entry must fit in rest of its DIRBLKSIZ block
704  *      record must be large enough to contain entry
705  *      name is not longer than MAXNAMLEN
706  *      name must be as long as advertised, and null terminated
707  */
708 /*
709  *      changed so that it confirms to ext2_check_dir_entry
710  */
711 static int
712 ext2_dirbadentry(dp, de, entryoffsetinblock)
713         struct vnode *dp;
714         struct ext2_dir_entry_2 *de;
715         int entryoffsetinblock;
716 {
717         int     DIRBLKSIZ = VTOI(dp)->i_e2fs->s_blocksize;
718
719         char * error_msg = NULL;
720
721         if (de->rec_len < EXT2_DIR_REC_LEN(1))
722                 error_msg = "rec_len is smaller than minimal";
723         else if (de->rec_len % 4 != 0)
724                 error_msg = "rec_len % 4 != 0";
725         else if (de->rec_len < EXT2_DIR_REC_LEN(de->name_len))
726                 error_msg = "reclen is too small for name_len";
727         else if (entryoffsetinblock + de->rec_len > DIRBLKSIZ)
728                 error_msg = "directory entry across blocks";
729         /* else LATER
730              if (de->inode > dir->i_sb->u.ext2_sb.s_es->s_inodes_count)
731                 error_msg = "inode out of bounds";
732         */
733
734         if (error_msg != NULL) {
735                 printf("bad directory entry: %s\n", error_msg);
736                 printf("offset=%d, inode=%lu, rec_len=%u, name_len=%u\n",
737                         entryoffsetinblock, (unsigned long)de->inode,
738                         de->rec_len, de->name_len);
739         }
740         return error_msg == NULL ? 0 : 1;
741 }
742
743 /*
744  * Write a directory entry after a call to namei, using the parameters
745  * that it left in nameidata.  The argument ip is the inode which the new
746  * directory entry will refer to.  Dvp is a pointer to the directory to
747  * be written, which was left locked by namei. Remaining parameters
748  * (dp->i_offset, dp->i_count) indicate how the space for the new
749  * entry is to be obtained.
750  */
751 int
752 ext2_direnter(ip, dvp, cnp)
753         struct inode *ip;
754         struct vnode *dvp;
755         struct componentname *cnp;
756 {
757         struct ext2_dir_entry_2 *ep, *nep;
758         struct inode *dp;
759         struct buf *bp;
760         struct ext2_dir_entry_2 newdir;
761         struct iovec aiov;
762         struct uio auio;
763         u_int dsize;
764         int error, loc, newentrysize, spacefree;
765         char *dirbuf;
766         int     DIRBLKSIZ = ip->i_e2fs->s_blocksize;
767
768
769 #if DIAGNOSTIC
770         if ((cnp->cn_flags & CNP_SAVENAME) == 0)
771                 panic("direnter: missing name");
772 #endif
773         dp = VTOI(dvp);
774         newdir.inode = ip->i_number;
775         newdir.name_len = cnp->cn_namelen;
776         if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
777             EXT2_FEATURE_INCOMPAT_FILETYPE))
778                 newdir.file_type = DTTOFT(IFTODT(ip->i_mode));
779         else
780                 newdir.file_type = EXT2_FT_UNKNOWN;
781         bcopy(cnp->cn_nameptr, newdir.name, (unsigned)cnp->cn_namelen + 1);
782         newentrysize = EXT2_DIR_REC_LEN(newdir.name_len);
783         if (dp->i_count == 0) {
784                 /*
785                  * If dp->i_count is 0, then namei could find no
786                  * space in the directory. Here, dp->i_offset will
787                  * be on a directory block boundary and we will write the
788                  * new entry into a fresh block.
789                  */
790                 if (dp->i_offset & (DIRBLKSIZ - 1))
791                         panic("ext2_direnter: newblk");
792                 auio.uio_offset = dp->i_offset;
793                 newdir.rec_len = DIRBLKSIZ;
794                 auio.uio_resid = newentrysize;
795                 aiov.iov_len = newentrysize;
796                 aiov.iov_base = (caddr_t)&newdir;
797                 auio.uio_iov = &aiov;
798                 auio.uio_iovcnt = 1;
799                 auio.uio_rw = UIO_WRITE;
800                 auio.uio_segflg = UIO_SYSSPACE;
801                 auio.uio_td = NULL;
802                 error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
803                 if (DIRBLKSIZ >
804                     VFSTOUFS(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
805                         /* XXX should grow with balloc() */
806                         panic("ext2_direnter: frag size");
807                 else if (!error) {
808                         dp->i_size = roundup(dp->i_size, DIRBLKSIZ);
809                         dp->i_flag |= IN_CHANGE;
810                 }
811                 return (error);
812         }
813
814         /*
815          * If dp->i_count is non-zero, then namei found space
816          * for the new entry in the range dp->i_offset to
817          * dp->i_offset + dp->i_count in the directory.
818          * To use this space, we may have to compact the entries located
819          * there, by copying them together towards the beginning of the
820          * block, leaving the free space in one usable chunk at the end.
821          */
822
823         /*
824          * Increase size of directory if entry eats into new space.
825          * This should never push the size past a new multiple of
826          * DIRBLKSIZE.
827          *
828          * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
829          */
830         if (dp->i_offset + dp->i_count > dp->i_size)
831                 dp->i_size = dp->i_offset + dp->i_count;
832         /*
833          * Get the block containing the space for the new directory entry.
834          */
835         if ((error = UFS_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp)) != 0)
836                 return (error);
837         /*
838          * Find space for the new entry. In the simple case, the entry at
839          * offset base will have the space. If it does not, then namei
840          * arranged that compacting the region dp->i_offset to
841          * dp->i_offset + dp->i_count would yield the
842          * space.
843          */
844         ep = (struct ext2_dir_entry_2 *)dirbuf;
845         dsize = EXT2_DIR_REC_LEN(ep->name_len);
846         spacefree = ep->rec_len - dsize;
847         for (loc = ep->rec_len; loc < dp->i_count; ) {
848                 nep = (struct ext2_dir_entry_2 *)(dirbuf + loc);
849                 if (ep->inode) {
850                         /* trim the existing slot */
851                         ep->rec_len = dsize;
852                         ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
853                 } else {
854                         /* overwrite; nothing there; header is ours */
855                         spacefree += dsize;
856                 }
857                 dsize = EXT2_DIR_REC_LEN(nep->name_len);
858                 spacefree += nep->rec_len - dsize;
859                 loc += nep->rec_len;
860                 bcopy((caddr_t)nep, (caddr_t)ep, dsize);
861         }
862         /*
863          * Update the pointer fields in the previous entry (if any),
864          * copy in the new entry, and write out the block.
865          */
866         if (ep->inode == 0) {
867                 if (spacefree + dsize < newentrysize)
868                         panic("ext2_direnter: compact1");
869                 newdir.rec_len = spacefree + dsize;
870         } else {
871                 if (spacefree < newentrysize)
872                         panic("ext2_direnter: compact2");
873                 newdir.rec_len = spacefree;
874                 ep->rec_len = dsize;
875                 ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
876         }
877         bcopy((caddr_t)&newdir, (caddr_t)ep, (u_int)newentrysize);
878         error = VOP_BWRITE(bp->b_vp, bp);
879         dp->i_flag |= IN_CHANGE | IN_UPDATE;
880         if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
881                 error = UFS_TRUNCATE(dvp, (off_t)dp->i_endoff, IO_SYNC,
882                     cnp->cn_cred, cnp->cn_td);
883         return (error);
884 }
885
886 /*
887  * Remove a directory entry after a call to namei, using
888  * the parameters which it left in nameidata. The entry
889  * dp->i_offset contains the offset into the directory of the
890  * entry to be eliminated.  The dp->i_count field contains the
891  * size of the previous record in the directory.  If this
892  * is 0, the first entry is being deleted, so we need only
893  * zero the inode number to mark the entry as free.  If the
894  * entry is not the first in the directory, we must reclaim
895  * the space of the now empty record by adding the record size
896  * to the size of the previous entry.
897  */
898 int
899 ext2_dirremove(dvp, cnp)
900         struct vnode *dvp;
901         struct componentname *cnp;
902 {
903         struct inode *dp;
904         struct ext2_dir_entry_2 *ep;
905         struct buf *bp;
906         int error;
907          
908         dp = VTOI(dvp);
909         if (dp->i_count == 0) {
910                 /*
911                  * First entry in block: set d_ino to zero.
912                  */
913                 if ((error =
914                     UFS_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
915                         return (error);
916                 ep->inode = 0;
917                 error = VOP_BWRITE(bp->b_vp, bp);
918                 dp->i_flag |= IN_CHANGE | IN_UPDATE;
919                 return (error);
920         }
921         /*
922          * Collapse new free space into previous entry.
923          */
924         if ((error = UFS_BLKATOFF(dvp, (off_t)(dp->i_offset - dp->i_count),
925             (char **)&ep, &bp)) != 0)
926                 return (error);
927         ep->rec_len += dp->i_reclen;
928         error = VOP_BWRITE(bp->b_vp, bp);
929         dp->i_flag |= IN_CHANGE | IN_UPDATE;
930         return (error);
931 }
932
933 /*
934  * Rewrite an existing directory entry to point at the inode
935  * supplied.  The parameters describing the directory entry are
936  * set up by a call to namei.
937  */
938 int
939 ext2_dirrewrite(dp, ip, cnp)
940         struct inode *dp, *ip;
941         struct componentname *cnp;
942 {
943         struct buf *bp;
944         struct ext2_dir_entry_2 *ep;
945         struct vnode *vdp = ITOV(dp);
946         int error;
947
948         if ((error = UFS_BLKATOFF(vdp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
949                 return (error);
950         ep->inode = ip->i_number;
951         if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
952             EXT2_FEATURE_INCOMPAT_FILETYPE))
953                 ep->file_type = DTTOFT(IFTODT(ip->i_mode));
954         else
955                 ep->file_type = EXT2_FT_UNKNOWN;
956         error = VOP_BWRITE(bp->b_vp, bp);
957         dp->i_flag |= IN_CHANGE | IN_UPDATE;
958         return (error);
959 }
960
961 /*
962  * Check if a directory is empty or not.
963  * Inode supplied must be locked.
964  *
965  * Using a struct dirtemplate here is not precisely
966  * what we want, but better than using a struct direct.
967  *
968  * NB: does not handle corrupted directories.
969  */
970 int
971 ext2_dirempty(ip, parentino, cred)
972         struct inode *ip;
973         ino_t parentino;
974         struct ucred *cred;
975 {
976         off_t off;
977         struct dirtemplate dbuf;
978         struct ext2_dir_entry_2 *dp = (struct ext2_dir_entry_2 *)&dbuf;
979         int error, count, namlen;
980                  
981 #define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
982
983         for (off = 0; off < ip->i_size; off += dp->rec_len) {
984                 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ, off,
985                    UIO_SYSSPACE, IO_NODELOCKED, cred, &count, NULL);
986                 /*
987                  * Since we read MINDIRSIZ, residual must
988                  * be 0 unless we're at end of file.
989                  */
990                 if (error || count != 0)
991                         return (0);
992                 /* avoid infinite loops */
993                 if (dp->rec_len == 0)
994                         return (0);
995                 /* skip empty entries */
996                 if (dp->inode == 0)
997                         continue;
998                 /* accept only "." and ".." */
999                 namlen = dp->name_len;
1000                 if (namlen > 2)
1001                         return (0);
1002                 if (dp->name[0] != '.')
1003                         return (0);
1004                 /*
1005                  * At this point namlen must be 1 or 2.
1006                  * 1 implies ".", 2 implies ".." if second
1007                  * char is also "."
1008                  */
1009                 if (namlen == 1)
1010                         continue;
1011                 if (dp->name[1] == '.' && dp->inode == parentino)
1012                         continue;
1013                 return (0);
1014         }
1015         return (1);
1016 }
1017
1018 /*
1019  * Check if source directory is in the path of the target directory.
1020  * Target is supplied locked, source is unlocked.
1021  * The target is always vput before returning.
1022  */
1023 int
1024 ext2_checkpath(source, target, cred)
1025         struct inode *source, *target;
1026         struct ucred *cred;
1027 {
1028         struct vnode *vp;
1029         int error, rootino, namlen;
1030         struct dirtemplate dirbuf;
1031
1032         vp = ITOV(target);
1033         if (target->i_number == source->i_number) {
1034                 error = EEXIST;
1035                 goto out;
1036         }
1037         rootino = ROOTINO;
1038         error = 0;
1039         if (target->i_number == rootino)
1040                 goto out;
1041
1042         for (;;) {
1043                 if (vp->v_type != VDIR) {
1044                         error = ENOTDIR;
1045                         break;
1046                 }
1047                 error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1048                         sizeof (struct dirtemplate), (off_t)0, UIO_SYSSPACE,
1049                         IO_NODELOCKED, cred, (int *)0, NULL);
1050                 if (error != 0)
1051                         break;
1052                 namlen = dirbuf.dotdot_type;    /* like ufs little-endian */
1053                 if (namlen != 2 ||
1054                     dirbuf.dotdot_name[0] != '.' ||
1055                     dirbuf.dotdot_name[1] != '.') {
1056                         error = ENOTDIR;
1057                         break;
1058                 }
1059                 if (dirbuf.dotdot_ino == source->i_number) {
1060                         error = EINVAL;
1061                         break;
1062                 }
1063                 if (dirbuf.dotdot_ino == rootino)
1064                         break;
1065                 vput(vp);
1066                 if ((error = VFS_VGET(vp->v_mount, dirbuf.dotdot_ino, &vp)) != 0) {
1067                         vp = NULL;
1068                         break;
1069                 }
1070         }
1071
1072 out:
1073         if (error == ENOTDIR)
1074                 printf("checkpath: .. not a directory\n");
1075         if (vp != NULL)
1076                 vput(vp);
1077         return (error);
1078 }
1079