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