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