2 * modified for Lites 1.1
4 * Aug 1995, Godmar Back (gback@cs.utah.edu)
5 * University of Utah, Department of Computer Science
7 * $FreeBSD: src/sys/gnu/ext2fs/ext2_lookup.c,v 1.21.2.3 2002/11/17 02:02:42 bde Exp $
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.
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * 3. Neither the name of the University nor the names of its contributors
27 * may be used to endorse or promote products derived from this software
28 * without specific prior written permission.
30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * @(#)ufs_lookup.c 8.6 (Berkeley) 4/1/94
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/namei.h>
49 #include <sys/mount.h>
50 #include <sys/vnode.h>
51 #include <sys/malloc.h>
52 #include <sys/dirent.h>
57 #include "ext2_mount.h"
58 #include "ext2_extern.h"
60 #include "ext2_fs_sb.h"
63 DIRBLKSIZE in ffs is DEV_BSIZE (in most cases 512)
64 while it is the native blocksize in ext2fs - thus, a #define
65 is no longer appropriate
71 static u_char ext2_ft_to_dt[] = {
72 DT_UNKNOWN, /* EXT2_FT_UNKNOWN */
73 DT_REG, /* EXT2_FT_REG_FILE */
74 DT_DIR, /* EXT2_FT_DIR */
75 DT_CHR, /* EXT2_FT_CHRDEV */
76 DT_BLK, /* EXT2_FT_BLKDEV */
77 DT_FIFO, /* EXT2_FT_FIFO */
78 DT_SOCK, /* EXT2_FT_SOCK */
79 DT_LNK, /* EXT2_FT_SYMLINK */
82 ((ft) > NELEM(ext2_ft_to_dt) ? \
83 DT_UNKNOWN : ext2_ft_to_dt[(ft)])
85 static u_char dt_to_ext2_ft[] = {
86 EXT2_FT_UNKNOWN, /* DT_UNKNOWN */
87 EXT2_FT_FIFO, /* DT_FIFO */
88 EXT2_FT_CHRDEV, /* DT_CHR */
89 EXT2_FT_UNKNOWN, /* unused */
90 EXT2_FT_DIR, /* DT_DIR */
91 EXT2_FT_UNKNOWN, /* unused */
92 EXT2_FT_BLKDEV, /* DT_BLK */
93 EXT2_FT_UNKNOWN, /* unused */
94 EXT2_FT_REG_FILE, /* DT_REG */
95 EXT2_FT_UNKNOWN, /* unused */
96 EXT2_FT_SYMLINK, /* DT_LNK */
97 EXT2_FT_UNKNOWN, /* unused */
98 EXT2_FT_SOCK, /* DT_SOCK */
99 EXT2_FT_UNKNOWN, /* unused */
100 EXT2_FT_UNKNOWN, /* DT_WHT */
103 ((dt) > NELEM(dt_to_ext2_ft) ? \
104 EXT2_FT_UNKNOWN : dt_to_ext2_ft[(dt)])
106 static int ext2_dirbadentry (struct vnode *dp,
107 struct ext2_dir_entry_2 *de,
108 int entryoffsetinblock);
111 * Vnode op for reading directories.
113 * The routine below assumes that the on-disk format of a directory
114 * is the same as that defined by <sys/dirent.h>. If the on-disk
115 * format changes, then it will be necessary to do a conversion
116 * from the on-disk format that read returns to the format defined
120 * this is exactly what we do here - the problem is that the conversion
121 * will blow up some entries by four bytes, so it can't be done in place.
122 * This is too bad. Right now the conversion is done entry by entry, the
123 * converted entry is sent via uiomove.
125 * XXX allocate a buffer, convert as many entries as possible, then send
126 * the whole buffer to uiomove
128 * ext2_readdir(struct vnode *a_vp, struct uio *a_uio, struct ucred *a_cred)
131 ext2_readdir(struct vop_readdir_args *ap)
133 struct uio *uio = ap->a_uio;
135 struct ext2_dir_entry_2 *edp, *dp;
140 int DIRBLKSIZ = VTOI(ap->a_vp)->i_e2fs->s_blocksize;
142 off_t startoffset = uio->uio_offset;
144 error = vn_lock(ap->a_vp, LK_EXCLUSIVE | LK_RETRY | LK_FAILRECLAIM);
148 count = uio->uio_resid;
150 * Avoid complications for partial directory entries by adjusting
151 * the i/o to end at a block boundary. Don't give up (like ufs
152 * does) if the initial adjustment gives a negative count, since
153 * many callers don't supply a large enough buffer. The correct
154 * size is a little larger than DIRBLKSIZ to allow for expansion
155 * of directory entries, but some callers just use 512.
157 count -= (uio->uio_offset + count) & (DIRBLKSIZ -1);
160 if (count > MAXBSIZE) /* limit to a reasonable size */
164 kprintf("ext2_readdir: uio_offset = %lld, uio_resid = %d, count = %d\n",
165 uio->uio_offset, uio->uio_resid, count);
169 auio.uio_iov = &aiov;
171 auio.uio_resid = count;
172 auio.uio_segflg = UIO_SYSSPACE;
173 aiov.iov_len = count;
174 dirbuf = kmalloc(count, M_TEMP, M_WAITOK);
175 aiov.iov_base = dirbuf;
176 error = VOP_READ(ap->a_vp, &auio, 0, ap->a_cred);
178 readcnt = count - auio.uio_resid;
179 edp = (struct ext2_dir_entry_2 *)&dirbuf[readcnt];
181 for (dp = (struct ext2_dir_entry_2 *)dirbuf;
182 !error && uio->uio_resid > 0 && dp < edp; ) {
184 * "New" ext2fs directory entries differ in 3 ways
185 * from ufs on-disk ones:
186 * - the name is not necessarily NUL-terminated.
187 * - the file type field always exists and always
188 * follows the name length field.
189 * - the file type is encoded in a different way.
191 * "Old" ext2fs directory entries need no special
192 * conversions, since they binary compatible with
193 * "new" entries having a file type of 0 (i.e.,
194 * EXT2_FT_UNKNOWN). Splitting the old name length
195 * field didn't make a mess like it did in ufs,
196 * because ext2fs uses a machine-dependent disk
199 if (dp->rec_len <= 0) {
203 retval = vop_write_dirent(&error, uio, dp->inode,
204 FTTODT(dp->file_type), dp->name_len, dp->name);
209 dp = (struct ext2_dir_entry_2 *)((char *)dp + dp->rec_len);
213 /* we need to correct uio_offset */
214 uio->uio_offset = startoffset + (caddr_t)dp - dirbuf;
216 if (!error && ap->a_ncookies != NULL) {
217 off_t *cookiep, *cookies, *ecookies;
220 if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
221 panic("ext2fs_readdir: unexpected uio from NFS server");
223 cookies = kmalloc(ncookies * sizeof(off_t),
226 cookies = kmalloc(sizeof(off_t), M_TEMP,
230 for (dp = (struct ext2_dir_entry_2 *)dirbuf,
231 cookiep = cookies, ecookies = cookies + ncookies;
233 dp = (struct ext2_dir_entry_2 *)((caddr_t) dp + dp->rec_len)) {
237 *ap->a_ncookies = ncookies;
238 *ap->a_cookies = cookies;
241 kfree(dirbuf, M_TEMP);
243 *ap->a_eofflag = VTOI(ap->a_vp)->i_size <= uio->uio_offset;
249 * Convert a component of a pathname into a pointer to a locked inode.
250 * This is a very central and rather complicated routine.
251 * If the file system is not maintained in a strict tree hierarchy,
252 * this can result in a deadlock situation (see comments in code below).
254 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
255 * on whether the name is to be looked up, created, renamed, or deleted.
256 * When CREATE, RENAME, or DELETE is specified, information usable in
257 * creating, renaming, or deleting a directory entry may be calculated.
258 * If flag has LOCKPARENT or'ed into it and the target of the pathname
259 * exists, lookup returns both the target and its parent directory locked.
260 * When creating or renaming and LOCKPARENT is specified, the target may
261 * not be ".". When deleting and LOCKPARENT is specified, the target may
262 * be "."., but the caller must check to ensure it does an vrele and vput
263 * instead of two vputs.
265 * Overall outline of ufs_lookup:
267 * search for name in directory, to found or notfound
269 * if creating, return locked directory, leaving info on available slots
272 * if at end of path and deleting, return information to allow delete
273 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
274 * inode and return info to allow rewrite
275 * if not at end, add name to cache; if at end and neither creating
276 * nor deleting, add name to cache
278 * ext2_lookup(struct vnode *a_dvp, struct vnode **a_vpp,
279 * struct componentname *a_cnp)
282 ext2_lookup(struct vop_old_lookup_args *ap)
284 struct vnode *vdp; /* vnode for directory being searched */
285 struct inode *dp; /* inode for directory being searched */
286 struct buf *bp; /* a buffer of directory entries */
287 struct ext2_dir_entry_2 *ep; /* the current directory entry */
288 int entryoffsetinblock; /* offset of ep in bp's buffer */
289 enum {NONE, COMPACT, FOUND} slotstatus;
290 doff_t slotoffset; /* offset of area with free space */
291 int slotsize; /* size of area at slotoffset */
292 int slotfreespace; /* amount of space free in slot */
293 int slotneeded; /* size of the entry we're seeking */
294 int numdirpasses; /* strategy for directory search */
295 doff_t endsearch; /* offset to end directory search */
296 doff_t prevoff; /* prev entry dp->i_offset */
297 struct vnode *pdp; /* saved dp during symlink work */
298 struct vnode *tdp; /* returned by VFS_VGET */
299 doff_t enduseful; /* pointer past last used dir slot */
300 u_long bmask; /* block offset mask */
301 int lockparent; /* 1 => lockparent flag is set */
302 int wantparent; /* 1 => wantparent or lockparent flag */
304 struct vnode **vpp = ap->a_vpp;
305 struct componentname *cnp = ap->a_cnp;
306 struct ucred *cred = cnp->cn_cred;
307 int flags = cnp->cn_flags;
308 int nameiop = cnp->cn_nameiop;
310 int DIRBLKSIZ = VTOI(ap->a_dvp)->i_e2fs->s_blocksize;
317 lockparent = flags & CNP_LOCKPARENT;
318 wantparent = flags & (CNP_LOCKPARENT|CNP_WANTPARENT);
321 * We now have a segment name to search for, and a directory to search.
325 * Suppress search for slots unless creating
326 * file and at end of pathname, in which case
327 * we watch for a place to put the new file in
328 * case it doesn't already exist.
331 slotfreespace = slotsize = slotneeded = 0;
332 if (nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) {
334 slotneeded = EXT2_DIR_REC_LEN(cnp->cn_namelen);
336 slotneeded = (sizeof(struct direct) - MAXNAMLEN +
337 cnp->cn_namelen + 3) &~ 3; */
341 * If there is cached information on a previous search of
342 * this directory, pick up where we last left off.
343 * We cache only lookups as these are the most common
344 * and have the greatest payoff. Caching CREATE has little
345 * benefit as it usually must search the entire directory
346 * to determine that the entry does not exist. Caching the
347 * location of the last DELETE or RENAME has not reduced
348 * profiling time and hence has been removed in the interest
351 bmask = VFSTOEXT2(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
352 if (nameiop != NAMEI_LOOKUP || dp->i_diroff == 0 ||
353 dp->i_diroff > dp->i_size) {
354 entryoffsetinblock = 0;
358 dp->i_offset = dp->i_diroff;
359 if ((entryoffsetinblock = dp->i_offset & bmask) &&
360 (error = EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)))
364 prevoff = dp->i_offset;
365 endsearch = roundup(dp->i_size, DIRBLKSIZ);
369 while (dp->i_offset < endsearch) {
371 * If necessary, get the next directory block.
373 if ((dp->i_offset & bmask) == 0) {
377 EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)) != 0)
379 entryoffsetinblock = 0;
382 * If still looking for a slot, and at a DIRBLKSIZE
383 * boundary, have to start looking for free space again.
385 if (slotstatus == NONE &&
386 (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
391 * Get pointer to next entry.
392 * Full validation checks are slow, so we only check
393 * enough to insure forward progress through the
394 * directory. Complete checks can be run by patching
395 * "dirchk" to be true.
397 ep = (struct ext2_dir_entry_2 *)
398 ((char *)bp->b_data + entryoffsetinblock);
399 if (ep->rec_len == 0 ||
400 (dirchk && ext2_dirbadentry(vdp, ep, entryoffsetinblock))) {
402 ext2_dirbad(dp, dp->i_offset, "mangled entry");
403 i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
405 entryoffsetinblock += i;
410 * If an appropriate sized slot has not yet been found,
411 * check to see if one is available. Also accumulate space
412 * in the current block so that we can determine if
413 * compaction is viable.
415 if (slotstatus != FOUND) {
416 int size = ep->rec_len;
419 size -= EXT2_DIR_REC_LEN(ep->name_len);
421 if (size >= slotneeded) {
423 slotoffset = dp->i_offset;
424 slotsize = ep->rec_len;
425 } else if (slotstatus == NONE) {
426 slotfreespace += size;
427 if (slotoffset == -1)
428 slotoffset = dp->i_offset;
429 if (slotfreespace >= slotneeded) {
430 slotstatus = COMPACT;
431 slotsize = dp->i_offset +
432 ep->rec_len - slotoffset;
439 * Check for a name match.
442 namlen = ep->name_len;
443 if (namlen == cnp->cn_namelen &&
444 !bcmp(cnp->cn_nameptr, ep->name,
447 * Save directory entry's inode number and
448 * reclen in ndp->ni_ufs area, and release
451 dp->i_ino = ep->inode;
452 dp->i_reclen = ep->rec_len;
456 prevoff = dp->i_offset;
457 dp->i_offset += ep->rec_len;
458 entryoffsetinblock += ep->rec_len;
460 enduseful = dp->i_offset;
464 * If we started in the middle of the directory and failed
465 * to find our target, we must check the beginning as well.
467 if (numdirpasses == 2) {
470 endsearch = dp->i_diroff;
476 * If creating, and at end of pathname and current
477 * directory has not been removed, then can consider
478 * allowing file to be created.
480 if ((nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) &&
483 * Access for write is interpreted as allowing
484 * creation of files in the directory.
486 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
489 * Return an indication of where the new directory
490 * entry should be put. If we didn't find a slot,
491 * then set dp->i_count to 0 indicating
492 * that the new slot belongs at the end of the
493 * directory. If we found a slot, then the new entry
494 * can be put in the range from dp->i_offset to
495 * dp->i_offset + dp->i_count.
497 if (slotstatus == NONE) {
498 dp->i_offset = roundup(dp->i_size, DIRBLKSIZ);
500 enduseful = dp->i_offset;
502 dp->i_offset = slotoffset;
503 dp->i_count = slotsize;
504 if (enduseful < slotoffset + slotsize)
505 enduseful = slotoffset + slotsize;
507 dp->i_endoff = roundup(enduseful, DIRBLKSIZ);
508 dp->i_flag |= IN_CHANGE | IN_UPDATE;
510 * We return with the directory locked, so that
511 * the parameters we set up above will still be
512 * valid if we actually decide to do a direnter().
513 * We return ni_vp == NULL to indicate that the entry
514 * does not currently exist; we leave a pointer to
515 * the (locked) directory inode in ndp->ni_dvp.
516 * The pathname buffer is saved so that the name
517 * can be obtained later.
519 * NB - if the directory is unlocked, then this
520 * information cannot be used.
524 return (EJUSTRETURN);
530 * Check that directory length properly reflects presence
533 if (entryoffsetinblock + EXT2_DIR_REC_LEN(ep->name_len)
535 ext2_dirbad(dp, dp->i_offset, "i_size too small");
536 dp->i_size = entryoffsetinblock+EXT2_DIR_REC_LEN(ep->name_len);
537 dp->i_flag |= IN_CHANGE | IN_UPDATE;
542 * Found component in pathname.
543 * If the final component of path name, save information
544 * in the cache as to where the entry was found.
546 if (nameiop == NAMEI_LOOKUP)
547 dp->i_diroff = dp->i_offset &~ (DIRBLKSIZ - 1);
550 * If deleting, and at end of pathname, return
551 * parameters which can be used to remove file.
552 * If the wantparent flag isn't set, we return only
553 * the directory (in ndp->ni_dvp), otherwise we go
554 * on and lock the inode, being careful with ".".
556 if (nameiop == NAMEI_DELETE) {
558 * Write access to directory required to delete files.
560 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
563 * Return pointer to current entry in dp->i_offset,
564 * and distance past previous entry (if there
565 * is a previous entry in this block) in dp->i_count.
566 * Save directory inode pointer in ndp->ni_dvp for dirremove().
568 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
571 dp->i_count = dp->i_offset - prevoff;
572 if (dp->i_number == dp->i_ino) {
577 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
580 * If directory is "sticky", then user must own
581 * the directory, or the file in it, else she
582 * may not delete it (unless she's root). This
583 * implements append-only directories.
585 if ((dp->i_mode & ISVTX) &&
587 cred->cr_uid != dp->i_uid &&
588 VTOI(tdp)->i_uid != cred->cr_uid) {
599 * If rewriting (RENAME), return the inode and the
600 * information required to rewrite the present directory
601 * Must get inode of directory entry to verify it's a
602 * regular file, or empty directory.
604 if (nameiop == NAMEI_RENAME && wantparent) {
605 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
608 * Careful about locking second inode.
609 * This can only occur if the target is ".".
611 if (dp->i_number == dp->i_ino)
613 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
622 * Step through the translation in the name. We do not `vput' the
623 * directory because we may need it again if a symbolic link
624 * is relative to the current directory. Instead we save it
625 * unlocked as "pdp". We must get the target inode before unlocking
626 * the directory to insure that the inode will not be removed
627 * before we get it. We prevent deadlock by always fetching
628 * inodes from the root, moving down the directory tree. Thus
629 * when following backward pointers ".." we must unlock the
630 * parent directory before getting the requested directory.
631 * There is a potential race condition here if both the current
632 * and parent directories are removed before the VFS_VGET for the
633 * inode associated with ".." returns. We hope that this occurs
634 * infrequently since we cannot avoid this race condition without
635 * implementing a sophisticated deadlock detection algorithm.
636 * Note also that this simple deadlock detection scheme will not
637 * work if the file system has any hard links other than ".."
638 * that point backwards in the directory structure.
641 if (flags & CNP_ISDOTDOT) {
642 vn_unlock(pdp); /* race to get the inode */
643 error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp);
645 vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
649 error = vn_lock(pdp, LK_EXCLUSIVE | LK_FAILRECLAIM);
656 } else if (dp->i_number == dp->i_ino) {
657 vref(vdp); /* we want ourself, ie "." */
660 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
664 cnp->cn_flags |= CNP_PDIRUNLOCK;
672 ext2_dirbad(struct inode *ip, doff_t offset, char *how)
676 mp = ITOV(ip)->v_mount;
677 kprintf("%s: bad dir ino %lu at offset %ld: %s\n",
678 mp->mnt_stat.f_mntfromname, (u_long)ip->i_number,
680 if ((mp->mnt_flag & MNT_RDONLY) == 0)
681 panic("ufs_dirbad: bad dir");
685 * Do consistency checking on a directory entry:
686 * record length must be multiple of 4
687 * entry must fit in rest of its DIRBLKSIZ block
688 * record must be large enough to contain entry
689 * name is not longer than MAXNAMLEN
690 * name must be as long as advertised, and null terminated
693 * changed so that it confirms to ext2_check_dir_entry
696 ext2_dirbadentry(struct vnode *dp, struct ext2_dir_entry_2 *de,
697 int entryoffsetinblock)
699 int DIRBLKSIZ = VTOI(dp)->i_e2fs->s_blocksize;
701 char *error_msg = NULL;
703 if (de->rec_len < EXT2_DIR_REC_LEN(1))
704 error_msg = "rec_len is smaller than minimal";
705 else if (de->rec_len % 4 != 0)
706 error_msg = "rec_len % 4 != 0";
707 else if (de->rec_len < EXT2_DIR_REC_LEN(de->name_len))
708 error_msg = "reclen is too small for name_len";
709 else if (entryoffsetinblock + de->rec_len > DIRBLKSIZ)
710 error_msg = "directory entry across blocks";
712 if (de->inode > dir->i_sb->u.ext2_sb.s_es->s_inodes_count)
713 error_msg = "inode out of bounds";
716 if (error_msg != NULL) {
717 kprintf("bad directory entry: %s\n", error_msg);
718 kprintf("offset=%d, inode=%lu, rec_len=%u, name_len=%u\n",
719 entryoffsetinblock, (unsigned long)de->inode,
720 de->rec_len, de->name_len);
722 return error_msg == NULL ? 0 : 1;
726 * Write a directory entry after a call to namei, using the parameters
727 * that it left in the directory inode. The argument ip is the inode which
728 * the new directory entry will refer to. Dvp is a pointer to the directory
729 * to be written, which was left locked by namei. Remaining parameters
730 * (dp->i_offset, dp->i_count) indicate how the space for the new
731 * entry is to be obtained.
734 ext2_direnter(struct inode *ip, struct vnode *dvp, struct componentname *cnp)
736 struct ext2_dir_entry_2 *ep, *nep;
739 struct ext2_dir_entry_2 newdir;
743 int error, loc, newentrysize, spacefree;
745 int DIRBLKSIZ = ip->i_e2fs->s_blocksize;
749 newdir.inode = ip->i_number;
750 newdir.name_len = cnp->cn_namelen;
751 if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
752 EXT2_FEATURE_INCOMPAT_FILETYPE))
753 newdir.file_type = DTTOFT(IFTODT(ip->i_mode));
755 newdir.file_type = EXT2_FT_UNKNOWN;
756 bcopy(cnp->cn_nameptr, newdir.name, (unsigned)cnp->cn_namelen + 1);
757 newentrysize = EXT2_DIR_REC_LEN(newdir.name_len);
758 if (dp->i_count == 0) {
760 * If dp->i_count is 0, then namei could find no
761 * space in the directory. Here, dp->i_offset will
762 * be on a directory block boundary and we will write the
763 * new entry into a fresh block.
765 if (dp->i_offset & (DIRBLKSIZ - 1))
766 panic("ext2_direnter: newblk");
767 auio.uio_offset = dp->i_offset;
768 newdir.rec_len = DIRBLKSIZ;
769 auio.uio_resid = newentrysize;
770 aiov.iov_len = newentrysize;
771 aiov.iov_base = (caddr_t)&newdir;
772 auio.uio_iov = &aiov;
774 auio.uio_rw = UIO_WRITE;
775 auio.uio_segflg = UIO_SYSSPACE;
777 error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
779 VFSTOEXT2(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
780 /* XXX should grow with balloc() */
781 panic("ext2_direnter: frag size");
783 dp->i_size = roundup(dp->i_size, DIRBLKSIZ);
784 dp->i_flag |= IN_CHANGE;
790 * If dp->i_count is non-zero, then namei found space
791 * for the new entry in the range dp->i_offset to
792 * dp->i_offset + dp->i_count in the directory.
793 * To use this space, we may have to compact the entries located
794 * there, by copying them together towards the beginning of the
795 * block, leaving the free space in one usable chunk at the end.
799 * Increase size of directory if entry eats into new space.
800 * This should never push the size past a new multiple of
803 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
805 if (dp->i_offset + dp->i_count > dp->i_size)
806 dp->i_size = dp->i_offset + dp->i_count;
808 * Get the block containing the space for the new directory entry.
810 if ((error = EXT2_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp)) != 0)
813 * Find space for the new entry. In the simple case, the entry at
814 * offset base will have the space. If it does not, then namei
815 * arranged that compacting the region dp->i_offset to
816 * dp->i_offset + dp->i_count would yield the
819 ep = (struct ext2_dir_entry_2 *)dirbuf;
820 dsize = EXT2_DIR_REC_LEN(ep->name_len);
821 spacefree = ep->rec_len - dsize;
822 for (loc = ep->rec_len; loc < dp->i_count; ) {
823 nep = (struct ext2_dir_entry_2 *)(dirbuf + loc);
825 /* trim the existing slot */
827 ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
829 /* overwrite; nothing there; header is ours */
832 dsize = EXT2_DIR_REC_LEN(nep->name_len);
833 spacefree += nep->rec_len - dsize;
835 bcopy((caddr_t)nep, (caddr_t)ep, dsize);
838 * Update the pointer fields in the previous entry (if any),
839 * copy in the new entry, and write out the block.
841 if (ep->inode == 0) {
842 if (spacefree + dsize < newentrysize)
843 panic("ext2_direnter: compact1");
844 newdir.rec_len = spacefree + dsize;
846 if (spacefree < newentrysize)
847 panic("ext2_direnter: compact2");
848 newdir.rec_len = spacefree;
850 ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
852 bcopy((caddr_t)&newdir, (caddr_t)ep, (u_int)newentrysize);
854 dp->i_flag |= IN_CHANGE | IN_UPDATE;
855 if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
856 error = EXT2_TRUNCATE(dvp, (off_t)dp->i_endoff, IO_SYNC,
862 * Remove a directory entry after a call to namei, using
863 * the parameters which it left in the directory inode. The entry
864 * dp->i_offset contains the offset into the directory of the
865 * entry to be eliminated. The dp->i_count field contains the
866 * size of the previous record in the directory. If this
867 * is 0, the first entry is being deleted, so we need only
868 * zero the inode number to mark the entry as free. If the
869 * entry is not the first in the directory, we must reclaim
870 * the space of the now empty record by adding the record size
871 * to the size of the previous entry.
874 ext2_dirremove(struct vnode *dvp, struct componentname *cnp)
877 struct ext2_dir_entry_2 *ep;
882 if (dp->i_count == 0) {
884 * First entry in block: set d_ino to zero.
887 EXT2_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
891 dp->i_flag |= IN_CHANGE | IN_UPDATE;
895 * Collapse new free space into previous entry.
897 if ((error = EXT2_BLKATOFF(dvp, (off_t)(dp->i_offset - dp->i_count),
898 (char **)&ep, &bp)) != 0)
900 ep->rec_len += dp->i_reclen;
902 dp->i_flag |= IN_CHANGE | IN_UPDATE;
907 * Rewrite an existing directory entry to point at the inode
908 * supplied. The parameters describing the directory entry are
909 * set up by a call to namei.
912 ext2_dirrewrite(struct inode *dp, struct inode *ip, struct componentname *cnp)
915 struct ext2_dir_entry_2 *ep;
916 struct vnode *vdp = ITOV(dp);
919 if ((error = EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
921 ep->inode = ip->i_number;
922 if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
923 EXT2_FEATURE_INCOMPAT_FILETYPE))
924 ep->file_type = DTTOFT(IFTODT(ip->i_mode));
926 ep->file_type = EXT2_FT_UNKNOWN;
928 dp->i_flag |= IN_CHANGE | IN_UPDATE;
933 * Check if a directory is empty or not.
934 * Inode supplied must be locked.
936 * Using a struct dirtemplate here is not precisely
937 * what we want, but better than using a struct direct.
939 * NB: does not handle corrupted directories.
942 ext2_dirempty(struct inode *ip, ino_t parentino, struct ucred *cred)
945 struct dirtemplate dbuf;
946 struct ext2_dir_entry_2 *dp = (struct ext2_dir_entry_2 *)&dbuf;
947 int error, count, namlen;
949 #define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
951 for (off = 0; off < ip->i_size; off += dp->rec_len) {
952 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ, off,
953 UIO_SYSSPACE, IO_NODELOCKED, cred, &count);
955 * Since we read MINDIRSIZ, residual must
956 * be 0 unless we're at end of file.
958 if (error || count != 0)
960 /* avoid infinite loops */
961 if (dp->rec_len == 0)
963 /* skip empty entries */
966 /* accept only "." and ".." */
967 namlen = dp->name_len;
970 if (dp->name[0] != '.')
973 * At this point namlen must be 1 or 2.
974 * 1 implies ".", 2 implies ".." if second
979 if (dp->name[1] == '.' && dp->inode == parentino)
987 * Check if source directory is in the path of the target directory.
988 * Target is supplied locked, source is unlocked.
989 * The target is always vput before returning.
992 ext2_checkpath(struct inode *source, struct inode *target, struct ucred *cred)
995 int error, rootino, namlen;
996 struct dirtemplate dirbuf;
999 if (target->i_number == source->i_number) {
1003 rootino = EXT2_ROOTINO;
1005 if (target->i_number == rootino)
1009 if (vp->v_type != VDIR) {
1013 error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
1014 sizeof (struct dirtemplate), (off_t)0,
1015 UIO_SYSSPACE, IO_NODELOCKED, cred, NULL);
1018 namlen = dirbuf.dotdot_type; /* like ufs little-endian */
1020 dirbuf.dotdot_name[0] != '.' ||
1021 dirbuf.dotdot_name[1] != '.') {
1025 if (dirbuf.dotdot_ino == source->i_number) {
1029 if (dirbuf.dotdot_ino == rootino)
1032 if ((error = VFS_VGET(vp->v_mount, NULL, dirbuf.dotdot_ino, &vp)) != 0) {
1039 if (error == ENOTDIR)
1040 kprintf("checkpath: .. not a directory\n");