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