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