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