xref: /openbsd-src/sys/msdosfs/msdosfs_vnops.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /*	$OpenBSD: msdosfs_vnops.c,v 1.112 2016/06/19 11:54:33 natano Exp $	*/
2 /*	$NetBSD: msdosfs_vnops.c,v 1.63 1997/10/17 11:24:19 ws Exp $	*/
3 
4 /*-
5  * Copyright (C) 2005 Thomas Wang.
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/namei.h>
55 #include <sys/resourcevar.h>	/* defines plimit structure in proc struct */
56 #include <sys/file.h>		/* define FWRITE ... */
57 #include <sys/stat.h>
58 #include <sys/buf.h>
59 #include <sys/proc.h>
60 #include <sys/mount.h>
61 #include <sys/vnode.h>
62 #include <sys/lock.h>
63 #include <sys/signalvar.h>
64 #include <sys/specdev.h> /* XXX */	/* defines v_rdev */
65 #include <sys/malloc.h>
66 #include <sys/pool.h>
67 #include <sys/dirent.h>		/* defines dirent structure */
68 #include <sys/lockf.h>
69 #include <sys/poll.h>
70 #include <sys/unistd.h>
71 
72 #include <msdosfs/bpb.h>
73 #include <msdosfs/direntry.h>
74 #include <msdosfs/denode.h>
75 #include <msdosfs/msdosfsmount.h>
76 #include <msdosfs/fat.h>
77 
78 static uint32_t fileidhash(uint64_t);
79 
80 int msdosfs_bmaparray(struct vnode *, daddr_t, daddr_t *, int *);
81 int msdosfs_kqfilter(void *);
82 int filt_msdosfsread(struct knote *, long);
83 int filt_msdosfswrite(struct knote *, long);
84 int filt_msdosfsvnode(struct knote *, long);
85 void filt_msdosfsdetach(struct knote *);
86 
87 /*
88  * Some general notes:
89  *
90  * In the ufs filesystem the inodes, superblocks, and indirect blocks are
91  * read/written using the vnode for the filesystem. Blocks that represent
92  * the contents of a file are read/written using the vnode for the file
93  * (including directories when they are read/written as files). This
94  * presents problems for the dos filesystem because data that should be in
95  * an inode (if dos had them) resides in the directory itself.  Since we
96  * must update directory entries without the benefit of having the vnode
97  * for the directory we must use the vnode for the filesystem.  This means
98  * that when a directory is actually read/written (via read, write, or
99  * readdir, or seek) we must use the vnode for the filesystem instead of
100  * the vnode for the directory as would happen in ufs. This is to insure we
101  * retrieve the correct block from the buffer cache since the hash value is
102  * based upon the vnode address and the desired block number.
103  */
104 
105 /*
106  * Create a regular file. On entry the directory to contain the file being
107  * created is locked.  We must release before we return. We must also free
108  * the pathname buffer pointed at by cnp->cn_pnbuf, always on error, or
109  * only if the SAVESTART bit in cn_flags is clear on success.
110  */
111 int
112 msdosfs_create(void *v)
113 {
114 	struct vop_create_args *ap = v;
115 	struct componentname *cnp = ap->a_cnp;
116 	struct denode ndirent;
117 	struct denode *dep;
118 	struct denode *pdep = VTODE(ap->a_dvp);
119 	int error;
120 	struct timespec ts;
121 
122 #ifdef MSDOSFS_DEBUG
123 	printf("msdosfs_create(cnp %p, vap %p\n", cnp, ap->a_vap);
124 #endif
125 
126 	/*
127 	 * If this is the root directory and there is no space left we
128 	 * can't do anything.  This is because the root directory can not
129 	 * change size.
130 	 */
131 	if (pdep->de_StartCluster == MSDOSFSROOT
132 	    && pdep->de_fndoffset >= pdep->de_FileSize) {
133 		error = ENOSPC;
134 		goto bad;
135 	}
136 
137 	/*
138 	 * Create a directory entry for the file, then call createde() to
139 	 * have it installed. NOTE: DOS files are always executable.  We
140 	 * use the absence of the owner write bit to make the file
141 	 * readonly.
142 	 */
143 #ifdef DIAGNOSTIC
144 	if ((cnp->cn_flags & HASBUF) == 0)
145 		panic("msdosfs_create: no name");
146 #endif
147 	bzero(&ndirent, sizeof(ndirent));
148 	if ((error = uniqdosname(pdep, cnp, ndirent.de_Name)) != 0)
149 		goto bad;
150 
151 	ndirent.de_Attributes = (ap->a_vap->va_mode & VWRITE) ?
152 				ATTR_ARCHIVE : ATTR_ARCHIVE | ATTR_READONLY;
153 	ndirent.de_StartCluster = 0;
154 	ndirent.de_FileSize = 0;
155 	ndirent.de_dev = pdep->de_dev;
156 	ndirent.de_devvp = pdep->de_devvp;
157 	ndirent.de_pmp = pdep->de_pmp;
158 	ndirent.de_flag = DE_ACCESS | DE_CREATE | DE_UPDATE;
159 	getnanotime(&ts);
160 	DETIMES(&ndirent, &ts, &ts, &ts);
161 	if ((error = createde(&ndirent, pdep, &dep, cnp)) != 0)
162 		goto bad;
163 	if ((cnp->cn_flags & SAVESTART) == 0)
164 		pool_put(&namei_pool, cnp->cn_pnbuf);
165 	VN_KNOTE(ap->a_dvp, NOTE_WRITE);
166 	vput(ap->a_dvp);
167 	*ap->a_vpp = DETOV(dep);
168 	return (0);
169 
170 bad:
171 	pool_put(&namei_pool, cnp->cn_pnbuf);
172 	vput(ap->a_dvp);
173 	return (error);
174 }
175 
176 int
177 msdosfs_mknod(void *v)
178 {
179 	struct vop_mknod_args *ap = v;
180 
181 	pool_put(&namei_pool, ap->a_cnp->cn_pnbuf);
182 	VN_KNOTE(ap->a_dvp, NOTE_WRITE);
183 	vput(ap->a_dvp);
184 	return (EINVAL);
185 }
186 
187 int
188 msdosfs_open(void *v)
189 {
190 #if 0
191 	struct vop_open_args /* {
192 		struct vnode *a_vp;
193 		int a_mode;
194 		struct ucred *a_cred;
195 		struct proc *a_p;
196 	} */ *ap;
197 #endif
198 
199 	return (0);
200 }
201 
202 int
203 msdosfs_close(void *v)
204 {
205 	struct vop_close_args *ap = v;
206 	struct vnode *vp = ap->a_vp;
207 	struct denode *dep = VTODE(vp);
208 	struct timespec ts;
209 
210 	if (vp->v_usecount > 1 && !VOP_ISLOCKED(vp)) {
211 		getnanotime(&ts);
212 		DETIMES(dep, &ts, &ts, &ts);
213 	}
214 	return (0);
215 }
216 
217 int
218 msdosfs_access(void *v)
219 {
220 	struct vop_access_args *ap = v;
221 	struct denode *dep = VTODE(ap->a_vp);
222 	struct msdosfsmount *pmp = dep->de_pmp;
223 	mode_t dosmode;
224 
225 	dosmode = (S_IRUSR|S_IRGRP|S_IROTH);
226 	if ((dep->de_Attributes & ATTR_READONLY) == 0)
227 		dosmode |= (S_IWUSR|S_IWGRP|S_IWOTH);
228 	if (dep->de_Attributes & ATTR_DIRECTORY) {
229 		dosmode |= (dosmode & S_IRUSR) ? S_IXUSR : 0;
230 		dosmode |= (dosmode & S_IRGRP) ? S_IXGRP : 0;
231 		dosmode |= (dosmode & S_IROTH) ? S_IXOTH : 0;
232 	}
233 	dosmode &= pmp->pm_mask;
234 
235 	return (vaccess(ap->a_vp->v_type, dosmode, pmp->pm_uid, pmp->pm_gid,
236 	    ap->a_mode, ap->a_cred));
237 }
238 
239 int
240 msdosfs_getattr(void *v)
241 {
242 	struct vop_getattr_args *ap = v;
243 	struct denode *dep = VTODE(ap->a_vp);
244 	struct msdosfsmount *pmp = dep->de_pmp;
245 	struct vattr *vap = ap->a_vap;
246 	struct timespec ts;
247 	uint32_t fileid;
248 
249 	getnanotime(&ts);
250 	DETIMES(dep, &ts, &ts, &ts);
251 	vap->va_fsid = dep->de_dev;
252 
253 	/*
254 	 * The following computation of the fileid must be the same as
255 	 * that used in msdosfs_readdir() to compute d_fileno. If not,
256 	 * pwd doesn't work.
257 	 *
258 	 * We now use the starting cluster number as the fileid/fileno.
259 	 * This works for both files and directories (including the root
260 	 * directory, on FAT32).  Even on FAT32, this will at most be a
261 	 * 28-bit number, as the high 4 bits of FAT32 cluster numbers
262 	 * are reserved.
263 	 *
264 	 * However, we do need to do something for 0-length files, which
265 	 * will not have a starting cluster number.
266 	 *
267 	 * These files cannot be directories, since (except for /, which
268 	 * is special-cased anyway) directories contain entries for . and
269 	 * .., so must have non-zero length.
270 	 *
271 	 * In this case, we just create a non-cryptographic hash of the
272 	 * original fileid calculation, and set the top bit.
273 	 *
274 	 * This algorithm has the benefit that all directories, and all
275 	 * non-zero-length files, will have fileids that are persistent
276 	 * across mounts and reboots, and that cannot collide (as long
277 	 * as the filesystem is not corrupt).  Zero-length files will
278 	 * have fileids that are persistent, but that may collide.  We
279 	 * will just have to live with that.
280 	 */
281 	fileid = dep->de_StartCluster;
282 
283 	if (dep->de_Attributes & ATTR_DIRECTORY) {
284 		/* Special-case root */
285 		if (dep->de_StartCluster == MSDOSFSROOT)
286 			fileid = FAT32(pmp) ? pmp->pm_rootdirblk : 1;
287 	} else {
288 		if (dep->de_FileSize == 0) {
289 			uint32_t dirsperblk;
290 			uint64_t fileid64;
291 
292 			dirsperblk = pmp->pm_BytesPerSec /
293 			    sizeof(struct direntry);
294 
295 			fileid64 = (dep->de_dirclust == MSDOSFSROOT) ?
296 			    roottobn(pmp, 0) : cntobn(pmp, dep->de_dirclust);
297 			fileid64 *= dirsperblk;
298 			fileid64 += dep->de_diroffset / sizeof(struct direntry);
299 
300 			fileid = fileidhash(fileid64);
301 		}
302 	}
303 
304 	vap->va_fileid = fileid;
305 	vap->va_mode = (S_IRUSR|S_IRGRP|S_IROTH);
306 	if ((dep->de_Attributes & ATTR_READONLY) == 0)
307 		vap->va_mode |= (S_IWUSR|S_IWGRP|S_IWOTH);
308 	if (dep->de_Attributes & ATTR_DIRECTORY) {
309 		vap->va_mode |= S_IFDIR;
310 		vap->va_mode |= (vap->va_mode & S_IRUSR) ? S_IXUSR : 0;
311 		vap->va_mode |= (vap->va_mode & S_IRGRP) ? S_IXGRP : 0;
312 		vap->va_mode |= (vap->va_mode & S_IROTH) ? S_IXOTH : 0;
313 	}
314 	vap->va_mode &= dep->de_pmp->pm_mask;
315 	vap->va_nlink = 1;
316 	vap->va_gid = dep->de_pmp->pm_gid;
317 	vap->va_uid = dep->de_pmp->pm_uid;
318 	vap->va_rdev = 0;
319 	vap->va_size = dep->de_FileSize;
320 	dos2unixtime(dep->de_MDate, dep->de_MTime, 0, &vap->va_mtime);
321 	if (dep->de_pmp->pm_flags & MSDOSFSMNT_LONGNAME) {
322 		dos2unixtime(dep->de_ADate, 0, 0, &vap->va_atime);
323 		dos2unixtime(dep->de_CDate, dep->de_CTime, dep->de_CTimeHundredth, &vap->va_ctime);
324 	} else {
325 		vap->va_atime = vap->va_mtime;
326 		vap->va_ctime = vap->va_mtime;
327 	}
328 	vap->va_flags = 0;
329 	if ((dep->de_Attributes & ATTR_ARCHIVE) == 0)
330 		vap->va_flags |= SF_ARCHIVED;
331 	vap->va_gen = 0;
332 	vap->va_blocksize = dep->de_pmp->pm_bpcluster;
333 	vap->va_bytes = (dep->de_FileSize + dep->de_pmp->pm_crbomask) &
334 				~(dep->de_pmp->pm_crbomask);
335 	vap->va_type = ap->a_vp->v_type;
336 	return (0);
337 }
338 
339 int
340 msdosfs_setattr(void *v)
341 {
342 	struct vop_setattr_args *ap = v;
343 	struct vnode *vp = ap->a_vp;
344 	struct denode *dep = VTODE(ap->a_vp);
345 	struct msdosfsmount *pmp = dep->de_pmp;
346 	struct vattr *vap = ap->a_vap;
347 	struct ucred *cred = ap->a_cred;
348 	int error = 0;
349 
350 #ifdef MSDOSFS_DEBUG
351 	printf("msdosfs_setattr(): vp %p, vap %p, cred %p, p %p\n",
352 	    ap->a_vp, vap, cred, ap->a_p);
353 #endif
354 	if ((vap->va_type != VNON) || (vap->va_nlink != VNOVAL) ||
355 	    (vap->va_fsid != VNOVAL) || (vap->va_fileid != VNOVAL) ||
356 	    (vap->va_blocksize != VNOVAL) || (vap->va_rdev != VNOVAL) ||
357 	    (vap->va_bytes != VNOVAL) || (vap->va_gen != VNOVAL)) {
358 #ifdef MSDOSFS_DEBUG
359 		printf("msdosfs_setattr(): returning EINVAL\n");
360 		printf("    va_type %d, va_nlink %x, va_fsid %ld, "
361 		    "va_fileid %llx\n", vap->va_type, vap->va_nlink,
362 		    vap->va_fsid, (unsigned long long)vap->va_fileid);
363 		printf("    va_blocksize %lx, va_rdev %x, va_bytes %llx, "
364 		    "va_gen %lx\n", vap->va_blocksize,
365 		    (unsigned int)vap->va_rdev,
366 		    (unsigned long long)vap->va_bytes, vap->va_gen);
367 #endif
368 		return (EINVAL);
369 	}
370 	if (vap->va_flags != VNOVAL) {
371 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
372 			return (EINVAL);
373 		if (cred->cr_uid != pmp->pm_uid) {
374 			error = suser_ucred(cred);
375 			if (error)
376 				return (error);
377 		}
378 		/*
379 		 * We are very inconsistent about handling unsupported
380 		 * attributes.  We ignored the access time and the
381 		 * read and execute bits.  We were strict for the other
382 		 * attributes.
383 		 *
384 		 * Here we are strict, stricter than ufs in not allowing
385 		 * users to attempt to set SF_SETTABLE bits or anyone to
386 		 * set unsupported bits.  However, we ignore attempts to
387 		 * set ATTR_ARCHIVE for directories `cp -pr' from a more
388 		 * sensible filesystem attempts it a lot.
389 		 */
390 		if (vap->va_flags & SF_SETTABLE) {
391 			error = suser_ucred(cred);
392 			if (error)
393 				return (error);
394 		}
395 		if (vap->va_flags & ~SF_ARCHIVED)
396 			return EOPNOTSUPP;
397 		if (vap->va_flags & SF_ARCHIVED)
398 			dep->de_Attributes &= ~ATTR_ARCHIVE;
399 		else if (!(dep->de_Attributes & ATTR_DIRECTORY))
400 			dep->de_Attributes |= ATTR_ARCHIVE;
401 		dep->de_flag |= DE_MODIFIED;
402 	}
403 
404 	if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
405 		uid_t uid;
406 		gid_t gid;
407 
408 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
409 			return (EINVAL);
410 		uid = vap->va_uid;
411 		if (uid == (uid_t)VNOVAL)
412 			uid = pmp->pm_uid;
413 		gid = vap->va_gid;
414 		if (gid == (gid_t)VNOVAL)
415 			gid = pmp->pm_gid;
416 		if (cred->cr_uid != pmp->pm_uid || uid != pmp->pm_uid ||
417 		    (gid != pmp->pm_gid && !groupmember(gid, cred))) {
418 			error = suser_ucred(cred);
419 			if (error)
420 				return (error);
421 		}
422 		if (uid != pmp->pm_uid || gid != pmp->pm_gid)
423 			return EINVAL;
424 	}
425 
426 	if (vap->va_size != VNOVAL) {
427 		switch (vp->v_type) {
428 		case VDIR:
429 			return (EISDIR);
430 		case VREG:
431 			/*
432 			 * Truncation is only supported for regular files,
433 			 * Disallow it if the filesystem is read-only.
434 			 */
435 			if (vp->v_mount->mnt_flag & MNT_RDONLY)
436 				return (EINVAL);
437 			break;
438 		default:
439 			/*
440 			 * According to POSIX, the result is unspecified
441 			 * for file types other than regular files,
442 			 * directories and shared memory objects.  We
443 			 * don't support any file types except regular
444 			 * files and directories in this file system, so
445 			 * this (default) case is unreachable and can do
446 			 * anything.  Keep falling through to detrunc()
447 			 * for now.
448 			 */
449 			break;
450 		}
451 		error = detrunc(dep, vap->va_size, 0, cred, ap->a_p);
452 		if (error)
453 			return error;
454 	}
455 	if ((vap->va_vaflags & VA_UTIMES_CHANGE) ||
456 	    vap->va_atime.tv_nsec != VNOVAL ||
457 	    vap->va_mtime.tv_nsec != VNOVAL) {
458 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
459 			return (EINVAL);
460 		if (cred->cr_uid != pmp->pm_uid &&
461 		    (error = suser_ucred(cred)) &&
462 		    ((vap->va_vaflags & VA_UTIMES_NULL) == 0 ||
463 		    (error = VOP_ACCESS(ap->a_vp, VWRITE, cred, ap->a_p))))
464 			return (error);
465 		if (vp->v_type != VDIR) {
466 			if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95) == 0 &&
467 			    vap->va_atime.tv_nsec != VNOVAL) {
468 				dep->de_flag &= ~DE_ACCESS;
469 				unix2dostime(&vap->va_atime, &dep->de_ADate,
470 				    NULL, NULL);
471 			}
472 			if (vap->va_mtime.tv_nsec != VNOVAL) {
473 				dep->de_flag &= ~DE_UPDATE;
474 				unix2dostime(&vap->va_mtime, &dep->de_MDate,
475 				    &dep->de_MTime, NULL);
476 			}
477 			dep->de_Attributes |= ATTR_ARCHIVE;
478 			dep->de_flag |= DE_MODIFIED;
479 		}
480 	}
481 	/*
482 	 * DOS files only have the ability to have their writability
483 	 * attribute set, so we use the owner write bit to set the readonly
484 	 * attribute.
485 	 */
486 	if (vap->va_mode != (mode_t)VNOVAL) {
487 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
488 			return (EINVAL);
489 		if (cred->cr_uid != pmp->pm_uid) {
490 			error = suser_ucred(cred);
491 			if (error)
492 				return (error);
493 		}
494 		if (vp->v_type != VDIR) {
495 			/* We ignore the read and execute bits. */
496 			if (vap->va_mode & VWRITE)
497 				dep->de_Attributes &= ~ATTR_READONLY;
498 			else
499 				dep->de_Attributes |= ATTR_READONLY;
500 			dep->de_Attributes |= ATTR_ARCHIVE;
501 			dep->de_flag |= DE_MODIFIED;
502 		}
503 	}
504 	VN_KNOTE(ap->a_vp, NOTE_ATTRIB);
505 	return (deupdat(dep, 1));
506 }
507 
508 int
509 msdosfs_read(void *v)
510 {
511 	struct vop_read_args *ap = v;
512 	struct vnode *vp = ap->a_vp;
513 	struct denode *dep = VTODE(vp);
514 	struct msdosfsmount *pmp = dep->de_pmp;
515 	struct uio *uio = ap->a_uio;
516 	int isadir, error = 0;
517 	uint32_t n, diff, size, on;
518 	struct buf *bp;
519 	daddr_t cn;
520 
521 	/*
522 	 * If they didn't ask for any data, then we are done.
523 	 */
524 	if (uio->uio_resid == 0)
525 		return (0);
526 	if (uio->uio_offset < 0)
527 		return (EINVAL);
528 
529 	isadir = dep->de_Attributes & ATTR_DIRECTORY;
530 	do {
531 		if (uio->uio_offset >= dep->de_FileSize)
532 			return (0);
533 
534 		cn = de_cluster(pmp, uio->uio_offset);
535 		size = pmp->pm_bpcluster;
536 		on = uio->uio_offset & pmp->pm_crbomask;
537 		n = ulmin(pmp->pm_bpcluster - on, uio->uio_resid);
538 
539 		/*
540 		 * de_FileSize is uint32_t, and we know that uio_offset <
541 		 * de_FileSize, so uio->uio_offset < 2^32.  Therefore
542 		 * the cast to uint32_t on the next line is safe.
543 		 */
544 		diff = dep->de_FileSize - (uint32_t)uio->uio_offset;
545 		if (diff < n)
546 			n = diff;
547 
548 		/*
549 		 * If we are operating on a directory file then be sure to
550 		 * do i/o with the vnode for the filesystem instead of the
551 		 * vnode for the directory.
552 		 */
553 		if (isadir) {
554 			error = pcbmap(dep, cn, &cn, 0, &size);
555 			if (error)
556 				return (error);
557 			error = bread(pmp->pm_devvp, cn, size, &bp);
558 		} else {
559 			if (de_cn2off(pmp, cn + 1) >= dep->de_FileSize)
560 				error = bread(vp, cn, size, &bp);
561 			else
562 				error = bread_cluster(vp, cn, size, &bp);
563 		}
564 		n = min(n, pmp->pm_bpcluster - bp->b_resid);
565 		if (error) {
566 			brelse(bp);
567 			return (error);
568 		}
569 		error = uiomove(bp->b_data + on, n, uio);
570 		brelse(bp);
571 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
572 	if (!isadir && !(vp->v_mount->mnt_flag & MNT_NOATIME))
573 		dep->de_flag |= DE_ACCESS;
574 	return (error);
575 }
576 
577 /*
578  * Write data to a file or directory.
579  */
580 int
581 msdosfs_write(void *v)
582 {
583 	struct vop_write_args *ap = v;
584 	uint32_t n, croffset;
585 	size_t resid;
586 	ssize_t overrun;
587 	int extended = 0;
588 	uint32_t osize;
589 	int error = 0;
590 	uint32_t count, lastcn;
591 	daddr_t cn;
592 	struct buf *bp;
593 	int ioflag = ap->a_ioflag;
594 	struct uio *uio = ap->a_uio;
595 	struct vnode *vp = ap->a_vp;
596 	struct vnode *thisvp;
597 	struct denode *dep = VTODE(vp);
598 	struct msdosfsmount *pmp = dep->de_pmp;
599 	struct ucred *cred = ap->a_cred;
600 
601 #ifdef MSDOSFS_DEBUG
602 	printf("msdosfs_write(vp %p, uio %p, ioflag %08x, cred %p\n",
603 	    vp, uio, ioflag, cred);
604 	printf("msdosfs_write(): diroff %d, dirclust %d, startcluster %d\n",
605 	    dep->de_diroffset, dep->de_dirclust, dep->de_StartCluster);
606 #endif
607 
608 	switch (vp->v_type) {
609 	case VREG:
610 		if (ioflag & IO_APPEND)
611 			uio->uio_offset = dep->de_FileSize;
612 		thisvp = vp;
613 		break;
614 	case VDIR:
615 		return EISDIR;
616 	default:
617 		panic("msdosfs_write(): bad file type");
618 	}
619 
620 	if (uio->uio_offset < 0)
621 		return (EINVAL);
622 
623 	if (uio->uio_resid == 0)
624 		return (0);
625 
626 	/* Don't bother to try to write files larger than the f/s limit */
627 	if (uio->uio_offset > MSDOSFS_FILESIZE_MAX ||
628 	    uio->uio_resid > (MSDOSFS_FILESIZE_MAX - uio->uio_offset))
629 		return (EFBIG);
630 
631 	/* do the filesize rlimit check */
632 	if ((error = vn_fsizechk(vp, uio, ioflag, &overrun)))
633 		return (error);
634 
635 	/*
636 	 * If the offset we are starting the write at is beyond the end of
637 	 * the file, then they've done a seek.  Unix filesystems allow
638 	 * files with holes in them, DOS doesn't so we must fill the hole
639 	 * with zeroed blocks.
640 	 */
641 	if (uio->uio_offset > dep->de_FileSize) {
642 		if ((error = deextend(dep, uio->uio_offset, cred)) != 0)
643 			goto out;
644 	}
645 
646 	/*
647 	 * Remember some values in case the write fails.
648 	 */
649 	resid = uio->uio_resid;
650 	osize = dep->de_FileSize;
651 
652 	/*
653 	 * If we write beyond the end of the file, extend it to its ultimate
654 	 * size ahead of the time to hopefully get a contiguous area.
655 	 */
656 	if (uio->uio_offset + resid > osize) {
657 		extended = 1;
658 		count = de_clcount(pmp, uio->uio_offset + resid) -
659 			de_clcount(pmp, osize);
660 		if ((error = extendfile(dep, count, NULL, NULL, 0)) &&
661 		    (error != ENOSPC || (ioflag & IO_UNIT)))
662 			goto errexit;
663 		lastcn = dep->de_fc[FC_LASTFC].fc_frcn;
664 	} else
665 		lastcn = de_clcount(pmp, osize) - 1;
666 
667 	do {
668 		croffset = uio->uio_offset & pmp->pm_crbomask;
669 		cn = de_cluster(pmp, uio->uio_offset);
670 
671 		if (cn > lastcn) {
672 			error = ENOSPC;
673 			break;
674 		}
675 
676 		if (croffset == 0 &&
677 		    (de_cluster(pmp, uio->uio_offset + uio->uio_resid) > cn ||
678 		     (uio->uio_offset + uio->uio_resid) >= dep->de_FileSize)) {
679 			/*
680 			 * If either the whole cluster gets written,
681 			 * or we write the cluster from its start beyond EOF,
682 			 * then no need to read data from disk.
683 			 */
684 			bp = getblk(thisvp, cn, pmp->pm_bpcluster, 0, 0);
685 			clrbuf(bp);
686 			/*
687 			 * Do the bmap now, since pcbmap needs buffers
688 			 * for the fat table. (see msdosfs_strategy)
689 			 */
690 			if (bp->b_blkno == bp->b_lblkno) {
691 				error = pcbmap(dep, bp->b_lblkno, &cn, 0, 0);
692 				if (error)
693 					bp->b_blkno = -1;
694 				else
695 					bp->b_blkno = cn;
696 			}
697 			if (bp->b_blkno == -1) {
698 				brelse(bp);
699 				if (!error)
700 					error = EIO;		/* XXX */
701 				break;
702 			}
703 		} else {
704 			/*
705 			 * The block we need to write into exists, so
706 			 * read it in.
707 			 */
708 			error = bread(thisvp, cn, pmp->pm_bpcluster, &bp);
709 			if (error) {
710 				brelse(bp);
711 				break;
712 			}
713 		}
714 
715 		n = ulmin(uio->uio_resid, pmp->pm_bpcluster - croffset);
716 		if (uio->uio_offset + n > dep->de_FileSize) {
717 			dep->de_FileSize = uio->uio_offset + n;
718 			uvm_vnp_setsize(vp, dep->de_FileSize);
719 		}
720 		uvm_vnp_uncache(vp);
721 		/*
722 		 * Should these vnode_pager_* functions be done on dir
723 		 * files?
724 		 */
725 
726 		/*
727 		 * Copy the data from user space into the buf header.
728 		 */
729 		error = uiomove(bp->b_data + croffset, n, uio);
730 
731 		/*
732 		 * If they want this synchronous then write it and wait for
733 		 * it.  Otherwise, if on a cluster boundary write it
734 		 * asynchronously so we can move on to the next block
735 		 * without delay.  Otherwise do a delayed write because we
736 		 * may want to write somemore into the block later.
737 		 */
738 #if 0
739 		if (ioflag & IO_NOCACHE)
740 			bp->b_flags |= B_NOCACHE;
741 #endif
742 		if (ioflag & IO_SYNC)
743 			(void) bwrite(bp);
744 		else if (n + croffset == pmp->pm_bpcluster)
745 			bawrite(bp);
746 		else
747 			bdwrite(bp);
748 		dep->de_flag |= DE_UPDATE;
749 	} while (error == 0 && uio->uio_resid > 0);
750 
751 	if (resid > uio->uio_resid)
752 		 VN_KNOTE(ap->a_vp, NOTE_WRITE | (extended ? NOTE_EXTEND : 0));
753 
754 	if (dep->de_FileSize < osize)
755 		VN_KNOTE(ap->a_vp, NOTE_TRUNCATE);
756 
757 	/*
758 	 * If the write failed and they want us to, truncate the file back
759 	 * to the size it was before the write was attempted.
760 	 */
761 errexit:
762 	if (error) {
763 		if (ioflag & IO_UNIT) {
764 			detrunc(dep, osize, ioflag & IO_SYNC, NOCRED, NULL);
765 			uio->uio_offset -= resid - uio->uio_resid;
766 			uio->uio_resid = resid;
767 		} else {
768 			detrunc(dep, dep->de_FileSize, ioflag & IO_SYNC, NOCRED, NULL);
769 			if (uio->uio_resid != resid)
770 				error = 0;
771 		}
772 	} else if (ioflag & IO_SYNC)
773 		error = deupdat(dep, 1);
774 
775 out:
776 	/* correct the result for writes clamped by vn_fsizechk() */
777 	uio->uio_resid += overrun;
778 	return (error);
779 }
780 
781 int
782 msdosfs_ioctl(void *v)
783 {
784 #if 0
785 	struct vop_ioctl_args /* {
786 		struct vnode *a_vp;
787 		uint32_t a_command;
788 		caddr_t a_data;
789 		int a_fflag;
790 		struct ucred *a_cred;
791 		struct proc *a_p;
792 	} */ *ap;
793 #endif
794 
795 	return (ENOTTY);
796 }
797 
798 int
799 msdosfs_poll(void *v)
800 {
801 	struct vop_poll_args *ap = v;
802 
803 	return (ap->a_events & (POLLIN | POLLOUT | POLLRDNORM | POLLWRNORM));
804 }
805 
806 /*
807  * Flush the blocks of a file to disk.
808  *
809  * This function is worthless for vnodes that represent directories. Maybe we
810  * could just do a sync if they try an fsync on a directory file.
811  */
812 int
813 msdosfs_fsync(void *v)
814 {
815 	struct vop_fsync_args *ap = v;
816 	struct vnode *vp = ap->a_vp;
817 
818 	vflushbuf(vp, ap->a_waitfor == MNT_WAIT);
819 	return (deupdat(VTODE(vp), ap->a_waitfor == MNT_WAIT));
820 }
821 
822 /*
823  * Flush the blocks of a file to disk.
824  *
825  * This function is worthless for vnodes that represent directories. Maybe we
826  * could just do a sync if they try an fsync on a directory file.
827  */
828 int
829 msdosfs_remove(void *v)
830 {
831 	struct vop_remove_args *ap = v;
832 	struct denode *dep = VTODE(ap->a_vp);
833 	struct denode *ddep = VTODE(ap->a_dvp);
834 	int error;
835 
836 	if (ap->a_vp->v_type == VDIR)
837 		error = EPERM;
838 	else
839 		error = removede(ddep, dep);
840 
841 	VN_KNOTE(ap->a_vp, NOTE_DELETE);
842 	VN_KNOTE(ap->a_dvp, NOTE_WRITE);
843 
844 #ifdef MSDOSFS_DEBUG
845 	printf("msdosfs_remove(), dep %p, v_usecount %d\n", dep,
846 	    ap->a_vp->v_usecount);
847 #endif
848 	if (ddep == dep)
849 		vrele(ap->a_vp);
850 	else
851 		vput(ap->a_vp);	/* causes msdosfs_inactive() to be called
852 				 * via vrele() */
853 	vput(ap->a_dvp);
854 	return (error);
855 }
856 
857 /*
858  * DOS filesystems don't know what links are. But since we already called
859  * msdosfs_lookup() with create and lockparent, the parent is locked so we
860  * have to free it before we return the error.
861  */
862 int
863 msdosfs_link(void *v)
864 {
865 	struct vop_link_args *ap = v;
866 
867 	VOP_ABORTOP(ap->a_dvp, ap->a_cnp);
868 	vput(ap->a_dvp);
869 	return (EOPNOTSUPP);
870 }
871 
872 /*
873  * Renames on files require moving the denode to a new hash queue since the
874  * denode's location is used to compute which hash queue to put the file
875  * in. Unless it is a rename in place.  For example "mv a b".
876  *
877  * What follows is the basic algorithm:
878  *
879  * if (file move) {
880  *	if (dest file exists) {
881  *		remove dest file
882  *	}
883  *	if (dest and src in same directory) {
884  *		rewrite name in existing directory slot
885  *	} else {
886  *		write new entry in dest directory
887  *		update offset and dirclust in denode
888  *		move denode to new hash chain
889  *		clear old directory entry
890  *	}
891  * } else {
892  *	directory move
893  *	if (dest directory exists) {
894  *		if (dest is not empty) {
895  *			return ENOTEMPTY
896  *		}
897  *		remove dest directory
898  *	}
899  *	if (dest and src in same directory) {
900  *		rewrite name in existing entry
901  *	} else {
902  *		be sure dest is not a child of src directory
903  *		write entry in dest directory
904  *		update "." and ".." in moved directory
905  *		update offset and dirclust in denode
906  *		move denode to new hash chain
907  *		clear old directory entry for moved directory
908  *	}
909  * }
910  *
911  * On entry:
912  *	source's parent directory is unlocked
913  *	source file or directory is unlocked
914  *	destination's parent directory is locked
915  *	destination file or directory is locked if it exists
916  *
917  * On exit:
918  *	all denodes should be released
919  *
920  * Notes:
921  * I'm not sure how the memory containing the pathnames pointed at by the
922  * componentname structures is freed, there may be some memory bleeding
923  * for each rename done.
924  */
925 int
926 msdosfs_rename(void *v)
927 {
928 	struct vop_rename_args *ap = v;
929 	struct vnode *tvp = ap->a_tvp;
930 	struct vnode *tdvp = ap->a_tdvp;
931 	struct vnode *fvp = ap->a_fvp;
932 	struct vnode *fdvp = ap->a_fdvp;
933 	struct componentname *tcnp = ap->a_tcnp;
934 	struct componentname *fcnp = ap->a_fcnp;
935 	struct proc *p = curproc; /* XXX */
936 	struct denode *ip, *xp, *dp, *zp;
937 	u_char toname[11], oldname[11];
938 	uint32_t from_diroffset, to_diroffset;
939 	u_char to_count;
940 	int doingdirectory = 0, newparent = 0;
941 	int error;
942 	uint32_t cn, pcl;
943 	daddr_t bn;
944 	struct msdosfsmount *pmp;
945 	struct direntry *dotdotp;
946 	struct buf *bp;
947 
948 	pmp = VFSTOMSDOSFS(fdvp->v_mount);
949 
950 #ifdef DIAGNOSTIC
951 	if ((tcnp->cn_flags & HASBUF) == 0 ||
952 	    (fcnp->cn_flags & HASBUF) == 0)
953 		panic("msdosfs_rename: no name");
954 #endif
955 	/*
956 	 * Check for cross-device rename.
957 	 */
958 	if ((fvp->v_mount != tdvp->v_mount) ||
959 	    (tvp && (fvp->v_mount != tvp->v_mount))) {
960 		error = EXDEV;
961 abortit:
962 		VOP_ABORTOP(tdvp, tcnp);
963 		if (tdvp == tvp)
964 			vrele(tdvp);
965 		else
966 			vput(tdvp);
967 		if (tvp)
968 			vput(tvp);
969 		VOP_ABORTOP(fdvp, fcnp);
970 		vrele(fdvp);
971 		vrele(fvp);
972 		return (error);
973 	}
974 
975 	/*
976 	 * If source and dest are the same, do nothing.
977 	 */
978 	if (tvp == fvp) {
979 		error = 0;
980 		goto abortit;
981 	}
982 
983 	/* */
984 	if ((error = vn_lock(fvp, LK_EXCLUSIVE | LK_RETRY, p)) != 0)
985 		goto abortit;
986 	dp = VTODE(fdvp);
987 	ip = VTODE(fvp);
988 
989 	/*
990 	 * Be sure we are not renaming ".", "..", or an alias of ".". This
991 	 * leads to a crippled directory tree.  It's pretty tough to do a
992 	 * "ls" or "pwd" with the "." directory entry missing, and "cd .."
993 	 * doesn't work if the ".." entry is missing.
994 	 */
995 	if (ip->de_Attributes & ATTR_DIRECTORY) {
996 		/*
997 		 * Avoid ".", "..", and aliases of "." for obvious reasons.
998 		 */
999 		if ((fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
1000 		    dp == ip ||
1001 		    (fcnp->cn_flags & ISDOTDOT) ||
1002 		    (tcnp->cn_flags & ISDOTDOT) ||
1003 		    (ip->de_flag & DE_RENAME)) {
1004 			VOP_UNLOCK(fvp, p);
1005 			error = EINVAL;
1006 			goto abortit;
1007 		}
1008 		ip->de_flag |= DE_RENAME;
1009 		doingdirectory++;
1010 	}
1011 	VN_KNOTE(fdvp, NOTE_WRITE);	/* XXX right place? */
1012 
1013 	/*
1014 	 * When the target exists, both the directory
1015 	 * and target vnodes are returned locked.
1016 	 */
1017 	dp = VTODE(tdvp);
1018 	xp = tvp ? VTODE(tvp) : NULL;
1019 	/*
1020 	 * Remember direntry place to use for destination
1021 	 */
1022 	to_diroffset = dp->de_fndoffset;
1023 	to_count = dp->de_fndcnt;
1024 
1025 	/*
1026 	 * If ".." must be changed (ie the directory gets a new
1027 	 * parent) then the source directory must not be in the
1028 	 * directory hierarchy above the target, as this would
1029 	 * orphan everything below the source directory. Also
1030 	 * the user must have write permission in the source so
1031 	 * as to be able to change "..". We must repeat the call
1032 	 * to namei, as the parent directory is unlocked by the
1033 	 * call to doscheckpath().
1034 	 */
1035 	error = VOP_ACCESS(fvp, VWRITE, tcnp->cn_cred, tcnp->cn_proc);
1036 	VOP_UNLOCK(fvp, p);
1037 	if (VTODE(fdvp)->de_StartCluster != VTODE(tdvp)->de_StartCluster)
1038 		newparent = 1;
1039 	vrele(fdvp);
1040 	if (doingdirectory && newparent) {
1041 		if (error)	/* write access check above */
1042 			goto bad1;
1043 		if (xp != NULL)
1044 			vput(tvp);
1045 		/*
1046 		 * doscheckpath() vput()'s dp,
1047 		 * so we have to do a relookup afterwards
1048 		 */
1049 		if ((error = doscheckpath(ip, dp)) != 0)
1050 			goto out;
1051 		if ((tcnp->cn_flags & SAVESTART) == 0)
1052 			panic("msdosfs_rename: lost to startdir");
1053 		if ((error = vfs_relookup(tdvp, &tvp, tcnp)) != 0)
1054 			goto out;
1055 		dp = VTODE(tdvp);
1056 		xp = tvp ? VTODE(tvp) : NULL;
1057 	}
1058 
1059 	VN_KNOTE(tdvp, NOTE_WRITE);
1060 
1061 	if (xp != NULL) {
1062 		/*
1063 		 * Target must be empty if a directory and have no links
1064 		 * to it. Also, ensure source and target are compatible
1065 		 * (both directories, or both not directories).
1066 		 */
1067 		if (xp->de_Attributes & ATTR_DIRECTORY) {
1068 			if (!dosdirempty(xp)) {
1069 				error = ENOTEMPTY;
1070 				goto bad1;
1071 			}
1072 			if (!doingdirectory) {
1073 				error = ENOTDIR;
1074 				goto bad1;
1075 			}
1076 			cache_purge(tdvp);
1077 		} else if (doingdirectory) {
1078 			error = EISDIR;
1079 			goto bad1;
1080 		}
1081 		if ((error = removede(dp, xp)) != 0)
1082 			goto bad1;
1083 		VN_KNOTE(tvp, NOTE_DELETE);
1084 		vput(tvp);
1085 		xp = NULL;
1086 	}
1087 
1088 	/*
1089 	 * Convert the filename in tcnp into a dos filename. We copy this
1090 	 * into the denode and directory entry for the destination
1091 	 * file/directory.
1092 	 */
1093 	if ((error = uniqdosname(VTODE(tdvp), tcnp, toname)) != 0)
1094 		goto bad1;
1095 
1096 	/*
1097 	 * Since from wasn't locked at various places above,
1098 	 * have to do a relookup here.
1099 	 */
1100 	fcnp->cn_flags &= ~MODMASK;
1101 	fcnp->cn_flags |= LOCKPARENT | LOCKLEAF;
1102 	if ((fcnp->cn_flags & SAVESTART) == 0)
1103 		panic("msdosfs_rename: lost from startdir");
1104 	if (!newparent)
1105 		VOP_UNLOCK(tdvp, p);
1106 	(void) vfs_relookup(fdvp, &fvp, fcnp);
1107 	if (fvp == NULL) {
1108 		/*
1109 		 * From name has disappeared.
1110 		 */
1111 		if (doingdirectory)
1112 			panic("rename: lost dir entry");
1113 		vrele(ap->a_fvp);
1114 		if (newparent)
1115 			VOP_UNLOCK(tdvp, p);
1116 		vrele(tdvp);
1117 		return 0;
1118 	}
1119 	xp = VTODE(fvp);
1120 	zp = VTODE(fdvp);
1121 	from_diroffset = zp->de_fndoffset;
1122 
1123 	/*
1124 	 * Ensure that the directory entry still exists and has not
1125 	 * changed till now. If the source is a file the entry may
1126 	 * have been unlinked or renamed. In either case there is
1127 	 * no further work to be done. If the source is a directory
1128 	 * then it cannot have been rmdir'ed or renamed; this is
1129 	 * prohibited by the DE_RENAME flag.
1130 	 */
1131 	if (xp != ip) {
1132 		if (doingdirectory)
1133 			panic("rename: lost dir entry");
1134 		vrele(ap->a_fvp);
1135 		if (newparent)
1136 			VOP_UNLOCK(fdvp, p);
1137 		xp = NULL;
1138 	} else {
1139 		vrele(fvp);
1140 		xp = NULL;
1141 
1142 		/*
1143 		 * First write a new entry in the destination
1144 		 * directory and mark the entry in the source directory
1145 		 * as deleted.  Then move the denode to the correct hash
1146 		 * chain for its new location in the filesystem.  And, if
1147 		 * we moved a directory, then update its .. entry to point
1148 		 * to the new parent directory.
1149 		 */
1150 		bcopy(ip->de_Name, oldname, 11);
1151 		bcopy(toname, ip->de_Name, 11);	/* update denode */
1152 		dp->de_fndoffset = to_diroffset;
1153 		dp->de_fndcnt = to_count;
1154 		error = createde(ip, dp, NULL, tcnp);
1155 		if (error) {
1156 			bcopy(oldname, ip->de_Name, 11);
1157 			if (newparent)
1158 				VOP_UNLOCK(fdvp, p);
1159 			goto bad;
1160 		}
1161 		ip->de_refcnt++;
1162 		zp->de_fndoffset = from_diroffset;
1163 		if ((error = removede(zp, ip)) != 0) {
1164 			/* XXX should really panic here, fs is corrupt */
1165 			if (newparent)
1166 				VOP_UNLOCK(fdvp, p);
1167 			goto bad;
1168 		}
1169 
1170 		cache_purge(fvp);
1171 
1172 		if (!doingdirectory) {
1173 			error = pcbmap(dp, de_cluster(pmp, to_diroffset), 0,
1174 				       &ip->de_dirclust, 0);
1175 			if (error) {
1176 				/* XXX should really panic here, fs is corrupt */
1177 				if (newparent)
1178 					VOP_UNLOCK(fdvp, p);
1179 				goto bad;
1180 			}
1181 			ip->de_diroffset = to_diroffset;
1182 			if (ip->de_dirclust != MSDOSFSROOT)
1183 				ip->de_diroffset &= pmp->pm_crbomask;
1184 		}
1185 		reinsert(ip);
1186 		if (newparent)
1187 			VOP_UNLOCK(fdvp, p);
1188 	}
1189 
1190 	/*
1191 	 * If we moved a directory to a new parent directory, then we must
1192 	 * fixup the ".." entry in the moved directory.
1193 	 */
1194 	if (doingdirectory && newparent) {
1195 		cn = ip->de_StartCluster;
1196 		if (cn == MSDOSFSROOT) {
1197 			/* this should never happen */
1198 			panic("msdosfs_rename: updating .. in root directory?");
1199 		} else
1200 			bn = cntobn(pmp, cn);
1201 		error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster, &bp);
1202 		if (error) {
1203 			/* XXX should really panic here, fs is corrupt */
1204 			brelse(bp);
1205 			goto bad;
1206 		}
1207 		dotdotp = (struct direntry *)bp->b_data;
1208 		putushort(dotdotp[0].deStartCluster, cn);
1209 		pcl = dp->de_StartCluster;
1210 		if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1211 			pcl = 0;
1212 		putushort(dotdotp[1].deStartCluster, pcl);
1213 		if (FAT32(pmp)) {
1214 			putushort(dotdotp[0].deHighClust, cn >> 16);
1215 			putushort(dotdotp[1].deHighClust, pcl >> 16);
1216 		}
1217 		if ((error = bwrite(bp)) != 0) {
1218 			/* XXX should really panic here, fs is corrupt */
1219 			goto bad;
1220 		}
1221 	}
1222 
1223 	VN_KNOTE(fvp, NOTE_RENAME);
1224 
1225 bad:
1226 	VOP_UNLOCK(fvp, p);
1227 	vrele(fdvp);
1228 bad1:
1229 	if (xp)
1230 		vput(tvp);
1231 	vput(tdvp);
1232 out:
1233 	ip->de_flag &= ~DE_RENAME;
1234 	vrele(fvp);
1235 	return (error);
1236 
1237 }
1238 
1239 struct {
1240 	struct direntry dot;
1241 	struct direntry dotdot;
1242 } dosdirtemplate = {
1243 	{	".       ", "   ",			/* the . entry */
1244 		ATTR_DIRECTORY,				/* file attribute */
1245 		CASE_LOWER_BASE | CASE_LOWER_EXT,	/* lower case */
1246 		0,					/* create time 100ths */
1247 		{ 0, 0 }, { 0, 0 },			/* create time & date */
1248 		{ 0, 0 },				/* access date */
1249 		{ 0, 0 },				/* high bits of start cluster */
1250 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1251 		{ 0, 0 },				/* startcluster */
1252 		{ 0, 0, 0, 0 }				/* filesize */
1253 	},
1254 	{	"..      ", "   ",			/* the .. entry */
1255 		ATTR_DIRECTORY,				/* file attribute */
1256 		CASE_LOWER_BASE | CASE_LOWER_EXT,	/* lower case */
1257 		0,					/* create time 100ths */
1258 		{ 0, 0 }, { 0, 0 },			/* create time & date */
1259 		{ 0, 0 },				/* access date */
1260 		{ 0, 0 },				/* high bits of start cluster */
1261 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1262 		{ 0, 0 },				/* startcluster */
1263 		{ 0, 0, 0, 0 }				/* filesize */
1264 	}
1265 };
1266 
1267 int
1268 msdosfs_mkdir(void *v)
1269 {
1270 	struct vop_mkdir_args *ap = v;
1271 	struct componentname *cnp = ap->a_cnp;
1272 	struct denode ndirent;
1273 	struct denode *dep;
1274 	struct denode *pdep = VTODE(ap->a_dvp);
1275 	int error;
1276 	daddr_t bn;
1277 	uint32_t newcluster, pcl;
1278 	struct direntry *denp;
1279 	struct msdosfsmount *pmp = pdep->de_pmp;
1280 	struct buf *bp;
1281 	struct timespec ts;
1282 
1283 	/*
1284 	 * If this is the root directory and there is no space left we
1285 	 * can't do anything.  This is because the root directory can not
1286 	 * change size.
1287 	 */
1288 	if (pdep->de_StartCluster == MSDOSFSROOT
1289 	    && pdep->de_fndoffset >= pdep->de_FileSize) {
1290 		error = ENOSPC;
1291 		goto bad2;
1292 	}
1293 
1294 	/*
1295 	 * Allocate a cluster to hold the about to be created directory.
1296 	 */
1297 	error = clusteralloc(pmp, 0, 1, CLUST_EOFE, &newcluster, NULL);
1298 	if (error)
1299 		goto bad2;
1300 
1301 	bzero(&ndirent, sizeof(ndirent));
1302 	ndirent.de_pmp = pmp;
1303 	ndirent.de_flag = DE_ACCESS | DE_CREATE | DE_UPDATE;
1304 	getnanotime(&ts);
1305 	DETIMES(&ndirent, &ts, &ts, &ts);
1306 
1307 	/*
1308 	 * Now fill the cluster with the "." and ".." entries. And write
1309 	 * the cluster to disk.  This way it is there for the parent
1310 	 * directory to be pointing at if there were a crash.
1311 	 */
1312 	bn = cntobn(pmp, newcluster);
1313 	/* always succeeds */
1314 	bp = getblk(pmp->pm_devvp, bn, pmp->pm_bpcluster, 0, 0);
1315 	bzero(bp->b_data, pmp->pm_bpcluster);
1316 	bcopy(&dosdirtemplate, bp->b_data, sizeof dosdirtemplate);
1317 	denp = (struct direntry *)bp->b_data;
1318 	putushort(denp[0].deStartCluster, newcluster);
1319 	putushort(denp[0].deCDate, ndirent.de_CDate);
1320 	putushort(denp[0].deCTime, ndirent.de_CTime);
1321 	denp[0].deCTimeHundredth = ndirent.de_CTimeHundredth;
1322 	putushort(denp[0].deADate, ndirent.de_ADate);
1323 	putushort(denp[0].deMDate, ndirent.de_MDate);
1324 	putushort(denp[0].deMTime, ndirent.de_MTime);
1325 	pcl = pdep->de_StartCluster;
1326 	if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1327 		pcl = 0;
1328 	putushort(denp[1].deStartCluster, pcl);
1329 	putushort(denp[1].deCDate, ndirent.de_CDate);
1330 	putushort(denp[1].deCTime, ndirent.de_CTime);
1331 	denp[1].deCTimeHundredth = ndirent.de_CTimeHundredth;
1332 	putushort(denp[1].deADate, ndirent.de_ADate);
1333 	putushort(denp[1].deMDate, ndirent.de_MDate);
1334 	putushort(denp[1].deMTime, ndirent.de_MTime);
1335 	if (FAT32(pmp)) {
1336 		putushort(denp[0].deHighClust, newcluster >> 16);
1337 		putushort(denp[1].deHighClust, pdep->de_StartCluster >> 16);
1338 	}
1339 
1340 	if ((error = bwrite(bp)) != 0)
1341 		goto bad;
1342 
1343 	/*
1344 	 * Now build up a directory entry pointing to the newly allocated
1345 	 * cluster.  This will be written to an empty slot in the parent
1346 	 * directory.
1347 	 */
1348 #ifdef DIAGNOSTIC
1349 	if ((cnp->cn_flags & HASBUF) == 0)
1350 		panic("msdosfs_mkdir: no name");
1351 #endif
1352 	if ((error = uniqdosname(pdep, cnp, ndirent.de_Name)) != 0)
1353 		goto bad;
1354 
1355 	ndirent.de_Attributes = ATTR_DIRECTORY;
1356 	ndirent.de_StartCluster = newcluster;
1357 	ndirent.de_FileSize = 0;
1358 	ndirent.de_dev = pdep->de_dev;
1359 	ndirent.de_devvp = pdep->de_devvp;
1360 	if ((error = createde(&ndirent, pdep, &dep, cnp)) != 0)
1361 		goto bad;
1362 	if ((cnp->cn_flags & SAVESTART) == 0)
1363 		pool_put(&namei_pool, cnp->cn_pnbuf);
1364 	VN_KNOTE(ap->a_dvp, NOTE_WRITE | NOTE_LINK);
1365 	vput(ap->a_dvp);
1366 	*ap->a_vpp = DETOV(dep);
1367 	return (0);
1368 
1369 bad:
1370 	clusterfree(pmp, newcluster, NULL);
1371 bad2:
1372 	pool_put(&namei_pool, cnp->cn_pnbuf);
1373 	vput(ap->a_dvp);
1374 	return (error);
1375 }
1376 
1377 int
1378 msdosfs_rmdir(void *v)
1379 {
1380 	struct vop_rmdir_args *ap = v;
1381 	struct vnode *vp = ap->a_vp;
1382 	struct vnode *dvp = ap->a_dvp;
1383 	struct componentname *cnp = ap->a_cnp;
1384 	struct denode *ip, *dp;
1385 	int error;
1386 
1387 	ip = VTODE(vp);
1388 	dp = VTODE(dvp);
1389 	/*
1390 	 * No rmdir "." please.
1391 	 */
1392 	if (dp == ip) {
1393 		vrele(dvp);
1394 		vput(vp);
1395 		return (EINVAL);
1396 	}
1397 	/*
1398 	 * Verify the directory is empty (and valid).
1399 	 * (Rmdir ".." won't be valid since
1400 	 *  ".." will contain a reference to
1401 	 *  the current directory and thus be
1402 	 *  non-empty.)
1403 	 */
1404 	error = 0;
1405 	if (!dosdirempty(ip) || ip->de_flag & DE_RENAME) {
1406 		error = ENOTEMPTY;
1407 		goto out;
1408 	}
1409 
1410 	VN_KNOTE(dvp, NOTE_WRITE | NOTE_LINK);
1411 
1412 	/*
1413 	 * Delete the entry from the directory.  For dos filesystems this
1414 	 * gets rid of the directory entry on disk, the in memory copy
1415 	 * still exists but the de_refcnt is <= 0.  This prevents it from
1416 	 * being found by deget().  When the vput() on dep is done we give
1417 	 * up access and eventually msdosfs_reclaim() will be called which
1418 	 * will remove it from the denode cache.
1419 	 */
1420 	if ((error = removede(dp, ip)) != 0)
1421 		goto out;
1422 	/*
1423 	 * This is where we decrement the link count in the parent
1424 	 * directory.  Since dos filesystems don't do this we just purge
1425 	 * the name cache and let go of the parent directory denode.
1426 	 */
1427 	cache_purge(dvp);
1428 	vput(dvp);
1429 	dvp = NULL;
1430 	/*
1431 	 * Truncate the directory that is being deleted.
1432 	 */
1433 	error = detrunc(ip, (uint32_t)0, IO_SYNC, cnp->cn_cred, cnp->cn_proc);
1434 	cache_purge(vp);
1435 out:
1436 	if (dvp)
1437 		vput(dvp);
1438 	VN_KNOTE(vp, NOTE_DELETE);
1439 	vput(vp);
1440 	return (error);
1441 }
1442 
1443 /*
1444  * DOS filesystems don't know what symlinks are.
1445  */
1446 int
1447 msdosfs_symlink(void *v)
1448 {
1449 	struct vop_symlink_args *ap = v;
1450 
1451 	VOP_ABORTOP(ap->a_dvp, ap->a_cnp);
1452 	vput(ap->a_dvp);
1453 	return (EOPNOTSUPP);
1454 }
1455 
1456 int
1457 msdosfs_readdir(void *v)
1458 {
1459 	struct vop_readdir_args *ap = v;
1460 	int error = 0;
1461 	int diff;
1462 	long n;
1463 	int blsize;
1464 	long on;
1465 	long lost;
1466 	long count;
1467 	uint32_t dirsperblk;
1468 	uint32_t cn, lbn;
1469 	uint32_t fileno;
1470 	long bias = 0;
1471 	daddr_t bn;
1472 	struct buf *bp;
1473 	struct denode *dep = VTODE(ap->a_vp);
1474 	struct msdosfsmount *pmp = dep->de_pmp;
1475 	struct direntry *dentp;
1476 	struct dirent dirbuf;
1477 	struct uio *uio = ap->a_uio;
1478 	off_t offset, wlast = -1;
1479 	int chksum = -1;
1480 
1481 #ifdef MSDOSFS_DEBUG
1482 	printf("msdosfs_readdir(): vp %p, uio %p, cred %p, eofflagp %p\n",
1483 	    ap->a_vp, uio, ap->a_cred, ap->a_eofflag);
1484 #endif
1485 
1486 	/*
1487 	 * msdosfs_readdir() won't operate properly on regular files since
1488 	 * it does i/o only with the filesystem vnode, and hence can
1489 	 * retrieve the wrong block from the buffer cache for a plain file.
1490 	 * So, fail attempts to readdir() on a plain file.
1491 	 */
1492 	if ((dep->de_Attributes & ATTR_DIRECTORY) == 0)
1493 		return (ENOTDIR);
1494 
1495 	/*
1496 	 * To be safe, initialize dirbuf
1497 	 */
1498 	bzero(&dirbuf, sizeof(dirbuf));
1499 
1500 	/*
1501 	 * If the user buffer is smaller than the size of one dos directory
1502 	 * entry or the file offset is not a multiple of the size of a
1503 	 * directory entry, then we fail the read.
1504 	 */
1505 	count = uio->uio_resid & ~(sizeof(struct direntry) - 1);
1506 	offset = uio->uio_offset;
1507 	if (count < sizeof(struct direntry) ||
1508 	    (offset & (sizeof(struct direntry) - 1)))
1509 		return (EINVAL);
1510 	lost = uio->uio_resid - count;
1511 	uio->uio_resid = count;
1512 
1513 	dirsperblk = pmp->pm_BytesPerSec / sizeof(struct direntry);
1514 
1515 	/*
1516 	 * If they are reading from the root directory then, we simulate
1517 	 * the . and .. entries since these don't exist in the root
1518 	 * directory.  We also set the offset bias to make up for having to
1519 	 * simulate these entries. By this I mean that at file offset 64 we
1520 	 * read the first entry in the root directory that lives on disk.
1521 	 */
1522 	if (dep->de_StartCluster == MSDOSFSROOT
1523 	    || (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)) {
1524 #if 0
1525 		printf("msdosfs_readdir(): going after . or .. in root dir, offset %d\n",
1526 		    offset);
1527 #endif
1528 		bias = 2 * sizeof(struct direntry);
1529 		if (offset < bias) {
1530 			for (n = (int)offset / sizeof(struct direntry);
1531 			     n < 2; n++) {
1532 			        if (FAT32(pmp))
1533 				        dirbuf.d_fileno = pmp->pm_rootdirblk;
1534 				else
1535 				        dirbuf.d_fileno = 1;
1536 				dirbuf.d_type = DT_DIR;
1537 				switch (n) {
1538 				case 0:
1539 					dirbuf.d_namlen = 1;
1540 					strlcpy(dirbuf.d_name, ".",
1541 					    sizeof dirbuf.d_name);
1542 					break;
1543 				case 1:
1544 					dirbuf.d_namlen = 2;
1545 					strlcpy(dirbuf.d_name, "..",
1546 					    sizeof dirbuf.d_name);
1547 					break;
1548 				}
1549 				dirbuf.d_reclen = DIRENT_SIZE(&dirbuf);
1550 				dirbuf.d_off = offset +
1551 				    sizeof(struct direntry);
1552 				if (uio->uio_resid < dirbuf.d_reclen)
1553 					goto out;
1554 				error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1555 				if (error)
1556 					goto out;
1557 				offset = dirbuf.d_off;
1558 			}
1559 		}
1560 	}
1561 
1562 	while (uio->uio_resid > 0) {
1563 		lbn = de_cluster(pmp, offset - bias);
1564 		on = (offset - bias) & pmp->pm_crbomask;
1565 		n = min(pmp->pm_bpcluster - on, uio->uio_resid);
1566 		diff = dep->de_FileSize - (offset - bias);
1567 		if (diff <= 0)
1568 			break;
1569 		n = min(n, diff);
1570 		if ((error = pcbmap(dep, lbn, &bn, &cn, &blsize)) != 0)
1571 			break;
1572 		error = bread(pmp->pm_devvp, bn, blsize, &bp);
1573 		if (error) {
1574 			brelse(bp);
1575 			return (error);
1576 		}
1577 		n = min(n, blsize - bp->b_resid);
1578 
1579 		/*
1580 		 * Convert from dos directory entries to fs-independent
1581 		 * directory entries.
1582 		 */
1583 		for (dentp = (struct direntry *)(bp->b_data + on);
1584 		     (char *)dentp < bp->b_data + on + n;
1585 		     dentp++, offset += sizeof(struct direntry)) {
1586 #if 0
1587 			printf("rd: dentp %08x prev %08x crnt %08x deName %02x attr %02x\n",
1588 			    dentp, prev, crnt, dentp->deName[0], dentp->deAttributes);
1589 #endif
1590 			/*
1591 			 * If this is an unused entry, we can stop.
1592 			 */
1593 			if (dentp->deName[0] == SLOT_EMPTY) {
1594 				brelse(bp);
1595 				goto out;
1596 			}
1597 			/*
1598 			 * Skip deleted entries.
1599 			 */
1600 			if (dentp->deName[0] == SLOT_DELETED) {
1601 				chksum = -1;
1602 				wlast = -1;
1603 				continue;
1604 			}
1605 
1606 			/*
1607 			 * Handle Win95 long directory entries
1608 			 */
1609 			if (dentp->deAttributes == ATTR_WIN95) {
1610 				struct winentry *wep;
1611 				if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
1612 					continue;
1613 				wep = (struct winentry *)dentp;
1614 				chksum = win2unixfn(wep, &dirbuf, chksum);
1615 				if (wep->weCnt & WIN_LAST)
1616 					wlast = offset;
1617 				continue;
1618 			}
1619 
1620 			/*
1621 			 * Skip volume labels
1622 			 */
1623 			if (dentp->deAttributes & ATTR_VOLUME) {
1624 				chksum = -1;
1625 				wlast = -1;
1626 				continue;
1627 			}
1628 
1629 			/*
1630 			 * This computation of d_fileno must match
1631 			 * the computation of va_fileid in
1632 			 * msdosfs_getattr.
1633 			 */
1634 			fileno = getushort(dentp->deStartCluster);
1635 			if (FAT32(pmp))
1636 			    fileno |= getushort(dentp->deHighClust) << 16;
1637 
1638 			if (dentp->deAttributes & ATTR_DIRECTORY) {
1639 				/* Special-case root */
1640 				if (fileno == MSDOSFSROOT)  {
1641 					fileno = FAT32(pmp) ?
1642 					    pmp->pm_rootdirblk : 1;
1643 				}
1644 
1645 				dirbuf.d_fileno = fileno;
1646 				dirbuf.d_type = DT_DIR;
1647 			} else {
1648 				if (getulong(dentp->deFileSize) == 0) {
1649 					uint64_t fileno64;
1650 
1651 					fileno64 = (cn == MSDOSFSROOT) ?
1652 					    roottobn(pmp, 0) : cntobn(pmp, cn);
1653 
1654 					fileno64 *= dirsperblk;
1655 					fileno64 += dentp -
1656 					    (struct direntry *)bp->b_data;
1657 
1658 					fileno = fileidhash(fileno64);
1659 				}
1660 
1661 				dirbuf.d_fileno = fileno;
1662 				dirbuf.d_type = DT_REG;
1663 			}
1664 
1665 			if (chksum != winChksum(dentp->deName))
1666 				dirbuf.d_namlen = dos2unixfn(dentp->deName,
1667 				    (u_char *)dirbuf.d_name,
1668 				    pmp->pm_flags & MSDOSFSMNT_SHORTNAME);
1669 			else
1670 				dirbuf.d_name[dirbuf.d_namlen] = 0;
1671 			chksum = -1;
1672 			dirbuf.d_reclen = DIRENT_SIZE(&dirbuf);
1673 			dirbuf.d_off = offset + sizeof(struct direntry);
1674 			if (uio->uio_resid < dirbuf.d_reclen) {
1675 				brelse(bp);
1676 				/* Remember long-name offset. */
1677 				if (wlast != -1)
1678 					offset = wlast;
1679 				goto out;
1680 			}
1681 			wlast = -1;
1682 			error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1683 			if (error) {
1684 				brelse(bp);
1685 				goto out;
1686 			}
1687 		}
1688 		brelse(bp);
1689 	}
1690 
1691 out:
1692 	uio->uio_offset = offset;
1693 	uio->uio_resid += lost;
1694 	if (dep->de_FileSize - (offset - bias) <= 0)
1695 		*ap->a_eofflag = 1;
1696 	else
1697 		*ap->a_eofflag = 0;
1698 	return (error);
1699 }
1700 
1701 /*
1702  * DOS filesystems don't know what symlinks are.
1703  */
1704 int
1705 msdosfs_readlink(void *v)
1706 {
1707 #if 0
1708 	struct vop_readlink_args /* {
1709 		struct vnode *a_vp;
1710 		struct uio *a_uio;
1711 		struct ucred *a_cred;
1712 	} */ *ap;
1713 #endif
1714 
1715 	return (EINVAL);
1716 }
1717 
1718 int
1719 msdosfs_lock(void *v)
1720 {
1721 	struct vop_lock_args *ap = v;
1722 	struct vnode *vp = ap->a_vp;
1723 
1724 	return rrw_enter(&VTODE(vp)->de_lock, ap->a_flags & LK_RWFLAGS);
1725 }
1726 
1727 int
1728 msdosfs_unlock(void *v)
1729 {
1730 	struct vop_unlock_args *ap = v;
1731 	struct vnode *vp = ap->a_vp;
1732 
1733 	rrw_exit(&VTODE(vp)->de_lock);
1734 	return 0;
1735 }
1736 
1737 int
1738 msdosfs_islocked(void *v)
1739 {
1740 	struct vop_islocked_args *ap = v;
1741 
1742 	return rrw_status(&VTODE(ap->a_vp)->de_lock);
1743 }
1744 
1745 /*
1746  * vp  - address of vnode file the file
1747  * bn  - which cluster we are interested in mapping to a filesystem block number
1748  * vpp - returns the vnode for the block special file holding the filesystem
1749  *	 containing the file of interest
1750  * bnp - address of where to return the filesystem relative block number
1751  */
1752 int
1753 msdosfs_bmap(void *v)
1754 {
1755 	struct vop_bmap_args *ap = v;
1756 	struct denode *dep = VTODE(ap->a_vp);
1757 
1758 	if (ap->a_vpp != NULL)
1759 		*ap->a_vpp = dep->de_devvp;
1760 	if (ap->a_bnp == NULL)
1761 		return (0);
1762 
1763 	return (msdosfs_bmaparray(ap->a_vp, ap->a_bn, ap->a_bnp, ap->a_runp));
1764 }
1765 
1766 int
1767 msdosfs_bmaparray(struct vnode *vp, daddr_t cn, daddr_t *bnp, int *runp)
1768 {
1769 	struct denode *dep = VTODE(vp);
1770 	struct msdosfsmount *pmp = dep->de_pmp;
1771 	struct mount *mp;
1772 	int error, maxrun = 0, run;
1773 	daddr_t daddr;
1774 
1775 	mp = vp->v_mount;
1776 
1777 	if (runp) {
1778 		/*
1779 		 * XXX
1780 		 * If MAXBSIZE is the largest transfer the disks can handle,
1781 		 * we probably want maxrun to be 1 block less so that we
1782 		 * don't create a block larger than the device can handle.
1783 		 */
1784 		*runp = 0;
1785 		maxrun = min(MAXBSIZE / mp->mnt_stat.f_iosize - 1,
1786 		    pmp->pm_maxcluster - cn);
1787 	}
1788 
1789 	if ((error = pcbmap(dep, cn, bnp, 0, 0)) != 0)
1790 		return (error);
1791 
1792 	for (run = 1; run <= maxrun; run++) {
1793 		error = pcbmap(dep, cn + run, &daddr, 0, 0);
1794 		if (error != 0 || (daddr != *bnp + de_cn2bn(pmp, run)))
1795 			break;
1796 	}
1797 
1798 	if (runp)
1799 		*runp = run - 1;
1800 
1801 	return (0);
1802 }
1803 
1804 int
1805 msdosfs_strategy(void *v)
1806 {
1807 	struct vop_strategy_args *ap = v;
1808 	struct buf *bp = ap->a_bp;
1809 	struct denode *dep = VTODE(bp->b_vp);
1810 	struct vnode *vp;
1811 	int error = 0;
1812 	int s;
1813 
1814 	if (bp->b_vp->v_type == VBLK || bp->b_vp->v_type == VCHR)
1815 		panic("msdosfs_strategy: spec");
1816 	/*
1817 	 * If we don't already know the filesystem relative block number
1818 	 * then get it using pcbmap().  If pcbmap() returns the block
1819 	 * number as -1 then we've got a hole in the file.  DOS filesystems
1820 	 * don't allow files with holes, so we shouldn't ever see this.
1821 	 */
1822 	if (bp->b_blkno == bp->b_lblkno) {
1823 		error = pcbmap(dep, bp->b_lblkno, &bp->b_blkno, 0, 0);
1824 		if (error)
1825 			bp->b_blkno = -1;
1826 		if (bp->b_blkno == -1)
1827 			clrbuf(bp);
1828 	}
1829 	if (bp->b_blkno == -1) {
1830 		s = splbio();
1831 		biodone(bp);
1832 		splx(s);
1833 		return (error);
1834 	}
1835 
1836 	/*
1837 	 * Read/write the block from/to the disk that contains the desired
1838 	 * file block.
1839 	 */
1840 
1841 	vp = dep->de_devvp;
1842 	bp->b_dev = vp->v_rdev;
1843 	(vp->v_op->vop_strategy)(ap);
1844 	return (0);
1845 }
1846 
1847 int
1848 msdosfs_print(void *v)
1849 {
1850 	struct vop_print_args *ap = v;
1851 	struct denode *dep = VTODE(ap->a_vp);
1852 
1853 	printf(
1854 	    "tag VT_MSDOSFS, startcluster %u, dircluster %u, diroffset %u ",
1855 	    dep->de_StartCluster, dep->de_dirclust, dep->de_diroffset);
1856 	printf(" dev %d, %d, %s\n",
1857 	    major(dep->de_dev), minor(dep->de_dev),
1858 	    VOP_ISLOCKED(ap->a_vp) ? "(LOCKED)" : "");
1859 #ifdef DIAGNOSTIC
1860 	printf("\n");
1861 #endif
1862 
1863 	return (0);
1864 }
1865 
1866 int
1867 msdosfs_advlock(void *v)
1868 {
1869 	struct vop_advlock_args *ap = v;
1870 	struct denode *dep = VTODE(ap->a_vp);
1871 
1872 	return (lf_advlock(&dep->de_lockf, dep->de_FileSize, ap->a_id, ap->a_op,
1873 	    ap->a_fl, ap->a_flags));
1874 }
1875 
1876 int
1877 msdosfs_pathconf(void *v)
1878 {
1879 	struct vop_pathconf_args *ap = v;
1880 	struct msdosfsmount *pmp = VTODE(ap->a_vp)->de_pmp;
1881 	int error = 0;
1882 
1883 	switch (ap->a_name) {
1884 	case _PC_LINK_MAX:
1885 		*ap->a_retval = 1;
1886 		break;
1887 	case _PC_NAME_MAX:
1888 		*ap->a_retval = pmp->pm_flags & MSDOSFSMNT_LONGNAME ? WIN_MAXLEN : 12;
1889 		break;
1890 	case _PC_CHOWN_RESTRICTED:
1891 		*ap->a_retval = 1;
1892 		break;
1893 	case _PC_NO_TRUNC:
1894 		*ap->a_retval = 0;
1895 		break;
1896 	case _PC_TIMESTAMP_RESOLUTION:
1897 		*ap->a_retval = 2000000000;	/* 2 billion nanoseconds */
1898 		break;
1899 	default:
1900 		error = EINVAL;
1901 		break;
1902 	}
1903 
1904 	return (error);
1905 }
1906 
1907 /*
1908  * Thomas Wang's hash function, severely hacked to always set the high
1909  * bit on the number it returns (so no longer a proper hash function).
1910  */
1911 static uint32_t
1912 fileidhash(uint64_t fileid)
1913 {
1914 	uint64_t c1 = 0x6e5ea73858134343LL;
1915 	uint64_t c2 = 0xb34e8f99a2ec9ef5LL;
1916 
1917 	/*
1918 	 * We now have the original fileid value, as 64-bit value.
1919 	 * We need to reduce it to 32-bits, with the top bit set.
1920 	 */
1921 	fileid ^= ((c1 ^ fileid) >> 32);
1922 	fileid *= c1;
1923 	fileid ^= ((c2 ^ fileid) >> 31);
1924 	fileid *= c2;
1925 	fileid ^= ((c1 ^ fileid) >> 32);
1926 
1927 	return (uint32_t)(fileid | 0x80000000);
1928 }
1929 
1930 /* Global vfs data structures for msdosfs */
1931 struct vops msdosfs_vops = {
1932 	.vop_lookup	= msdosfs_lookup,
1933 	.vop_create	= msdosfs_create,
1934 	.vop_mknod	= msdosfs_mknod,
1935 	.vop_open	= msdosfs_open,
1936 	.vop_close	= msdosfs_close,
1937 	.vop_access	= msdosfs_access,
1938 	.vop_getattr	= msdosfs_getattr,
1939 	.vop_setattr	= msdosfs_setattr,
1940 	.vop_read	= msdosfs_read,
1941 	.vop_write	= msdosfs_write,
1942 	.vop_ioctl	= msdosfs_ioctl,
1943 	.vop_poll	= msdosfs_poll,
1944 	.vop_kqfilter	= msdosfs_kqfilter,
1945 	.vop_fsync	= msdosfs_fsync,
1946 	.vop_remove	= msdosfs_remove,
1947 	.vop_link	= msdosfs_link,
1948 	.vop_rename	= msdosfs_rename,
1949 	.vop_mkdir	= msdosfs_mkdir,
1950 	.vop_rmdir	= msdosfs_rmdir,
1951 	.vop_symlink	= msdosfs_symlink,
1952 	.vop_readdir	= msdosfs_readdir,
1953 	.vop_readlink	= msdosfs_readlink,
1954 	.vop_abortop	= vop_generic_abortop,
1955 	.vop_inactive	= msdosfs_inactive,
1956 	.vop_reclaim	= msdosfs_reclaim,
1957 	.vop_lock	= msdosfs_lock,
1958 	.vop_unlock	= msdosfs_unlock,
1959 	.vop_bmap	= msdosfs_bmap,
1960 	.vop_strategy	= msdosfs_strategy,
1961 	.vop_print	= msdosfs_print,
1962 	.vop_islocked	= msdosfs_islocked,
1963 	.vop_pathconf	= msdosfs_pathconf,
1964 	.vop_advlock	= msdosfs_advlock,
1965 	.vop_bwrite	= vop_generic_bwrite,
1966 	.vop_revoke	= vop_generic_revoke,
1967 };
1968 
1969 struct filterops msdosfsread_filtops =
1970 	{ 1, NULL, filt_msdosfsdetach, filt_msdosfsread };
1971 struct filterops msdosfswrite_filtops =
1972 	{ 1, NULL, filt_msdosfsdetach, filt_msdosfswrite };
1973 struct filterops msdosfsvnode_filtops =
1974 	{ 1, NULL, filt_msdosfsdetach, filt_msdosfsvnode };
1975 
1976 int
1977 msdosfs_kqfilter(void *v)
1978 {
1979 	struct vop_kqfilter_args *ap = v;
1980 	struct vnode *vp = ap->a_vp;
1981 	struct knote *kn = ap->a_kn;
1982 
1983 	switch (kn->kn_filter) {
1984 	case EVFILT_READ:
1985 		kn->kn_fop = &msdosfsread_filtops;
1986 		break;
1987 	case EVFILT_WRITE:
1988 		kn->kn_fop = &msdosfswrite_filtops;
1989 		break;
1990 	case EVFILT_VNODE:
1991 		kn->kn_fop = &msdosfsvnode_filtops;
1992 		break;
1993 	default:
1994 		return (EINVAL);
1995 	}
1996 
1997 	kn->kn_hook = (caddr_t)vp;
1998 
1999 	SLIST_INSERT_HEAD(&vp->v_selectinfo.si_note, kn, kn_selnext);
2000 
2001 	return (0);
2002 }
2003 
2004 void
2005 filt_msdosfsdetach(struct knote *kn)
2006 {
2007 	struct vnode *vp = (struct vnode *)kn->kn_hook;
2008 
2009 	SLIST_REMOVE(&vp->v_selectinfo.si_note, kn, knote, kn_selnext);
2010 }
2011 
2012 int
2013 filt_msdosfsread(struct knote *kn, long hint)
2014 {
2015 	struct vnode *vp = (struct vnode *)kn->kn_hook;
2016 	struct denode *dep = VTODE(vp);
2017 
2018 	/*
2019 	 * filesystem is gone, so set the EOF flag and schedule
2020 	 * the knote for deletion.
2021 	 */
2022 	if (hint == NOTE_REVOKE) {
2023 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2024 		return (1);
2025 	}
2026 
2027 	kn->kn_data = dep->de_FileSize - kn->kn_fp->f_offset;
2028 	if (kn->kn_data == 0 && kn->kn_sfflags & NOTE_EOF) {
2029 		kn->kn_fflags |= NOTE_EOF;
2030 		return (1);
2031 	}
2032 	return (kn->kn_data != 0);
2033 }
2034 
2035 int
2036 filt_msdosfswrite(struct knote *kn, long hint)
2037 {
2038 	/*
2039 	 * filesystem is gone, so set the EOF flag and schedule
2040 	 * the knote for deletion.
2041 	 */
2042 	if (hint == NOTE_REVOKE) {
2043 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
2044 		return (1);
2045 	}
2046 
2047 	kn->kn_data = 0;
2048 	return (1);
2049 }
2050 
2051 int
2052 filt_msdosfsvnode(struct knote *kn, long hint)
2053 {
2054 	if (kn->kn_sfflags & hint)
2055 		kn->kn_fflags |= hint;
2056 	if (hint == NOTE_REVOKE) {
2057 		kn->kn_flags |= EV_EOF;
2058 		return (1);
2059 	}
2060 	return (kn->kn_fflags != 0);
2061 }
2062