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