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