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