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