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