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