msdosfs_lookup.c revision 33747
1/*	$Id: msdosfs_lookup.c,v 1.15 1998/02/18 09:28:41 jkh 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,
641					cnt++, chksum,
642					pmp->pm_flags & MSDOSFSMNT_U2WTABLE,
643					pmp->pm_u2w));
644				break;
645		}
646	}
647
648	if ((error = bwrite(bp)) != 0)
649		return error;
650
651	/*
652	 * If they want us to return with the denode gotten.
653	 */
654	if (depp) {
655		if (dep->de_Attributes & ATTR_DIRECTORY) {
656			dirclust = dep->de_StartCluster;
657			if (FAT32(pmp) && dirclust == pmp->pm_rootdirblk)
658				dirclust = MSDOSFSROOT;
659			if (dirclust == MSDOSFSROOT)
660				diroffset = MSDOSFSROOT_OFS;
661			else
662				diroffset = 0;
663		}
664		return deget(pmp, dirclust, diroffset, depp);
665	}
666
667	return 0;
668}
669
670/*
671 * Be sure a directory is empty except for "." and "..". Return 1 if empty,
672 * return 0 if not empty or error.
673 */
674int
675dosdirempty(dep)
676	struct denode *dep;
677{
678	int blsize;
679	int error;
680	u_long cn;
681	daddr_t bn;
682	struct buf *bp;
683	struct msdosfsmount *pmp = dep->de_pmp;
684	struct direntry *dentp;
685
686	/*
687	 * Since the filesize field in directory entries for a directory is
688	 * zero, we just have to feel our way through the directory until
689	 * we hit end of file.
690	 */
691	for (cn = 0;; cn++) {
692		if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
693			if (error == E2BIG)
694				return (1);	/* it's empty */
695			return (0);
696		}
697		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
698		if (error) {
699			brelse(bp);
700			return (0);
701		}
702		for (dentp = (struct direntry *)bp->b_data;
703		     (char *)dentp < bp->b_data + blsize;
704		     dentp++) {
705			if (dentp->deName[0] != SLOT_DELETED &&
706			    (dentp->deAttributes & ATTR_VOLUME) == 0) {
707				/*
708				 * In dos directories an entry whose name
709				 * starts with SLOT_EMPTY (0) starts the
710				 * beginning of the unused part of the
711				 * directory, so we can just return that it
712				 * is empty.
713				 */
714				if (dentp->deName[0] == SLOT_EMPTY) {
715					brelse(bp);
716					return (1);
717				}
718				/*
719				 * Any names other than "." and ".." in a
720				 * directory mean it is not empty.
721				 */
722				if (bcmp(dentp->deName, ".          ", 11) &&
723				    bcmp(dentp->deName, "..         ", 11)) {
724					brelse(bp);
725#ifdef MSDOSFS_DEBUG
726					printf("dosdirempty(): entry found %02x, %02x\n",
727					    dentp->deName[0], dentp->deName[1]);
728#endif
729					return (0);	/* not empty */
730				}
731			}
732		}
733		brelse(bp);
734	}
735	/* NOTREACHED */
736}
737
738/*
739 * Check to see if the directory described by target is in some
740 * subdirectory of source.  This prevents something like the following from
741 * succeeding and leaving a bunch or files and directories orphaned. mv
742 * /a/b/c /a/b/c/d/e/f Where c and f are directories.
743 *
744 * source - the inode for /a/b/c
745 * target - the inode for /a/b/c/d/e/f
746 *
747 * Returns 0 if target is NOT a subdirectory of source.
748 * Otherwise returns a non-zero error number.
749 * The target inode is always unlocked on return.
750 */
751int
752doscheckpath(source, target)
753	struct denode *source;
754	struct denode *target;
755{
756	daddr_t scn;
757	struct msdosfsmount *pmp;
758	struct direntry *ep;
759	struct denode *dep;
760	struct buf *bp = NULL;
761	int error = 0;
762
763	dep = target;
764	if ((target->de_Attributes & ATTR_DIRECTORY) == 0 ||
765	    (source->de_Attributes & ATTR_DIRECTORY) == 0) {
766		error = ENOTDIR;
767		goto out;
768	}
769	if (dep->de_StartCluster == source->de_StartCluster) {
770		error = EEXIST;
771		goto out;
772	}
773	if (dep->de_StartCluster == MSDOSFSROOT)
774		goto out;
775	pmp = dep->de_pmp;
776#ifdef	DIAGNOSTIC
777	if (pmp != source->de_pmp)
778		panic("doscheckpath: source and target on different filesystems");
779#endif
780	if (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)
781		goto out;
782
783	for (;;) {
784		if ((dep->de_Attributes & ATTR_DIRECTORY) == 0) {
785			error = ENOTDIR;
786			break;
787		}
788		scn = dep->de_StartCluster;
789		error = bread(pmp->pm_devvp, cntobn(pmp, scn),
790			      pmp->pm_bpcluster, NOCRED, &bp);
791		if (error)
792			break;
793
794		ep = (struct direntry *) bp->b_data + 1;
795		if ((ep->deAttributes & ATTR_DIRECTORY) == 0 ||
796		    bcmp(ep->deName, "..         ", 11) != 0) {
797			error = ENOTDIR;
798			break;
799		}
800		scn = getushort(ep->deStartCluster);
801		if (FAT32(pmp))
802			scn |= getushort(ep->deHighClust) << 16;
803
804		if (scn == source->de_StartCluster) {
805			error = EINVAL;
806			break;
807		}
808		if (scn == MSDOSFSROOT)
809			break;
810		if (FAT32(pmp) && scn == pmp->pm_rootdirblk) {
811			/*
812			 * scn should be 0 in this case,
813			 * but we silently ignore the error.
814			 */
815			break;
816		}
817
818		vput(DETOV(dep));
819		brelse(bp);
820		bp = NULL;
821		/* NOTE: deget() clears dep on error */
822		if ((error = deget(pmp, scn, 0, &dep)) != 0)
823			break;
824	}
825out:;
826	if (bp)
827		brelse(bp);
828	if (error == ENOTDIR)
829		printf("doscheckpath(): .. not a directory?\n");
830	if (dep != NULL)
831		vput(DETOV(dep));
832	return (error);
833}
834
835/*
836 * Read in the disk block containing the directory entry (dirclu, dirofs)
837 * and return the address of the buf header, and the address of the
838 * directory entry within the block.
839 */
840int
841readep(pmp, dirclust, diroffset, bpp, epp)
842	struct msdosfsmount *pmp;
843	u_long dirclust, diroffset;
844	struct buf **bpp;
845	struct direntry **epp;
846{
847	int error;
848	daddr_t bn;
849	int blsize;
850	u_long boff;
851
852	boff = diroffset & ~pmp->pm_crbomask;
853	blsize = pmp->pm_bpcluster;
854	if (dirclust == MSDOSFSROOT
855	    && de_blk(pmp, diroffset + blsize) > pmp->pm_rootdirsize)
856		blsize = de_bn2off(pmp, pmp->pm_rootdirsize) & pmp->pm_crbomask;
857	bn = detobn(pmp, dirclust, diroffset);
858	if ((error = bread(pmp->pm_devvp, bn, blsize, NOCRED, bpp)) != 0) {
859		brelse(*bpp);
860		*bpp = NULL;
861		return (error);
862	}
863	if (epp)
864		*epp = bptoep(pmp, *bpp, diroffset);
865	return (0);
866}
867
868/*
869 * Read in the disk block containing the directory entry dep came from and
870 * return the address of the buf header, and the address of the directory
871 * entry within the block.
872 */
873int
874readde(dep, bpp, epp)
875	struct denode *dep;
876	struct buf **bpp;
877	struct direntry **epp;
878{
879
880	return (readep(dep->de_pmp, dep->de_dirclust, dep->de_diroffset,
881	    bpp, epp));
882}
883
884/*
885 * Remove a directory entry. At this point the file represented by the
886 * directory entry to be removed is still full length until noone has it
887 * open.  When the file no longer being used msdosfs_inactive() is called
888 * and will truncate the file to 0 length.  When the vnode containing the
889 * denode is needed for some other purpose by VFS it will call
890 * msdosfs_reclaim() which will remove the denode from the denode cache.
891 */
892int
893removede(pdep, dep)
894	struct denode *pdep;	/* directory where the entry is removed */
895	struct denode *dep;	/* file to be removed */
896{
897	int error;
898	struct direntry *ep;
899	struct buf *bp;
900	daddr_t bn;
901	int blsize;
902	struct msdosfsmount *pmp = pdep->de_pmp;
903	u_long offset = pdep->de_fndoffset;
904
905#ifdef MSDOSFS_DEBUG
906	printf("removede(): filename %s, dep %p, offset %08lx\n",
907	    dep->de_Name, dep, offset);
908#endif
909
910	dep->de_refcnt--;
911	offset += sizeof(struct direntry);
912	do {
913		offset -= sizeof(struct direntry);
914		error = pcbmap(pdep, de_cluster(pmp, offset), &bn, 0, &blsize);
915		if (error)
916			return error;
917		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
918		if (error) {
919			brelse(bp);
920			return error;
921		}
922		ep = bptoep(pmp, bp, offset);
923		/*
924		 * Check whether, if we came here the second time, i.e.
925		 * when underflowing into the previous block, the last
926		 * entry in this block is a longfilename entry, too.
927		 */
928		if (ep->deAttributes != ATTR_WIN95
929		    && offset != pdep->de_fndoffset) {
930			brelse(bp);
931			break;
932		}
933		offset += sizeof(struct direntry);
934		while (1) {
935			/*
936			 * We are a bit agressive here in that we delete any Win95
937			 * entries preceding this entry, not just the ones we "own".
938			 * Since these presumably aren't valid anyway,
939			 * there should be no harm.
940			 */
941			offset -= sizeof(struct direntry);
942			ep--->deName[0] = SLOT_DELETED;
943			if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95)
944			    || !(offset & pmp->pm_crbomask)
945			    || ep->deAttributes != ATTR_WIN95)
946				break;
947		}
948		if ((error = bwrite(bp)) != 0)
949			return error;
950	} while (!(pmp->pm_flags & MSDOSFSMNT_NOWIN95)
951	    && !(offset & pmp->pm_crbomask)
952	    && offset);
953	return 0;
954}
955
956/*
957 * Create a unique DOS name in dvp
958 */
959int
960uniqdosname(dep, cnp, cp)
961	struct denode *dep;
962	struct componentname *cnp;
963	u_char *cp;
964{
965	struct msdosfsmount *pmp = dep->de_pmp;
966	struct direntry *dentp;
967	int gen;
968	int blsize;
969	u_long cn;
970	daddr_t bn;
971	struct buf *bp;
972	int error;
973
974	for (gen = 1;; gen++) {
975		/*
976		 * Generate DOS name with generation number
977		 */
978		if (!unix2dosfn((const u_char *)cnp->cn_nameptr, cp,
979		    cnp->cn_namelen, gen))
980			return gen == 1 ? EINVAL : EEXIST;
981
982		/*
983		 * Now look for a dir entry with this exact name
984		 */
985		for (cn = error = 0; !error; cn++) {
986			if ((error = pcbmap(dep, cn, &bn, 0, &blsize)) != 0) {
987				if (error == E2BIG)	/* EOF reached and not found */
988					return 0;
989				return error;
990			}
991			error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
992			if (error) {
993				brelse(bp);
994				return error;
995			}
996			for (dentp = (struct direntry *)bp->b_data;
997			     (char *)dentp < bp->b_data + blsize;
998			     dentp++) {
999				if (dentp->deName[0] == SLOT_EMPTY) {
1000					/*
1001					 * Last used entry and not found
1002					 */
1003					brelse(bp);
1004					return 0;
1005				}
1006				/*
1007				 * Ignore volume labels and Win95 entries
1008				 */
1009				if (dentp->deAttributes & ATTR_VOLUME)
1010					continue;
1011				if (!bcmp(dentp->deName, cp, 11)) {
1012					error = EEXIST;
1013					break;
1014				}
1015			}
1016			brelse(bp);
1017		}
1018	}
1019}
1020
1021/*
1022 * Find any Win'95 long filename entry in directory dep
1023 */
1024int
1025findwin95(dep)
1026	struct denode *dep;
1027{
1028	struct msdosfsmount *pmp = dep->de_pmp;
1029	struct direntry *dentp;
1030	int blsize;
1031	u_long cn;
1032	daddr_t bn;
1033	struct buf *bp;
1034
1035	/*
1036	 * Read through the directory looking for Win'95 entries
1037	 * Note: Error currently handled just as EOF			XXX
1038	 */
1039	for (cn = 0;; cn++) {
1040		if (pcbmap(dep, cn, &bn, 0, &blsize))
1041			return 0;
1042		if (bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp)) {
1043			brelse(bp);
1044			return 0;
1045		}
1046		for (dentp = (struct direntry *)bp->b_data;
1047		     (char *)dentp < bp->b_data + blsize;
1048		     dentp++) {
1049			if (dentp->deName[0] == SLOT_EMPTY) {
1050				/*
1051				 * Last used entry and not found
1052				 */
1053				brelse(bp);
1054				return 0;
1055			}
1056			if (dentp->deName[0] == SLOT_DELETED) {
1057				/*
1058				 * Ignore deleted files
1059				 * Note: might be an indication of Win'95 anyway	XXX
1060				 */
1061				continue;
1062			}
1063			if (dentp->deAttributes == ATTR_WIN95) {
1064				brelse(bp);
1065				return 1;
1066			}
1067		}
1068		brelse(bp);
1069	}
1070}
1071