xref: /freebsd/sys/fs/msdosfs/msdosfs_vnops.c (revision bb2d13b686e3ccf6c3ccb36209dfb7dcc108b182)
1 /* $FreeBSD$ */
2 /*	$NetBSD: msdosfs_vnops.c,v 1.68 1998/02/10 14:10:04 mrg Exp $	*/
3 
4 /*-
5  * SPDX-License-Identifier: BSD-4-Clause
6  *
7  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
8  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
9  * All rights reserved.
10  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by TooLs GmbH.
23  * 4. The name of TooLs GmbH may not be used to endorse or promote products
24  *    derived from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
32  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
34  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 /*-
38  * Written by Paul Popelka (paulp@uts.amdahl.com)
39  *
40  * You can do anything you want with this software, just don't say you wrote
41  * it, and don't remove this notice.
42  *
43  * This software is provided "as is".
44  *
45  * The author supplies this software to be publicly redistributed on the
46  * understanding that the author is not responsible for the correct
47  * functioning of this software in any circumstances and is not liable for
48  * any damages caused by this software.
49  *
50  * October 1992
51  */
52 
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/bio.h>
56 #include <sys/buf.h>
57 #include <sys/clock.h>
58 #include <sys/dirent.h>
59 #include <sys/lock.h>
60 #include <sys/lockf.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/unistd.h>
69 #include <sys/vmmeter.h>
70 #include <sys/vnode.h>
71 
72 #include <vm/vm.h>
73 #include <vm/vm_extern.h>
74 #include <vm/vnode_pager.h>
75 
76 #include <fs/msdosfs/bpb.h>
77 #include <fs/msdosfs/direntry.h>
78 #include <fs/msdosfs/denode.h>
79 #include <fs/msdosfs/fat.h>
80 #include <fs/msdosfs/msdosfsmount.h>
81 
82 /*
83  * Prototypes for MSDOSFS vnode operations
84  */
85 static vop_create_t	msdosfs_create;
86 static vop_mknod_t	msdosfs_mknod;
87 static vop_open_t	msdosfs_open;
88 static vop_close_t	msdosfs_close;
89 static vop_access_t	msdosfs_access;
90 static vop_getattr_t	msdosfs_getattr;
91 static vop_setattr_t	msdosfs_setattr;
92 static vop_read_t	msdosfs_read;
93 static vop_write_t	msdosfs_write;
94 static vop_fsync_t	msdosfs_fsync;
95 static vop_remove_t	msdosfs_remove;
96 static vop_link_t	msdosfs_link;
97 static vop_rename_t	msdosfs_rename;
98 static vop_mkdir_t	msdosfs_mkdir;
99 static vop_rmdir_t	msdosfs_rmdir;
100 static vop_symlink_t	msdosfs_symlink;
101 static vop_readdir_t	msdosfs_readdir;
102 static vop_bmap_t	msdosfs_bmap;
103 static vop_getpages_t	msdosfs_getpages;
104 static vop_strategy_t	msdosfs_strategy;
105 static vop_print_t	msdosfs_print;
106 static vop_pathconf_t	msdosfs_pathconf;
107 static vop_vptofh_t	msdosfs_vptofh;
108 
109 /*
110  * Some general notes:
111  *
112  * In the ufs filesystem the inodes, superblocks, and indirect blocks are
113  * read/written using the vnode for the filesystem. Blocks that represent
114  * the contents of a file are read/written using the vnode for the file
115  * (including directories when they are read/written as files). This
116  * presents problems for the dos filesystem because data that should be in
117  * an inode (if dos had them) resides in the directory itself.  Since we
118  * must update directory entries without the benefit of having the vnode
119  * for the directory we must use the vnode for the filesystem.  This means
120  * that when a directory is actually read/written (via read, write, or
121  * readdir, or seek) we must use the vnode for the filesystem instead of
122  * the vnode for the directory as would happen in ufs. This is to insure we
123  * retrieve the correct block from the buffer cache since the hash value is
124  * based upon the vnode address and the desired block number.
125  */
126 
127 /*
128  * Create a regular file. On entry the directory to contain the file being
129  * created is locked.  We must release before we return. We must also free
130  * the pathname buffer pointed at by cnp->cn_pnbuf, always on error, or
131  * only if the SAVESTART bit in cn_flags is clear on success.
132  */
133 static int
134 msdosfs_create(struct vop_create_args *ap)
135 {
136 	struct componentname *cnp = ap->a_cnp;
137 	struct denode ndirent;
138 	struct denode *dep;
139 	struct denode *pdep = VTODE(ap->a_dvp);
140 	struct timespec ts;
141 	int error;
142 
143 #ifdef MSDOSFS_DEBUG
144 	printf("msdosfs_create(cnp %p, vap %p\n", cnp, ap->a_vap);
145 #endif
146 
147 	/*
148 	 * If this is the root directory and there is no space left we
149 	 * can't do anything.  This is because the root directory can not
150 	 * change size.
151 	 */
152 	if (pdep->de_StartCluster == MSDOSFSROOT
153 	    && pdep->de_fndoffset >= pdep->de_FileSize) {
154 		error = ENOSPC;
155 		goto bad;
156 	}
157 
158 	/*
159 	 * Create a directory entry for the file, then call createde() to
160 	 * have it installed. NOTE: DOS files are always executable.  We
161 	 * use the absence of the owner write bit to make the file
162 	 * readonly.
163 	 */
164 	memset(&ndirent, 0, sizeof(ndirent));
165 	error = uniqdosname(pdep, cnp, ndirent.de_Name);
166 	if (error)
167 		goto bad;
168 
169 	ndirent.de_Attributes = ATTR_ARCHIVE;
170 	ndirent.de_LowerCase = 0;
171 	ndirent.de_StartCluster = 0;
172 	ndirent.de_FileSize = 0;
173 	ndirent.de_pmp = pdep->de_pmp;
174 	ndirent.de_flag = DE_ACCESS | DE_CREATE | DE_UPDATE;
175 	vfs_timestamp(&ts);
176 	DETIMES(&ndirent, &ts, &ts, &ts);
177 	error = createde(&ndirent, pdep, &dep, cnp);
178 	if (error)
179 		goto bad;
180 	*ap->a_vpp = DETOV(dep);
181 	if ((cnp->cn_flags & MAKEENTRY) != 0)
182 		cache_enter(ap->a_dvp, *ap->a_vpp, cnp);
183 	return (0);
184 
185 bad:
186 	return (error);
187 }
188 
189 static int
190 msdosfs_mknod(struct vop_mknod_args *ap)
191 {
192 
193     return (EINVAL);
194 }
195 
196 static int
197 msdosfs_open(struct vop_open_args *ap)
198 {
199 	struct denode *dep = VTODE(ap->a_vp);
200 	vnode_create_vobject(ap->a_vp, dep->de_FileSize, ap->a_td);
201 	return 0;
202 }
203 
204 static int
205 msdosfs_close(struct vop_close_args *ap)
206 {
207 	struct vnode *vp = ap->a_vp;
208 	struct denode *dep = VTODE(vp);
209 	struct timespec ts;
210 
211 	VI_LOCK(vp);
212 	if (vp->v_usecount > 1) {
213 		vfs_timestamp(&ts);
214 		DETIMES(dep, &ts, &ts, &ts);
215 	}
216 	VI_UNLOCK(vp);
217 	return 0;
218 }
219 
220 static int
221 msdosfs_access(struct vop_access_args *ap)
222 {
223 	struct vnode *vp = ap->a_vp;
224 	struct denode *dep = VTODE(ap->a_vp);
225 	struct msdosfsmount *pmp = dep->de_pmp;
226 	mode_t file_mode;
227 	accmode_t accmode = ap->a_accmode;
228 
229 	file_mode = S_IRWXU|S_IRWXG|S_IRWXO;
230 	file_mode &= (vp->v_type == VDIR ? pmp->pm_dirmask : pmp->pm_mask);
231 
232 	/*
233 	 * Disallow writing to directories and regular files if the
234 	 * filesystem is read-only.
235 	 */
236 	if (accmode & VWRITE) {
237 		switch (vp->v_type) {
238 		case VREG:
239 		case VDIR:
240 			if (vp->v_mount->mnt_flag & MNT_RDONLY)
241 				return (EROFS);
242 			break;
243 		default:
244 			break;
245 		}
246 	}
247 
248 	return (vaccess(vp->v_type, file_mode, pmp->pm_uid, pmp->pm_gid,
249 	    ap->a_accmode, ap->a_cred));
250 }
251 
252 static int
253 msdosfs_getattr(struct vop_getattr_args *ap)
254 {
255 	struct denode *dep = VTODE(ap->a_vp);
256 	struct msdosfsmount *pmp = dep->de_pmp;
257 	struct vattr *vap = ap->a_vap;
258 	mode_t mode;
259 	struct timespec ts;
260 	u_long dirsperblk = pmp->pm_BytesPerSec / sizeof(struct direntry);
261 	uint64_t fileid;
262 
263 	vfs_timestamp(&ts);
264 	DETIMES(dep, &ts, &ts, &ts);
265 	vap->va_fsid = dev2udev(pmp->pm_dev);
266 	/*
267 	 * The following computation of the fileid must be the same as that
268 	 * used in msdosfs_readdir() to compute d_fileno. If not, pwd
269 	 * doesn't work.
270 	 */
271 	if (dep->de_Attributes & ATTR_DIRECTORY) {
272 		fileid = (uint64_t)cntobn(pmp, dep->de_StartCluster) *
273 		    dirsperblk;
274 		if (dep->de_StartCluster == MSDOSFSROOT)
275 			fileid = 1;
276 	} else {
277 		fileid = (uint64_t)cntobn(pmp, dep->de_dirclust) *
278 		    dirsperblk;
279 		if (dep->de_dirclust == MSDOSFSROOT)
280 			fileid = (uint64_t)roottobn(pmp, 0) * dirsperblk;
281 		fileid += (uoff_t)dep->de_diroffset / sizeof(struct direntry);
282 	}
283 	vap->va_fileid = fileid;
284 
285 	mode = S_IRWXU|S_IRWXG|S_IRWXO;
286 	if (dep->de_Attributes & ATTR_READONLY)
287 		mode &= ~(S_IWUSR|S_IWGRP|S_IWOTH);
288 	vap->va_mode = mode &
289 	    (ap->a_vp->v_type == VDIR ? pmp->pm_dirmask : pmp->pm_mask);
290 	vap->va_uid = pmp->pm_uid;
291 	vap->va_gid = pmp->pm_gid;
292 	vap->va_nlink = 1;
293 	vap->va_rdev = NODEV;
294 	vap->va_size = dep->de_FileSize;
295 	fattime2timespec(dep->de_MDate, dep->de_MTime, 0, 0, &vap->va_mtime);
296 	vap->va_ctime = vap->va_mtime;
297 	if (pmp->pm_flags & MSDOSFSMNT_LONGNAME) {
298 		fattime2timespec(dep->de_ADate, 0, 0, 0, &vap->va_atime);
299 		fattime2timespec(dep->de_CDate, dep->de_CTime, dep->de_CHun,
300 		    0, &vap->va_birthtime);
301 	} else {
302 		vap->va_atime = vap->va_mtime;
303 		vap->va_birthtime.tv_sec = -1;
304 		vap->va_birthtime.tv_nsec = 0;
305 	}
306 	vap->va_flags = 0;
307 	if (dep->de_Attributes & ATTR_ARCHIVE)
308 		vap->va_flags |= UF_ARCHIVE;
309 	if (dep->de_Attributes & ATTR_HIDDEN)
310 		vap->va_flags |= UF_HIDDEN;
311 	if (dep->de_Attributes & ATTR_READONLY)
312 		vap->va_flags |= UF_READONLY;
313 	if (dep->de_Attributes & ATTR_SYSTEM)
314 		vap->va_flags |= UF_SYSTEM;
315 	vap->va_gen = 0;
316 	vap->va_blocksize = pmp->pm_bpcluster;
317 	vap->va_bytes =
318 	    (dep->de_FileSize + pmp->pm_crbomask) & ~pmp->pm_crbomask;
319 	vap->va_type = ap->a_vp->v_type;
320 	vap->va_filerev = dep->de_modrev;
321 	return (0);
322 }
323 
324 static int
325 msdosfs_setattr(struct vop_setattr_args *ap)
326 {
327 	struct vnode *vp = ap->a_vp;
328 	struct denode *dep = VTODE(ap->a_vp);
329 	struct msdosfsmount *pmp = dep->de_pmp;
330 	struct vattr *vap = ap->a_vap;
331 	struct ucred *cred = ap->a_cred;
332 	struct thread *td = curthread;
333 	int error = 0;
334 
335 #ifdef MSDOSFS_DEBUG
336 	printf("msdosfs_setattr(): vp %p, vap %p, cred %p\n",
337 	    ap->a_vp, vap, cred);
338 #endif
339 
340 	/*
341 	 * Check for unsettable attributes.
342 	 */
343 	if ((vap->va_type != VNON) || (vap->va_nlink != VNOVAL) ||
344 	    (vap->va_fsid != VNOVAL) || (vap->va_fileid != VNOVAL) ||
345 	    (vap->va_blocksize != VNOVAL) || (vap->va_rdev != VNOVAL) ||
346 	    (vap->va_bytes != VNOVAL) || (vap->va_gen != VNOVAL)) {
347 #ifdef MSDOSFS_DEBUG
348 		printf("msdosfs_setattr(): returning EINVAL\n");
349 		printf("    va_type %d, va_nlink %llx, va_fsid %llx, va_fileid %llx\n",
350 		    vap->va_type, (unsigned long long)vap->va_nlink,
351 		    (unsigned long long)vap->va_fsid,
352 		    (unsigned long long)vap->va_fileid);
353 		printf("    va_blocksize %lx, va_rdev %llx, va_bytes %llx, va_gen %lx\n",
354 		    vap->va_blocksize, (unsigned long long)vap->va_rdev,
355 		    (unsigned long long)vap->va_bytes, vap->va_gen);
356 		printf("    va_uid %x, va_gid %x\n",
357 		    vap->va_uid, vap->va_gid);
358 #endif
359 		return (EINVAL);
360 	}
361 
362 	/*
363 	 * We don't allow setting attributes on the root directory.
364 	 * The special case for the root directory is because before
365 	 * FAT32, the root directory didn't have an entry for itself
366 	 * (and was otherwise special).  With FAT32, the root
367 	 * directory is not so special, but still doesn't have an
368 	 * entry for itself.
369 	 */
370 	if (vp->v_vflag & VV_ROOT)
371 		return (EINVAL);
372 
373 	if (vap->va_flags != VNOVAL) {
374 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
375 			return (EROFS);
376 		if (cred->cr_uid != pmp->pm_uid) {
377 			error = priv_check_cred(cred, PRIV_VFS_ADMIN);
378 			if (error)
379 				return (error);
380 		}
381 		/*
382 		 * We are very inconsistent about handling unsupported
383 		 * attributes.  We ignored the access time and the
384 		 * read and execute bits.  We were strict for the other
385 		 * attributes.
386 		 */
387 		if (vap->va_flags & ~(UF_ARCHIVE | UF_HIDDEN | UF_READONLY |
388 		    UF_SYSTEM))
389 			return EOPNOTSUPP;
390 		if (vap->va_flags & UF_ARCHIVE)
391 			dep->de_Attributes |= ATTR_ARCHIVE;
392 		else
393 			dep->de_Attributes &= ~ATTR_ARCHIVE;
394 		if (vap->va_flags & UF_HIDDEN)
395 			dep->de_Attributes |= ATTR_HIDDEN;
396 		else
397 			dep->de_Attributes &= ~ATTR_HIDDEN;
398 		/* We don't allow changing the readonly bit on directories. */
399 		if (vp->v_type != VDIR) {
400 			if (vap->va_flags & UF_READONLY)
401 				dep->de_Attributes |= ATTR_READONLY;
402 			else
403 				dep->de_Attributes &= ~ATTR_READONLY;
404 		}
405 		if (vap->va_flags & UF_SYSTEM)
406 			dep->de_Attributes |= ATTR_SYSTEM;
407 		else
408 			dep->de_Attributes &= ~ATTR_SYSTEM;
409 		dep->de_flag |= DE_MODIFIED;
410 	}
411 
412 	if (vap->va_uid != (uid_t)VNOVAL || vap->va_gid != (gid_t)VNOVAL) {
413 		uid_t uid;
414 		gid_t gid;
415 
416 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
417 			return (EROFS);
418 		uid = vap->va_uid;
419 		if (uid == (uid_t)VNOVAL)
420 			uid = pmp->pm_uid;
421 		gid = vap->va_gid;
422 		if (gid == (gid_t)VNOVAL)
423 			gid = pmp->pm_gid;
424 		if (cred->cr_uid != pmp->pm_uid || uid != pmp->pm_uid ||
425 		    (gid != pmp->pm_gid && !groupmember(gid, cred))) {
426 			error = priv_check_cred(cred, PRIV_VFS_CHOWN);
427 			if (error)
428 				return (error);
429 		}
430 		if (uid != pmp->pm_uid || gid != pmp->pm_gid)
431 			return EINVAL;
432 	}
433 
434 	if (vap->va_size != VNOVAL) {
435 		switch (vp->v_type) {
436 		case VDIR:
437 			return (EISDIR);
438 		case VREG:
439 			/*
440 			 * Truncation is only supported for regular files,
441 			 * Disallow it if the filesystem is read-only.
442 			 */
443 			if (vp->v_mount->mnt_flag & MNT_RDONLY)
444 				return (EROFS);
445 			break;
446 		default:
447 			/*
448 			 * According to POSIX, the result is unspecified
449 			 * for file types other than regular files,
450 			 * directories and shared memory objects.  We
451 			 * don't support any file types except regular
452 			 * files and directories in this file system, so
453 			 * this (default) case is unreachable and can do
454 			 * anything.  Keep falling through to detrunc()
455 			 * for now.
456 			 */
457 			break;
458 		}
459 		error = vn_rlimit_trunc(vap->va_size, td);
460 		if (error != 0)
461 			return (error);
462 		error = detrunc(dep, vap->va_size, 0, cred);
463 		if (error)
464 			return error;
465 	}
466 	if (vap->va_atime.tv_sec != VNOVAL || vap->va_mtime.tv_sec != VNOVAL) {
467 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
468 			return (EROFS);
469 		error = vn_utimes_perm(vp, vap, cred, td);
470 		if (error != 0)
471 			return (error);
472 		if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95) == 0 &&
473 		    vap->va_atime.tv_sec != VNOVAL) {
474 			dep->de_flag &= ~DE_ACCESS;
475 			timespec2fattime(&vap->va_atime, 0,
476 			    &dep->de_ADate, NULL, NULL);
477 		}
478 		if (vap->va_mtime.tv_sec != VNOVAL) {
479 			dep->de_flag &= ~DE_UPDATE;
480 			timespec2fattime(&vap->va_mtime, 0,
481 			    &dep->de_MDate, &dep->de_MTime, NULL);
482 		}
483 		/*
484 		 * We don't set the archive bit when modifying the time of
485 		 * a directory to emulate the Windows/DOS behavior.
486 		 */
487 		if (vp->v_type != VDIR)
488 			dep->de_Attributes |= ATTR_ARCHIVE;
489 		dep->de_flag |= DE_MODIFIED;
490 	}
491 	/*
492 	 * DOS files only have the ability to have their writability
493 	 * attribute set, so we use the owner write bit to set the readonly
494 	 * attribute.
495 	 */
496 	if (vap->va_mode != (mode_t)VNOVAL) {
497 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
498 			return (EROFS);
499 		if (cred->cr_uid != pmp->pm_uid) {
500 			error = priv_check_cred(cred, PRIV_VFS_ADMIN);
501 			if (error)
502 				return (error);
503 		}
504 		if (vp->v_type != VDIR) {
505 			/* We ignore the read and execute bits. */
506 			if (vap->va_mode & S_IWUSR)
507 				dep->de_Attributes &= ~ATTR_READONLY;
508 			else
509 				dep->de_Attributes |= ATTR_READONLY;
510 			dep->de_Attributes |= ATTR_ARCHIVE;
511 			dep->de_flag |= DE_MODIFIED;
512 		}
513 	}
514 	return (deupdat(dep, 0));
515 }
516 
517 static int
518 msdosfs_read(struct vop_read_args *ap)
519 {
520 	int error = 0;
521 	int blsize;
522 	int isadir;
523 	ssize_t orig_resid;
524 	u_int n;
525 	u_long diff;
526 	u_long on;
527 	daddr_t lbn;
528 	daddr_t rablock;
529 	int rasize;
530 	int seqcount;
531 	struct buf *bp;
532 	struct vnode *vp = ap->a_vp;
533 	struct denode *dep = VTODE(vp);
534 	struct msdosfsmount *pmp = dep->de_pmp;
535 	struct uio *uio = ap->a_uio;
536 
537 	/*
538 	 * If they didn't ask for any data, then we are done.
539 	 */
540 	orig_resid = uio->uio_resid;
541 	if (orig_resid == 0)
542 		return (0);
543 
544 	/*
545 	 * The caller is supposed to ensure that
546 	 * uio->uio_offset >= 0 and uio->uio_resid >= 0.
547 	 * We don't need to check for large offsets as in ffs because
548 	 * dep->de_FileSize <= MSDOSFS_FILESIZE_MAX < OFF_MAX, so large
549 	 * offsets cannot cause overflow even in theory.
550 	 */
551 
552 	seqcount = ap->a_ioflag >> IO_SEQSHIFT;
553 
554 	isadir = dep->de_Attributes & ATTR_DIRECTORY;
555 	do {
556 		if (uio->uio_offset >= dep->de_FileSize)
557 			break;
558 		lbn = de_cluster(pmp, uio->uio_offset);
559 		rablock = lbn + 1;
560 		blsize = pmp->pm_bpcluster;
561 		on = uio->uio_offset & pmp->pm_crbomask;
562 		/*
563 		 * If we are operating on a directory file then be sure to
564 		 * do i/o with the vnode for the filesystem instead of the
565 		 * vnode for the directory.
566 		 */
567 		if (isadir) {
568 			/* convert cluster # to block # */
569 			error = pcbmap(dep, lbn, &lbn, 0, &blsize);
570 			if (error == E2BIG) {
571 				error = EINVAL;
572 				break;
573 			} else if (error)
574 				break;
575 			error = bread(pmp->pm_devvp, lbn, blsize, NOCRED, &bp);
576 		} else if (de_cn2off(pmp, rablock) >= dep->de_FileSize) {
577 			error = bread(vp, lbn, blsize, NOCRED, &bp);
578 		} else if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0) {
579 			error = cluster_read(vp, dep->de_FileSize, lbn, blsize,
580 			    NOCRED, on + uio->uio_resid, seqcount, 0, &bp);
581 		} else if (seqcount > 1) {
582 			rasize = blsize;
583 			error = breadn(vp, lbn,
584 			    blsize, &rablock, &rasize, 1, NOCRED, &bp);
585 		} else {
586 			error = bread(vp, lbn, blsize, NOCRED, &bp);
587 		}
588 		if (error) {
589 			brelse(bp);
590 			break;
591 		}
592 		diff = pmp->pm_bpcluster - on;
593 		n = diff > uio->uio_resid ? uio->uio_resid : diff;
594 		diff = dep->de_FileSize - uio->uio_offset;
595 		if (diff < n)
596 			n = diff;
597 		diff = blsize - bp->b_resid;
598 		if (diff < n)
599 			n = diff;
600 		error = vn_io_fault_uiomove(bp->b_data + on, (int) n, uio);
601 		brelse(bp);
602 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
603 	if (!isadir && (error == 0 || uio->uio_resid != orig_resid) &&
604 	    (vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
605 		dep->de_flag |= DE_ACCESS;
606 	return (error);
607 }
608 
609 /*
610  * Write data to a file or directory.
611  */
612 static int
613 msdosfs_write(struct vop_write_args *ap)
614 {
615 	int n;
616 	int croffset;
617 	ssize_t resid, r;
618 	u_long osize;
619 	int error = 0;
620 	u_long count;
621 	int seqcount;
622 	daddr_t bn, lastcn;
623 	struct buf *bp;
624 	int ioflag = ap->a_ioflag;
625 	struct uio *uio = ap->a_uio;
626 	struct vnode *vp = ap->a_vp;
627 	struct vnode *thisvp;
628 	struct denode *dep = VTODE(vp);
629 	struct msdosfsmount *pmp = dep->de_pmp;
630 	struct ucred *cred = ap->a_cred;
631 
632 #ifdef MSDOSFS_DEBUG
633 	printf("msdosfs_write(vp %p, uio %p, ioflag %x, cred %p\n",
634 	    vp, uio, ioflag, cred);
635 	printf("msdosfs_write(): diroff %lu, dirclust %lu, startcluster %lu\n",
636 	    dep->de_diroffset, dep->de_dirclust, dep->de_StartCluster);
637 #endif
638 
639 	switch (vp->v_type) {
640 	case VREG:
641 		if (ioflag & IO_APPEND)
642 			uio->uio_offset = dep->de_FileSize;
643 		thisvp = vp;
644 		break;
645 	case VDIR:
646 		return EISDIR;
647 	default:
648 		panic("msdosfs_write(): bad file type");
649 	}
650 
651 	/*
652 	 * This is needed (unlike in ffs_write()) because we extend the
653 	 * file outside of the loop but we don't want to extend the file
654 	 * for writes of 0 bytes.
655 	 */
656 	if (uio->uio_resid == 0)
657 		return (0);
658 
659 	/*
660 	 * The caller is supposed to ensure that
661 	 * uio->uio_offset >= 0 and uio->uio_resid >= 0.
662 	 *
663 	 * If they've exceeded their filesize limit, tell them about it.
664 	 */
665 	error = vn_rlimit_fsizex(vp, uio, MSDOSFS_FILESIZE_MAX, &r,
666 	    uio->uio_td);
667 	if (error != 0) {
668 		vn_rlimit_fsizex_res(uio, r);
669 		return (error);
670 	}
671 
672 	/*
673 	 * If the offset we are starting the write at is beyond the end of
674 	 * the file, then they've done a seek.  Unix filesystems allow
675 	 * files with holes in them, DOS doesn't so we must fill the hole
676 	 * with zeroed blocks.
677 	 */
678 	if (uio->uio_offset > dep->de_FileSize) {
679 		error = deextend(dep, uio->uio_offset, cred);
680 		if (error != 0) {
681 			vn_rlimit_fsizex_res(uio, r);
682 			return (error);
683 		}
684 	}
685 
686 	/*
687 	 * Remember some values in case the write fails.
688 	 */
689 	resid = uio->uio_resid;
690 	osize = dep->de_FileSize;
691 
692 	/*
693 	 * If we write beyond the end of the file, extend it to its ultimate
694 	 * size ahead of the time to hopefully get a contiguous area.
695 	 */
696 	if (uio->uio_offset + resid > osize) {
697 		count = de_clcount(pmp, uio->uio_offset + resid) -
698 			de_clcount(pmp, osize);
699 		error = extendfile(dep, count, NULL, NULL, 0);
700 		if (error &&  (error != ENOSPC || (ioflag & IO_UNIT)))
701 			goto errexit;
702 		lastcn = dep->de_fc[FC_LASTFC].fc_frcn;
703 	} else
704 		lastcn = de_clcount(pmp, osize) - 1;
705 
706 	seqcount = ioflag >> IO_SEQSHIFT;
707 	do {
708 		if (de_cluster(pmp, uio->uio_offset) > lastcn) {
709 			error = ENOSPC;
710 			break;
711 		}
712 
713 		croffset = uio->uio_offset & pmp->pm_crbomask;
714 		n = min(uio->uio_resid, pmp->pm_bpcluster - croffset);
715 		if (uio->uio_offset + n > dep->de_FileSize) {
716 			dep->de_FileSize = uio->uio_offset + n;
717 			/* The object size needs to be set before buffer is allocated */
718 			vnode_pager_setsize(vp, dep->de_FileSize);
719 		}
720 
721 		bn = de_cluster(pmp, uio->uio_offset);
722 		if ((uio->uio_offset & pmp->pm_crbomask) == 0
723 		    && (de_cluster(pmp, uio->uio_offset + uio->uio_resid)
724 			> de_cluster(pmp, uio->uio_offset)
725 			|| uio->uio_offset + uio->uio_resid >= dep->de_FileSize)) {
726 			/*
727 			 * If either the whole cluster gets written,
728 			 * or we write the cluster from its start beyond EOF,
729 			 * then no need to read data from disk.
730 			 */
731 			bp = getblk(thisvp, bn, pmp->pm_bpcluster, 0, 0, 0);
732 			/*
733 			 * This call to vfs_bio_clrbuf() ensures that
734 			 * even if vn_io_fault_uiomove() below faults,
735 			 * garbage from the newly instantiated buffer
736 			 * is not exposed to the userspace via mmap().
737 			 */
738 			vfs_bio_clrbuf(bp);
739 			/*
740 			 * Do the bmap now, since pcbmap needs buffers
741 			 * for the FAT table. (see msdosfs_strategy)
742 			 */
743 			if (bp->b_blkno == bp->b_lblkno) {
744 				error = pcbmap(dep, bp->b_lblkno, &bn, 0, 0);
745 				if (error)
746 					bp->b_blkno = -1;
747 				else
748 					bp->b_blkno = bn;
749 			}
750 			if (bp->b_blkno == -1) {
751 				brelse(bp);
752 				if (!error)
753 					error = EIO;		/* XXX */
754 				break;
755 			}
756 		} else {
757 			/*
758 			 * The block we need to write into exists, so read it in.
759 			 */
760 			error = bread(thisvp, bn, pmp->pm_bpcluster, cred, &bp);
761 			if (error) {
762 				break;
763 			}
764 		}
765 
766 		/*
767 		 * Should these vnode_pager_* functions be done on dir
768 		 * files?
769 		 */
770 
771 		/*
772 		 * Copy the data from user space into the buf header.
773 		 */
774 		error = vn_io_fault_uiomove(bp->b_data + croffset, n, uio);
775 		if (error) {
776 			brelse(bp);
777 			break;
778 		}
779 
780 		/* Prepare for clustered writes in some else clauses. */
781 		if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0)
782 			bp->b_flags |= B_CLUSTEROK;
783 
784 		/*
785 		 * If IO_SYNC, then each buffer is written synchronously.
786 		 * Otherwise, if we have a severe page deficiency then
787 		 * write the buffer asynchronously.  Otherwise, if on a
788 		 * cluster boundary then write the buffer asynchronously,
789 		 * combining it with contiguous clusters if permitted and
790 		 * possible, since we don't expect more writes into this
791 		 * buffer soon.  Otherwise, do a delayed write because we
792 		 * expect more writes into this buffer soon.
793 		 */
794 		if (ioflag & IO_SYNC)
795 			(void)bwrite(bp);
796 		else if (vm_page_count_severe() || buf_dirty_count_severe())
797 			bawrite(bp);
798 		else if (n + croffset == pmp->pm_bpcluster) {
799 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0)
800 				cluster_write(vp, &dep->de_clusterw, bp,
801 				    dep->de_FileSize, seqcount, 0);
802 			else
803 				bawrite(bp);
804 		} else
805 			bdwrite(bp);
806 		dep->de_flag |= DE_UPDATE;
807 	} while (error == 0 && uio->uio_resid > 0);
808 
809 	/*
810 	 * If the write failed and they want us to, truncate the file back
811 	 * to the size it was before the write was attempted.
812 	 */
813 errexit:
814 	if (error) {
815 		if (ioflag & IO_UNIT) {
816 			detrunc(dep, osize, ioflag & IO_SYNC, NOCRED);
817 			uio->uio_offset -= resid - uio->uio_resid;
818 			uio->uio_resid = resid;
819 		} else {
820 			detrunc(dep, dep->de_FileSize, ioflag & IO_SYNC, NOCRED);
821 			if (uio->uio_resid != resid)
822 				error = 0;
823 		}
824 	} else if (ioflag & IO_SYNC)
825 		error = deupdat(dep, 1);
826 	vn_rlimit_fsizex_res(uio, r);
827 	return (error);
828 }
829 
830 /*
831  * Flush the blocks of a file to disk.
832  */
833 static int
834 msdosfs_fsync(struct vop_fsync_args *ap)
835 {
836 	struct vnode *devvp;
837 	int allerror, error;
838 
839 	vop_stdfsync(ap);
840 
841 	/*
842 	* If the syncing request comes from fsync(2), sync the entire
843 	* FAT and any other metadata that happens to be on devvp.  We
844 	* need this mainly for the FAT.  We write the FAT sloppily, and
845 	* syncing it all now is the best we can easily do to get all
846 	* directory entries associated with the file (not just the file)
847 	* fully synced.  The other metadata includes critical metadata
848 	* for all directory entries, but only in the MNT_ASYNC case.  We
849 	* will soon sync all metadata in the file's directory entry.
850 	* Non-critical metadata for associated directory entries only
851 	* gets synced accidentally, as in most file systems.
852 	*/
853 	if (ap->a_waitfor != MNT_NOWAIT) {
854 		devvp = VTODE(ap->a_vp)->de_pmp->pm_devvp;
855 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
856 		allerror = VOP_FSYNC(devvp, MNT_WAIT, ap->a_td);
857 		VOP_UNLOCK(devvp);
858 	} else
859 		allerror = 0;
860 
861 	error = deupdat(VTODE(ap->a_vp), ap->a_waitfor != MNT_NOWAIT);
862 	if (allerror == 0)
863 		allerror = error;
864 	return (allerror);
865 }
866 
867 static int
868 msdosfs_remove(struct vop_remove_args *ap)
869 {
870 	struct denode *dep = VTODE(ap->a_vp);
871 	struct denode *ddep = VTODE(ap->a_dvp);
872 	int error;
873 
874 	if (ap->a_vp->v_type == VDIR)
875 		error = EPERM;
876 	else
877 		error = removede(ddep, dep);
878 #ifdef MSDOSFS_DEBUG
879 	printf("msdosfs_remove(), dep %p, v_usecount %d\n", dep, ap->a_vp->v_usecount);
880 #endif
881 	return (error);
882 }
883 
884 /*
885  * DOS filesystems don't know what links are.
886  */
887 static int
888 msdosfs_link(struct vop_link_args *ap)
889 {
890 	return (EOPNOTSUPP);
891 }
892 
893 /*
894  * Renames on files require moving the denode to a new hash queue since the
895  * denode's location is used to compute which hash queue to put the file
896  * in. Unless it is a rename in place.  For example "mv a b".
897  *
898  * What follows is the basic algorithm:
899  *
900  * if (file move) {
901  *	if (dest file exists) {
902  *		remove dest file
903  *	}
904  *	if (dest and src in same directory) {
905  *		rewrite name in existing directory slot
906  *	} else {
907  *		write new entry in dest directory
908  *		update offset and dirclust in denode
909  *		move denode to new hash chain
910  *		clear old directory entry
911  *	}
912  * } else {
913  *	directory move
914  *	if (dest directory exists) {
915  *		if (dest is not empty) {
916  *			return ENOTEMPTY
917  *		}
918  *		remove dest directory
919  *	}
920  *	if (dest and src in same directory) {
921  *		rewrite name in existing entry
922  *	} else {
923  *		be sure dest is not a child of src directory
924  *		write entry in dest directory
925  *		update "." and ".." in moved directory
926  *		clear old directory entry for moved directory
927  *	}
928  * }
929  *
930  * On entry:
931  *	source's parent directory is unlocked
932  *	source file or directory is unlocked
933  *	destination's parent directory is locked
934  *	destination file or directory is locked if it exists
935  *
936  * On exit:
937  *	all denodes should be released
938  */
939 static int
940 msdosfs_rename(struct vop_rename_args *ap)
941 {
942 	struct vnode *fdvp, *fvp, *tdvp, *tvp, *vp;
943 	struct componentname *fcnp, *tcnp;
944 	struct denode *fdip, *fip, *tdip, *tip, *nip;
945 	u_char toname[12], oldname[11];
946 	u_long to_diroffset;
947 	bool checkpath_locked, doingdirectory, newparent;
948 	int error;
949 	u_long cn, pcl, blkoff;
950 	daddr_t bn, wait_scn, scn;
951 	struct msdosfsmount *pmp;
952 	struct direntry *dotdotp;
953 	struct buf *bp;
954 
955 	tdvp = ap->a_tdvp;
956 	fvp = ap->a_fvp;
957 	fdvp = ap->a_fdvp;
958 	tvp = ap->a_tvp;
959 	tcnp = ap->a_tcnp;
960 	fcnp = ap->a_fcnp;
961 	pmp = VFSTOMSDOSFS(fdvp->v_mount);
962 
963 	/*
964 	 * Check for cross-device rename.
965 	 */
966 	if (fvp->v_mount != tdvp->v_mount ||
967 	    (tvp != NULL && fvp->v_mount != tvp->v_mount)) {
968 		error = EXDEV;
969 		goto abortit;
970 	}
971 
972 	/*
973 	 * If source and dest are the same, do nothing.
974 	 */
975 	if (tvp == fvp) {
976 		error = 0;
977 		goto abortit;
978 	}
979 
980 	/*
981 	 * When the target exists, both the directory
982 	 * and target vnodes are passed locked.
983 	 */
984 	VOP_UNLOCK(tdvp);
985 	if (tvp != NULL && tvp != tdvp)
986 		VOP_UNLOCK(tvp);
987 
988 	checkpath_locked = false;
989 
990 relock:
991 	doingdirectory = newparent = false;
992 
993 	error = vn_lock(fdvp, LK_EXCLUSIVE);
994 	if (error != 0)
995 		goto releout;
996 	if (vn_lock(tdvp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
997 		VOP_UNLOCK(fdvp);
998 		error = vn_lock(tdvp, LK_EXCLUSIVE);
999 		if (error != 0)
1000 			goto releout;
1001 		VOP_UNLOCK(tdvp);
1002 		goto relock;
1003 	}
1004 
1005 	error = msdosfs_lookup_ino(fdvp, NULL, fcnp, &scn, &blkoff);
1006 	if (error != 0) {
1007 		VOP_UNLOCK(fdvp);
1008 		VOP_UNLOCK(tdvp);
1009 		goto releout;
1010 	}
1011 	error = deget(pmp, scn, blkoff, LK_EXCLUSIVE | LK_NOWAIT, &nip);
1012 	if (error != 0) {
1013 		VOP_UNLOCK(fdvp);
1014 		VOP_UNLOCK(tdvp);
1015 		if (error != EBUSY)
1016 			goto releout;
1017 		error = deget(pmp, scn, blkoff, LK_EXCLUSIVE, &nip);
1018 		if (error != 0)
1019 			goto releout;
1020 		vp = fvp;
1021 		fvp = DETOV(nip);
1022 		VOP_UNLOCK(fvp);
1023 		vrele(vp);
1024 		goto relock;
1025 	}
1026 	vrele(fvp);
1027 	fvp = DETOV(nip);
1028 
1029 	error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1030 	if (error != 0 && error != EJUSTRETURN) {
1031 		VOP_UNLOCK(fdvp);
1032 		VOP_UNLOCK(tdvp);
1033 		VOP_UNLOCK(fvp);
1034 		goto releout;
1035 	}
1036 	if (error == EJUSTRETURN && tvp != NULL) {
1037 		vrele(tvp);
1038 		tvp = NULL;
1039 	}
1040 	if (error == 0) {
1041 		nip = NULL;
1042 		error = deget(pmp, scn, blkoff, LK_EXCLUSIVE | LK_NOWAIT,
1043 		    &nip);
1044 		if (tvp != NULL) {
1045 			vrele(tvp);
1046 			tvp = NULL;
1047 		}
1048 		if (error != 0) {
1049 			VOP_UNLOCK(fdvp);
1050 			VOP_UNLOCK(tdvp);
1051 			VOP_UNLOCK(fvp);
1052 			if (error != EBUSY)
1053 				goto releout;
1054 			error = deget(pmp, scn, blkoff, LK_EXCLUSIVE,
1055 			    &nip);
1056 			if (error != 0)
1057 				goto releout;
1058 			vput(DETOV(nip));
1059 			goto relock;
1060 		}
1061 		tvp = DETOV(nip);
1062 	}
1063 
1064 	fdip = VTODE(fdvp);
1065 	fip = VTODE(fvp);
1066 	tdip = VTODE(tdvp);
1067 	tip = tvp != NULL ? VTODE(tvp) : NULL;
1068 
1069 	/*
1070 	 * Remember direntry place to use for destination
1071 	 */
1072 	to_diroffset = tdip->de_fndoffset;
1073 
1074 	/*
1075 	 * Be sure we are not renaming ".", "..", or an alias of ".". This
1076 	 * leads to a crippled directory tree.  It's pretty tough to do a
1077 	 * "ls" or "pwd" with the "." directory entry missing, and "cd .."
1078 	 * doesn't work if the ".." entry is missing.
1079 	 */
1080 	if ((fip->de_Attributes & ATTR_DIRECTORY) != 0) {
1081 		/*
1082 		 * Avoid ".", "..", and aliases of "." for obvious reasons.
1083 		 */
1084 		if ((fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
1085 		    fdip == fip ||
1086 		    (fcnp->cn_flags & ISDOTDOT) != 0 ||
1087 		    (tcnp->cn_flags & ISDOTDOT) != 0) {
1088 			error = EINVAL;
1089 			goto unlock;
1090 		}
1091 		doingdirectory = true;
1092 	}
1093 
1094 	/*
1095 	 * If ".." must be changed (ie the directory gets a new
1096 	 * parent) then the source directory must not be in the
1097 	 * directory hierarchy above the target, as this would
1098 	 * orphan everything below the source directory. Also
1099 	 * the user must have write permission in the source so
1100 	 * as to be able to change "..". We must repeat the call
1101 	 * to namei, as the parent directory is unlocked by the
1102 	 * call to doscheckpath().
1103 	 */
1104 	error = VOP_ACCESS(fvp, VWRITE, tcnp->cn_cred, curthread);
1105 	if (fdip->de_StartCluster != tdip->de_StartCluster)
1106 		newparent = true;
1107 	if (doingdirectory && newparent) {
1108 		if (error != 0)	/* write access check above */
1109 			goto unlock;
1110 		lockmgr(&pmp->pm_checkpath_lock, LK_EXCLUSIVE, NULL);
1111 		checkpath_locked = true;
1112 		error = doscheckpath(fip, tdip, &wait_scn);
1113 		if (wait_scn != 0) {
1114 			lockmgr(&pmp->pm_checkpath_lock, LK_RELEASE, NULL);
1115 			checkpath_locked = false;
1116 			VOP_UNLOCK(fdvp);
1117 			VOP_UNLOCK(tdvp);
1118 			VOP_UNLOCK(fvp);
1119 			if (tvp != NULL && tvp != tdvp)
1120 				VOP_UNLOCK(tvp);
1121 			error = deget(pmp, wait_scn, 0, LK_EXCLUSIVE,
1122 			    &nip);
1123 			if (error == 0) {
1124 				vput(DETOV(nip));
1125 				goto relock;
1126 			}
1127 		}
1128 		if (error != 0)
1129 			goto unlock;
1130 		if ((tcnp->cn_flags & SAVESTART) == 0)
1131 			panic("msdosfs_rename: lost to startdir");
1132 	}
1133 
1134 	if (tip != NULL) {
1135 		/*
1136 		 * Target must be empty if a directory and have no links
1137 		 * to it. Also, ensure source and target are compatible
1138 		 * (both directories, or both not directories).
1139 		 */
1140 		if ((tip->de_Attributes & ATTR_DIRECTORY) != 0) {
1141 			if (!dosdirempty(tip)) {
1142 				error = ENOTEMPTY;
1143 				goto unlock;
1144 			}
1145 			if (!doingdirectory) {
1146 				error = ENOTDIR;
1147 				goto unlock;
1148 			}
1149 			cache_purge(tdvp);
1150 		} else if (doingdirectory) {
1151 			error = EISDIR;
1152 			goto unlock;
1153 		}
1154 		error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1155 		MPASS(error == 0);
1156 		error = removede(tdip, tip);
1157 		if (error != 0)
1158 			goto unlock;
1159 		vput(tvp);
1160 		tvp = NULL;
1161 		tip = NULL;
1162 	}
1163 
1164 	/*
1165 	 * Convert the filename in tcnp into a dos filename. We copy this
1166 	 * into the denode and directory entry for the destination
1167 	 * file/directory.
1168 	 */
1169 	error = uniqdosname(tdip, tcnp, toname);
1170 	if (error != 0)
1171 		goto unlock;
1172 
1173 	/*
1174 	 * First write a new entry in the destination
1175 	 * directory and mark the entry in the source directory
1176 	 * as deleted.  Then move the denode to the correct hash
1177 	 * chain for its new location in the filesystem.  And, if
1178 	 * we moved a directory, then update its .. entry to point
1179 	 * to the new parent directory.
1180 	 */
1181 	memcpy(oldname, fip->de_Name, 11);
1182 	memcpy(fip->de_Name, toname, 11);	/* update denode */
1183 	error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1184 	MPASS(error == EJUSTRETURN);
1185 	error = createde(fip, tdip, NULL, tcnp);
1186 	if (error != 0) {
1187 		memcpy(fip->de_Name, oldname, 11);
1188 		goto unlock;
1189 	}
1190 
1191 	/*
1192 	 * If fip is for a directory, then its name should always
1193 	 * be "." since it is for the directory entry in the
1194 	 * directory itself (msdosfs_lookup() always translates
1195 	 * to the "." entry so as to get a unique denode, except
1196 	 * for the root directory there are different
1197 	 * complications).  However, we just corrupted its name
1198 	 * to pass the correct name to createde().  Undo this.
1199 	 */
1200 	if ((fip->de_Attributes & ATTR_DIRECTORY) != 0)
1201 		memcpy(fip->de_Name, oldname, 11);
1202 	fip->de_refcnt++;
1203 	error = msdosfs_lookup_ino(fdvp, NULL, fcnp, &scn, &blkoff);
1204 	MPASS(error == 0);
1205 	error = removede(fdip, fip);
1206 	if (error != 0) {
1207 		/* XXX should downgrade to ro here, fs is corrupt */
1208 		goto unlock;
1209 	}
1210 	if (!doingdirectory) {
1211 		error = pcbmap(tdip, de_cluster(pmp, to_diroffset), 0,
1212 		    &fip->de_dirclust, 0);
1213 		if (error != 0) {
1214 			/*
1215 			 * XXX should downgrade to ro here,
1216 			 * fs is corrupt
1217 			 */
1218 			goto unlock;
1219 		}
1220 		if (fip->de_dirclust == MSDOSFSROOT)
1221 			fip->de_diroffset = to_diroffset;
1222 		else
1223 			fip->de_diroffset = to_diroffset & pmp->pm_crbomask;
1224 	}
1225 	reinsert(fip);
1226 
1227 	/*
1228 	 * If we moved a directory to a new parent directory, then we must
1229 	 * fixup the ".." entry in the moved directory.
1230 	 */
1231 	if (doingdirectory && newparent) {
1232 		cn = fip->de_StartCluster;
1233 		if (cn == MSDOSFSROOT) {
1234 			/* this should never happen */
1235 			panic("msdosfs_rename(): updating .. in root directory?");
1236 		} else
1237 			bn = cntobn(pmp, cn);
1238 		error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster,
1239 		    NOCRED, &bp);
1240 		if (error != 0) {
1241 			/* XXX should downgrade to ro here, fs is corrupt */
1242 			goto unlock;
1243 		}
1244 		dotdotp = (struct direntry *)bp->b_data + 1;
1245 		pcl = tdip->de_StartCluster;
1246 		if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1247 			pcl = MSDOSFSROOT;
1248 		putushort(dotdotp->deStartCluster, pcl);
1249 		if (FAT32(pmp))
1250 			putushort(dotdotp->deHighClust, pcl >> 16);
1251 		if (DOINGASYNC(fvp))
1252 			bdwrite(bp);
1253 		else if ((error = bwrite(bp)) != 0) {
1254 			/* XXX should downgrade to ro here, fs is corrupt */
1255 			goto unlock;
1256 		}
1257 	}
1258 
1259 	/*
1260 	 * The msdosfs lookup is case insensitive. Several aliases may
1261 	 * be inserted for a single directory entry. As a consequnce,
1262 	 * name cache purge done by lookup for fvp when DELETE op for
1263 	 * namei is specified, might be not enough to expunge all
1264 	 * namecache entries that were installed for this direntry.
1265 	 */
1266 	cache_purge(fvp);
1267 
1268 unlock:
1269 	if (checkpath_locked)
1270 		lockmgr(&pmp->pm_checkpath_lock, LK_RELEASE, NULL);
1271 	vput(fdvp);
1272 	vput(fvp);
1273 	if (tvp != NULL) {
1274 		if (tvp != tdvp)
1275 			vput(tvp);
1276 		else
1277 			vrele(tvp);
1278 	}
1279 	vput(tdvp);
1280 	return (error);
1281 releout:
1282 	MPASS(!checkpath_locked);
1283 	vrele(tdvp);
1284 	if (tvp != NULL)
1285 		vrele(tvp);
1286 	vrele(fdvp);
1287 	vrele(fvp);
1288 	return (error);
1289 abortit:
1290 	if (tdvp == tvp)
1291 		vrele(tdvp);
1292 	else
1293 		vput(tdvp);
1294 	if (tvp != NULL)
1295 		vput(tvp);
1296 	vrele(fdvp);
1297 	vrele(fvp);
1298 	return (error);
1299 }
1300 
1301 static struct {
1302 	struct direntry dot;
1303 	struct direntry dotdot;
1304 } dosdirtemplate = {
1305 	{	".          ",				/* the . entry */
1306 		ATTR_DIRECTORY,				/* file attribute */
1307 		0,					/* reserved */
1308 		0, { 0, 0 }, { 0, 0 },			/* create time & date */
1309 		{ 0, 0 },				/* access date */
1310 		{ 0, 0 },				/* high bits of start cluster */
1311 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1312 		{ 0, 0 },				/* startcluster */
1313 		{ 0, 0, 0, 0 }				/* filesize */
1314 	},
1315 	{	"..         ",				/* the .. entry */
1316 		ATTR_DIRECTORY,				/* file attribute */
1317 		0,					/* reserved */
1318 		0, { 0, 0 }, { 0, 0 },			/* create time & date */
1319 		{ 0, 0 },				/* access date */
1320 		{ 0, 0 },				/* high bits of start cluster */
1321 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1322 		{ 0, 0 },				/* startcluster */
1323 		{ 0, 0, 0, 0 }				/* filesize */
1324 	}
1325 };
1326 
1327 static int
1328 msdosfs_mkdir(struct vop_mkdir_args *ap)
1329 {
1330 	struct componentname *cnp = ap->a_cnp;
1331 	struct denode *dep;
1332 	struct denode *pdep = VTODE(ap->a_dvp);
1333 	struct direntry *denp;
1334 	struct msdosfsmount *pmp = pdep->de_pmp;
1335 	struct buf *bp;
1336 	u_long newcluster, pcl;
1337 	int bn;
1338 	int error;
1339 	struct denode ndirent;
1340 	struct timespec ts;
1341 
1342 	/*
1343 	 * If this is the root directory and there is no space left we
1344 	 * can't do anything.  This is because the root directory can not
1345 	 * change size.
1346 	 */
1347 	if (pdep->de_StartCluster == MSDOSFSROOT
1348 	    && pdep->de_fndoffset >= pdep->de_FileSize) {
1349 		error = ENOSPC;
1350 		goto bad2;
1351 	}
1352 
1353 	/*
1354 	 * Allocate a cluster to hold the about to be created directory.
1355 	 */
1356 	error = clusteralloc(pmp, 0, 1, CLUST_EOFE, &newcluster, NULL);
1357 	if (error)
1358 		goto bad2;
1359 
1360 	memset(&ndirent, 0, sizeof(ndirent));
1361 	ndirent.de_pmp = pmp;
1362 	ndirent.de_flag = DE_ACCESS | DE_CREATE | DE_UPDATE;
1363 	vfs_timestamp(&ts);
1364 	DETIMES(&ndirent, &ts, &ts, &ts);
1365 
1366 	/*
1367 	 * Now fill the cluster with the "." and ".." entries. And write
1368 	 * the cluster to disk.  This way it is there for the parent
1369 	 * directory to be pointing at if there were a crash.
1370 	 */
1371 	bn = cntobn(pmp, newcluster);
1372 	/* always succeeds */
1373 	bp = getblk(pmp->pm_devvp, bn, pmp->pm_bpcluster, 0, 0, 0);
1374 	memset(bp->b_data, 0, pmp->pm_bpcluster);
1375 	memcpy(bp->b_data, &dosdirtemplate, sizeof dosdirtemplate);
1376 	denp = (struct direntry *)bp->b_data;
1377 	putushort(denp[0].deStartCluster, newcluster);
1378 	putushort(denp[0].deCDate, ndirent.de_CDate);
1379 	putushort(denp[0].deCTime, ndirent.de_CTime);
1380 	denp[0].deCHundredth = ndirent.de_CHun;
1381 	putushort(denp[0].deADate, ndirent.de_ADate);
1382 	putushort(denp[0].deMDate, ndirent.de_MDate);
1383 	putushort(denp[0].deMTime, ndirent.de_MTime);
1384 	pcl = pdep->de_StartCluster;
1385 	/*
1386 	 * Although the root directory has a non-magic starting cluster
1387 	 * number for FAT32, chkdsk and fsck_msdosfs still require
1388 	 * references to it in dotdot entries to be magic.
1389 	 */
1390 	if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1391 		pcl = MSDOSFSROOT;
1392 	putushort(denp[1].deStartCluster, pcl);
1393 	putushort(denp[1].deCDate, ndirent.de_CDate);
1394 	putushort(denp[1].deCTime, ndirent.de_CTime);
1395 	denp[1].deCHundredth = ndirent.de_CHun;
1396 	putushort(denp[1].deADate, ndirent.de_ADate);
1397 	putushort(denp[1].deMDate, ndirent.de_MDate);
1398 	putushort(denp[1].deMTime, ndirent.de_MTime);
1399 	if (FAT32(pmp)) {
1400 		putushort(denp[0].deHighClust, newcluster >> 16);
1401 		putushort(denp[1].deHighClust, pcl >> 16);
1402 	}
1403 
1404 	if (DOINGASYNC(ap->a_dvp))
1405 		bdwrite(bp);
1406 	else if ((error = bwrite(bp)) != 0)
1407 		goto bad;
1408 
1409 	/*
1410 	 * Now build up a directory entry pointing to the newly allocated
1411 	 * cluster.  This will be written to an empty slot in the parent
1412 	 * directory.
1413 	 */
1414 	error = uniqdosname(pdep, cnp, ndirent.de_Name);
1415 	if (error)
1416 		goto bad;
1417 
1418 	ndirent.de_Attributes = ATTR_DIRECTORY;
1419 	ndirent.de_LowerCase = 0;
1420 	ndirent.de_StartCluster = newcluster;
1421 	ndirent.de_FileSize = 0;
1422 	error = createde(&ndirent, pdep, &dep, cnp);
1423 	if (error)
1424 		goto bad;
1425 	*ap->a_vpp = DETOV(dep);
1426 	return (0);
1427 
1428 bad:
1429 	clusterfree(pmp, newcluster);
1430 bad2:
1431 	return (error);
1432 }
1433 
1434 static int
1435 msdosfs_rmdir(struct vop_rmdir_args *ap)
1436 {
1437 	struct vnode *vp = ap->a_vp;
1438 	struct vnode *dvp = ap->a_dvp;
1439 	struct componentname *cnp = ap->a_cnp;
1440 	struct denode *ip, *dp;
1441 	int error;
1442 
1443 	ip = VTODE(vp);
1444 	dp = VTODE(dvp);
1445 
1446 	/*
1447 	 * Verify the directory is empty (and valid).
1448 	 * (Rmdir ".." won't be valid since
1449 	 *  ".." will contain a reference to
1450 	 *  the current directory and thus be
1451 	 *  non-empty.)
1452 	 */
1453 	error = 0;
1454 	if (!dosdirempty(ip)) {
1455 		error = ENOTEMPTY;
1456 		goto out;
1457 	}
1458 	/*
1459 	 * Delete the entry from the directory.  For dos filesystems this
1460 	 * gets rid of the directory entry on disk, the in memory copy
1461 	 * still exists but the de_refcnt is <= 0.  This prevents it from
1462 	 * being found by deget().  When the vput() on dep is done we give
1463 	 * up access and eventually msdosfs_reclaim() will be called which
1464 	 * will remove it from the denode cache.
1465 	 */
1466 	error = removede(dp, ip);
1467 	if (error)
1468 		goto out;
1469 	/*
1470 	 * This is where we decrement the link count in the parent
1471 	 * directory.  Since dos filesystems don't do this we just purge
1472 	 * the name cache.
1473 	 */
1474 	cache_purge(dvp);
1475 	/*
1476 	 * Truncate the directory that is being deleted.
1477 	 */
1478 	error = detrunc(ip, (u_long)0, IO_SYNC, cnp->cn_cred);
1479 	cache_purge(vp);
1480 
1481 out:
1482 	return (error);
1483 }
1484 
1485 /*
1486  * DOS filesystems don't know what symlinks are.
1487  */
1488 static int
1489 msdosfs_symlink(struct vop_symlink_args *ap)
1490 {
1491 	return (EOPNOTSUPP);
1492 }
1493 
1494 static int
1495 msdosfs_readdir(struct vop_readdir_args *ap)
1496 {
1497 	struct mbnambuf nb;
1498 	int error = 0;
1499 	int diff;
1500 	long n;
1501 	int blsize;
1502 	long on;
1503 	u_long cn;
1504 	u_long dirsperblk;
1505 	long bias = 0;
1506 	daddr_t bn, lbn;
1507 	struct buf *bp;
1508 	struct denode *dep = VTODE(ap->a_vp);
1509 	struct msdosfsmount *pmp = dep->de_pmp;
1510 	struct direntry *dentp;
1511 	struct dirent dirbuf;
1512 	struct uio *uio = ap->a_uio;
1513 	uint64_t *cookies = NULL;
1514 	int ncookies = 0;
1515 	off_t offset, off;
1516 	int chksum = -1;
1517 
1518 #ifdef MSDOSFS_DEBUG
1519 	printf("msdosfs_readdir(): vp %p, uio %p, cred %p, eofflagp %p\n",
1520 	    ap->a_vp, uio, ap->a_cred, ap->a_eofflag);
1521 #endif
1522 
1523 	/*
1524 	 * msdosfs_readdir() won't operate properly on regular files since
1525 	 * it does i/o only with the filesystem vnode, and hence can
1526 	 * retrieve the wrong block from the buffer cache for a plain file.
1527 	 * So, fail attempts to readdir() on a plain file.
1528 	 */
1529 	if ((dep->de_Attributes & ATTR_DIRECTORY) == 0)
1530 		return (ENOTDIR);
1531 
1532 	/*
1533 	 * To be safe, initialize dirbuf
1534 	 */
1535 	memset(dirbuf.d_name, 0, sizeof(dirbuf.d_name));
1536 
1537 	/*
1538 	 * If the user buffer is smaller than the size of one dos directory
1539 	 * entry or the file offset is not a multiple of the size of a
1540 	 * directory entry, then we fail the read.
1541 	 */
1542 	off = offset = uio->uio_offset;
1543 	if (uio->uio_resid < sizeof(struct direntry) ||
1544 	    (offset & (sizeof(struct direntry) - 1)))
1545 		return (EINVAL);
1546 
1547 	if (ap->a_ncookies) {
1548 		ncookies = uio->uio_resid / 16;
1549 		cookies = malloc(ncookies * sizeof(*cookies), M_TEMP,
1550 		       M_WAITOK);
1551 		*ap->a_cookies = cookies;
1552 		*ap->a_ncookies = ncookies;
1553 	}
1554 
1555 	dirsperblk = pmp->pm_BytesPerSec / sizeof(struct direntry);
1556 
1557 	/*
1558 	 * If they are reading from the root directory then, we simulate
1559 	 * the . and .. entries since these don't exist in the root
1560 	 * directory.  We also set the offset bias to make up for having to
1561 	 * simulate these entries. By this I mean that at file offset 64 we
1562 	 * read the first entry in the root directory that lives on disk.
1563 	 */
1564 	if (dep->de_StartCluster == MSDOSFSROOT
1565 	    || (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)) {
1566 #if 0
1567 		printf("msdosfs_readdir(): going after . or .. in root dir, offset %d\n",
1568 		    offset);
1569 #endif
1570 		bias = 2 * sizeof(struct direntry);
1571 		if (offset < bias) {
1572 			for (n = (int)offset / sizeof(struct direntry);
1573 			     n < 2; n++) {
1574 				dirbuf.d_fileno = FAT32(pmp) ?
1575 				    (uint64_t)cntobn(pmp, pmp->pm_rootdirblk) *
1576 				    dirsperblk : 1;
1577 				dirbuf.d_type = DT_DIR;
1578 				switch (n) {
1579 				case 0:
1580 					dirbuf.d_namlen = 1;
1581 					dirbuf.d_name[0] = '.';
1582 					break;
1583 				case 1:
1584 					dirbuf.d_namlen = 2;
1585 					dirbuf.d_name[0] = '.';
1586 					dirbuf.d_name[1] = '.';
1587 					break;
1588 				}
1589 				dirbuf.d_reclen = GENERIC_DIRSIZ(&dirbuf);
1590 				/* NOTE: d_off is the offset of the *next* entry. */
1591 				dirbuf.d_off = offset + sizeof(struct direntry);
1592 				dirent_terminate(&dirbuf);
1593 				if (uio->uio_resid < dirbuf.d_reclen)
1594 					goto out;
1595 				error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1596 				if (error)
1597 					goto out;
1598 				offset += sizeof(struct direntry);
1599 				off = offset;
1600 				if (cookies) {
1601 					*cookies++ = offset;
1602 					if (--ncookies <= 0)
1603 						goto out;
1604 				}
1605 			}
1606 		}
1607 	}
1608 
1609 	mbnambuf_init(&nb);
1610 	off = offset;
1611 	while (uio->uio_resid > 0) {
1612 		lbn = de_cluster(pmp, offset - bias);
1613 		on = (offset - bias) & pmp->pm_crbomask;
1614 		n = min(pmp->pm_bpcluster - on, uio->uio_resid);
1615 		diff = dep->de_FileSize - (offset - bias);
1616 		if (diff <= 0)
1617 			break;
1618 		n = min(n, diff);
1619 		error = pcbmap(dep, lbn, &bn, &cn, &blsize);
1620 		if (error)
1621 			break;
1622 		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
1623 		if (error) {
1624 			return (error);
1625 		}
1626 		n = min(n, blsize - bp->b_resid);
1627 		if (n == 0) {
1628 			brelse(bp);
1629 			return (EIO);
1630 		}
1631 
1632 		/*
1633 		 * Convert from dos directory entries to fs-independent
1634 		 * directory entries.
1635 		 */
1636 		for (dentp = (struct direntry *)(bp->b_data + on);
1637 		     (char *)dentp < bp->b_data + on + n;
1638 		     dentp++, offset += sizeof(struct direntry)) {
1639 #if 0
1640 			printf("rd: dentp %08x prev %08x crnt %08x deName %02x attr %02x\n",
1641 			    dentp, prev, crnt, dentp->deName[0], dentp->deAttributes);
1642 #endif
1643 			/*
1644 			 * If this is an unused entry, we can stop.
1645 			 */
1646 			if (dentp->deName[0] == SLOT_EMPTY) {
1647 				brelse(bp);
1648 				goto out;
1649 			}
1650 			/*
1651 			 * Skip deleted entries.
1652 			 */
1653 			if (dentp->deName[0] == SLOT_DELETED) {
1654 				chksum = -1;
1655 				mbnambuf_init(&nb);
1656 				continue;
1657 			}
1658 
1659 			/*
1660 			 * Handle Win95 long directory entries
1661 			 */
1662 			if (dentp->deAttributes == ATTR_WIN95) {
1663 				if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
1664 					continue;
1665 				chksum = win2unixfn(&nb,
1666 				    (struct winentry *)dentp, chksum, pmp);
1667 				continue;
1668 			}
1669 
1670 			/*
1671 			 * Skip volume labels
1672 			 */
1673 			if (dentp->deAttributes & ATTR_VOLUME) {
1674 				chksum = -1;
1675 				mbnambuf_init(&nb);
1676 				continue;
1677 			}
1678 			/*
1679 			 * This computation of d_fileno must match
1680 			 * the computation of va_fileid in
1681 			 * msdosfs_getattr.
1682 			 */
1683 			if (dentp->deAttributes & ATTR_DIRECTORY) {
1684 				cn = getushort(dentp->deStartCluster);
1685 				if (FAT32(pmp)) {
1686 					cn |= getushort(dentp->deHighClust) <<
1687 					    16;
1688 					if (cn == MSDOSFSROOT)
1689 						cn = pmp->pm_rootdirblk;
1690 				}
1691 				if (cn == MSDOSFSROOT && !FAT32(pmp))
1692 					dirbuf.d_fileno = 1;
1693 				else
1694 					dirbuf.d_fileno = cntobn(pmp, cn) *
1695 					    dirsperblk;
1696 				dirbuf.d_type = DT_DIR;
1697 			} else {
1698 				dirbuf.d_fileno = (uoff_t)offset /
1699 				    sizeof(struct direntry);
1700 				dirbuf.d_type = DT_REG;
1701 			}
1702 
1703 			if (chksum != winChksum(dentp->deName)) {
1704 				dirbuf.d_namlen = dos2unixfn(dentp->deName,
1705 				    (u_char *)dirbuf.d_name,
1706 				    dentp->deLowerCase |
1707 					((pmp->pm_flags & MSDOSFSMNT_SHORTNAME) ?
1708 					(LCASE_BASE | LCASE_EXT) : 0),
1709 				    pmp);
1710 				mbnambuf_init(&nb);
1711 			} else
1712 				mbnambuf_flush(&nb, &dirbuf);
1713 			chksum = -1;
1714 			dirbuf.d_reclen = GENERIC_DIRSIZ(&dirbuf);
1715 			/* NOTE: d_off is the offset of the *next* entry. */
1716 			dirbuf.d_off = offset + sizeof(struct direntry);
1717 			dirent_terminate(&dirbuf);
1718 			if (uio->uio_resid < dirbuf.d_reclen) {
1719 				brelse(bp);
1720 				goto out;
1721 			}
1722 			error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1723 			if (error) {
1724 				brelse(bp);
1725 				goto out;
1726 			}
1727 			if (cookies) {
1728 				*cookies++ = offset + sizeof(struct direntry);
1729 				if (--ncookies <= 0) {
1730 					brelse(bp);
1731 					goto out;
1732 				}
1733 			}
1734 			off = offset + sizeof(struct direntry);
1735 		}
1736 		brelse(bp);
1737 	}
1738 out:
1739 	/* Subtract unused cookies */
1740 	if (ap->a_ncookies)
1741 		*ap->a_ncookies -= ncookies;
1742 
1743 	uio->uio_offset = off;
1744 
1745 	/*
1746 	 * Set the eofflag (NFS uses it)
1747 	 */
1748 	if (ap->a_eofflag) {
1749 		if (dep->de_FileSize - (offset - bias) <= 0)
1750 			*ap->a_eofflag = 1;
1751 		else
1752 			*ap->a_eofflag = 0;
1753 	}
1754 	return (error);
1755 }
1756 
1757 /*-
1758  * a_vp   - pointer to the file's vnode
1759  * a_bn   - logical block number within the file (cluster number for us)
1760  * a_bop  - where to return the bufobj of the special file containing the fs
1761  * a_bnp  - where to return the "physical" block number corresponding to a_bn
1762  *          (relative to the special file; units are blocks of size DEV_BSIZE)
1763  * a_runp - where to return the "run past" a_bn.  This is the count of logical
1764  *          blocks whose physical blocks (together with a_bn's physical block)
1765  *          are contiguous.
1766  * a_runb - where to return the "run before" a_bn.
1767  */
1768 static int
1769 msdosfs_bmap(struct vop_bmap_args *ap)
1770 {
1771 	struct fatcache savefc;
1772 	struct denode *dep;
1773 	struct mount *mp;
1774 	struct msdosfsmount *pmp;
1775 	struct vnode *vp;
1776 	daddr_t runbn;
1777 	u_long cn;
1778 	int bnpercn, error, maxio, maxrun, run;
1779 
1780 	vp = ap->a_vp;
1781 	dep = VTODE(vp);
1782 	pmp = dep->de_pmp;
1783 	if (ap->a_bop != NULL)
1784 		*ap->a_bop = &pmp->pm_devvp->v_bufobj;
1785 	if (ap->a_bnp == NULL)
1786 		return (0);
1787 	if (ap->a_runp != NULL)
1788 		*ap->a_runp = 0;
1789 	if (ap->a_runb != NULL)
1790 		*ap->a_runb = 0;
1791 	cn = ap->a_bn;
1792 	if (cn != ap->a_bn)
1793 		return (EFBIG);
1794 	error = pcbmap(dep, cn, ap->a_bnp, NULL, NULL);
1795 	if (error != 0 || (ap->a_runp == NULL && ap->a_runb == NULL))
1796 		return (error);
1797 
1798 	/*
1799 	 * Prepare to back out updates of the fatchain cache after the one
1800 	 * for the first block done by pcbmap() above.  Without the backout,
1801 	 * then whenever the caller doesn't do i/o to all of the blocks that
1802 	 * we find, the single useful cache entry would be too far in advance
1803 	 * of the actual i/o to work for the next sequential i/o.  Then the
1804 	 * FAT would be searched from the beginning.  With the backout, the
1805 	 * FAT is searched starting at most a few blocks early.  This wastes
1806 	 * much less time.  Time is also wasted finding more blocks than the
1807 	 * caller will do i/o to.  This is necessary because the runlength
1808 	 * parameters are output-only.
1809 	 */
1810 	savefc = dep->de_fc[FC_LASTMAP];
1811 
1812 	mp = vp->v_mount;
1813 	maxio = mp->mnt_iosize_max / mp->mnt_stat.f_iosize;
1814 	bnpercn = de_cn2bn(pmp, 1);
1815 	if (ap->a_runp != NULL) {
1816 		maxrun = ulmin(maxio - 1, pmp->pm_maxcluster - cn);
1817 		for (run = 1; run <= maxrun; run++) {
1818 			if (pcbmap(dep, cn + run, &runbn, NULL, NULL) != 0 ||
1819 			    runbn != *ap->a_bnp + run * bnpercn)
1820 				break;
1821 		}
1822 		*ap->a_runp = run - 1;
1823 	}
1824 	if (ap->a_runb != NULL) {
1825 		maxrun = ulmin(maxio - 1, cn);
1826 		for (run = 1; run < maxrun; run++) {
1827 			if (pcbmap(dep, cn - run, &runbn, NULL, NULL) != 0 ||
1828 			    runbn != *ap->a_bnp - run * bnpercn)
1829 				break;
1830 		}
1831 		*ap->a_runb = run - 1;
1832 	}
1833 	dep->de_fc[FC_LASTMAP] = savefc;
1834 	return (0);
1835 }
1836 
1837 SYSCTL_NODE(_vfs, OID_AUTO, msdosfs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1838     "msdos filesystem");
1839 static int use_buf_pager = 1;
1840 SYSCTL_INT(_vfs_msdosfs, OID_AUTO, use_buf_pager, CTLFLAG_RWTUN,
1841     &use_buf_pager, 0,
1842     "Use buffer pager instead of bmap");
1843 
1844 static daddr_t
1845 msdosfs_gbp_getblkno(struct vnode *vp, vm_ooffset_t off)
1846 {
1847 
1848 	return (de_cluster(VTODE(vp)->de_pmp, off));
1849 }
1850 
1851 static int
1852 msdosfs_gbp_getblksz(struct vnode *vp, daddr_t lbn, long *sz)
1853 {
1854 
1855 	*sz = VTODE(vp)->de_pmp->pm_bpcluster;
1856 	return (0);
1857 }
1858 
1859 static int
1860 msdosfs_getpages(struct vop_getpages_args *ap)
1861 {
1862 
1863 	if (use_buf_pager)
1864 		return (vfs_bio_getpages(ap->a_vp, ap->a_m, ap->a_count,
1865 		    ap->a_rbehind, ap->a_rahead, msdosfs_gbp_getblkno,
1866 		    msdosfs_gbp_getblksz));
1867 	return (vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
1868 	    ap->a_rbehind, ap->a_rahead, NULL, NULL));
1869 }
1870 
1871 static int
1872 msdosfs_strategy(struct vop_strategy_args *ap)
1873 {
1874 	struct buf *bp = ap->a_bp;
1875 	struct denode *dep = VTODE(ap->a_vp);
1876 	struct bufobj *bo;
1877 	int error = 0;
1878 	daddr_t blkno;
1879 
1880 	/*
1881 	 * If we don't already know the filesystem relative block number
1882 	 * then get it using pcbmap().  If pcbmap() returns the block
1883 	 * number as -1 then we've got a hole in the file.  DOS filesystems
1884 	 * don't allow files with holes, so we shouldn't ever see this.
1885 	 */
1886 	if (bp->b_blkno == bp->b_lblkno) {
1887 		error = pcbmap(dep, bp->b_lblkno, &blkno, 0, 0);
1888 		bp->b_blkno = blkno;
1889 		if (error) {
1890 			bp->b_error = error;
1891 			bp->b_ioflags |= BIO_ERROR;
1892 			bufdone(bp);
1893 			return (0);
1894 		}
1895 		if ((long)bp->b_blkno == -1)
1896 			vfs_bio_clrbuf(bp);
1897 	}
1898 	if (bp->b_blkno == -1) {
1899 		bufdone(bp);
1900 		return (0);
1901 	}
1902 	/*
1903 	 * Read/write the block from/to the disk that contains the desired
1904 	 * file block.
1905 	 */
1906 	bp->b_iooffset = dbtob(bp->b_blkno);
1907 	bo = dep->de_pmp->pm_bo;
1908 	BO_STRATEGY(bo, bp);
1909 	return (0);
1910 }
1911 
1912 static int
1913 msdosfs_print(struct vop_print_args *ap)
1914 {
1915 	struct denode *dep = VTODE(ap->a_vp);
1916 
1917 	printf("\tstartcluster %lu, dircluster %lu, diroffset %lu, ",
1918 	       dep->de_StartCluster, dep->de_dirclust, dep->de_diroffset);
1919 	printf("on dev %s\n", devtoname(dep->de_pmp->pm_dev));
1920 	return (0);
1921 }
1922 
1923 static int
1924 msdosfs_pathconf(struct vop_pathconf_args *ap)
1925 {
1926 	struct msdosfsmount *pmp = VTODE(ap->a_vp)->de_pmp;
1927 
1928 	switch (ap->a_name) {
1929 	case _PC_FILESIZEBITS:
1930 		*ap->a_retval = 32;
1931 		return (0);
1932 	case _PC_LINK_MAX:
1933 		*ap->a_retval = 1;
1934 		return (0);
1935 	case _PC_NAME_MAX:
1936 		*ap->a_retval = pmp->pm_flags & MSDOSFSMNT_LONGNAME ? WIN_MAXLEN : 12;
1937 		return (0);
1938 	case _PC_CHOWN_RESTRICTED:
1939 		*ap->a_retval = 1;
1940 		return (0);
1941 	case _PC_NO_TRUNC:
1942 		*ap->a_retval = 0;
1943 		return (0);
1944 	default:
1945 		return (vop_stdpathconf(ap));
1946 	}
1947 	/* NOTREACHED */
1948 }
1949 
1950 static int
1951 msdosfs_vptofh(struct vop_vptofh_args *ap)
1952 {
1953 	struct denode *dep;
1954 	struct defid *defhp;
1955 
1956 	dep = VTODE(ap->a_vp);
1957 	defhp = (struct defid *)ap->a_fhp;
1958 	defhp->defid_len = sizeof(struct defid);
1959 	defhp->defid_dirclust = dep->de_dirclust;
1960 	defhp->defid_dirofs = dep->de_diroffset;
1961 	/* defhp->defid_gen = dep->de_gen; */
1962 	return (0);
1963 }
1964 
1965 /* Global vfs data structures for msdosfs */
1966 struct vop_vector msdosfs_vnodeops = {
1967 	.vop_default =		&default_vnodeops,
1968 
1969 	.vop_access =		msdosfs_access,
1970 	.vop_bmap =		msdosfs_bmap,
1971 	.vop_getpages =		msdosfs_getpages,
1972 	.vop_cachedlookup =	msdosfs_lookup,
1973 	.vop_open =		msdosfs_open,
1974 	.vop_close =		msdosfs_close,
1975 	.vop_create =		msdosfs_create,
1976 	.vop_fsync =		msdosfs_fsync,
1977 	.vop_fdatasync =	vop_stdfdatasync_buf,
1978 	.vop_getattr =		msdosfs_getattr,
1979 	.vop_inactive =		msdosfs_inactive,
1980 	.vop_link =		msdosfs_link,
1981 	.vop_lookup =		vfs_cache_lookup,
1982 	.vop_mkdir =		msdosfs_mkdir,
1983 	.vop_mknod =		msdosfs_mknod,
1984 	.vop_pathconf =		msdosfs_pathconf,
1985 	.vop_print =		msdosfs_print,
1986 	.vop_read =		msdosfs_read,
1987 	.vop_readdir =		msdosfs_readdir,
1988 	.vop_reclaim =		msdosfs_reclaim,
1989 	.vop_remove =		msdosfs_remove,
1990 	.vop_rename =		msdosfs_rename,
1991 	.vop_rmdir =		msdosfs_rmdir,
1992 	.vop_setattr =		msdosfs_setattr,
1993 	.vop_strategy =		msdosfs_strategy,
1994 	.vop_symlink =		msdosfs_symlink,
1995 	.vop_write =		msdosfs_write,
1996 	.vop_vptofh =		msdosfs_vptofh,
1997 };
1998 VFS_VOP_VECTOR_REGISTER(msdosfs_vnodeops);
1999