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