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