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