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