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