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