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