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