Home | History | Annotate | Line # | Download | only in msdosfs
msdosfs_lookup.c revision 1.10
      1 /*	$NetBSD: msdosfs_lookup.c,v 1.10 2006/11/25 12:17:30 scw Exp $	*/
      2 
      3 /*-
      4  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
      5  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
      6  * All rights reserved.
      7  * Original code by Paul Popelka (paulp (at) uts.amdahl.com) (see below).
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by TooLs GmbH.
     20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 /*
     35  * Written by Paul Popelka (paulp (at) uts.amdahl.com)
     36  *
     37  * You can do anything you want with this software, just don't say you wrote
     38  * it, and don't remove this notice.
     39  *
     40  * This software is provided "as is".
     41  *
     42  * The author supplies this software to be publicly redistributed on the
     43  * understanding that the author is not responsible for the correct
     44  * functioning of this software in any circumstances and is not liable for
     45  * any damages caused by this software.
     46  *
     47  * October 1992
     48  */
     49 
     50 #include <sys/cdefs.h>
     51 __KERNEL_RCSID(0, "$NetBSD: msdosfs_lookup.c,v 1.10 2006/11/25 12:17:30 scw Exp $");
     52 
     53 #include <sys/param.h>
     54 #include <sys/systm.h>
     55 #include <sys/namei.h>
     56 #include <sys/buf.h>
     57 #include <sys/vnode.h>
     58 #include <sys/mount.h>
     59 #include <sys/dirent.h>
     60 #include <sys/kauth.h>
     61 
     62 #include <fs/msdosfs/bpb.h>
     63 #include <fs/msdosfs/direntry.h>
     64 #include <fs/msdosfs/denode.h>
     65 #include <fs/msdosfs/msdosfsmount.h>
     66 #include <fs/msdosfs/fat.h>
     67 
     68 /*
     69  * When we search a directory the blocks containing directory entries are
     70  * read and examined.  The directory entries contain information that would
     71  * normally be in the inode of a unix filesystem.  This means that some of
     72  * a directory's contents may also be in memory resident denodes (sort of
     73  * an inode).  This can cause problems if we are searching while some other
     74  * process is modifying a directory.  To prevent one process from accessing
     75  * incompletely modified directory information we depend upon being the
     76  * sole owner of a directory block.  bread/brelse provide this service.
     77  * This being the case, when a process modifies a directory it must first
     78  * acquire the disk block that contains the directory entry to be modified.
     79  * Then update the disk block and the denode, and then write the disk block
     80  * out to disk.  This way disk blocks containing directory entries and in
     81  * memory denode's will be in synch.
     82  */
     83 int
     84 msdosfs_lookup(v)
     85 	void *v;
     86 {
     87 	struct vop_lookup_args /* {
     88 		struct vnode *a_dvp;
     89 		struct vnode **a_vpp;
     90 		struct componentname *a_cnp;
     91 	} */ *ap = v;
     92 	struct vnode *vdp = ap->a_dvp;
     93 	struct vnode **vpp = ap->a_vpp;
     94 	struct componentname *cnp = ap->a_cnp;
     95 	daddr_t bn;
     96 	int error;
     97 	int lockparent;
     98 	int wantparent;
     99 	int slotcount;
    100 	int slotoffset = 0;
    101 	int frcn;
    102 	u_long cluster;
    103 	int blkoff;
    104 	int diroff;
    105 	int blsize;
    106 	int isadir;		/* ~0 if found direntry is a directory	 */
    107 	u_long scn;		/* starting cluster number		 */
    108 	struct vnode *pdp;
    109 	struct denode *dp;
    110 	struct denode *tdp;
    111 	struct msdosfsmount *pmp;
    112 	struct buf *bp = 0;
    113 	struct direntry *dep;
    114 	u_char dosfilename[12];
    115 	int flags;
    116 	int nameiop = cnp->cn_nameiop;
    117 	int wincnt = 1;
    118 	int chksum = -1, chksum_ok;
    119 	int olddos = 1;
    120 
    121 	cnp->cn_flags &= ~PDIRUNLOCK; /* XXX why this ?? */
    122 	flags = cnp->cn_flags;
    123 
    124 #ifdef MSDOSFS_DEBUG
    125 	printf("msdosfs_lookup(): looking for %.*s\n",
    126 		(int)cnp->cn_namelen, cnp->cn_nameptr);
    127 #endif
    128 	dp = VTODE(vdp);
    129 	pmp = dp->de_pmp;
    130 	*vpp = NULL;
    131 	lockparent = flags & LOCKPARENT;
    132 	wantparent = flags & (LOCKPARENT | WANTPARENT);
    133 #ifdef MSDOSFS_DEBUG
    134 	printf("msdosfs_lookup(): vdp %p, dp %p, Attr %02x\n",
    135 	    vdp, dp, dp->de_Attributes);
    136 #endif
    137 
    138 	/*
    139 	 * Check accessiblity of directory.
    140 	 */
    141 	if ((error = VOP_ACCESS(vdp, VEXEC, cnp->cn_cred, cnp->cn_lwp)) != 0)
    142 		return (error);
    143 
    144 	if ((flags & ISLASTCN) && (vdp->v_mount->mnt_flag & MNT_RDONLY) &&
    145 	    (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
    146 		return (EROFS);
    147 
    148 	/*
    149 	 * We now have a segment name to search for, and a directory to search.
    150 	 *
    151 	 * Before tediously performing a linear scan of the directory,
    152 	 * check the name cache to see if the directory/name pair
    153 	 * we are looking for is known already.
    154 	 */
    155 	if ((error = cache_lookup(vdp, vpp, cnp)) >= 0)
    156 		return (error);
    157 
    158 	/*
    159 	 * If they are going after the . or .. entry in the root directory,
    160 	 * they won't find it.  DOS filesystems don't have them in the root
    161 	 * directory.  So, we fake it. deget() is in on this scam too.
    162 	 */
    163 	if ((vdp->v_flag & VROOT) && cnp->cn_nameptr[0] == '.' &&
    164 	    (cnp->cn_namelen == 1 ||
    165 		(cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.'))) {
    166 		isadir = ATTR_DIRECTORY;
    167 		scn = MSDOSFSROOT;
    168 #ifdef MSDOSFS_DEBUG
    169 		printf("msdosfs_lookup(): looking for . or .. in root directory\n");
    170 #endif
    171 		cluster = MSDOSFSROOT;
    172 		blkoff = MSDOSFSROOT_OFS;
    173 		goto foundroot;
    174 	}
    175 
    176 	switch (unix2dosfn((const u_char *)cnp->cn_nameptr, dosfilename,
    177 	    cnp->cn_namelen, 0)) {
    178 	case 0:
    179 		return (EINVAL);
    180 	case 1:
    181 		break;
    182 	case 2:
    183 		wincnt = winSlotCnt((const u_char *)cnp->cn_nameptr,
    184 		    cnp->cn_namelen) + 1;
    185 		break;
    186 	case 3:
    187 		olddos = 0;
    188 		wincnt = winSlotCnt((const u_char *)cnp->cn_nameptr,
    189 		    cnp->cn_namelen) + 1;
    190 		break;
    191 	}
    192 	if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
    193 		wincnt = 1;
    194 
    195 	/*
    196 	 * Suppress search for slots unless creating
    197 	 * file and at end of pathname, in which case
    198 	 * we watch for a place to put the new file in
    199 	 * case it doesn't already exist.
    200 	 */
    201 	slotcount = wincnt;
    202 	if ((nameiop == CREATE || nameiop == RENAME) &&
    203 	    (flags & ISLASTCN))
    204 		slotcount = 0;
    205 
    206 #ifdef MSDOSFS_DEBUG
    207 	printf("msdosfs_lookup(): dos filename: %s\n", dosfilename);
    208 #endif
    209 	/*
    210 	 * Search the directory pointed at by vdp for the name pointed at
    211 	 * by cnp->cn_nameptr.
    212 	 */
    213 	tdp = NULL;
    214 	/*
    215 	 * The outer loop ranges over the clusters that make up the
    216 	 * directory.  Note that the root directory is different from all
    217 	 * other directories.  It has a fixed number of blocks that are not
    218 	 * part of the pool of allocatable clusters.  So, we treat it a
    219 	 * little differently. The root directory starts at "cluster" 0.
    220 	 */
    221 	diroff = 0;
    222 	for (frcn = 0; diroff < dp->de_FileSize; frcn++) {
    223 		if ((error = pcbmap(dp, frcn, &bn, &cluster, &blsize)) != 0) {
    224 			if (error == E2BIG)
    225 				break;
    226 			return (error);
    227 		}
    228 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
    229 		    &bp);
    230 		if (error) {
    231 			brelse(bp);
    232 			return (error);
    233 		}
    234 		for (blkoff = 0; blkoff < blsize;
    235 		     blkoff += sizeof(struct direntry),
    236 		     diroff += sizeof(struct direntry)) {
    237 			dep = (struct direntry *)(bp->b_data + blkoff);
    238 			/*
    239 			 * If the slot is empty and we are still looking
    240 			 * for an empty then remember this one.  If the
    241 			 * slot is not empty then check to see if it
    242 			 * matches what we are looking for.  If the slot
    243 			 * has never been filled with anything, then the
    244 			 * remainder of the directory has never been used,
    245 			 * so there is no point in searching it.
    246 			 */
    247 			if (dep->deName[0] == SLOT_EMPTY ||
    248 			    dep->deName[0] == SLOT_DELETED) {
    249 				/*
    250 				 * Drop memory of previous long matches
    251 				 */
    252 				chksum = -1;
    253 
    254 				if (slotcount < wincnt) {
    255 					slotcount++;
    256 					slotoffset = diroff;
    257 				}
    258 				if (dep->deName[0] == SLOT_EMPTY) {
    259 					brelse(bp);
    260 					goto notfound;
    261 				}
    262 			} else {
    263 				/*
    264 				 * If there wasn't enough space for our
    265 				 * winentries, forget about the empty space
    266 				 */
    267 				if (slotcount < wincnt)
    268 					slotcount = 0;
    269 
    270 				/*
    271 				 * Check for Win95 long filename entry
    272 				 */
    273 				if (dep->deAttributes == ATTR_WIN95) {
    274 					if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
    275 						continue;
    276 
    277 					chksum = winChkName((const u_char *)cnp->cn_nameptr,
    278 							    cnp->cn_namelen,
    279 							    (struct winentry *)dep,
    280 							    chksum);
    281 					continue;
    282 				}
    283 
    284 				/*
    285 				 * Ignore volume labels (anywhere, not just
    286 				 * the root directory).
    287 				 */
    288 				if (dep->deAttributes & ATTR_VOLUME) {
    289 					chksum = -1;
    290 					continue;
    291 				}
    292 
    293 				/*
    294 				 * Check for a checksum or name match
    295 				 */
    296 				chksum_ok = (chksum == winChksum(dep->deName));
    297 				if (!chksum_ok
    298 				    && (!olddos || memcmp(dosfilename, dep->deName, 11))) {
    299 					chksum = -1;
    300 					continue;
    301 				}
    302 #ifdef MSDOSFS_DEBUG
    303 				printf("msdosfs_lookup(): match blkoff %d, diroff %d\n",
    304 				    blkoff, diroff);
    305 #endif
    306 				/*
    307 				 * Remember where this directory
    308 				 * entry came from for whoever did
    309 				 * this lookup.
    310 				 */
    311 				dp->de_fndoffset = diroff;
    312 				if (chksum_ok && nameiop == RENAME) {
    313 					/*
    314 					 * Target had correct long name
    315 					 * directory entries, reuse them
    316 					 * as needed.
    317 					 */
    318 					dp->de_fndcnt = wincnt - 1;
    319 				} else {
    320 					/*
    321 					 * Long name directory entries
    322 					 * not present or corrupt, can only
    323 					 * reuse dos directory entry.
    324 					 */
    325 					dp->de_fndcnt = 0;
    326 				}
    327 
    328 				goto found;
    329 			}
    330 		}	/* for (blkoff = 0; .... */
    331 		/*
    332 		 * Release the buffer holding the directory cluster just
    333 		 * searched.
    334 		 */
    335 		brelse(bp);
    336 	}	/* for (frcn = 0; ; frcn++) */
    337 
    338 notfound:
    339 	/*
    340 	 * We hold no disk buffers at this point.
    341 	 */
    342 
    343 	/*
    344 	 * If we get here we didn't find the entry we were looking for. But
    345 	 * that's ok if we are creating or renaming and are at the end of
    346 	 * the pathname and the directory hasn't been removed.
    347 	 */
    348 #ifdef MSDOSFS_DEBUG
    349 	printf("msdosfs_lookup(): op %d, refcnt %ld, slotcount %d, slotoffset %d\n",
    350 	    nameiop, dp->de_refcnt, slotcount, slotoffset);
    351 #endif
    352 	if ((nameiop == CREATE || nameiop == RENAME) &&
    353 	    (flags & ISLASTCN) && dp->de_refcnt != 0) {
    354 		/*
    355 		 * Access for write is interpreted as allowing
    356 		 * creation of files in the directory.
    357 		 */
    358 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_lwp);
    359 		if (error)
    360 			return (error);
    361 
    362 		/*
    363 		 * Fixup the slot description to point to the place where
    364 		 * we might put the new DOS direntry (putting the Win95
    365 		 * long name entries before that)
    366 		 */
    367 		if (!slotcount) {
    368 			slotcount = 1;
    369 			slotoffset = diroff;
    370 		}
    371 		if (wincnt > slotcount) {
    372 			slotoffset +=
    373 				sizeof(struct direntry) * (wincnt - slotcount);
    374 		}
    375 
    376 		/*
    377 		 * Return an indication of where the new directory
    378 		 * entry should be put.
    379 		 */
    380 		dp->de_fndoffset = slotoffset;
    381 		dp->de_fndcnt = wincnt - 1;
    382 
    383 		/*
    384 		 * We return with the directory locked, so that
    385 		 * the parameters we set up above will still be
    386 		 * valid if we actually decide to do a direnter().
    387 		 * We return ni_vp == NULL to indicate that the entry
    388 		 * does not currently exist; we leave a pointer to
    389 		 * the (locked) directory inode in ndp->ni_dvp.
    390 		 * The pathname buffer is saved so that the name
    391 		 * can be obtained later.
    392 		 *
    393 		 * NB - if the directory is unlocked, then this
    394 		 * information cannot be used.
    395 		 */
    396 		cnp->cn_flags |= SAVENAME;
    397 		if (!lockparent)
    398 			VOP_UNLOCK(vdp, 0);
    399 		return (EJUSTRETURN);
    400 	}
    401 
    402 #if 0
    403 	/*
    404 	 * Insert name into cache (as non-existent) if appropriate.
    405 	 *
    406 	 * XXX Negative caching is broken for msdosfs because the name
    407 	 * cache doesn't understand peculiarities such as case insensitivity
    408 	 * and 8.3 filenames.  Hence, it may not invalidate all negative
    409 	 * entries if a file with this name is later created.
    410 	 * e.g. creating a file 'foo' won't invalidate a negative entry
    411 	 * for 'FOO'.
    412 	 */
    413 	if ((cnp->cn_flags & MAKEENTRY) && nameiop != CREATE)
    414 		cache_enter(vdp, *vpp, cnp);
    415 #endif
    416 
    417 	return (ENOENT);
    418 
    419 found:
    420 	/*
    421 	 * NOTE:  We still have the buffer with matched directory entry at
    422 	 * this point.
    423 	 */
    424 	isadir = dep->deAttributes & ATTR_DIRECTORY;
    425 	scn = getushort(dep->deStartCluster);
    426 	if (FAT32(pmp)) {
    427 		scn |= getushort(dep->deHighClust) << 16;
    428 		if (scn == pmp->pm_rootdirblk) {
    429 			/*
    430 			 * There should actually be 0 here.
    431 			 * Just ignore the error.
    432 			 */
    433 			scn = MSDOSFSROOT;
    434 		}
    435 	}
    436 
    437 	if (isadir) {
    438 		cluster = scn;
    439 		if (cluster == MSDOSFSROOT)
    440 			blkoff = MSDOSFSROOT_OFS;
    441 		else
    442 			blkoff = 0;
    443 	} else if (cluster == MSDOSFSROOT)
    444 		blkoff = diroff;
    445 
    446 	/*
    447 	 * Now release buf to allow deget to read the entry again.
    448 	 * Reserving it here and giving it to deget could result
    449 	 * in a deadlock.
    450 	 */
    451 	brelse(bp);
    452 
    453 foundroot:
    454 	/*
    455 	 * If we entered at foundroot, then we are looking for the . or ..
    456 	 * entry of the filesystems root directory.  isadir and scn were
    457 	 * setup before jumping here.  And, bp is already null.
    458 	 */
    459 	if (FAT32(pmp) && scn == MSDOSFSROOT)
    460 		scn = pmp->pm_rootdirblk;
    461 
    462 	/*
    463 	 * If deleting, and at end of pathname, return
    464 	 * parameters which can be used to remove file.
    465 	 * If the wantparent flag isn't set, we return only
    466 	 * the directory (in ndp->ni_dvp), otherwise we go
    467 	 * on and lock the inode, being careful with ".".
    468 	 */
    469 	if (nameiop == DELETE && (flags & ISLASTCN)) {
    470 		/*
    471 		 * Don't allow deleting the root.
    472 		 */
    473 		if (blkoff == MSDOSFSROOT_OFS)
    474 			return EROFS;			/* really? XXX */
    475 
    476 		/*
    477 		 * Write access to directory required to delete files.
    478 		 */
    479 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_lwp);
    480 		if (error)
    481 			return (error);
    482 
    483 		/*
    484 		 * Return pointer to current entry in dp->i_offset.
    485 		 * Save directory inode pointer in ndp->ni_dvp for dirremove().
    486 		 */
    487 		if (dp->de_StartCluster == scn && isadir) {	/* "." */
    488 			VREF(vdp);
    489 			*vpp = vdp;
    490 			return (0);
    491 		}
    492 		if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
    493 			return (error);
    494 		*vpp = DETOV(tdp);
    495 		if (!lockparent) {
    496 			VOP_UNLOCK(vdp, 0);
    497 			cnp->cn_flags |= PDIRUNLOCK;
    498 		}
    499 		return (0);
    500 	}
    501 
    502 	/*
    503 	 * If rewriting (RENAME), return the inode and the
    504 	 * information required to rewrite the present directory
    505 	 * Must get inode of directory entry to verify it's a
    506 	 * regular file, or empty directory.
    507 	 */
    508 	if (nameiop == RENAME && wantparent &&
    509 	    (flags & ISLASTCN)) {
    510 
    511 		if (vdp->v_mount->mnt_flag & MNT_RDONLY)
    512 			return (EROFS);
    513 
    514 		if (blkoff == MSDOSFSROOT_OFS)
    515 			return EROFS;				/* really? XXX */
    516 
    517 		error = VOP_ACCESS(vdp, VWRITE, cnp->cn_cred, cnp->cn_lwp);
    518 		if (error)
    519 			return (error);
    520 
    521 		/*
    522 		 * Careful about locking second inode.
    523 		 * This can only occur if the target is ".".
    524 		 */
    525 		if (dp->de_StartCluster == scn && isadir)
    526 			return (EISDIR);
    527 
    528 		if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
    529 			return (error);
    530 		*vpp = DETOV(tdp);
    531 		cnp->cn_flags |= SAVENAME;
    532 		if (!lockparent) {
    533 			VOP_UNLOCK(vdp, 0);
    534 			cnp->cn_flags |= PDIRUNLOCK;
    535 		}
    536 		return (0);
    537 	}
    538 
    539 	/*
    540 	 * Step through the translation in the name.  We do not `vput' the
    541 	 * directory because we may need it again if a symbolic link
    542 	 * is relative to the current directory.  Instead we save it
    543 	 * unlocked as "pdp".  We must get the target inode before unlocking
    544 	 * the directory to insure that the inode will not be removed
    545 	 * before we get it.  We prevent deadlock by always fetching
    546 	 * inodes from the root, moving down the directory tree. Thus
    547 	 * when following backward pointers ".." we must unlock the
    548 	 * parent directory before getting the requested directory.
    549 	 * There is a potential race condition here if both the current
    550 	 * and parent directories are removed before the VFS_VGET for the
    551 	 * inode associated with ".." returns.  We hope that this occurs
    552 	 * infrequently since we cannot avoid this race condition without
    553 	 * implementing a sophisticated deadlock detection algorithm.
    554 	 * Note also that this simple deadlock detection scheme will not
    555 	 * work if the file system has any hard links other than ".."
    556 	 * that point backwards in the directory structure.
    557 	 */
    558 	pdp = vdp;
    559 	if (flags & ISDOTDOT) {
    560 		VOP_UNLOCK(pdp, 0);	/* race to get the inode */
    561 		cnp->cn_flags |= PDIRUNLOCK;
    562 		if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0) {
    563 			if (vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY) == 0)
    564 				cnp->cn_flags &= ~PDIRUNLOCK;
    565 			return (error);
    566 		}
    567 		if (lockparent && (flags & ISLASTCN)) {
    568 			if ((error = vn_lock(pdp, LK_EXCLUSIVE))) {
    569 				vput(DETOV(tdp));
    570 				return (error);
    571 			}
    572 			cnp->cn_flags &= ~PDIRUNLOCK;
    573 		}
    574 		*vpp = DETOV(tdp);
    575 	} else if (dp->de_StartCluster == scn && isadir) {
    576 		VREF(vdp);	/* we want ourself, ie "." */
    577 		*vpp = vdp;
    578 	} else {
    579 		if ((error = deget(pmp, cluster, blkoff, &tdp)) != 0)
    580 			return (error);
    581 		if (!lockparent || !(flags & ISLASTCN)) {
    582 			VOP_UNLOCK(pdp, 0);
    583 			cnp->cn_flags |= PDIRUNLOCK;
    584 		}
    585 		*vpp = DETOV(tdp);
    586 	}
    587 
    588 	/*
    589 	 * Insert name into cache if appropriate.
    590 	 */
    591 	if (cnp->cn_flags & MAKEENTRY)
    592 		cache_enter(vdp, *vpp, cnp);
    593 
    594 	return (0);
    595 }
    596 
    597 /*
    598  * dep  - directory entry to copy into the directory
    599  * ddep - directory to add to
    600  * depp - return the address of the denode for the created directory entry
    601  *	  if depp != 0
    602  * cnp  - componentname needed for Win95 long filenames
    603  */
    604 int
    605 createde(dep, ddep, depp, cnp)
    606 	struct denode *dep;
    607 	struct denode *ddep;
    608 	struct denode **depp;
    609 	struct componentname *cnp;
    610 {
    611 	int error, rberror;
    612 	u_long dirclust, clusoffset;
    613 	u_long fndoffset, havecnt=0, wcnt=1;
    614 	struct direntry *ndep;
    615 	struct msdosfsmount *pmp = ddep->de_pmp;
    616 	struct buf *bp;
    617 	daddr_t bn;
    618 	int blsize, i;
    619 	int async = ddep->de_pmp->pm_mountp->mnt_flag & MNT_ASYNC;
    620 
    621 #ifdef MSDOSFS_DEBUG
    622 	printf("createde(dep %p, ddep %p, depp %p, cnp %p)\n",
    623 	    dep, ddep, depp, cnp);
    624 #endif
    625 
    626 	/*
    627 	 * If no space left in the directory then allocate another cluster
    628 	 * and chain it onto the end of the file.  There is one exception
    629 	 * to this.  That is, if the root directory has no more space it
    630 	 * can NOT be expanded.  extendfile() checks for and fails attempts
    631 	 * to extend the root directory.  We just return an error in that
    632 	 * case.
    633 	 */
    634 	if (ddep->de_fndoffset >= ddep->de_FileSize) {
    635 		u_long needlen = ddep->de_fndoffset + sizeof(struct direntry)
    636 		    - ddep->de_FileSize;
    637 		dirclust = de_clcount(pmp, needlen);
    638 		if ((error = extendfile(ddep, dirclust, 0, 0, DE_CLEAR)) != 0) {
    639 			(void)detrunc(ddep, ddep->de_FileSize, 0, NOCRED, NULL);
    640 			goto err_norollback;
    641 		}
    642 
    643 		/*
    644 		 * Update the size of the directory
    645 		 */
    646 		ddep->de_FileSize += de_cn2off(pmp, dirclust);
    647 	}
    648 
    649 	/*
    650 	 * We just read in the cluster with space.  Copy the new directory
    651 	 * entry in.  Then write it to disk. NOTE:  DOS directories
    652 	 * do not get smaller as clusters are emptied.
    653 	 */
    654 	error = pcbmap(ddep, de_cluster(pmp, ddep->de_fndoffset),
    655 		       &bn, &dirclust, &blsize);
    656 	if (error)
    657 		goto err_norollback;
    658 	clusoffset = ddep->de_fndoffset;
    659 	if (dirclust != MSDOSFSROOT)
    660 		clusoffset &= pmp->pm_crbomask;
    661 	if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
    662 	    &bp)) != 0) {
    663 		brelse(bp);
    664 		goto err_norollback;
    665 	}
    666 	ndep = bptoep(pmp, bp, clusoffset);
    667 
    668 	DE_EXTERNALIZE(ndep, dep);
    669 
    670 	/*
    671 	 * Now write the Win95 long name
    672 	 */
    673 	if (ddep->de_fndcnt > 0) {
    674 		u_int8_t chksum = winChksum(ndep->deName);
    675 		const u_char *un = (const u_char *)cnp->cn_nameptr;
    676 		int unlen = cnp->cn_namelen;
    677 		u_long xhavecnt;
    678 
    679 		fndoffset = ddep->de_fndoffset;
    680 		xhavecnt = ddep->de_fndcnt + 1;
    681 
    682 		for(; wcnt < xhavecnt; wcnt++) {
    683 			if ((fndoffset & pmp->pm_crbomask) == 0) {
    684 				/* we should never get here if ddep is root
    685 				 * directory */
    686 
    687 				if (async)
    688 					(void) bdwrite(bp);
    689 				else if ((error = bwrite(bp)) != 0)
    690 					goto rollback;
    691 
    692 				fndoffset -= sizeof(struct direntry);
    693 				error = pcbmap(ddep,
    694 					       de_cluster(pmp, fndoffset),
    695 					       &bn, 0, &blsize);
    696 				if (error)
    697 					goto rollback;
    698 
    699 				error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn),
    700 				    blsize, NOCRED, &bp);
    701 				if (error) {
    702 					brelse(bp);
    703 					goto rollback;
    704 				}
    705 				ndep = bptoep(pmp, bp,
    706 						fndoffset & pmp->pm_crbomask);
    707 			} else {
    708 				ndep--;
    709 				fndoffset -= sizeof(struct direntry);
    710 			}
    711 			if (!unix2winfn(un, unlen, (struct winentry *)ndep,
    712 						wcnt, chksum))
    713 				break;
    714 		}
    715 	}
    716 
    717 	if (async)
    718 		bdwrite(bp);
    719 	else if ((error = bwrite(bp)) != 0)
    720 		goto rollback;
    721 
    722 	/*
    723 	 * If they want us to return with the denode gotten.
    724 	 */
    725 	if (depp) {
    726 		u_long diroffset = clusoffset;
    727 		if (dep->de_Attributes & ATTR_DIRECTORY) {
    728 			dirclust = dep->de_StartCluster;
    729 			if (FAT32(pmp) && dirclust == pmp->pm_rootdirblk)
    730 				dirclust = MSDOSFSROOT;
    731 			if (dirclust == MSDOSFSROOT)
    732 				diroffset = MSDOSFSROOT_OFS;
    733 			else
    734 				diroffset = 0;
    735 		}
    736 		return deget(pmp, dirclust, diroffset, depp);
    737 	}
    738 
    739 	return 0;
    740 
    741     rollback:
    742 	/*
    743 	 * Mark all slots modified so far as deleted. Note that we
    744 	 * can't just call removede(), since directory is not in
    745 	 * consistent state.
    746 	 */
    747 	fndoffset = ddep->de_fndoffset;
    748 	rberror = pcbmap(ddep, de_cluster(pmp, fndoffset),
    749 	       &bn, NULL, &blsize);
    750 	if (rberror)
    751 		goto err_norollback;
    752 	if ((rberror = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
    753 	    &bp)) != 0) {
    754 		brelse(bp);
    755 		goto err_norollback;
    756 	}
    757 	ndep = bptoep(pmp, bp, clusoffset);
    758 
    759 	havecnt = ddep->de_fndcnt + 1;
    760 	for(i=wcnt; i <= havecnt; i++) {
    761 		/* mark entry as deleted */
    762 		ndep->deName[0] = SLOT_DELETED;
    763 
    764 		if ((fndoffset & pmp->pm_crbomask) == 0) {
    765 			/* we should never get here if ddep is root
    766 			 * directory */
    767 
    768 			if (async)
    769 				bdwrite(bp);
    770 			else if ((rberror = bwrite(bp)) != 0)
    771 				goto err_norollback;
    772 
    773 			fndoffset -= sizeof(struct direntry);
    774 			rberror = pcbmap(ddep,
    775 				       de_cluster(pmp, fndoffset),
    776 				       &bn, 0, &blsize);
    777 			if (rberror)
    778 				goto err_norollback;
    779 
    780 			rberror = bread(pmp->pm_devvp, de_bn2kb(pmp, bn),
    781 			    blsize, NOCRED, &bp);
    782 			if (rberror) {
    783 				brelse(bp);
    784 				goto err_norollback;
    785 			}
    786 			ndep = bptoep(pmp, bp, fndoffset);
    787 		} else {
    788 			ndep--;
    789 			fndoffset -= sizeof(struct direntry);
    790 		}
    791 	}
    792 
    793 	/* ignore any further error */
    794 	if (async)
    795 		(void) bdwrite(bp);
    796 	else
    797 		(void) bwrite(bp);
    798 
    799     err_norollback:
    800 	return error;
    801 }
    802 
    803 /*
    804  * Be sure a directory is empty except for "." and "..". Return 1 if empty,
    805  * return 0 if not empty or error.
    806  */
    807 int
    808 dosdirempty(dep)
    809 	struct denode *dep;
    810 {
    811 	int blsize;
    812 	int error;
    813 	u_long cn;
    814 	daddr_t bn;
    815 	struct buf *bp;
    816 	struct msdosfsmount *pmp = dep->de_pmp;
    817 	struct direntry *dentp;
    818 
    819 	/*
    820 	 * Since the filesize field in directory entries for a directory is
    821 	 * zero, we just have to feel our way through the directory until
    822 	 * we hit end of file.
    823 	 */
    824 	for (cn = 0;; cn++) {
    825 		if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
    826 			if (error == E2BIG)
    827 				return (1);	/* it's empty */
    828 			return (0);
    829 		}
    830 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
    831 		    &bp);
    832 		if (error) {
    833 			brelse(bp);
    834 			return (0);
    835 		}
    836 		for (dentp = (struct direntry *)bp->b_data;
    837 		     (char *)dentp < bp->b_data + blsize;
    838 		     dentp++) {
    839 			if (dentp->deName[0] != SLOT_DELETED &&
    840 			    (dentp->deAttributes & ATTR_VOLUME) == 0) {
    841 				/*
    842 				 * In dos directories an entry whose name
    843 				 * starts with SLOT_EMPTY (0) starts the
    844 				 * beginning of the unused part of the
    845 				 * directory, so we can just return that it
    846 				 * is empty.
    847 				 */
    848 				if (dentp->deName[0] == SLOT_EMPTY) {
    849 					brelse(bp);
    850 					return (1);
    851 				}
    852 				/*
    853 				 * Any names other than "." and ".." in a
    854 				 * directory mean it is not empty.
    855 				 */
    856 				if (memcmp(dentp->deName, ".          ", 11) &&
    857 				    memcmp(dentp->deName, "..         ", 11)) {
    858 					brelse(bp);
    859 #ifdef MSDOSFS_DEBUG
    860 					printf("dosdirempty(): found %.11s, %d, %d\n",
    861 					    dentp->deName, dentp->deName[0],
    862 						dentp->deName[1]);
    863 #endif
    864 					return (0);	/* not empty */
    865 				}
    866 			}
    867 		}
    868 		brelse(bp);
    869 	}
    870 	/* NOTREACHED */
    871 }
    872 
    873 /*
    874  * Check to see if the directory described by target is in some
    875  * subdirectory of source.  This prevents something like the following from
    876  * succeeding and leaving a bunch or files and directories orphaned. mv
    877  * /a/b/c /a/b/c/d/e/f Where c and f are directories.
    878  *
    879  * source - the inode for /a/b/c
    880  * target - the inode for /a/b/c/d/e/f
    881  *
    882  * Returns 0 if target is NOT a subdirectory of source.
    883  * Otherwise returns a non-zero error number.
    884  * The target inode is always unlocked on return.
    885  */
    886 int
    887 doscheckpath(source, target)
    888 	struct denode *source;
    889 	struct denode *target;
    890 {
    891 	u_long scn;
    892 	struct msdosfsmount *pmp;
    893 	struct direntry *ep;
    894 	struct denode *dep;
    895 	struct buf *bp = NULL;
    896 	int error = 0;
    897 
    898 	dep = target;
    899 	if ((target->de_Attributes & ATTR_DIRECTORY) == 0 ||
    900 	    (source->de_Attributes & ATTR_DIRECTORY) == 0) {
    901 		error = ENOTDIR;
    902 		goto out;
    903 	}
    904 	if (dep->de_StartCluster == source->de_StartCluster) {
    905 		error = EEXIST;
    906 		goto out;
    907 	}
    908 	if (dep->de_StartCluster == MSDOSFSROOT)
    909 		goto out;
    910 	pmp = dep->de_pmp;
    911 #ifdef	DIAGNOSTIC
    912 	if (pmp != source->de_pmp)
    913 		panic("doscheckpath: source and target on different filesystems");
    914 #endif
    915 	if (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)
    916 		goto out;
    917 
    918 	for (;;) {
    919 		if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) {
    920 			error = ENOTDIR;
    921 			break;
    922 		}
    923 		scn = dep->de_StartCluster;
    924 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, cntobn(pmp, scn)),
    925 			      pmp->pm_bpcluster, NOCRED, &bp);
    926 		if (error)
    927 			break;
    928 
    929 		ep = (struct direntry *) bp->b_data + 1;
    930 		if ((ep->deAttributes & ATTR_DIRECTORY) == 0 ||
    931 		    memcmp(ep->deName, "..         ", 11) != 0) {
    932 			error = ENOTDIR;
    933 			break;
    934 		}
    935 		scn = getushort(ep->deStartCluster);
    936 		if (FAT32(pmp))
    937 			scn |= getushort(ep->deHighClust) << 16;
    938 
    939 		if (scn == source->de_StartCluster) {
    940 			error = EINVAL;
    941 			break;
    942 		}
    943 		if (scn == MSDOSFSROOT)
    944 			break;
    945 		if (FAT32(pmp) && scn == pmp->pm_rootdirblk) {
    946 			/*
    947 			 * scn should be 0 in this case,
    948 			 * but we silently ignore the error.
    949 			 */
    950 			break;
    951 		}
    952 
    953 		vput(DETOV(dep));
    954 		brelse(bp);
    955 		bp = NULL;
    956 		/* NOTE: deget() clears dep on error */
    957 		if ((error = deget(pmp, scn, 0, &dep)) != 0)
    958 			break;
    959 	}
    960 out:
    961 	if (bp)
    962 		brelse(bp);
    963 	if (error == ENOTDIR)
    964 		printf("doscheckpath(): .. not a directory?\n");
    965 	if (dep != NULL)
    966 		vput(DETOV(dep));
    967 	return (error);
    968 }
    969 
    970 /*
    971  * Read in the disk block containing the directory entry (dirclu, dirofs)
    972  * and return the address of the buf header, and the address of the
    973  * directory entry within the block.
    974  */
    975 int
    976 readep(pmp, dirclust, diroffset, bpp, epp)
    977 	struct msdosfsmount *pmp;
    978 	u_long dirclust, diroffset;
    979 	struct buf **bpp;
    980 	struct direntry **epp;
    981 {
    982 	int error;
    983 	daddr_t bn;
    984 	int blsize;
    985 
    986 	blsize = pmp->pm_bpcluster;
    987 	if (dirclust == MSDOSFSROOT
    988 	    && de_blk(pmp, diroffset + blsize) > pmp->pm_rootdirsize)
    989 		blsize = de_bn2off(pmp, pmp->pm_rootdirsize) & pmp->pm_crbomask;
    990 	bn = detobn(pmp, dirclust, diroffset);
    991 	if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
    992 	    bpp)) != 0) {
    993 		brelse(*bpp);
    994 		*bpp = NULL;
    995 		return (error);
    996 	}
    997 	if (epp)
    998 		*epp = bptoep(pmp, *bpp, diroffset);
    999 	return (0);
   1000 }
   1001 
   1002 /*
   1003  * Read in the disk block containing the directory entry dep came from and
   1004  * return the address of the buf header, and the address of the directory
   1005  * entry within the block.
   1006  */
   1007 int
   1008 readde(dep, bpp, epp)
   1009 	struct denode *dep;
   1010 	struct buf **bpp;
   1011 	struct direntry **epp;
   1012 {
   1013 	return (readep(dep->de_pmp, dep->de_dirclust, dep->de_diroffset,
   1014 			bpp, epp));
   1015 }
   1016 
   1017 /*
   1018  * Remove a directory entry. At this point the file represented by the
   1019  * directory entry to be removed is still full length until noone has it
   1020  * open.  When the file no longer being used msdosfs_inactive() is called
   1021  * and will truncate the file to 0 length.  When the vnode containing the
   1022  * denode is needed for some other purpose by VFS it will call
   1023  * msdosfs_reclaim() which will remove the denode from the denode cache.
   1024  */
   1025 int
   1026 removede(pdep, dep)
   1027 	struct denode *pdep;	/* directory where the entry is removed */
   1028 	struct denode *dep;	/* file to be removed */
   1029 {
   1030 	int error;
   1031 	struct direntry *ep;
   1032 	struct buf *bp;
   1033 	daddr_t bn;
   1034 	int blsize;
   1035 	struct msdosfsmount *pmp = pdep->de_pmp;
   1036 	u_long offset = pdep->de_fndoffset;
   1037 	int async = pdep->de_pmp->pm_mountp->mnt_flag & MNT_ASYNC;
   1038 
   1039 #ifdef MSDOSFS_DEBUG
   1040 	printf("removede(): filename %s, dep %p, offset %08lx\n",
   1041 	    dep->de_Name, dep, offset);
   1042 #endif
   1043 
   1044 	dep->de_refcnt--;
   1045 	offset += sizeof(struct direntry);
   1046 	do {
   1047 		offset -= sizeof(struct direntry);
   1048 		error = pcbmap(pdep, de_cluster(pmp, offset), &bn, 0, &blsize);
   1049 		if (error)
   1050 			return error;
   1051 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
   1052 		    &bp);
   1053 		if (error) {
   1054 			brelse(bp);
   1055 			return error;
   1056 		}
   1057 		ep = bptoep(pmp, bp, offset);
   1058 		/*
   1059 		 * Check whether, if we came here the second time, i.e.
   1060 		 * when underflowing into the previous block, the last
   1061 		 * entry in this block is a longfilename entry, too.
   1062 		 */
   1063 		if (ep->deAttributes != ATTR_WIN95
   1064 		    && offset != pdep->de_fndoffset) {
   1065 			brelse(bp);
   1066 			break;
   1067 		}
   1068 		offset += sizeof(struct direntry);
   1069 		while (1) {
   1070 			/*
   1071 			 * We are a bit agressive here in that we delete any Win95
   1072 			 * entries preceding this entry, not just the ones we "own".
   1073 			 * Since these presumably aren't valid anyway,
   1074 			 * there should be no harm.
   1075 			 */
   1076 			offset -= sizeof(struct direntry);
   1077 			ep--->deName[0] = SLOT_DELETED;
   1078 			if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95)
   1079 			    || !(offset & pmp->pm_crbomask)
   1080 			    || ep->deAttributes != ATTR_WIN95)
   1081 				break;
   1082 		}
   1083 		if (async)
   1084 			bdwrite(bp);
   1085 		else if ((error = bwrite(bp)) != 0)
   1086 			return error;
   1087 	} while (!(pmp->pm_flags & MSDOSFSMNT_NOWIN95)
   1088 	    && !(offset & pmp->pm_crbomask)
   1089 	    && offset);
   1090 	return 0;
   1091 }
   1092 
   1093 /*
   1094  * Create a unique DOS name in dvp
   1095  */
   1096 int
   1097 uniqdosname(dep, cnp, cp)
   1098 	struct denode *dep;
   1099 	struct componentname *cnp;
   1100 	u_char *cp;
   1101 {
   1102 	struct msdosfsmount *pmp = dep->de_pmp;
   1103 	struct direntry *dentp;
   1104 	int gen;
   1105 	int blsize;
   1106 	u_long cn;
   1107 	daddr_t bn;
   1108 	struct buf *bp;
   1109 	int error;
   1110 
   1111 	for (gen = 1;; gen++) {
   1112 		/*
   1113 		 * Generate DOS name with generation number
   1114 		 */
   1115 		if (!unix2dosfn((const u_char *)cnp->cn_nameptr, cp,
   1116 		    cnp->cn_namelen, gen))
   1117 			return gen == 1 ? EINVAL : EEXIST;
   1118 
   1119 		/*
   1120 		 * Now look for a dir entry with this exact name
   1121 		 */
   1122 		for (cn = error = 0; !error; cn++) {
   1123 			if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
   1124 				if (error == E2BIG)	/* EOF reached and not found */
   1125 					return 0;
   1126 				return error;
   1127 			}
   1128 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize,
   1129 			    NOCRED, &bp);
   1130 			if (error) {
   1131 				brelse(bp);
   1132 				return error;
   1133 			}
   1134 			for (dentp = (struct direntry *)bp->b_data;
   1135 			     (char *)dentp < bp->b_data + blsize;
   1136 			     dentp++) {
   1137 				if (dentp->deName[0] == SLOT_EMPTY) {
   1138 					/*
   1139 					 * Last used entry and not found
   1140 					 */
   1141 					brelse(bp);
   1142 					return 0;
   1143 				}
   1144 				/*
   1145 				 * Ignore volume labels and Win95 entries
   1146 				 */
   1147 				if (dentp->deAttributes & ATTR_VOLUME)
   1148 					continue;
   1149 				if (!memcmp(dentp->deName, cp, 11)) {
   1150 					error = EEXIST;
   1151 					break;
   1152 				}
   1153 			}
   1154 			brelse(bp);
   1155 		}
   1156 	}
   1157 }
   1158 
   1159 /*
   1160  * Find any Win'95 long filename entry in directory dep
   1161  */
   1162 int
   1163 findwin95(dep)
   1164 	struct denode *dep;
   1165 {
   1166 	struct msdosfsmount *pmp = dep->de_pmp;
   1167 	struct direntry *dentp;
   1168 	int blsize;
   1169 	u_long cn;
   1170 	daddr_t bn;
   1171 	struct buf *bp;
   1172 
   1173 	/*
   1174 	 * Read through the directory looking for Win'95 entries
   1175 	 * XXX Note: Error currently handled just as EOF
   1176 	 */
   1177 	for (cn = 0;; cn++) {
   1178 		if (pcbmap(dep, cn, &bn, 0, &blsize))
   1179 			return 0;
   1180 		if (bread(pmp->pm_devvp, de_bn2kb(pmp, bn), blsize, NOCRED,
   1181 		    &bp)) {
   1182 			brelse(bp);
   1183 			return 0;
   1184 		}
   1185 		for (dentp = (struct direntry *)bp->b_data;
   1186 		     (char *)dentp < bp->b_data + blsize;
   1187 		     dentp++) {
   1188 			if (dentp->deName[0] == SLOT_EMPTY) {
   1189 				/*
   1190 				 * Last used entry and not found
   1191 				 */
   1192 				brelse(bp);
   1193 				return 0;
   1194 			}
   1195 			if (dentp->deName[0] == SLOT_DELETED) {
   1196 				/*
   1197 				 * Ignore deleted files
   1198 				 * Note: might be an indication of Win'95
   1199 				 * anyway	XXX
   1200 				 */
   1201 				continue;
   1202 			}
   1203 			if (dentp->deAttributes == ATTR_WIN95) {
   1204 				brelse(bp);
   1205 				return 1;
   1206 			}
   1207 		}
   1208 		brelse(bp);
   1209 	}
   1210 }
   1211