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