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