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