1/*	$NetBSD: nfs_vfsops.c,v 1.246 2024/05/13 00:11:22 msaitoh Exp $	*/
2
3/*
4 * Copyright (c) 1989, 1993, 1995
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Rick Macklem at The University of Guelph.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 *	@(#)nfs_vfsops.c	8.12 (Berkeley) 5/20/95
35 */
36
37#include <sys/cdefs.h>
38__KERNEL_RCSID(0, "$NetBSD: nfs_vfsops.c,v 1.246 2024/05/13 00:11:22 msaitoh Exp $");
39
40#if defined(_KERNEL_OPT)
41#include "opt_nfs.h"
42#endif
43
44#include <sys/param.h>
45#include <sys/ioctl.h>
46#include <sys/signal.h>
47#include <sys/proc.h>
48#include <sys/namei.h>
49#include <sys/device.h>
50#include <sys/vnode.h>
51#include <sys/kernel.h>
52#include <sys/mount.h>
53#include <sys/buf.h>
54#include <sys/mbuf.h>
55#include <sys/dirent.h>
56#include <sys/socket.h>
57#include <sys/socketvar.h>
58#include <sys/sysctl.h>
59#include <sys/systm.h>
60#include <sys/timetc.h>
61#include <sys/kauth.h>
62#include <sys/module.h>
63
64#include <net/if.h>
65#include <net/route.h>
66#include <netinet/in.h>
67
68#include <nfs/rpcv2.h>
69#include <nfs/nfsproto.h>
70#include <nfs/nfsnode.h>
71#include <nfs/nfs.h>
72#include <nfs/nfsmount.h>
73#include <nfs/xdr_subs.h>
74#include <nfs/nfsm_subs.h>
75#include <nfs/nfsdiskless.h>
76#include <nfs/nfs_var.h>
77
78MODULE(MODULE_CLASS_VFS, nfs, NULL);
79
80extern struct nfsstats nfsstats;
81extern int nfs_ticks;
82
83/*
84 * keep a count of the nfs mounts to generate fictitious drive names
85 * for the per drive stats.
86 */
87unsigned int nfs_mount_count = 0;
88
89int nfs_commitsize;
90
91/*
92 * nfs vfs operations.
93 */
94
95extern const struct vnodeopv_desc nfsv2_vnodeop_opv_desc;
96extern const struct vnodeopv_desc spec_nfsv2nodeop_opv_desc;
97extern const struct vnodeopv_desc fifo_nfsv2nodeop_opv_desc;
98
99const struct vnodeopv_desc * const nfs_vnodeopv_descs[] = {
100	&nfsv2_vnodeop_opv_desc,
101	&spec_nfsv2nodeop_opv_desc,
102	&fifo_nfsv2nodeop_opv_desc,
103	NULL,
104};
105
106struct vfsops nfs_vfsops = {
107	.vfs_name = MOUNT_NFS,
108	.vfs_min_mount_data = sizeof (struct nfs_args),
109	.vfs_mount = nfs_mount,
110	.vfs_start = nfs_start,
111	.vfs_unmount = nfs_unmount,
112	.vfs_root = nfs_root,
113	.vfs_quotactl = (void *)eopnotsupp,
114	.vfs_statvfs = nfs_statvfs,
115	.vfs_sync = nfs_sync,
116	.vfs_loadvnode = nfs_loadvnode,
117	.vfs_vget = nfs_vget,
118	.vfs_fhtovp = nfs_fhtovp,
119	.vfs_vptofh = nfs_vptofh,
120	.vfs_init = nfs_vfs_init,
121	.vfs_done = nfs_vfs_done,
122	.vfs_mountroot = nfs_mountroot,
123	.vfs_snapshot = (void *)eopnotsupp,
124	.vfs_extattrctl = vfs_stdextattrctl,
125	.vfs_suspendctl = genfs_suspendctl,
126	.vfs_renamelock_enter = genfs_renamelock_enter,
127	.vfs_renamelock_exit = genfs_renamelock_exit,
128	.vfs_fsync = (void *)eopnotsupp,
129	.vfs_opv_descs = nfs_vnodeopv_descs
130};
131
132extern u_int32_t nfs_procids[NFS_NPROCS];
133extern u_int32_t nfs_prog, nfs_vers;
134
135static int nfs_mount_diskless(struct nfs_dlmount *, const char *,
136    struct mount **, struct vnode **, struct lwp *);
137
138static int
139nfs_modcmd(modcmd_t cmd, void *arg)
140{
141	int error;
142
143	switch (cmd) {
144	case MODULE_CMD_INIT:
145		error = vfs_attach(&nfs_vfsops);
146		return error;
147	case MODULE_CMD_FINI:
148		error = vfs_detach(&nfs_vfsops);
149		return error;
150	default:
151		return ENOTTY;
152	}
153}
154
155/*
156 * nfs statvfs call
157 */
158int
159nfs_statvfs(struct mount *mp, struct statvfs *sbp)
160{
161	struct lwp *l = curlwp;
162	struct vnode *vp;
163	struct nfs_statfs *sfp;
164	char *cp;
165	u_int32_t *tl;
166	int32_t t1, t2;
167	char *bpos, *dpos, *cp2;
168	struct nfsmount *nmp = VFSTONFS(mp);
169	int error = 0, retattr;
170#ifdef NFS_V2_ONLY
171	const int v3 = 0;
172#else
173	int v3 = (nmp->nm_flag & NFSMNT_NFSV3);
174#endif
175	struct mbuf *mreq, *mrep = NULL, *md, *mb;
176	kauth_cred_t cred;
177	u_quad_t tquad;
178	struct nfsnode *np;
179
180#ifndef nolint
181	sfp = (struct nfs_statfs *)0;
182#endif
183	vp = nmp->nm_vnode;
184	np = VTONFS(vp);
185	cred = kauth_cred_alloc();
186#ifndef NFS_V2_ONLY
187	if (v3 && (nmp->nm_iflag & NFSMNT_GOTFSINFO) == 0)
188		(void)nfs_fsinfo(nmp, vp, cred, l);
189#endif
190	nfsstats.rpccnt[NFSPROC_FSSTAT]++;
191	nfsm_reqhead(np, NFSPROC_FSSTAT, NFSX_FH(v3));
192	nfsm_fhtom(np, v3);
193	nfsm_request(np, NFSPROC_FSSTAT, l, cred);
194	if (v3)
195		nfsm_postop_attr(vp, retattr, 0);
196	if (error) {
197		if (mrep != NULL) {
198			if (mrep->m_next != NULL)
199				printf("nfs_vfsops: nfs_statvfs would lose buffers\n");
200			m_freem(mrep);
201		}
202		goto nfsmout;
203	}
204	nfsm_dissect(sfp, struct nfs_statfs *, NFSX_STATFS(v3));
205	sbp->f_flag = nmp->nm_flag;
206	sbp->f_iosize = uimin(nmp->nm_rsize, nmp->nm_wsize);
207	if (v3) {
208		sbp->f_frsize = sbp->f_bsize = NFS_FABLKSIZE;
209		tquad = fxdr_hyper(&sfp->sf_tbytes);
210		sbp->f_blocks = ((quad_t)tquad / (quad_t)NFS_FABLKSIZE);
211		tquad = fxdr_hyper(&sfp->sf_fbytes);
212		sbp->f_bfree = ((quad_t)tquad / (quad_t)NFS_FABLKSIZE);
213		tquad = fxdr_hyper(&sfp->sf_abytes);
214		tquad = ((quad_t)tquad / (quad_t)NFS_FABLKSIZE);
215		sbp->f_bresvd = sbp->f_bfree - tquad;
216		sbp->f_bavail = tquad;
217		/* Handle older NFS servers returning negative values */
218		if ((quad_t)sbp->f_bavail < 0)
219			sbp->f_bavail = 0;
220		tquad = fxdr_hyper(&sfp->sf_tfiles);
221		sbp->f_files = tquad;
222		tquad = fxdr_hyper(&sfp->sf_ffiles);
223		sbp->f_ffree = tquad;
224		sbp->f_favail = tquad;
225		sbp->f_fresvd = 0;
226	} else {
227		sbp->f_bsize = NFS_FABLKSIZE;
228		sbp->f_frsize = fxdr_unsigned(int32_t, sfp->sf_bsize);
229		sbp->f_blocks = fxdr_unsigned(int32_t, sfp->sf_blocks);
230		sbp->f_bfree = fxdr_unsigned(int32_t, sfp->sf_bfree);
231		sbp->f_bavail = fxdr_unsigned(int32_t, sfp->sf_bavail);
232		sbp->f_fresvd = 0;
233		sbp->f_files = 0;
234		sbp->f_ffree = 0;
235		sbp->f_favail = 0;
236		sbp->f_fresvd = 0;
237	}
238	copy_statvfs_info(sbp, mp);
239	nfsm_reqdone;
240	kauth_cred_free(cred);
241	return (error);
242}
243
244#ifndef NFS_V2_ONLY
245/*
246 * nfs version 3 fsinfo rpc call
247 */
248int
249nfs_fsinfo(struct nfsmount *nmp, struct vnode *vp, kauth_cred_t cred, struct lwp *l)
250{
251	struct nfsv3_fsinfo *fsp;
252	char *cp;
253	int32_t t1, t2;
254	u_int32_t *tl, pref, xmax;
255	char *bpos, *dpos, *cp2;
256	int error = 0, retattr;
257	struct mbuf *mreq, *mrep, *md, *mb;
258	u_int64_t maxfsize;
259	struct nfsnode *np = VTONFS(vp);
260
261	nfsstats.rpccnt[NFSPROC_FSINFO]++;
262	nfsm_reqhead(np, NFSPROC_FSINFO, NFSX_FH(1));
263	nfsm_fhtom(np, 1);
264	nfsm_request(np, NFSPROC_FSINFO, l, cred);
265	nfsm_postop_attr(vp, retattr, 0);
266	if (!error) {
267		nfsm_dissect(fsp, struct nfsv3_fsinfo *, NFSX_V3FSINFO);
268		pref = fxdr_unsigned(u_int32_t, fsp->fs_wtpref);
269		if ((nmp->nm_flag & NFSMNT_WSIZE) == 0 &&
270		    pref < nmp->nm_wsize && pref >= NFS_FABLKSIZE)
271			nmp->nm_wsize = (pref + NFS_FABLKSIZE - 1) &
272				~(NFS_FABLKSIZE - 1);
273		xmax = fxdr_unsigned(u_int32_t, fsp->fs_wtmax);
274		if (xmax < nmp->nm_wsize && xmax > 0) {
275			nmp->nm_wsize = xmax & ~(NFS_FABLKSIZE - 1);
276			if (nmp->nm_wsize == 0)
277				nmp->nm_wsize = xmax;
278		}
279		pref = fxdr_unsigned(u_int32_t, fsp->fs_rtpref);
280		if ((nmp->nm_flag & NFSMNT_RSIZE) == 0 &&
281		    pref < nmp->nm_rsize && pref >= NFS_FABLKSIZE)
282			nmp->nm_rsize = (pref + NFS_FABLKSIZE - 1) &
283				~(NFS_FABLKSIZE - 1);
284		xmax = fxdr_unsigned(u_int32_t, fsp->fs_rtmax);
285		if (xmax < nmp->nm_rsize && xmax > 0) {
286			nmp->nm_rsize = xmax & ~(NFS_FABLKSIZE - 1);
287			if (nmp->nm_rsize == 0)
288				nmp->nm_rsize = xmax;
289		}
290		pref = fxdr_unsigned(u_int32_t, fsp->fs_dtpref);
291		if (pref < nmp->nm_readdirsize && pref >= NFS_DIRFRAGSIZ)
292			nmp->nm_readdirsize = (pref + NFS_DIRFRAGSIZ - 1) &
293				~(NFS_DIRFRAGSIZ - 1);
294		if (xmax < nmp->nm_readdirsize && xmax > 0) {
295			nmp->nm_readdirsize = xmax & ~(NFS_DIRFRAGSIZ - 1);
296			if (nmp->nm_readdirsize == 0)
297				nmp->nm_readdirsize = xmax;
298		}
299		nmp->nm_maxfilesize = 0xffffffffffffffffull;
300		maxfsize = fxdr_hyper(&fsp->fs_maxfilesize);
301		if (maxfsize > 0 && maxfsize < nmp->nm_maxfilesize)
302			nmp->nm_maxfilesize = maxfsize;
303		nmp->nm_mountp->mnt_fs_bshift =
304		    ffs(MIN(nmp->nm_rsize, nmp->nm_wsize)) - 1;
305		nmp->nm_iflag |= NFSMNT_GOTFSINFO;
306	}
307	nfsm_reqdone;
308	return (error);
309}
310#endif
311
312/*
313 * Mount a remote root fs via. NFS.  It goes like this:
314 * - Call nfs_boot_init() to fill in the nfs_diskless struct
315 * - build the rootfs mount point and call mountnfs() to do the rest.
316 */
317int
318nfs_mountroot(void)
319{
320	struct timespec ts;
321	struct nfs_diskless *nd;
322	struct vattr attr;
323	struct mount *mp;
324	struct vnode *vp;
325	struct lwp *l;
326	time_t n;
327	int error;
328
329	l = curlwp; /* XXX */
330
331	if (device_class(root_device) != DV_IFNET)
332		return (ENODEV);
333
334	/*
335	 * XXX time must be non-zero when we init the interface or else
336	 * the arp code will wedge.  [Fixed now in if_ether.c]
337	 * However, the NFS attribute cache gives false "hits" when the
338	 * current time < nfs_attrtimeo(nmp, np) so keep this in for now.
339	 */
340	if (time_second < NFS_MAXATTRTIMO) {
341		ts.tv_sec = NFS_MAXATTRTIMO;
342		ts.tv_nsec = 0;
343		tc_setclock(&ts);
344	}
345
346	/*
347	 * Call nfs_boot_init() to fill in the nfs_diskless struct.
348	 * Side effect:  Finds and configures a network interface.
349	 */
350	nd = kmem_zalloc(sizeof(*nd), KM_SLEEP);
351	error = nfs_boot_init(nd, l);
352	if (error) {
353		kmem_free(nd, sizeof(*nd));
354		return (error);
355	}
356
357	/*
358	 * Create the root mount point.
359	 */
360	error = nfs_mount_diskless(&nd->nd_root, "/", &mp, &vp, l);
361	if (error)
362		goto out;
363	printf("root on %s\n", nd->nd_root.ndm_host);
364
365	/*
366	 * Link it into the mount list.
367	 */
368	mountlist_append(mp);
369	rootvp = vp;
370	mp->mnt_vnodecovered = NULLVP;
371	vfs_unbusy(mp);
372
373	/* Get root attributes (for the time). */
374	vn_lock(vp, LK_SHARED | LK_RETRY);
375	error = VOP_GETATTR(vp, &attr, l->l_cred);
376	VOP_UNLOCK(vp);
377	if (error)
378		panic("nfs_mountroot: getattr for root");
379	n = attr.va_atime.tv_sec;
380#ifdef	DEBUG
381	printf("root time: 0x%jx\n", (intmax_t)n);
382#endif
383	setrootfstime(n);
384
385out:
386	if (error)
387		nfs_boot_cleanup(nd, l);
388	kmem_free(nd, sizeof(*nd));
389	return (error);
390}
391
392/*
393 * Internal version of mount system call for diskless setup.
394 * Separate function because we used to call it twice.
395 * (once for root and once for swap)
396 */
397static int
398nfs_mount_diskless(struct nfs_dlmount *ndmntp, const char *mntname, struct mount **mpp, struct vnode **vpp, struct lwp *l)
399	/* mntname:	 mount point name */
400{
401	struct mount *mp;
402	struct mbuf *m;
403	int error;
404
405	vfs_rootmountalloc(MOUNT_NFS, mntname, &mp);
406
407	mp->mnt_op = &nfs_vfsops;
408
409	/*
410	 * Historical practice expects NFS root file systems to
411	 * be initially mounted r/w.
412	 */
413	mp->mnt_flag &= ~MNT_RDONLY;
414
415	/* Get mbuf for server sockaddr. */
416	m = m_get(M_WAIT, MT_SONAME);
417	if (m == NULL)
418		panic("nfs_mountroot: mget soname for %s", mntname);
419	MCLAIM(m, &nfs_mowner);
420	memcpy(mtod(m, void *), (void *)ndmntp->ndm_args.addr,
421	      (m->m_len = ndmntp->ndm_args.addr->sa_len));
422
423	error = mountnfs(&ndmntp->ndm_args, mp, m, mntname,
424			 ndmntp->ndm_args.hostname, vpp, l);
425	if (error) {
426		vfs_unbusy(mp);
427		vfs_rele(mp);
428		printf("nfs_mountroot: mount %s failed: %d\n",
429		       mntname, error);
430	} else
431		*mpp = mp;
432
433	return (error);
434}
435
436void
437nfs_decode_args(struct nfsmount *nmp, struct nfs_args *argp, struct lwp *l)
438{
439	int s;
440	int adjsock;
441	int maxio;
442
443	s = splsoftnet();
444
445	/*
446	 * Silently clear NFSMNT_NOCONN if it's a TCP mount, it makes
447	 * no sense in that context.
448	 */
449	if (argp->sotype == SOCK_STREAM)
450		argp->flags &= ~NFSMNT_NOCONN;
451
452	/*
453	 * Cookie translation is not needed for v2, silently ignore it.
454	 */
455	if ((argp->flags & (NFSMNT_XLATECOOKIE|NFSMNT_NFSV3)) ==
456	    NFSMNT_XLATECOOKIE)
457		argp->flags &= ~NFSMNT_XLATECOOKIE;
458
459	/* Re-bind if rsrvd port requested and wasn't on one */
460	adjsock = !(nmp->nm_flag & NFSMNT_RESVPORT)
461		  && (argp->flags & NFSMNT_RESVPORT);
462	/* Also re-bind if we're switching to/from a connected UDP socket */
463	adjsock |= ((nmp->nm_flag & NFSMNT_NOCONN) !=
464		    (argp->flags & NFSMNT_NOCONN));
465
466	/* Update flags. */
467	nmp->nm_flag = argp->flags;
468	splx(s);
469
470	if ((argp->flags & NFSMNT_TIMEO) && argp->timeo > 0) {
471		nmp->nm_timeo = (argp->timeo * NFS_HZ + 5) / 10;
472		if (nmp->nm_timeo < NFS_MINTIMEO)
473			nmp->nm_timeo = NFS_MINTIMEO;
474		else if (nmp->nm_timeo > NFS_MAXTIMEO)
475			nmp->nm_timeo = NFS_MAXTIMEO;
476	}
477
478	if ((argp->flags & NFSMNT_RETRANS) && argp->retrans > 1) {
479		nmp->nm_retry = argp->retrans;
480		if (nmp->nm_retry > NFS_MAXREXMIT)
481			nmp->nm_retry = NFS_MAXREXMIT;
482	}
483
484#ifndef NFS_V2_ONLY
485	if (argp->flags & NFSMNT_NFSV3) {
486		if (argp->sotype == SOCK_DGRAM)
487			maxio = NFS_MAXDGRAMDATA;
488		else
489			maxio = NFS_MAXDATA;
490	} else
491#endif
492		maxio = NFS_V2MAXDATA;
493
494	if ((argp->flags & NFSMNT_WSIZE) && argp->wsize > 0) {
495		int osize = nmp->nm_wsize;
496		nmp->nm_wsize = argp->wsize;
497		/* Round down to multiple of blocksize */
498		nmp->nm_wsize &= ~(NFS_FABLKSIZE - 1);
499		if (nmp->nm_wsize <= 0)
500			nmp->nm_wsize = NFS_FABLKSIZE;
501		adjsock |= (nmp->nm_wsize != osize);
502	}
503	if (nmp->nm_wsize > maxio)
504		nmp->nm_wsize = maxio;
505	if (nmp->nm_wsize > MAXBSIZE)
506		nmp->nm_wsize = MAXBSIZE;
507
508	if ((argp->flags & NFSMNT_RSIZE) && argp->rsize > 0) {
509		int osize = nmp->nm_rsize;
510		nmp->nm_rsize = argp->rsize;
511		/* Round down to multiple of blocksize */
512		nmp->nm_rsize &= ~(NFS_FABLKSIZE - 1);
513		if (nmp->nm_rsize <= 0)
514			nmp->nm_rsize = NFS_FABLKSIZE;
515		adjsock |= (nmp->nm_rsize != osize);
516	}
517	if (nmp->nm_rsize > maxio)
518		nmp->nm_rsize = maxio;
519	if (nmp->nm_rsize > MAXBSIZE)
520		nmp->nm_rsize = MAXBSIZE;
521
522	if ((argp->flags & NFSMNT_READDIRSIZE) && argp->readdirsize > 0) {
523		nmp->nm_readdirsize = argp->readdirsize;
524		/* Round down to multiple of minimum blocksize */
525		nmp->nm_readdirsize &= ~(NFS_DIRFRAGSIZ - 1);
526		if (nmp->nm_readdirsize < NFS_DIRFRAGSIZ)
527			nmp->nm_readdirsize = NFS_DIRFRAGSIZ;
528		/* Bigger than buffer size makes no sense */
529		if (nmp->nm_readdirsize > NFS_DIRBLKSIZ)
530			nmp->nm_readdirsize = NFS_DIRBLKSIZ;
531	} else if (argp->flags & NFSMNT_RSIZE)
532		nmp->nm_readdirsize = nmp->nm_rsize;
533
534	if (nmp->nm_readdirsize > maxio)
535		nmp->nm_readdirsize = maxio;
536
537	if ((argp->flags & NFSMNT_MAXGRPS) && argp->maxgrouplist >= 0 &&
538		argp->maxgrouplist <= NFS_MAXGRPS)
539		nmp->nm_numgrps = argp->maxgrouplist;
540	if ((argp->flags & NFSMNT_READAHEAD) && argp->readahead >= 0 &&
541		argp->readahead <= NFS_MAXRAHEAD)
542		nmp->nm_readahead = argp->readahead;
543	if ((argp->flags & NFSMNT_DEADTHRESH) && argp->deadthresh >= 1 &&
544		argp->deadthresh <= NFS_NEVERDEAD)
545		nmp->nm_deadthresh = argp->deadthresh;
546
547	adjsock |= ((nmp->nm_sotype != argp->sotype) ||
548		    (nmp->nm_soproto != argp->proto));
549	nmp->nm_sotype = argp->sotype;
550	nmp->nm_soproto = argp->proto;
551
552	if (nmp->nm_so && adjsock) {
553		nfs_safedisconnect(nmp);
554		if (nmp->nm_sotype == SOCK_DGRAM)
555			while (nfs_connect(nmp, (struct nfsreq *)0, l)) {
556				printf("nfs_args: retrying connect\n");
557				kpause("nfscn3", false, hz, NULL);
558			}
559	}
560}
561
562/*
563 * VFS Operations.
564 *
565 * mount system call
566 * It seems a bit dumb to copyinstr() the host and path here and then
567 * memcpy() them in mountnfs(), but I wanted to detect errors before
568 * doing the sockargs() call because sockargs() allocates an mbuf and
569 * an error after that means that I have to release the mbuf.
570 */
571/* ARGSUSED */
572int
573nfs_mount(struct mount *mp, const char *path, void *data, size_t *data_len)
574{
575	struct lwp *l = curlwp;
576	int error;
577	struct nfs_args *args = data;
578	struct mbuf *nam;
579	struct nfsmount *nmp = VFSTONFS(mp);
580	struct sockaddr *sa;
581	struct vnode *vp;
582	char *pth, *hst;
583	size_t len;
584	u_char *nfh;
585
586	if (args == NULL)
587		return EINVAL;
588	if (*data_len < sizeof *args)
589		return EINVAL;
590
591	if (mp->mnt_flag & MNT_GETARGS) {
592
593		if (nmp == NULL)
594			return (EIO);
595		if (args->addr != NULL) {
596			sa = mtod(nmp->nm_nam, struct sockaddr *);
597			error = copyout(sa, args->addr, sa->sa_len);
598			if (error)
599				return (error);
600			args->addrlen = sa->sa_len;
601		} else
602			args->addrlen = 0;
603
604		args->version = NFS_ARGSVERSION;
605		args->sotype = nmp->nm_sotype;
606		args->proto = nmp->nm_soproto;
607		args->fh = NULL;
608		args->fhsize = 0;
609		args->flags = nmp->nm_flag;
610		args->wsize = nmp->nm_wsize;
611		args->rsize = nmp->nm_rsize;
612		args->readdirsize = nmp->nm_readdirsize;
613		args->timeo = nmp->nm_timeo;
614		args->retrans = nmp->nm_retry;
615		args->maxgrouplist = nmp->nm_numgrps;
616		args->readahead = nmp->nm_readahead;
617		args->leaseterm = 0; /* dummy */
618		args->deadthresh = nmp->nm_deadthresh;
619		args->hostname = NULL;
620		*data_len = sizeof *args;
621		return 0;
622	}
623
624	if (args->version != NFS_ARGSVERSION)
625		return (EPROGMISMATCH);
626	if (args->flags & (NFSMNT_NQNFS|NFSMNT_KERB))
627		return (EPROGUNAVAIL);
628#ifdef NFS_V2_ONLY
629	if (args->flags & NFSMNT_NFSV3)
630		return (EPROGMISMATCH);
631#endif
632	if (mp->mnt_flag & MNT_UPDATE) {
633		if (nmp == NULL)
634			return (EIO);
635		/*
636		 * When doing an update, we can't change from or to
637		 * v3, or change cookie translation
638		 */
639		args->flags = (args->flags & ~(NFSMNT_NFSV3|NFSMNT_XLATECOOKIE)) |
640		    (nmp->nm_flag & (NFSMNT_NFSV3|NFSMNT_XLATECOOKIE));
641		nfs_decode_args(nmp, args, l);
642		return (0);
643	}
644	if (args->fhsize < 0 || args->fhsize > NFSX_V3FHMAX)
645		return (EINVAL);
646	nfh = malloc(NFSX_V3FHMAX, M_TEMP, M_WAITOK);
647	error = copyin(args->fh, nfh, args->fhsize);
648	if (error)
649		goto free_nfh;
650	pth = malloc(MNAMELEN, M_TEMP, M_WAITOK);
651	error = copyinstr(path, pth, MNAMELEN - 1, &len);
652	if (error)
653		goto free_pth;
654	memset(&pth[len], 0, MNAMELEN - len);
655	hst = malloc(MNAMELEN, M_TEMP, M_WAITOK);
656	error = copyinstr(args->hostname, hst, MNAMELEN - 1, &len);
657	if (error)
658		goto free_hst;
659	memset(&hst[len], 0, MNAMELEN - len);
660	/* sockargs() call must be after above copyin() calls */
661	error = sockargs(&nam, args->addr, args->addrlen, UIO_USERSPACE,
662	    MT_SONAME);
663	if (error)
664		goto free_hst;
665	MCLAIM(nam, &nfs_mowner);
666	args->fh = nfh;
667	error = mountnfs(args, mp, nam, pth, hst, &vp, l);
668
669free_hst:
670	free(hst, M_TEMP);
671free_pth:
672	free(pth, M_TEMP);
673free_nfh:
674	free(nfh, M_TEMP);
675
676	return (error);
677}
678
679/*
680 * Common code for mount and mountroot
681 */
682int
683mountnfs(struct nfs_args *argp, struct mount *mp, struct mbuf *nam, const char *pth, const char *hst, struct vnode **vpp, struct lwp *l)
684{
685	struct nfsmount *nmp;
686	struct nfsnode *np;
687	struct vnode *vp;
688	int error;
689	struct vattr *attrs;
690	kauth_cred_t cr;
691	char iosname[IOSTATNAMELEN];
692
693	/*
694	 * If the number of nfs iothreads to use has never
695	 * been set, create a reasonable number of them.
696	 */
697
698	if (nfs_niothreads < 0) {
699		nfs_set_niothreads(NFS_DEFAULT_NIOTHREADS);
700	}
701
702	if (mp->mnt_flag & MNT_UPDATE) {
703		nmp = VFSTONFS(mp);
704		/* update paths, file handles, etc, here	XXX */
705		m_freem(nam);
706		return 0;
707	}
708	nmp = kmem_zalloc(sizeof(*nmp), KM_SLEEP);
709	TAILQ_INIT(&nmp->nm_uidlruhead);
710	TAILQ_INIT(&nmp->nm_bufq);
711	rw_init(&nmp->nm_writeverflock);
712	mutex_init(&nmp->nm_lock, MUTEX_DEFAULT, IPL_NONE);
713	cv_init(&nmp->nm_rcvcv, "nfsrcv");
714	cv_init(&nmp->nm_sndcv, "nfssnd");
715	cv_init(&nmp->nm_aiocv, "nfsaio");
716	cv_init(&nmp->nm_disconcv, "nfsdis");
717
718	mp->mnt_data = nmp;
719	mp->mnt_stat.f_namemax = NFS_MAXNAMLEN;
720	vfs_getnewfsid(mp);
721	nmp->nm_mountp = mp;
722
723#ifndef NFS_V2_ONLY
724	if ((argp->flags & NFSMNT_NFSV3) == 0)
725#endif
726	{
727		if (argp->fhsize != NFSX_V2FH) {
728			return EINVAL;
729		}
730	}
731
732	/*
733	 * V2 can only handle 32 bit filesizes. For v3, nfs_fsinfo
734	 * will overwrite this.
735	 */
736	nmp->nm_maxfilesize = 0xffffffffLL;
737
738	nmp->nm_timeo = NFS_TIMEO;
739	nmp->nm_retry = NFS_RETRANS;
740	nmp->nm_wsize = NFS_WSIZE;
741	nmp->nm_rsize = NFS_RSIZE;
742	nmp->nm_readdirsize = NFS_READDIRSIZE;
743	nmp->nm_numgrps = NFS_MAXGRPS;
744	nmp->nm_readahead = NFS_DEFRAHEAD;
745	nmp->nm_deadthresh = NFS_DEFDEADTHRESH;
746	error = set_statvfs_info(pth, UIO_SYSSPACE, hst, UIO_SYSSPACE,
747	    mp->mnt_op->vfs_name, mp, l);
748	if (error)
749		goto bad;
750	nmp->nm_nam = nam;
751
752	/* Set up the sockets and per-host congestion */
753	nmp->nm_sotype = argp->sotype;
754	nmp->nm_soproto = argp->proto;
755
756	nfs_decode_args(nmp, argp, l);
757
758	mp->mnt_fs_bshift = ffs(MIN(nmp->nm_rsize, nmp->nm_wsize)) - 1;
759	mp->mnt_dev_bshift = DEV_BSHIFT;
760
761	/*
762	 * For Connection based sockets (TCP,...) defer the connect until
763	 * the first request, in case the server is not responding.
764	 */
765	if (nmp->nm_sotype == SOCK_DGRAM &&
766		(error = nfs_connect(nmp, (struct nfsreq *)0, l)))
767		goto bad;
768
769	/*
770	 * This is silly, but it has to be set so that vinifod() works.
771	 * We do not want to do an nfs_statvfs() here since we can get
772	 * stuck on a dead server and we are holding a lock on the mount
773	 * point.
774	 */
775	mp->mnt_stat.f_iosize = NFS_MAXDGRAMDATA;
776	error = nfs_nget(mp, (nfsfh_t *)argp->fh, argp->fhsize, &np);
777	if (error)
778		goto bad;
779	vp = NFSTOV(np);
780	attrs = malloc(sizeof(struct vattr), M_TEMP, M_WAITOK);
781	VOP_GETATTR(vp, attrs, l->l_cred);
782	if ((nmp->nm_flag & NFSMNT_NFSV3) && (vp->v_type == VDIR)) {
783		cr = kauth_cred_alloc();
784		kauth_cred_setuid(cr, attrs->va_uid);
785		kauth_cred_seteuid(cr, attrs->va_uid);
786		kauth_cred_setsvuid(cr, attrs->va_uid);
787		kauth_cred_setgid(cr, attrs->va_gid);
788		kauth_cred_setegid(cr, attrs->va_gid);
789		kauth_cred_setsvgid(cr, attrs->va_gid);
790		nfs_cookieheuristic(vp, &nmp->nm_iflag, l, cr);
791		kauth_cred_free(cr);
792	}
793	free(attrs, M_TEMP);
794
795	/*
796	 * A reference count is needed on the nfsnode representing the
797	 * remote root.  If this object is not persistent, then backward
798	 * traversals of the mount point (i.e. "..") will not work if
799	 * the nfsnode gets flushed out of the cache. Ufs does not have
800	 * this problem, because one can identify root inodes by their
801	 * number == UFS_ROOTINO (2). So, just unlock, but no rele.
802	 */
803
804	nmp->nm_vnode = vp;
805	if (vp->v_type == VNON)
806		vp->v_type = VDIR;
807	vp->v_vflag |= VV_ROOT;
808	VOP_UNLOCK(vp);
809	*vpp = vp;
810
811	snprintf(iosname, sizeof(iosname), "nfs%u", nfs_mount_count++);
812	nmp->nm_stats = iostat_alloc(IOSTAT_NFS, nmp, iosname);
813
814	return (0);
815bad:
816	nfs_disconnect(nmp);
817	rw_destroy(&nmp->nm_writeverflock);
818	mutex_destroy(&nmp->nm_lock);
819	cv_destroy(&nmp->nm_rcvcv);
820	cv_destroy(&nmp->nm_sndcv);
821	cv_destroy(&nmp->nm_aiocv);
822	cv_destroy(&nmp->nm_disconcv);
823	kmem_free(nmp, sizeof(*nmp));
824	m_freem(nam);
825	return (error);
826}
827
828/*
829 * unmount system call
830 */
831int
832nfs_unmount(struct mount *mp, int mntflags)
833{
834	struct nfsmount *nmp = VFSTONFS(mp);
835	struct vnode *vp;
836	int error, flags = 0;
837
838	if (mntflags & MNT_FORCE) {
839		mutex_enter(&nmp->nm_lock);
840		flags |= FORCECLOSE;
841		nmp->nm_iflag |= NFSMNT_DISMNTFORCE;
842		mutex_exit(&nmp->nm_lock);
843
844	}
845
846	/*
847	 * Goes something like this..
848	 * - Check for activity on the root vnode (other than ourselves).
849	 * - Call vflush() to clear out vnodes for this file system,
850	 *   except for the root vnode.
851	 * - Decrement reference on the vnode representing remote root.
852	 * - Close the socket
853	 * - Free up the data structures
854	 */
855	/*
856	 * We need to decrement the ref. count on the nfsnode representing
857	 * the remote root.  See comment in mountnfs().
858	 */
859	vp = nmp->nm_vnode;
860	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
861	if (error != 0)
862		goto err;
863
864	if ((mntflags & MNT_FORCE) == 0 && vrefcnt(vp) > 1) {
865		VOP_UNLOCK(vp);
866		error = EBUSY;
867		goto err;
868	}
869
870	error = vflush(mp, vp, flags);
871	if (error) {
872		VOP_UNLOCK(vp);
873		goto err;
874	}
875
876	/*
877	 * We are now committed to the unmount; mark the mount structure
878	 * as doomed so that any sleepers kicked awake by nfs_disconnect
879	 * will go away cleanly.
880	 */
881	nmp->nm_iflag |= NFSMNT_DISMNT;
882
883	/*
884	 * No new async I/O will be added, but await for pending
885	 * ones to drain.
886	 */
887	while (nfs_iodbusy(nmp))
888		kpause("nfsumnt", false, hz, NULL);
889
890	/*
891	 * Clean up the stats... note that we carefully avoid decrementing
892	 * nfs_mount_count here for good reason - we may not be unmounting
893	 * the last thing mounted.
894	 */
895	iostat_free(nmp->nm_stats);
896
897	/*
898	 * There is one reference count to get rid of here
899	 * (see comment in mountnfs()).
900	 */
901	VOP_UNLOCK(vp);
902	vgone(vp);
903	nfs_disconnect(nmp);
904	m_freem(nmp->nm_nam);
905
906	rw_destroy(&nmp->nm_writeverflock);
907	mutex_destroy(&nmp->nm_lock);
908	cv_destroy(&nmp->nm_rcvcv);
909	cv_destroy(&nmp->nm_sndcv);
910	cv_destroy(&nmp->nm_aiocv);
911	cv_destroy(&nmp->nm_disconcv);
912	kmem_free(nmp, sizeof(*nmp));
913	return (0);
914
915err:
916	if (mntflags & MNT_FORCE) {
917		mutex_enter(&nmp->nm_lock);
918		nmp->nm_iflag &= ~NFSMNT_DISMNTFORCE;
919		mutex_exit(&nmp->nm_lock);
920	}
921
922	return error;
923}
924
925/*
926 * Return root of a filesystem
927 */
928int
929nfs_root(struct mount *mp, int lktype, struct vnode **vpp)
930{
931	struct vnode *vp;
932	struct nfsmount *nmp;
933	int error;
934
935	nmp = VFSTONFS(mp);
936	vp = nmp->nm_vnode;
937	vref(vp);
938	error = vn_lock(vp, lktype | LK_RETRY);
939	if (error != 0) {
940		vrele(vp);
941		return error;
942	}
943	*vpp = vp;
944	return (0);
945}
946
947extern int syncprt;
948
949static bool
950nfs_sync_selector(void *cl, struct vnode *vp)
951{
952
953	KASSERT(mutex_owned(vp->v_interlock));
954
955	return !LIST_EMPTY(&vp->v_dirtyblkhd) ||
956	    (vp->v_iflag & VI_ONWORKLST) != 0;
957}
958
959/*
960 * Flush out the buffer cache
961 */
962/* ARGSUSED */
963int
964nfs_sync(struct mount *mp, int waitfor, kauth_cred_t cred)
965{
966	struct vnode *vp;
967	struct vnode_iterator *marker;
968	int error, allerror = 0;
969
970	/*
971	 * Force stale buffer cache information to be flushed.
972	 */
973	vfs_vnode_iterator_init(mp, &marker);
974	while ((vp = vfs_vnode_iterator_next(marker, nfs_sync_selector,
975	    NULL)))
976	{
977		error = vn_lock(vp, LK_EXCLUSIVE);
978		if (error) {
979			vrele(vp);
980			continue;
981		}
982		error = VOP_FSYNC(vp, cred,
983		    waitfor == MNT_WAIT ? FSYNC_WAIT : 0, 0, 0);
984		if (error)
985			allerror = error;
986		vput(vp);
987	}
988	vfs_vnode_iterator_destroy(marker);
989	return allerror;
990}
991
992/*
993 * NFS flat namespace lookup.
994 * Currently unsupported.
995 */
996/* ARGSUSED */
997int
998nfs_vget(struct mount *mp, ino_t ino, int lktype, struct vnode **vpp)
999{
1000
1001	return (EOPNOTSUPP);
1002}
1003
1004/*
1005 * Do that sysctl thang...
1006 */
1007static int
1008sysctl_vfs_nfs_iothreads(SYSCTLFN_ARGS)
1009{
1010	struct sysctlnode node;
1011	int val;
1012	int error;
1013
1014	val = nfs_niothreads;
1015	node = *rnode;
1016	node.sysctl_data = &val;
1017        error = sysctl_lookup(SYSCTLFN_CALL(&node));
1018	if (error || newp == NULL)
1019		return error;
1020
1021	return nfs_set_niothreads(val);
1022}
1023
1024SYSCTL_SETUP(nfs_sysctl_init, "nfs sysctl")
1025{
1026
1027	sysctl_createv(clog, 0, NULL, NULL,
1028		       CTLFLAG_PERMANENT,
1029		       CTLTYPE_NODE, "nfs",
1030		       SYSCTL_DESCR("NFS vfs options"),
1031		       NULL, 0, NULL, 0,
1032		       CTL_VFS, 2, CTL_EOL);
1033	/*
1034	 * XXX the "2" above could be dynamic, thereby eliminating one
1035	 * more instance of the "number to vfs" mapping problem, but
1036	 * "2" is the order as taken from sys/mount.h
1037	 */
1038
1039	sysctl_createv(clog, 0, NULL, NULL,
1040		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1041		       CTLTYPE_STRUCT, "nfsstats",
1042		       SYSCTL_DESCR("NFS operation statistics"),
1043		       NULL, 0, &nfsstats, sizeof(nfsstats),
1044		       CTL_VFS, 2, NFS_NFSSTATS, CTL_EOL);
1045	sysctl_createv(clog, 0, NULL, NULL,
1046		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1047		       CTLTYPE_INT, "iothreads",
1048		       SYSCTL_DESCR("Number of NFS client processes desired"),
1049		       sysctl_vfs_nfs_iothreads, 0, NULL, 0,
1050		       CTL_VFS, 2, NFS_IOTHREADS, CTL_EOL);
1051}
1052
1053/* ARGSUSED */
1054int
1055nfs_fhtovp(struct mount *mp, struct fid *fid, int lktype, struct vnode **vpp)
1056{
1057	size_t fidsize;
1058	size_t fhsize;
1059	struct nfsnode *np;
1060	int error;
1061	struct vattr va;
1062
1063	fidsize = fid->fid_len;
1064	if (fidsize < sizeof(*fid)) {
1065		return EINVAL;
1066	}
1067	fhsize = fidsize - sizeof(*fid);
1068	if ((fhsize % NFSX_UNSIGNED) != 0) {
1069		return EINVAL;
1070	}
1071	if ((VFSTONFS(mp)->nm_flag & NFSMNT_NFSV3) != 0) {
1072		if (fhsize > NFSX_V3FHMAX || fhsize == 0) {
1073			return EINVAL;
1074		}
1075	} else {
1076		if (fhsize != NFSX_V2FH) {
1077			return EINVAL;
1078		}
1079	}
1080	/* XXX lktype ignored */
1081	error = nfs_nget(mp, (void *)fid->fid_data, fhsize, &np);
1082	if (error) {
1083		return error;
1084	}
1085	*vpp = NFSTOV(np);
1086	error = VOP_GETATTR(*vpp, &va, kauth_cred_get());
1087	if (error != 0) {
1088		vput(*vpp);
1089		*vpp = NULLVP;
1090	}
1091	return error;
1092}
1093
1094/* ARGSUSED */
1095int
1096nfs_vptofh(struct vnode *vp, struct fid *buf, size_t *bufsize)
1097{
1098	struct nfsnode *np;
1099	struct fid *fid;
1100	size_t fidsize;
1101	int error = 0;
1102
1103	np = VTONFS(vp);
1104	fidsize = sizeof(*fid) + np->n_fhsize;
1105	if (*bufsize < fidsize) {
1106		error = E2BIG;
1107	}
1108	*bufsize = fidsize;
1109	if (error == 0) {
1110		struct fid fid_store;
1111
1112		fid = &fid_store;
1113		memset(fid, 0, sizeof(*fid));
1114		fid->fid_len = fidsize;
1115		memcpy(buf, fid, sizeof(*fid));
1116		memcpy(buf->fid_data, np->n_fhp, np->n_fhsize);
1117	}
1118	return error;
1119}
1120
1121/*
1122 * Vfs start routine, a no-op.
1123 */
1124/* ARGSUSED */
1125int
1126nfs_start(struct mount *mp, int flags)
1127{
1128
1129	return (0);
1130}
1131
1132/*
1133 * Called once at VFS init to initialize client-specific data structures.
1134 */
1135void
1136nfs_vfs_init(void)
1137{
1138	unsigned scale;
1139
1140	/* Initialize NFS server / client shared data. */
1141	nfs_init();
1142	nfs_node_init();
1143
1144	/* Initialize the kqueue structures */
1145	nfs_kqinit();
1146	/* Initialize the iod structures */
1147	nfs_iodinit();
1148
1149	scale = PAGE_SHIFT - 4;
1150	nfs_commitsize = uimin(uvmexp.npages, INT_MAX >> scale) << scale;
1151}
1152
1153void
1154nfs_vfs_done(void)
1155{
1156
1157	nfs_node_done();
1158	nfs_kqfini();
1159	nfs_iodfini();
1160	nfs_fini();
1161}
1162