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