xref: /freebsd/sys/fs/msdosfs/msdosfs_vnops.c (revision 5b5b7e2ca2fa9a2418dd51749f4ef6f881ae7179)
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 = detrunc(dep, vap->va_size, 0, cred);
460 		if (error)
461 			return error;
462 	}
463 	if (vap->va_atime.tv_sec != VNOVAL || vap->va_mtime.tv_sec != VNOVAL) {
464 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
465 			return (EROFS);
466 		error = vn_utimes_perm(vp, vap, cred, td);
467 		if (error != 0)
468 			return (error);
469 		if ((pmp->pm_flags & MSDOSFSMNT_NOWIN95) == 0 &&
470 		    vap->va_atime.tv_sec != VNOVAL) {
471 			dep->de_flag &= ~DE_ACCESS;
472 			timespec2fattime(&vap->va_atime, 0,
473 			    &dep->de_ADate, NULL, NULL);
474 		}
475 		if (vap->va_mtime.tv_sec != VNOVAL) {
476 			dep->de_flag &= ~DE_UPDATE;
477 			timespec2fattime(&vap->va_mtime, 0,
478 			    &dep->de_MDate, &dep->de_MTime, NULL);
479 		}
480 		/*
481 		 * We don't set the archive bit when modifying the time of
482 		 * a directory to emulate the Windows/DOS behavior.
483 		 */
484 		if (vp->v_type != VDIR)
485 			dep->de_Attributes |= ATTR_ARCHIVE;
486 		dep->de_flag |= DE_MODIFIED;
487 	}
488 	/*
489 	 * DOS files only have the ability to have their writability
490 	 * attribute set, so we use the owner write bit to set the readonly
491 	 * attribute.
492 	 */
493 	if (vap->va_mode != (mode_t)VNOVAL) {
494 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
495 			return (EROFS);
496 		if (cred->cr_uid != pmp->pm_uid) {
497 			error = priv_check_cred(cred, PRIV_VFS_ADMIN);
498 			if (error)
499 				return (error);
500 		}
501 		if (vp->v_type != VDIR) {
502 			/* We ignore the read and execute bits. */
503 			if (vap->va_mode & S_IWUSR)
504 				dep->de_Attributes &= ~ATTR_READONLY;
505 			else
506 				dep->de_Attributes |= ATTR_READONLY;
507 			dep->de_Attributes |= ATTR_ARCHIVE;
508 			dep->de_flag |= DE_MODIFIED;
509 		}
510 	}
511 	return (deupdat(dep, 0));
512 }
513 
514 static int
515 msdosfs_read(struct vop_read_args *ap)
516 {
517 	int error = 0;
518 	int blsize;
519 	int isadir;
520 	ssize_t orig_resid;
521 	u_int n;
522 	u_long diff;
523 	u_long on;
524 	daddr_t lbn;
525 	daddr_t rablock;
526 	int rasize;
527 	int seqcount;
528 	struct buf *bp;
529 	struct vnode *vp = ap->a_vp;
530 	struct denode *dep = VTODE(vp);
531 	struct msdosfsmount *pmp = dep->de_pmp;
532 	struct uio *uio = ap->a_uio;
533 
534 	/*
535 	 * If they didn't ask for any data, then we are done.
536 	 */
537 	orig_resid = uio->uio_resid;
538 	if (orig_resid == 0)
539 		return (0);
540 
541 	/*
542 	 * The caller is supposed to ensure that
543 	 * uio->uio_offset >= 0 and uio->uio_resid >= 0.
544 	 * We don't need to check for large offsets as in ffs because
545 	 * dep->de_FileSize <= MSDOSFS_FILESIZE_MAX < OFF_MAX, so large
546 	 * offsets cannot cause overflow even in theory.
547 	 */
548 
549 	seqcount = ap->a_ioflag >> IO_SEQSHIFT;
550 
551 	isadir = dep->de_Attributes & ATTR_DIRECTORY;
552 	do {
553 		if (uio->uio_offset >= dep->de_FileSize)
554 			break;
555 		lbn = de_cluster(pmp, uio->uio_offset);
556 		rablock = lbn + 1;
557 		blsize = pmp->pm_bpcluster;
558 		on = uio->uio_offset & pmp->pm_crbomask;
559 		/*
560 		 * If we are operating on a directory file then be sure to
561 		 * do i/o with the vnode for the filesystem instead of the
562 		 * vnode for the directory.
563 		 */
564 		if (isadir) {
565 			/* convert cluster # to block # */
566 			error = pcbmap(dep, lbn, &lbn, 0, &blsize);
567 			if (error == E2BIG) {
568 				error = EINVAL;
569 				break;
570 			} else if (error)
571 				break;
572 			error = bread(pmp->pm_devvp, lbn, blsize, NOCRED, &bp);
573 		} else if (de_cn2off(pmp, rablock) >= dep->de_FileSize) {
574 			error = bread(vp, lbn, blsize, NOCRED, &bp);
575 		} else if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0) {
576 			error = cluster_read(vp, dep->de_FileSize, lbn, blsize,
577 			    NOCRED, on + uio->uio_resid, seqcount, 0, &bp);
578 		} else if (seqcount > 1) {
579 			rasize = blsize;
580 			error = breadn(vp, lbn,
581 			    blsize, &rablock, &rasize, 1, NOCRED, &bp);
582 		} else {
583 			error = bread(vp, lbn, blsize, NOCRED, &bp);
584 		}
585 		if (error) {
586 			brelse(bp);
587 			break;
588 		}
589 		diff = pmp->pm_bpcluster - on;
590 		n = diff > uio->uio_resid ? uio->uio_resid : diff;
591 		diff = dep->de_FileSize - uio->uio_offset;
592 		if (diff < n)
593 			n = diff;
594 		diff = blsize - bp->b_resid;
595 		if (diff < n)
596 			n = diff;
597 		error = vn_io_fault_uiomove(bp->b_data + on, (int) n, uio);
598 		brelse(bp);
599 	} while (error == 0 && uio->uio_resid > 0 && n != 0);
600 	if (!isadir && (error == 0 || uio->uio_resid != orig_resid) &&
601 	    (vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0)
602 		dep->de_flag |= DE_ACCESS;
603 	return (error);
604 }
605 
606 /*
607  * Write data to a file or directory.
608  */
609 static int
610 msdosfs_write(struct vop_write_args *ap)
611 {
612 	int n;
613 	int croffset;
614 	ssize_t resid;
615 	u_long osize;
616 	int error = 0;
617 	u_long count;
618 	int seqcount;
619 	daddr_t bn, lastcn;
620 	struct buf *bp;
621 	int ioflag = ap->a_ioflag;
622 	struct uio *uio = ap->a_uio;
623 	struct vnode *vp = ap->a_vp;
624 	struct vnode *thisvp;
625 	struct denode *dep = VTODE(vp);
626 	struct msdosfsmount *pmp = dep->de_pmp;
627 	struct ucred *cred = ap->a_cred;
628 
629 #ifdef MSDOSFS_DEBUG
630 	printf("msdosfs_write(vp %p, uio %p, ioflag %x, cred %p\n",
631 	    vp, uio, ioflag, cred);
632 	printf("msdosfs_write(): diroff %lu, dirclust %lu, startcluster %lu\n",
633 	    dep->de_diroffset, dep->de_dirclust, dep->de_StartCluster);
634 #endif
635 
636 	switch (vp->v_type) {
637 	case VREG:
638 		if (ioflag & IO_APPEND)
639 			uio->uio_offset = dep->de_FileSize;
640 		thisvp = vp;
641 		break;
642 	case VDIR:
643 		return EISDIR;
644 	default:
645 		panic("msdosfs_write(): bad file type");
646 	}
647 
648 	/*
649 	 * This is needed (unlike in ffs_write()) because we extend the
650 	 * file outside of the loop but we don't want to extend the file
651 	 * for writes of 0 bytes.
652 	 */
653 	if (uio->uio_resid == 0)
654 		return (0);
655 
656 	/*
657 	 * The caller is supposed to ensure that
658 	 * uio->uio_offset >= 0 and uio->uio_resid >= 0.
659 	 */
660 	if ((uoff_t)uio->uio_offset + uio->uio_resid > MSDOSFS_FILESIZE_MAX)
661 		return (EFBIG);
662 
663 	/*
664 	 * If they've exceeded their filesize limit, tell them about it.
665 	 */
666 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
667 		return (EFBIG);
668 
669 	/*
670 	 * If the offset we are starting the write at is beyond the end of
671 	 * the file, then they've done a seek.  Unix filesystems allow
672 	 * files with holes in them, DOS doesn't so we must fill the hole
673 	 * with zeroed blocks.
674 	 */
675 	if (uio->uio_offset > dep->de_FileSize) {
676 		error = deextend(dep, uio->uio_offset, cred);
677 		if (error)
678 			return (error);
679 	}
680 
681 	/*
682 	 * Remember some values in case the write fails.
683 	 */
684 	resid = uio->uio_resid;
685 	osize = dep->de_FileSize;
686 
687 	/*
688 	 * If we write beyond the end of the file, extend it to its ultimate
689 	 * size ahead of the time to hopefully get a contiguous area.
690 	 */
691 	if (uio->uio_offset + resid > osize) {
692 		count = de_clcount(pmp, uio->uio_offset + resid) -
693 			de_clcount(pmp, osize);
694 		error = extendfile(dep, count, NULL, NULL, 0);
695 		if (error &&  (error != ENOSPC || (ioflag & IO_UNIT)))
696 			goto errexit;
697 		lastcn = dep->de_fc[FC_LASTFC].fc_frcn;
698 	} else
699 		lastcn = de_clcount(pmp, osize) - 1;
700 
701 	seqcount = ioflag >> IO_SEQSHIFT;
702 	do {
703 		if (de_cluster(pmp, uio->uio_offset) > lastcn) {
704 			error = ENOSPC;
705 			break;
706 		}
707 
708 		croffset = uio->uio_offset & pmp->pm_crbomask;
709 		n = min(uio->uio_resid, pmp->pm_bpcluster - croffset);
710 		if (uio->uio_offset + n > dep->de_FileSize) {
711 			dep->de_FileSize = uio->uio_offset + n;
712 			/* The object size needs to be set before buffer is allocated */
713 			vnode_pager_setsize(vp, dep->de_FileSize);
714 		}
715 
716 		bn = de_cluster(pmp, uio->uio_offset);
717 		if ((uio->uio_offset & pmp->pm_crbomask) == 0
718 		    && (de_cluster(pmp, uio->uio_offset + uio->uio_resid)
719 			> de_cluster(pmp, uio->uio_offset)
720 			|| uio->uio_offset + uio->uio_resid >= dep->de_FileSize)) {
721 			/*
722 			 * If either the whole cluster gets written,
723 			 * or we write the cluster from its start beyond EOF,
724 			 * then no need to read data from disk.
725 			 */
726 			bp = getblk(thisvp, bn, pmp->pm_bpcluster, 0, 0, 0);
727 			/*
728 			 * This call to vfs_bio_clrbuf() ensures that
729 			 * even if vn_io_fault_uiomove() below faults,
730 			 * garbage from the newly instantiated buffer
731 			 * is not exposed to the userspace via mmap().
732 			 */
733 			vfs_bio_clrbuf(bp);
734 			/*
735 			 * Do the bmap now, since pcbmap needs buffers
736 			 * for the FAT table. (see msdosfs_strategy)
737 			 */
738 			if (bp->b_blkno == bp->b_lblkno) {
739 				error = pcbmap(dep, bp->b_lblkno, &bn, 0, 0);
740 				if (error)
741 					bp->b_blkno = -1;
742 				else
743 					bp->b_blkno = bn;
744 			}
745 			if (bp->b_blkno == -1) {
746 				brelse(bp);
747 				if (!error)
748 					error = EIO;		/* XXX */
749 				break;
750 			}
751 		} else {
752 			/*
753 			 * The block we need to write into exists, so read it in.
754 			 */
755 			error = bread(thisvp, bn, pmp->pm_bpcluster, cred, &bp);
756 			if (error) {
757 				break;
758 			}
759 		}
760 
761 		/*
762 		 * Should these vnode_pager_* functions be done on dir
763 		 * files?
764 		 */
765 
766 		/*
767 		 * Copy the data from user space into the buf header.
768 		 */
769 		error = vn_io_fault_uiomove(bp->b_data + croffset, n, uio);
770 		if (error) {
771 			brelse(bp);
772 			break;
773 		}
774 
775 		/* Prepare for clustered writes in some else clauses. */
776 		if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0)
777 			bp->b_flags |= B_CLUSTEROK;
778 
779 		/*
780 		 * If IO_SYNC, then each buffer is written synchronously.
781 		 * Otherwise, if we have a severe page deficiency then
782 		 * write the buffer asynchronously.  Otherwise, if on a
783 		 * cluster boundary then write the buffer asynchronously,
784 		 * combining it with contiguous clusters if permitted and
785 		 * possible, since we don't expect more writes into this
786 		 * buffer soon.  Otherwise, do a delayed write because we
787 		 * expect more writes into this buffer soon.
788 		 */
789 		if (ioflag & IO_SYNC)
790 			(void)bwrite(bp);
791 		else if (vm_page_count_severe() || buf_dirty_count_severe())
792 			bawrite(bp);
793 		else if (n + croffset == pmp->pm_bpcluster) {
794 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0)
795 				cluster_write(vp, &dep->de_clusterw, bp,
796 				    dep->de_FileSize, seqcount, 0);
797 			else
798 				bawrite(bp);
799 		} else
800 			bdwrite(bp);
801 		dep->de_flag |= DE_UPDATE;
802 	} while (error == 0 && uio->uio_resid > 0);
803 
804 	/*
805 	 * If the write failed and they want us to, truncate the file back
806 	 * to the size it was before the write was attempted.
807 	 */
808 errexit:
809 	if (error) {
810 		if (ioflag & IO_UNIT) {
811 			detrunc(dep, osize, ioflag & IO_SYNC, NOCRED);
812 			uio->uio_offset -= resid - uio->uio_resid;
813 			uio->uio_resid = resid;
814 		} else {
815 			detrunc(dep, dep->de_FileSize, ioflag & IO_SYNC, NOCRED);
816 			if (uio->uio_resid != resid)
817 				error = 0;
818 		}
819 	} else if (ioflag & IO_SYNC)
820 		error = deupdat(dep, 1);
821 	return (error);
822 }
823 
824 /*
825  * Flush the blocks of a file to disk.
826  */
827 static int
828 msdosfs_fsync(struct vop_fsync_args *ap)
829 {
830 	struct vnode *devvp;
831 	int allerror, error;
832 
833 	vop_stdfsync(ap);
834 
835 	/*
836 	* If the syncing request comes from fsync(2), sync the entire
837 	* FAT and any other metadata that happens to be on devvp.  We
838 	* need this mainly for the FAT.  We write the FAT sloppily, and
839 	* syncing it all now is the best we can easily do to get all
840 	* directory entries associated with the file (not just the file)
841 	* fully synced.  The other metadata includes critical metadata
842 	* for all directory entries, but only in the MNT_ASYNC case.  We
843 	* will soon sync all metadata in the file's directory entry.
844 	* Non-critical metadata for associated directory entries only
845 	* gets synced accidentally, as in most file systems.
846 	*/
847 	if (ap->a_waitfor != MNT_NOWAIT) {
848 		devvp = VTODE(ap->a_vp)->de_pmp->pm_devvp;
849 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
850 		allerror = VOP_FSYNC(devvp, MNT_WAIT, ap->a_td);
851 		VOP_UNLOCK(devvp);
852 	} else
853 		allerror = 0;
854 
855 	error = deupdat(VTODE(ap->a_vp), ap->a_waitfor != MNT_NOWAIT);
856 	if (allerror == 0)
857 		allerror = error;
858 	return (allerror);
859 }
860 
861 static int
862 msdosfs_remove(struct vop_remove_args *ap)
863 {
864 	struct denode *dep = VTODE(ap->a_vp);
865 	struct denode *ddep = VTODE(ap->a_dvp);
866 	int error;
867 
868 	if (ap->a_vp->v_type == VDIR)
869 		error = EPERM;
870 	else
871 		error = removede(ddep, dep);
872 #ifdef MSDOSFS_DEBUG
873 	printf("msdosfs_remove(), dep %p, v_usecount %d\n", dep, ap->a_vp->v_usecount);
874 #endif
875 	return (error);
876 }
877 
878 /*
879  * DOS filesystems don't know what links are.
880  */
881 static int
882 msdosfs_link(struct vop_link_args *ap)
883 {
884 	return (EOPNOTSUPP);
885 }
886 
887 /*
888  * Renames on files require moving the denode to a new hash queue since the
889  * denode's location is used to compute which hash queue to put the file
890  * in. Unless it is a rename in place.  For example "mv a b".
891  *
892  * What follows is the basic algorithm:
893  *
894  * if (file move) {
895  *	if (dest file exists) {
896  *		remove dest file
897  *	}
898  *	if (dest and src in same directory) {
899  *		rewrite name in existing directory slot
900  *	} else {
901  *		write new entry in dest directory
902  *		update offset and dirclust in denode
903  *		move denode to new hash chain
904  *		clear old directory entry
905  *	}
906  * } else {
907  *	directory move
908  *	if (dest directory exists) {
909  *		if (dest is not empty) {
910  *			return ENOTEMPTY
911  *		}
912  *		remove dest directory
913  *	}
914  *	if (dest and src in same directory) {
915  *		rewrite name in existing entry
916  *	} else {
917  *		be sure dest is not a child of src directory
918  *		write entry in dest directory
919  *		update "." and ".." in moved directory
920  *		clear old directory entry for moved directory
921  *	}
922  * }
923  *
924  * On entry:
925  *	source's parent directory is unlocked
926  *	source file or directory is unlocked
927  *	destination's parent directory is locked
928  *	destination file or directory is locked if it exists
929  *
930  * On exit:
931  *	all denodes should be released
932  */
933 static int
934 msdosfs_rename(struct vop_rename_args *ap)
935 {
936 	struct vnode *fdvp, *fvp, *tdvp, *tvp, *vp;
937 	struct componentname *fcnp, *tcnp;
938 	struct denode *fdip, *fip, *tdip, *tip, *nip;
939 	u_char toname[12], oldname[11];
940 	u_long to_diroffset;
941 	bool checkpath_locked, doingdirectory, newparent;
942 	int error;
943 	u_long cn, pcl, blkoff;
944 	daddr_t bn, wait_scn, scn;
945 	struct msdosfsmount *pmp;
946 	struct direntry *dotdotp;
947 	struct buf *bp;
948 
949 	tdvp = ap->a_tdvp;
950 	fvp = ap->a_fvp;
951 	fdvp = ap->a_fdvp;
952 	tvp = ap->a_tvp;
953 	tcnp = ap->a_tcnp;
954 	fcnp = ap->a_fcnp;
955 	pmp = VFSTOMSDOSFS(fdvp->v_mount);
956 
957 	/*
958 	 * Check for cross-device rename.
959 	 */
960 	if (fvp->v_mount != tdvp->v_mount ||
961 	    (tvp != NULL && fvp->v_mount != tvp->v_mount)) {
962 		error = EXDEV;
963 		goto abortit;
964 	}
965 
966 	/*
967 	 * If source and dest are the same, do nothing.
968 	 */
969 	if (tvp == fvp) {
970 		error = 0;
971 		goto abortit;
972 	}
973 
974 	/*
975 	 * When the target exists, both the directory
976 	 * and target vnodes are passed locked.
977 	 */
978 	VOP_UNLOCK(tdvp);
979 	if (tvp != NULL && tvp != tdvp)
980 		VOP_UNLOCK(tvp);
981 
982 	checkpath_locked = false;
983 
984 relock:
985 	doingdirectory = newparent = false;
986 
987 	error = vn_lock(fdvp, LK_EXCLUSIVE);
988 	if (error != 0)
989 		goto releout;
990 	if (vn_lock(tdvp, LK_EXCLUSIVE | LK_NOWAIT) != 0) {
991 		VOP_UNLOCK(fdvp);
992 		error = vn_lock(tdvp, LK_EXCLUSIVE);
993 		if (error != 0)
994 			goto releout;
995 		VOP_UNLOCK(tdvp);
996 		goto relock;
997 	}
998 
999 	error = msdosfs_lookup_ino(fdvp, NULL, fcnp, &scn, &blkoff);
1000 	if (error != 0) {
1001 		VOP_UNLOCK(fdvp);
1002 		VOP_UNLOCK(tdvp);
1003 		goto releout;
1004 	}
1005 	error = deget(pmp, scn, blkoff, LK_EXCLUSIVE | LK_NOWAIT, &nip);
1006 	if (error != 0) {
1007 		VOP_UNLOCK(fdvp);
1008 		VOP_UNLOCK(tdvp);
1009 		if (error != EBUSY)
1010 			goto releout;
1011 		error = deget(pmp, scn, blkoff, LK_EXCLUSIVE, &nip);
1012 		if (error != 0)
1013 			goto releout;
1014 		vp = fvp;
1015 		fvp = DETOV(nip);
1016 		VOP_UNLOCK(fvp);
1017 		vrele(vp);
1018 		goto relock;
1019 	}
1020 	vrele(fvp);
1021 	fvp = DETOV(nip);
1022 
1023 	error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1024 	if (error != 0 && error != EJUSTRETURN) {
1025 		VOP_UNLOCK(fdvp);
1026 		VOP_UNLOCK(tdvp);
1027 		VOP_UNLOCK(fvp);
1028 		goto releout;
1029 	}
1030 	if (error == EJUSTRETURN && tvp != NULL) {
1031 		vrele(tvp);
1032 		tvp = NULL;
1033 	}
1034 	if (error == 0) {
1035 		nip = NULL;
1036 		error = deget(pmp, scn, blkoff, LK_EXCLUSIVE | LK_NOWAIT,
1037 		    &nip);
1038 		if (tvp != NULL) {
1039 			vrele(tvp);
1040 			tvp = NULL;
1041 		}
1042 		if (error != 0) {
1043 			VOP_UNLOCK(fdvp);
1044 			VOP_UNLOCK(tdvp);
1045 			VOP_UNLOCK(fvp);
1046 			if (error != EBUSY)
1047 				goto releout;
1048 			error = deget(pmp, scn, blkoff, LK_EXCLUSIVE,
1049 			    &nip);
1050 			if (error != 0)
1051 				goto releout;
1052 			vput(DETOV(nip));
1053 			goto relock;
1054 		}
1055 		tvp = DETOV(nip);
1056 	}
1057 
1058 	fdip = VTODE(fdvp);
1059 	fip = VTODE(fvp);
1060 	tdip = VTODE(tdvp);
1061 	tip = tvp != NULL ? VTODE(tvp) : NULL;
1062 
1063 	/*
1064 	 * Remember direntry place to use for destination
1065 	 */
1066 	to_diroffset = tdip->de_fndoffset;
1067 
1068 	/*
1069 	 * Be sure we are not renaming ".", "..", or an alias of ".". This
1070 	 * leads to a crippled directory tree.  It's pretty tough to do a
1071 	 * "ls" or "pwd" with the "." directory entry missing, and "cd .."
1072 	 * doesn't work if the ".." entry is missing.
1073 	 */
1074 	if ((fip->de_Attributes & ATTR_DIRECTORY) != 0) {
1075 		/*
1076 		 * Avoid ".", "..", and aliases of "." for obvious reasons.
1077 		 */
1078 		if ((fcnp->cn_namelen == 1 && fcnp->cn_nameptr[0] == '.') ||
1079 		    fdip == fip ||
1080 		    (fcnp->cn_flags & ISDOTDOT) != 0 ||
1081 		    (tcnp->cn_flags & ISDOTDOT) != 0) {
1082 			error = EINVAL;
1083 			goto unlock;
1084 		}
1085 		doingdirectory = true;
1086 	}
1087 
1088 	/*
1089 	 * If ".." must be changed (ie the directory gets a new
1090 	 * parent) then the source directory must not be in the
1091 	 * directory hierarchy above the target, as this would
1092 	 * orphan everything below the source directory. Also
1093 	 * the user must have write permission in the source so
1094 	 * as to be able to change "..". We must repeat the call
1095 	 * to namei, as the parent directory is unlocked by the
1096 	 * call to doscheckpath().
1097 	 */
1098 	error = VOP_ACCESS(fvp, VWRITE, tcnp->cn_cred, curthread);
1099 	if (fdip->de_StartCluster != tdip->de_StartCluster)
1100 		newparent = true;
1101 	if (doingdirectory && newparent) {
1102 		if (error != 0)	/* write access check above */
1103 			goto unlock;
1104 		lockmgr(&pmp->pm_checkpath_lock, LK_EXCLUSIVE, NULL);
1105 		checkpath_locked = true;
1106 		error = doscheckpath(fip, tdip, &wait_scn);
1107 		if (wait_scn != 0) {
1108 			lockmgr(&pmp->pm_checkpath_lock, LK_RELEASE, NULL);
1109 			checkpath_locked = false;
1110 			VOP_UNLOCK(fdvp);
1111 			VOP_UNLOCK(tdvp);
1112 			VOP_UNLOCK(fvp);
1113 			if (tvp != NULL && tvp != tdvp)
1114 				VOP_UNLOCK(tvp);
1115 			error = deget(pmp, wait_scn, 0, LK_EXCLUSIVE,
1116 			    &nip);
1117 			if (error == 0) {
1118 				vput(DETOV(nip));
1119 				goto relock;
1120 			}
1121 		}
1122 		if (error != 0)
1123 			goto unlock;
1124 		if ((tcnp->cn_flags & SAVESTART) == 0)
1125 			panic("msdosfs_rename: lost to startdir");
1126 	}
1127 
1128 	if (tip != NULL) {
1129 		/*
1130 		 * Target must be empty if a directory and have no links
1131 		 * to it. Also, ensure source and target are compatible
1132 		 * (both directories, or both not directories).
1133 		 */
1134 		if ((tip->de_Attributes & ATTR_DIRECTORY) != 0) {
1135 			if (!dosdirempty(tip)) {
1136 				error = ENOTEMPTY;
1137 				goto unlock;
1138 			}
1139 			if (!doingdirectory) {
1140 				error = ENOTDIR;
1141 				goto unlock;
1142 			}
1143 			cache_purge(tdvp);
1144 		} else if (doingdirectory) {
1145 			error = EISDIR;
1146 			goto unlock;
1147 		}
1148 		error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1149 		MPASS(error == 0);
1150 		error = removede(tdip, tip);
1151 		if (error != 0)
1152 			goto unlock;
1153 		vput(tvp);
1154 		tvp = NULL;
1155 		tip = NULL;
1156 	}
1157 
1158 	/*
1159 	 * Convert the filename in tcnp into a dos filename. We copy this
1160 	 * into the denode and directory entry for the destination
1161 	 * file/directory.
1162 	 */
1163 	error = uniqdosname(tdip, tcnp, toname);
1164 	if (error != 0)
1165 		goto unlock;
1166 
1167 	/*
1168 	 * First write a new entry in the destination
1169 	 * directory and mark the entry in the source directory
1170 	 * as deleted.  Then move the denode to the correct hash
1171 	 * chain for its new location in the filesystem.  And, if
1172 	 * we moved a directory, then update its .. entry to point
1173 	 * to the new parent directory.
1174 	 */
1175 	memcpy(oldname, fip->de_Name, 11);
1176 	memcpy(fip->de_Name, toname, 11);	/* update denode */
1177 	error = msdosfs_lookup_ino(tdvp, NULL, tcnp, &scn, &blkoff);
1178 	MPASS(error == EJUSTRETURN);
1179 	error = createde(fip, tdip, NULL, tcnp);
1180 	if (error != 0) {
1181 		memcpy(fip->de_Name, oldname, 11);
1182 		goto unlock;
1183 	}
1184 
1185 	/*
1186 	 * If fip is for a directory, then its name should always
1187 	 * be "." since it is for the directory entry in the
1188 	 * directory itself (msdosfs_lookup() always translates
1189 	 * to the "." entry so as to get a unique denode, except
1190 	 * for the root directory there are different
1191 	 * complications).  However, we just corrupted its name
1192 	 * to pass the correct name to createde().  Undo this.
1193 	 */
1194 	if ((fip->de_Attributes & ATTR_DIRECTORY) != 0)
1195 		memcpy(fip->de_Name, oldname, 11);
1196 	fip->de_refcnt++;
1197 	error = msdosfs_lookup_ino(fdvp, NULL, fcnp, &scn, &blkoff);
1198 	MPASS(error == 0);
1199 	error = removede(fdip, fip);
1200 	if (error != 0) {
1201 		/* XXX should downgrade to ro here, fs is corrupt */
1202 		goto unlock;
1203 	}
1204 	if (!doingdirectory) {
1205 		error = pcbmap(tdip, de_cluster(pmp, to_diroffset), 0,
1206 		    &fip->de_dirclust, 0);
1207 		if (error != 0) {
1208 			/*
1209 			 * XXX should downgrade to ro here,
1210 			 * fs is corrupt
1211 			 */
1212 			goto unlock;
1213 		}
1214 		if (fip->de_dirclust == MSDOSFSROOT)
1215 			fip->de_diroffset = to_diroffset;
1216 		else
1217 			fip->de_diroffset = to_diroffset & pmp->pm_crbomask;
1218 	}
1219 	reinsert(fip);
1220 
1221 	/*
1222 	 * If we moved a directory to a new parent directory, then we must
1223 	 * fixup the ".." entry in the moved directory.
1224 	 */
1225 	if (doingdirectory && newparent) {
1226 		cn = fip->de_StartCluster;
1227 		if (cn == MSDOSFSROOT) {
1228 			/* this should never happen */
1229 			panic("msdosfs_rename(): updating .. in root directory?");
1230 		} else
1231 			bn = cntobn(pmp, cn);
1232 		error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster,
1233 		    NOCRED, &bp);
1234 		if (error != 0) {
1235 			/* XXX should downgrade to ro here, fs is corrupt */
1236 			goto unlock;
1237 		}
1238 		dotdotp = (struct direntry *)bp->b_data + 1;
1239 		pcl = tdip->de_StartCluster;
1240 		if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1241 			pcl = MSDOSFSROOT;
1242 		putushort(dotdotp->deStartCluster, pcl);
1243 		if (FAT32(pmp))
1244 			putushort(dotdotp->deHighClust, pcl >> 16);
1245 		if (DOINGASYNC(fvp))
1246 			bdwrite(bp);
1247 		else if ((error = bwrite(bp)) != 0) {
1248 			/* XXX should downgrade to ro here, fs is corrupt */
1249 			goto unlock;
1250 		}
1251 	}
1252 
1253 	/*
1254 	 * The msdosfs lookup is case insensitive. Several aliases may
1255 	 * be inserted for a single directory entry. As a consequnce,
1256 	 * name cache purge done by lookup for fvp when DELETE op for
1257 	 * namei is specified, might be not enough to expunge all
1258 	 * namecache entries that were installed for this direntry.
1259 	 */
1260 	cache_purge(fvp);
1261 
1262 unlock:
1263 	if (checkpath_locked)
1264 		lockmgr(&pmp->pm_checkpath_lock, LK_RELEASE, NULL);
1265 	vput(fdvp);
1266 	vput(fvp);
1267 	if (tvp != NULL) {
1268 		if (tvp != tdvp)
1269 			vput(tvp);
1270 		else
1271 			vrele(tvp);
1272 	}
1273 	vput(tdvp);
1274 	return (error);
1275 releout:
1276 	MPASS(!checkpath_locked);
1277 	vrele(tdvp);
1278 	if (tvp != NULL)
1279 		vrele(tvp);
1280 	vrele(fdvp);
1281 	vrele(fvp);
1282 	return (error);
1283 abortit:
1284 	if (tdvp == tvp)
1285 		vrele(tdvp);
1286 	else
1287 		vput(tdvp);
1288 	if (tvp != NULL)
1289 		vput(tvp);
1290 	vrele(fdvp);
1291 	vrele(fvp);
1292 	return (error);
1293 }
1294 
1295 static struct {
1296 	struct direntry dot;
1297 	struct direntry dotdot;
1298 } dosdirtemplate = {
1299 	{	".          ",				/* the . entry */
1300 		ATTR_DIRECTORY,				/* file attribute */
1301 		0,					/* reserved */
1302 		0, { 0, 0 }, { 0, 0 },			/* create time & date */
1303 		{ 0, 0 },				/* access date */
1304 		{ 0, 0 },				/* high bits of start cluster */
1305 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1306 		{ 0, 0 },				/* startcluster */
1307 		{ 0, 0, 0, 0 }				/* filesize */
1308 	},
1309 	{	"..         ",				/* the .. entry */
1310 		ATTR_DIRECTORY,				/* file attribute */
1311 		0,					/* reserved */
1312 		0, { 0, 0 }, { 0, 0 },			/* create time & date */
1313 		{ 0, 0 },				/* access date */
1314 		{ 0, 0 },				/* high bits of start cluster */
1315 		{ 210, 4 }, { 210, 4 },			/* modify time & date */
1316 		{ 0, 0 },				/* startcluster */
1317 		{ 0, 0, 0, 0 }				/* filesize */
1318 	}
1319 };
1320 
1321 static int
1322 msdosfs_mkdir(struct vop_mkdir_args *ap)
1323 {
1324 	struct componentname *cnp = ap->a_cnp;
1325 	struct denode *dep;
1326 	struct denode *pdep = VTODE(ap->a_dvp);
1327 	struct direntry *denp;
1328 	struct msdosfsmount *pmp = pdep->de_pmp;
1329 	struct buf *bp;
1330 	u_long newcluster, pcl;
1331 	int bn;
1332 	int error;
1333 	struct denode ndirent;
1334 	struct timespec ts;
1335 
1336 	/*
1337 	 * If this is the root directory and there is no space left we
1338 	 * can't do anything.  This is because the root directory can not
1339 	 * change size.
1340 	 */
1341 	if (pdep->de_StartCluster == MSDOSFSROOT
1342 	    && pdep->de_fndoffset >= pdep->de_FileSize) {
1343 		error = ENOSPC;
1344 		goto bad2;
1345 	}
1346 
1347 	/*
1348 	 * Allocate a cluster to hold the about to be created directory.
1349 	 */
1350 	error = clusteralloc(pmp, 0, 1, CLUST_EOFE, &newcluster, NULL);
1351 	if (error)
1352 		goto bad2;
1353 
1354 	memset(&ndirent, 0, sizeof(ndirent));
1355 	ndirent.de_pmp = pmp;
1356 	ndirent.de_flag = DE_ACCESS | DE_CREATE | DE_UPDATE;
1357 	vfs_timestamp(&ts);
1358 	DETIMES(&ndirent, &ts, &ts, &ts);
1359 
1360 	/*
1361 	 * Now fill the cluster with the "." and ".." entries. And write
1362 	 * the cluster to disk.  This way it is there for the parent
1363 	 * directory to be pointing at if there were a crash.
1364 	 */
1365 	bn = cntobn(pmp, newcluster);
1366 	/* always succeeds */
1367 	bp = getblk(pmp->pm_devvp, bn, pmp->pm_bpcluster, 0, 0, 0);
1368 	memset(bp->b_data, 0, pmp->pm_bpcluster);
1369 	memcpy(bp->b_data, &dosdirtemplate, sizeof dosdirtemplate);
1370 	denp = (struct direntry *)bp->b_data;
1371 	putushort(denp[0].deStartCluster, newcluster);
1372 	putushort(denp[0].deCDate, ndirent.de_CDate);
1373 	putushort(denp[0].deCTime, ndirent.de_CTime);
1374 	denp[0].deCHundredth = ndirent.de_CHun;
1375 	putushort(denp[0].deADate, ndirent.de_ADate);
1376 	putushort(denp[0].deMDate, ndirent.de_MDate);
1377 	putushort(denp[0].deMTime, ndirent.de_MTime);
1378 	pcl = pdep->de_StartCluster;
1379 	/*
1380 	 * Although the root directory has a non-magic starting cluster
1381 	 * number for FAT32, chkdsk and fsck_msdosfs still require
1382 	 * references to it in dotdot entries to be magic.
1383 	 */
1384 	if (FAT32(pmp) && pcl == pmp->pm_rootdirblk)
1385 		pcl = MSDOSFSROOT;
1386 	putushort(denp[1].deStartCluster, pcl);
1387 	putushort(denp[1].deCDate, ndirent.de_CDate);
1388 	putushort(denp[1].deCTime, ndirent.de_CTime);
1389 	denp[1].deCHundredth = ndirent.de_CHun;
1390 	putushort(denp[1].deADate, ndirent.de_ADate);
1391 	putushort(denp[1].deMDate, ndirent.de_MDate);
1392 	putushort(denp[1].deMTime, ndirent.de_MTime);
1393 	if (FAT32(pmp)) {
1394 		putushort(denp[0].deHighClust, newcluster >> 16);
1395 		putushort(denp[1].deHighClust, pcl >> 16);
1396 	}
1397 
1398 	if (DOINGASYNC(ap->a_dvp))
1399 		bdwrite(bp);
1400 	else if ((error = bwrite(bp)) != 0)
1401 		goto bad;
1402 
1403 	/*
1404 	 * Now build up a directory entry pointing to the newly allocated
1405 	 * cluster.  This will be written to an empty slot in the parent
1406 	 * directory.
1407 	 */
1408 	error = uniqdosname(pdep, cnp, ndirent.de_Name);
1409 	if (error)
1410 		goto bad;
1411 
1412 	ndirent.de_Attributes = ATTR_DIRECTORY;
1413 	ndirent.de_LowerCase = 0;
1414 	ndirent.de_StartCluster = newcluster;
1415 	ndirent.de_FileSize = 0;
1416 	error = createde(&ndirent, pdep, &dep, cnp);
1417 	if (error)
1418 		goto bad;
1419 	*ap->a_vpp = DETOV(dep);
1420 	return (0);
1421 
1422 bad:
1423 	clusterfree(pmp, newcluster);
1424 bad2:
1425 	return (error);
1426 }
1427 
1428 static int
1429 msdosfs_rmdir(struct vop_rmdir_args *ap)
1430 {
1431 	struct vnode *vp = ap->a_vp;
1432 	struct vnode *dvp = ap->a_dvp;
1433 	struct componentname *cnp = ap->a_cnp;
1434 	struct denode *ip, *dp;
1435 	int error;
1436 
1437 	ip = VTODE(vp);
1438 	dp = VTODE(dvp);
1439 
1440 	/*
1441 	 * Verify the directory is empty (and valid).
1442 	 * (Rmdir ".." won't be valid since
1443 	 *  ".." will contain a reference to
1444 	 *  the current directory and thus be
1445 	 *  non-empty.)
1446 	 */
1447 	error = 0;
1448 	if (!dosdirempty(ip)) {
1449 		error = ENOTEMPTY;
1450 		goto out;
1451 	}
1452 	/*
1453 	 * Delete the entry from the directory.  For dos filesystems this
1454 	 * gets rid of the directory entry on disk, the in memory copy
1455 	 * still exists but the de_refcnt is <= 0.  This prevents it from
1456 	 * being found by deget().  When the vput() on dep is done we give
1457 	 * up access and eventually msdosfs_reclaim() will be called which
1458 	 * will remove it from the denode cache.
1459 	 */
1460 	error = removede(dp, ip);
1461 	if (error)
1462 		goto out;
1463 	/*
1464 	 * This is where we decrement the link count in the parent
1465 	 * directory.  Since dos filesystems don't do this we just purge
1466 	 * the name cache.
1467 	 */
1468 	cache_purge(dvp);
1469 	/*
1470 	 * Truncate the directory that is being deleted.
1471 	 */
1472 	error = detrunc(ip, (u_long)0, IO_SYNC, cnp->cn_cred);
1473 	cache_purge(vp);
1474 
1475 out:
1476 	return (error);
1477 }
1478 
1479 /*
1480  * DOS filesystems don't know what symlinks are.
1481  */
1482 static int
1483 msdosfs_symlink(struct vop_symlink_args *ap)
1484 {
1485 	return (EOPNOTSUPP);
1486 }
1487 
1488 static int
1489 msdosfs_readdir(struct vop_readdir_args *ap)
1490 {
1491 	struct mbnambuf nb;
1492 	int error = 0;
1493 	int diff;
1494 	long n;
1495 	int blsize;
1496 	long on;
1497 	u_long cn;
1498 	u_long dirsperblk;
1499 	long bias = 0;
1500 	daddr_t bn, lbn;
1501 	struct buf *bp;
1502 	struct denode *dep = VTODE(ap->a_vp);
1503 	struct msdosfsmount *pmp = dep->de_pmp;
1504 	struct direntry *dentp;
1505 	struct dirent dirbuf;
1506 	struct uio *uio = ap->a_uio;
1507 	uint64_t *cookies = NULL;
1508 	int ncookies = 0;
1509 	off_t offset, off;
1510 	int chksum = -1;
1511 
1512 #ifdef MSDOSFS_DEBUG
1513 	printf("msdosfs_readdir(): vp %p, uio %p, cred %p, eofflagp %p\n",
1514 	    ap->a_vp, uio, ap->a_cred, ap->a_eofflag);
1515 #endif
1516 
1517 	/*
1518 	 * msdosfs_readdir() won't operate properly on regular files since
1519 	 * it does i/o only with the filesystem vnode, and hence can
1520 	 * retrieve the wrong block from the buffer cache for a plain file.
1521 	 * So, fail attempts to readdir() on a plain file.
1522 	 */
1523 	if ((dep->de_Attributes & ATTR_DIRECTORY) == 0)
1524 		return (ENOTDIR);
1525 
1526 	/*
1527 	 * To be safe, initialize dirbuf
1528 	 */
1529 	memset(dirbuf.d_name, 0, sizeof(dirbuf.d_name));
1530 
1531 	/*
1532 	 * If the user buffer is smaller than the size of one dos directory
1533 	 * entry or the file offset is not a multiple of the size of a
1534 	 * directory entry, then we fail the read.
1535 	 */
1536 	off = offset = uio->uio_offset;
1537 	if (uio->uio_resid < sizeof(struct direntry) ||
1538 	    (offset & (sizeof(struct direntry) - 1)))
1539 		return (EINVAL);
1540 
1541 	if (ap->a_ncookies) {
1542 		ncookies = uio->uio_resid / 16;
1543 		cookies = malloc(ncookies * sizeof(*cookies), M_TEMP,
1544 		       M_WAITOK);
1545 		*ap->a_cookies = cookies;
1546 		*ap->a_ncookies = ncookies;
1547 	}
1548 
1549 	dirsperblk = pmp->pm_BytesPerSec / sizeof(struct direntry);
1550 
1551 	/*
1552 	 * If they are reading from the root directory then, we simulate
1553 	 * the . and .. entries since these don't exist in the root
1554 	 * directory.  We also set the offset bias to make up for having to
1555 	 * simulate these entries. By this I mean that at file offset 64 we
1556 	 * read the first entry in the root directory that lives on disk.
1557 	 */
1558 	if (dep->de_StartCluster == MSDOSFSROOT
1559 	    || (FAT32(pmp) && dep->de_StartCluster == pmp->pm_rootdirblk)) {
1560 #if 0
1561 		printf("msdosfs_readdir(): going after . or .. in root dir, offset %d\n",
1562 		    offset);
1563 #endif
1564 		bias = 2 * sizeof(struct direntry);
1565 		if (offset < bias) {
1566 			for (n = (int)offset / sizeof(struct direntry);
1567 			     n < 2; n++) {
1568 				dirbuf.d_fileno = FAT32(pmp) ?
1569 				    (uint64_t)cntobn(pmp, pmp->pm_rootdirblk) *
1570 				    dirsperblk : 1;
1571 				dirbuf.d_type = DT_DIR;
1572 				switch (n) {
1573 				case 0:
1574 					dirbuf.d_namlen = 1;
1575 					dirbuf.d_name[0] = '.';
1576 					break;
1577 				case 1:
1578 					dirbuf.d_namlen = 2;
1579 					dirbuf.d_name[0] = '.';
1580 					dirbuf.d_name[1] = '.';
1581 					break;
1582 				}
1583 				dirbuf.d_reclen = GENERIC_DIRSIZ(&dirbuf);
1584 				/* NOTE: d_off is the offset of the *next* entry. */
1585 				dirbuf.d_off = offset + sizeof(struct direntry);
1586 				dirent_terminate(&dirbuf);
1587 				if (uio->uio_resid < dirbuf.d_reclen)
1588 					goto out;
1589 				error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1590 				if (error)
1591 					goto out;
1592 				offset += sizeof(struct direntry);
1593 				off = offset;
1594 				if (cookies) {
1595 					*cookies++ = offset;
1596 					if (--ncookies <= 0)
1597 						goto out;
1598 				}
1599 			}
1600 		}
1601 	}
1602 
1603 	mbnambuf_init(&nb);
1604 	off = offset;
1605 	while (uio->uio_resid > 0) {
1606 		lbn = de_cluster(pmp, offset - bias);
1607 		on = (offset - bias) & pmp->pm_crbomask;
1608 		n = min(pmp->pm_bpcluster - on, uio->uio_resid);
1609 		diff = dep->de_FileSize - (offset - bias);
1610 		if (diff <= 0)
1611 			break;
1612 		n = min(n, diff);
1613 		error = pcbmap(dep, lbn, &bn, &cn, &blsize);
1614 		if (error)
1615 			break;
1616 		error = bread(pmp->pm_devvp, bn, blsize, NOCRED, &bp);
1617 		if (error) {
1618 			return (error);
1619 		}
1620 		n = min(n, blsize - bp->b_resid);
1621 		if (n == 0) {
1622 			brelse(bp);
1623 			return (EIO);
1624 		}
1625 
1626 		/*
1627 		 * Convert from dos directory entries to fs-independent
1628 		 * directory entries.
1629 		 */
1630 		for (dentp = (struct direntry *)(bp->b_data + on);
1631 		     (char *)dentp < bp->b_data + on + n;
1632 		     dentp++, offset += sizeof(struct direntry)) {
1633 #if 0
1634 			printf("rd: dentp %08x prev %08x crnt %08x deName %02x attr %02x\n",
1635 			    dentp, prev, crnt, dentp->deName[0], dentp->deAttributes);
1636 #endif
1637 			/*
1638 			 * If this is an unused entry, we can stop.
1639 			 */
1640 			if (dentp->deName[0] == SLOT_EMPTY) {
1641 				brelse(bp);
1642 				goto out;
1643 			}
1644 			/*
1645 			 * Skip deleted entries.
1646 			 */
1647 			if (dentp->deName[0] == SLOT_DELETED) {
1648 				chksum = -1;
1649 				mbnambuf_init(&nb);
1650 				continue;
1651 			}
1652 
1653 			/*
1654 			 * Handle Win95 long directory entries
1655 			 */
1656 			if (dentp->deAttributes == ATTR_WIN95) {
1657 				if (pmp->pm_flags & MSDOSFSMNT_SHORTNAME)
1658 					continue;
1659 				chksum = win2unixfn(&nb,
1660 				    (struct winentry *)dentp, chksum, pmp);
1661 				continue;
1662 			}
1663 
1664 			/*
1665 			 * Skip volume labels
1666 			 */
1667 			if (dentp->deAttributes & ATTR_VOLUME) {
1668 				chksum = -1;
1669 				mbnambuf_init(&nb);
1670 				continue;
1671 			}
1672 			/*
1673 			 * This computation of d_fileno must match
1674 			 * the computation of va_fileid in
1675 			 * msdosfs_getattr.
1676 			 */
1677 			if (dentp->deAttributes & ATTR_DIRECTORY) {
1678 				cn = getushort(dentp->deStartCluster);
1679 				if (FAT32(pmp)) {
1680 					cn |= getushort(dentp->deHighClust) <<
1681 					    16;
1682 					if (cn == MSDOSFSROOT)
1683 						cn = pmp->pm_rootdirblk;
1684 				}
1685 				if (cn == MSDOSFSROOT && !FAT32(pmp))
1686 					dirbuf.d_fileno = 1;
1687 				else
1688 					dirbuf.d_fileno = cntobn(pmp, cn) *
1689 					    dirsperblk;
1690 				dirbuf.d_type = DT_DIR;
1691 			} else {
1692 				dirbuf.d_fileno = (uoff_t)offset /
1693 				    sizeof(struct direntry);
1694 				dirbuf.d_type = DT_REG;
1695 			}
1696 
1697 			if (chksum != winChksum(dentp->deName)) {
1698 				dirbuf.d_namlen = dos2unixfn(dentp->deName,
1699 				    (u_char *)dirbuf.d_name,
1700 				    dentp->deLowerCase |
1701 					((pmp->pm_flags & MSDOSFSMNT_SHORTNAME) ?
1702 					(LCASE_BASE | LCASE_EXT) : 0),
1703 				    pmp);
1704 				mbnambuf_init(&nb);
1705 			} else
1706 				mbnambuf_flush(&nb, &dirbuf);
1707 			chksum = -1;
1708 			dirbuf.d_reclen = GENERIC_DIRSIZ(&dirbuf);
1709 			/* NOTE: d_off is the offset of the *next* entry. */
1710 			dirbuf.d_off = offset + sizeof(struct direntry);
1711 			dirent_terminate(&dirbuf);
1712 			if (uio->uio_resid < dirbuf.d_reclen) {
1713 				brelse(bp);
1714 				goto out;
1715 			}
1716 			error = uiomove(&dirbuf, dirbuf.d_reclen, uio);
1717 			if (error) {
1718 				brelse(bp);
1719 				goto out;
1720 			}
1721 			if (cookies) {
1722 				*cookies++ = offset + sizeof(struct direntry);
1723 				if (--ncookies <= 0) {
1724 					brelse(bp);
1725 					goto out;
1726 				}
1727 			}
1728 			off = offset + sizeof(struct direntry);
1729 		}
1730 		brelse(bp);
1731 	}
1732 out:
1733 	/* Subtract unused cookies */
1734 	if (ap->a_ncookies)
1735 		*ap->a_ncookies -= ncookies;
1736 
1737 	uio->uio_offset = off;
1738 
1739 	/*
1740 	 * Set the eofflag (NFS uses it)
1741 	 */
1742 	if (ap->a_eofflag) {
1743 		if (dep->de_FileSize - (offset - bias) <= 0)
1744 			*ap->a_eofflag = 1;
1745 		else
1746 			*ap->a_eofflag = 0;
1747 	}
1748 	return (error);
1749 }
1750 
1751 /*-
1752  * a_vp   - pointer to the file's vnode
1753  * a_bn   - logical block number within the file (cluster number for us)
1754  * a_bop  - where to return the bufobj of the special file containing the fs
1755  * a_bnp  - where to return the "physical" block number corresponding to a_bn
1756  *          (relative to the special file; units are blocks of size DEV_BSIZE)
1757  * a_runp - where to return the "run past" a_bn.  This is the count of logical
1758  *          blocks whose physical blocks (together with a_bn's physical block)
1759  *          are contiguous.
1760  * a_runb - where to return the "run before" a_bn.
1761  */
1762 static int
1763 msdosfs_bmap(struct vop_bmap_args *ap)
1764 {
1765 	struct fatcache savefc;
1766 	struct denode *dep;
1767 	struct mount *mp;
1768 	struct msdosfsmount *pmp;
1769 	struct vnode *vp;
1770 	daddr_t runbn;
1771 	u_long cn;
1772 	int bnpercn, error, maxio, maxrun, run;
1773 
1774 	vp = ap->a_vp;
1775 	dep = VTODE(vp);
1776 	pmp = dep->de_pmp;
1777 	if (ap->a_bop != NULL)
1778 		*ap->a_bop = &pmp->pm_devvp->v_bufobj;
1779 	if (ap->a_bnp == NULL)
1780 		return (0);
1781 	if (ap->a_runp != NULL)
1782 		*ap->a_runp = 0;
1783 	if (ap->a_runb != NULL)
1784 		*ap->a_runb = 0;
1785 	cn = ap->a_bn;
1786 	if (cn != ap->a_bn)
1787 		return (EFBIG);
1788 	error = pcbmap(dep, cn, ap->a_bnp, NULL, NULL);
1789 	if (error != 0 || (ap->a_runp == NULL && ap->a_runb == NULL))
1790 		return (error);
1791 
1792 	/*
1793 	 * Prepare to back out updates of the fatchain cache after the one
1794 	 * for the first block done by pcbmap() above.  Without the backout,
1795 	 * then whenever the caller doesn't do i/o to all of the blocks that
1796 	 * we find, the single useful cache entry would be too far in advance
1797 	 * of the actual i/o to work for the next sequential i/o.  Then the
1798 	 * FAT would be searched from the beginning.  With the backout, the
1799 	 * FAT is searched starting at most a few blocks early.  This wastes
1800 	 * much less time.  Time is also wasted finding more blocks than the
1801 	 * caller will do i/o to.  This is necessary because the runlength
1802 	 * parameters are output-only.
1803 	 */
1804 	savefc = dep->de_fc[FC_LASTMAP];
1805 
1806 	mp = vp->v_mount;
1807 	maxio = mp->mnt_iosize_max / mp->mnt_stat.f_iosize;
1808 	bnpercn = de_cn2bn(pmp, 1);
1809 	if (ap->a_runp != NULL) {
1810 		maxrun = ulmin(maxio - 1, pmp->pm_maxcluster - cn);
1811 		for (run = 1; run <= maxrun; run++) {
1812 			if (pcbmap(dep, cn + run, &runbn, NULL, NULL) != 0 ||
1813 			    runbn != *ap->a_bnp + run * bnpercn)
1814 				break;
1815 		}
1816 		*ap->a_runp = run - 1;
1817 	}
1818 	if (ap->a_runb != NULL) {
1819 		maxrun = ulmin(maxio - 1, cn);
1820 		for (run = 1; run < maxrun; run++) {
1821 			if (pcbmap(dep, cn - run, &runbn, NULL, NULL) != 0 ||
1822 			    runbn != *ap->a_bnp - run * bnpercn)
1823 				break;
1824 		}
1825 		*ap->a_runb = run - 1;
1826 	}
1827 	dep->de_fc[FC_LASTMAP] = savefc;
1828 	return (0);
1829 }
1830 
1831 SYSCTL_NODE(_vfs, OID_AUTO, msdosfs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1832     "msdos filesystem");
1833 static int use_buf_pager = 1;
1834 SYSCTL_INT(_vfs_msdosfs, OID_AUTO, use_buf_pager, CTLFLAG_RWTUN,
1835     &use_buf_pager, 0,
1836     "Use buffer pager instead of bmap");
1837 
1838 static daddr_t
1839 msdosfs_gbp_getblkno(struct vnode *vp, vm_ooffset_t off)
1840 {
1841 
1842 	return (de_cluster(VTODE(vp)->de_pmp, off));
1843 }
1844 
1845 static int
1846 msdosfs_gbp_getblksz(struct vnode *vp, daddr_t lbn, long *sz)
1847 {
1848 
1849 	*sz = VTODE(vp)->de_pmp->pm_bpcluster;
1850 	return (0);
1851 }
1852 
1853 static int
1854 msdosfs_getpages(struct vop_getpages_args *ap)
1855 {
1856 
1857 	if (use_buf_pager)
1858 		return (vfs_bio_getpages(ap->a_vp, ap->a_m, ap->a_count,
1859 		    ap->a_rbehind, ap->a_rahead, msdosfs_gbp_getblkno,
1860 		    msdosfs_gbp_getblksz));
1861 	return (vnode_pager_generic_getpages(ap->a_vp, ap->a_m, ap->a_count,
1862 	    ap->a_rbehind, ap->a_rahead, NULL, NULL));
1863 }
1864 
1865 static int
1866 msdosfs_strategy(struct vop_strategy_args *ap)
1867 {
1868 	struct buf *bp = ap->a_bp;
1869 	struct denode *dep = VTODE(ap->a_vp);
1870 	struct bufobj *bo;
1871 	int error = 0;
1872 	daddr_t blkno;
1873 
1874 	/*
1875 	 * If we don't already know the filesystem relative block number
1876 	 * then get it using pcbmap().  If pcbmap() returns the block
1877 	 * number as -1 then we've got a hole in the file.  DOS filesystems
1878 	 * don't allow files with holes, so we shouldn't ever see this.
1879 	 */
1880 	if (bp->b_blkno == bp->b_lblkno) {
1881 		error = pcbmap(dep, bp->b_lblkno, &blkno, 0, 0);
1882 		bp->b_blkno = blkno;
1883 		if (error) {
1884 			bp->b_error = error;
1885 			bp->b_ioflags |= BIO_ERROR;
1886 			bufdone(bp);
1887 			return (0);
1888 		}
1889 		if ((long)bp->b_blkno == -1)
1890 			vfs_bio_clrbuf(bp);
1891 	}
1892 	if (bp->b_blkno == -1) {
1893 		bufdone(bp);
1894 		return (0);
1895 	}
1896 	/*
1897 	 * Read/write the block from/to the disk that contains the desired
1898 	 * file block.
1899 	 */
1900 	bp->b_iooffset = dbtob(bp->b_blkno);
1901 	bo = dep->de_pmp->pm_bo;
1902 	BO_STRATEGY(bo, bp);
1903 	return (0);
1904 }
1905 
1906 static int
1907 msdosfs_print(struct vop_print_args *ap)
1908 {
1909 	struct denode *dep = VTODE(ap->a_vp);
1910 
1911 	printf("\tstartcluster %lu, dircluster %lu, diroffset %lu, ",
1912 	       dep->de_StartCluster, dep->de_dirclust, dep->de_diroffset);
1913 	printf("on dev %s\n", devtoname(dep->de_pmp->pm_dev));
1914 	return (0);
1915 }
1916 
1917 static int
1918 msdosfs_pathconf(struct vop_pathconf_args *ap)
1919 {
1920 	struct msdosfsmount *pmp = VTODE(ap->a_vp)->de_pmp;
1921 
1922 	switch (ap->a_name) {
1923 	case _PC_FILESIZEBITS:
1924 		*ap->a_retval = 32;
1925 		return (0);
1926 	case _PC_LINK_MAX:
1927 		*ap->a_retval = 1;
1928 		return (0);
1929 	case _PC_NAME_MAX:
1930 		*ap->a_retval = pmp->pm_flags & MSDOSFSMNT_LONGNAME ? WIN_MAXLEN : 12;
1931 		return (0);
1932 	case _PC_CHOWN_RESTRICTED:
1933 		*ap->a_retval = 1;
1934 		return (0);
1935 	case _PC_NO_TRUNC:
1936 		*ap->a_retval = 0;
1937 		return (0);
1938 	default:
1939 		return (vop_stdpathconf(ap));
1940 	}
1941 	/* NOTREACHED */
1942 }
1943 
1944 static int
1945 msdosfs_vptofh(struct vop_vptofh_args *ap)
1946 {
1947 	struct denode *dep;
1948 	struct defid *defhp;
1949 
1950 	dep = VTODE(ap->a_vp);
1951 	defhp = (struct defid *)ap->a_fhp;
1952 	defhp->defid_len = sizeof(struct defid);
1953 	defhp->defid_dirclust = dep->de_dirclust;
1954 	defhp->defid_dirofs = dep->de_diroffset;
1955 	/* defhp->defid_gen = dep->de_gen; */
1956 	return (0);
1957 }
1958 
1959 /* Global vfs data structures for msdosfs */
1960 struct vop_vector msdosfs_vnodeops = {
1961 	.vop_default =		&default_vnodeops,
1962 
1963 	.vop_access =		msdosfs_access,
1964 	.vop_bmap =		msdosfs_bmap,
1965 	.vop_getpages =		msdosfs_getpages,
1966 	.vop_cachedlookup =	msdosfs_lookup,
1967 	.vop_open =		msdosfs_open,
1968 	.vop_close =		msdosfs_close,
1969 	.vop_create =		msdosfs_create,
1970 	.vop_fsync =		msdosfs_fsync,
1971 	.vop_fdatasync =	vop_stdfdatasync_buf,
1972 	.vop_getattr =		msdosfs_getattr,
1973 	.vop_inactive =		msdosfs_inactive,
1974 	.vop_link =		msdosfs_link,
1975 	.vop_lookup =		vfs_cache_lookup,
1976 	.vop_mkdir =		msdosfs_mkdir,
1977 	.vop_mknod =		msdosfs_mknod,
1978 	.vop_pathconf =		msdosfs_pathconf,
1979 	.vop_print =		msdosfs_print,
1980 	.vop_read =		msdosfs_read,
1981 	.vop_readdir =		msdosfs_readdir,
1982 	.vop_reclaim =		msdosfs_reclaim,
1983 	.vop_remove =		msdosfs_remove,
1984 	.vop_rename =		msdosfs_rename,
1985 	.vop_rmdir =		msdosfs_rmdir,
1986 	.vop_setattr =		msdosfs_setattr,
1987 	.vop_strategy =		msdosfs_strategy,
1988 	.vop_symlink =		msdosfs_symlink,
1989 	.vop_write =		msdosfs_write,
1990 	.vop_vptofh =		msdosfs_vptofh,
1991 };
1992 VFS_VOP_VECTOR_REGISTER(msdosfs_vnodeops);
1993