xref: /linux/fs/nfsd/nfsctl.c (revision d141ec2825b4d3ec52f27c43bdd864090159273a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Syscall interface to knfsd.
4  *
5  * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
6  */
7 
8 #include <linux/slab.h>
9 #include <linux/namei.h>
10 #include <linux/ctype.h>
11 #include <linux/fs_context.h>
12 
13 #include <linux/sunrpc/cache.h>
14 #include <linux/sunrpc/svcsock.h>
15 #include <linux/lockd/bind.h>
16 #include <linux/sunrpc/addr.h>
17 #include <linux/sunrpc/gss_api.h>
18 #include <linux/sunrpc/rpc_pipe_fs.h>
19 #include <linux/sunrpc/svc.h>
20 #include <linux/module.h>
21 #include <linux/fsnotify.h>
22 #include <linux/nfslocalio.h>
23 
24 #include "idmap.h"
25 #include "nfsd.h"
26 #include "netns.h"
27 #include "stats.h"
28 #include "cache.h"
29 #include "state.h"
30 #include "netns.h"
31 #include "pnfs.h"
32 #include "filecache.h"
33 #include "trace.h"
34 #include "netlink.h"
35 
36 /*
37  *	We have a single directory with several nodes in it.
38  */
39 enum {
40 	NFSD_Root = 1,
41 	NFSD_List,
42 	NFSD_Export_Stats,
43 	NFSD_Export_features,
44 	NFSD_Fh,
45 	NFSD_FO_UnlockIP,
46 	NFSD_FO_UnlockFS,
47 	NFSD_Threads,
48 	NFSD_Pool_Threads,
49 	NFSD_Pool_Stats,
50 	NFSD_Reply_Cache_Stats,
51 	NFSD_Versions,
52 	NFSD_Ports,
53 	NFSD_MaxBlkSize,
54 	NFSD_Filecache,
55 	NFSD_Leasetime,
56 	NFSD_Gracetime,
57 	NFSD_RecoveryDir,
58 	NFSD_V4EndGrace,
59 	NFSD_MaxReserved
60 };
61 
62 /*
63  * write() for these nodes.
64  */
65 static ssize_t write_filehandle(struct file *file, char *buf, size_t size);
66 static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size);
67 static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size);
68 static ssize_t write_threads(struct file *file, char *buf, size_t size);
69 static ssize_t write_pool_threads(struct file *file, char *buf, size_t size);
70 static ssize_t write_versions(struct file *file, char *buf, size_t size);
71 static ssize_t write_ports(struct file *file, char *buf, size_t size);
72 static ssize_t write_maxblksize(struct file *file, char *buf, size_t size);
73 #ifdef CONFIG_NFSD_V4
74 static ssize_t write_leasetime(struct file *file, char *buf, size_t size);
75 static ssize_t write_gracetime(struct file *file, char *buf, size_t size);
76 #ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING
77 static ssize_t write_recoverydir(struct file *file, char *buf, size_t size);
78 #endif
79 static ssize_t write_v4_end_grace(struct file *file, char *buf, size_t size);
80 #endif
81 
82 static ssize_t (*const write_op[])(struct file *, char *, size_t) = {
83 	[NFSD_Fh] = write_filehandle,
84 	[NFSD_FO_UnlockIP] = write_unlock_ip,
85 	[NFSD_FO_UnlockFS] = write_unlock_fs,
86 	[NFSD_Threads] = write_threads,
87 	[NFSD_Pool_Threads] = write_pool_threads,
88 	[NFSD_Versions] = write_versions,
89 	[NFSD_Ports] = write_ports,
90 	[NFSD_MaxBlkSize] = write_maxblksize,
91 #ifdef CONFIG_NFSD_V4
92 	[NFSD_Leasetime] = write_leasetime,
93 	[NFSD_Gracetime] = write_gracetime,
94 #ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING
95 	[NFSD_RecoveryDir] = write_recoverydir,
96 #endif
97 	[NFSD_V4EndGrace] = write_v4_end_grace,
98 #endif
99 };
100 
nfsctl_transaction_write(struct file * file,const char __user * buf,size_t size,loff_t * pos)101 static ssize_t nfsctl_transaction_write(struct file *file, const char __user *buf, size_t size, loff_t *pos)
102 {
103 	ino_t ino =  file_inode(file)->i_ino;
104 	char *data;
105 	ssize_t rv;
106 
107 	if (ino >= ARRAY_SIZE(write_op) || !write_op[ino])
108 		return -EINVAL;
109 
110 	data = simple_transaction_get(file, buf, size);
111 	if (IS_ERR(data))
112 		return PTR_ERR(data);
113 
114 	rv = write_op[ino](file, data, size);
115 	if (rv < 0)
116 		return rv;
117 
118 	simple_transaction_set(file, rv);
119 	return size;
120 }
121 
nfsctl_transaction_read(struct file * file,char __user * buf,size_t size,loff_t * pos)122 static ssize_t nfsctl_transaction_read(struct file *file, char __user *buf, size_t size, loff_t *pos)
123 {
124 	if (! file->private_data) {
125 		/* An attempt to read a transaction file without writing
126 		 * causes a 0-byte write so that the file can return
127 		 * state information
128 		 */
129 		ssize_t rv = nfsctl_transaction_write(file, buf, 0, pos);
130 		if (rv < 0)
131 			return rv;
132 	}
133 	return simple_transaction_read(file, buf, size, pos);
134 }
135 
136 static const struct file_operations transaction_ops = {
137 	.write		= nfsctl_transaction_write,
138 	.read		= nfsctl_transaction_read,
139 	.release	= simple_transaction_release,
140 	.llseek		= default_llseek,
141 };
142 
exports_net_open(struct net * net,struct file * file)143 static int exports_net_open(struct net *net, struct file *file)
144 {
145 	int err;
146 	struct seq_file *seq;
147 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
148 
149 	err = seq_open(file, &nfs_exports_op);
150 	if (err)
151 		return err;
152 
153 	seq = file->private_data;
154 	seq->private = nn->svc_export_cache;
155 	get_net(net);
156 	return 0;
157 }
158 
exports_release(struct inode * inode,struct file * file)159 static int exports_release(struct inode *inode, struct file *file)
160 {
161 	struct seq_file *seq = file->private_data;
162 	struct cache_detail *cd = seq->private;
163 
164 	put_net(cd->net);
165 	return seq_release(inode, file);
166 }
167 
exports_nfsd_open(struct inode * inode,struct file * file)168 static int exports_nfsd_open(struct inode *inode, struct file *file)
169 {
170 	return exports_net_open(inode->i_sb->s_fs_info, file);
171 }
172 
173 static const struct file_operations exports_nfsd_operations = {
174 	.open		= exports_nfsd_open,
175 	.read		= seq_read,
176 	.llseek		= seq_lseek,
177 	.release	= exports_release,
178 };
179 
export_features_show(struct seq_file * m,void * v)180 static int export_features_show(struct seq_file *m, void *v)
181 {
182 	seq_printf(m, "0x%x 0x%x\n", NFSEXP_ALLFLAGS, NFSEXP_SECINFO_FLAGS);
183 	return 0;
184 }
185 
186 DEFINE_SHOW_ATTRIBUTE(export_features);
187 
nfsd_pool_stats_open(struct inode * inode,struct file * file)188 static int nfsd_pool_stats_open(struct inode *inode, struct file *file)
189 {
190 	struct nfsd_net *nn = net_generic(inode->i_sb->s_fs_info, nfsd_net_id);
191 
192 	return svc_pool_stats_open(&nn->nfsd_info, file);
193 }
194 
195 static const struct file_operations pool_stats_operations = {
196 	.open		= nfsd_pool_stats_open,
197 	.read		= seq_read,
198 	.llseek		= seq_lseek,
199 	.release	= seq_release,
200 };
201 
202 DEFINE_SHOW_ATTRIBUTE(nfsd_reply_cache_stats);
203 
204 DEFINE_SHOW_ATTRIBUTE(nfsd_file_cache_stats);
205 
206 /*----------------------------------------------------------------------------*/
207 /*
208  * payload - write methods
209  */
210 
netns(struct file * file)211 static inline struct net *netns(struct file *file)
212 {
213 	return file_inode(file)->i_sb->s_fs_info;
214 }
215 
216 /*
217  * write_unlock_ip - Release all locks used by a client
218  *
219  * Experimental.
220  *
221  * Input:
222  *			buf:	'\n'-terminated C string containing a
223  *				presentation format IP address
224  *			size:	length of C string in @buf
225  * Output:
226  *	On success:	returns zero if all specified locks were released;
227  *			returns one if one or more locks were not released
228  *	On error:	return code is negative errno value
229  */
write_unlock_ip(struct file * file,char * buf,size_t size)230 static ssize_t write_unlock_ip(struct file *file, char *buf, size_t size)
231 {
232 	struct sockaddr_storage address;
233 	struct sockaddr *sap = (struct sockaddr *)&address;
234 	size_t salen = sizeof(address);
235 	char *fo_path;
236 	struct net *net = netns(file);
237 
238 	/* sanity check */
239 	if (size == 0)
240 		return -EINVAL;
241 
242 	if (buf[size-1] != '\n')
243 		return -EINVAL;
244 
245 	fo_path = buf;
246 	if (qword_get(&buf, fo_path, size) < 0)
247 		return -EINVAL;
248 
249 	if (rpc_pton(net, fo_path, size, sap, salen) == 0)
250 		return -EINVAL;
251 
252 	trace_nfsd_ctl_unlock_ip(net, sap, svc_addr_len(sap));
253 	return nlmsvc_unlock_all_by_ip(sap);
254 }
255 
256 /*
257  * write_unlock_fs - Release all locks on a local file system
258  *
259  * Experimental.
260  *
261  * Input:
262  *			buf:	'\n'-terminated C string containing the
263  *				absolute pathname of a local file system
264  *			size:	length of C string in @buf
265  * Output:
266  *	On success:	returns zero if all specified locks were released;
267  *			returns one if one or more locks were not released
268  *	On error:	return code is negative errno value
269  */
write_unlock_fs(struct file * file,char * buf,size_t size)270 static ssize_t write_unlock_fs(struct file *file, char *buf, size_t size)
271 {
272 	struct path path;
273 	char *fo_path;
274 	int error;
275 	struct nfsd_net *nn;
276 
277 	/* sanity check */
278 	if (size == 0)
279 		return -EINVAL;
280 
281 	if (buf[size-1] != '\n')
282 		return -EINVAL;
283 
284 	fo_path = buf;
285 	if (qword_get(&buf, fo_path, size) < 0)
286 		return -EINVAL;
287 	trace_nfsd_ctl_unlock_fs(netns(file), fo_path);
288 	error = kern_path(fo_path, 0, &path);
289 	if (error)
290 		return error;
291 
292 	/*
293 	 * XXX: Needs better sanity checking.  Otherwise we could end up
294 	 * releasing locks on the wrong file system.
295 	 *
296 	 * For example:
297 	 * 1.  Does the path refer to a directory?
298 	 * 2.  Is that directory a mount point, or
299 	 * 3.  Is that directory the root of an exported file system?
300 	 */
301 	error = nlmsvc_unlock_all_by_sb(path.dentry->d_sb);
302 	mutex_lock(&nfsd_mutex);
303 	nn = net_generic(netns(file), nfsd_net_id);
304 	if (test_bit(NFSD_NET_UP, &nn->flags)) {
305 		nfsd4_cancel_copy_by_sb(netns(file), path.dentry->d_sb);
306 		nfsd4_revoke_states(nn, path.dentry->d_sb);
307 	} else {
308 		error = -EINVAL;
309 	}
310 	mutex_unlock(&nfsd_mutex);
311 
312 	path_put(&path);
313 	return error;
314 }
315 
316 /*
317  * write_filehandle - Get a variable-length NFS file handle by path
318  *
319  * On input, the buffer contains a '\n'-terminated C string comprised of
320  * three alphanumeric words separated by whitespace.  The string may
321  * contain escape sequences.
322  *
323  * Input:
324  *			buf:
325  *				domain:		client domain name
326  *				path:		export pathname
327  *				maxsize:	numeric maximum size of
328  *						@buf
329  *			size:	length of C string in @buf
330  * Output:
331  *	On success:	passed-in buffer filled with '\n'-terminated C
332  *			string containing a ASCII hex text version
333  *			of the NFS file handle;
334  *			return code is the size in bytes of the string
335  *	On error:	return code is negative errno value
336  */
write_filehandle(struct file * file,char * buf,size_t size)337 static ssize_t write_filehandle(struct file *file, char *buf, size_t size)
338 {
339 	char *dname, *path;
340 	int maxsize;
341 	char *mesg = buf;
342 	int len;
343 	struct auth_domain *dom;
344 	struct knfsd_fh fh;
345 
346 	if (size == 0)
347 		return -EINVAL;
348 
349 	if (buf[size-1] != '\n')
350 		return -EINVAL;
351 	buf[size-1] = 0;
352 
353 	dname = mesg;
354 	len = qword_get(&mesg, dname, size);
355 	if (len <= 0)
356 		return -EINVAL;
357 
358 	path = dname+len+1;
359 	len = qword_get(&mesg, path, size);
360 	if (len <= 0)
361 		return -EINVAL;
362 
363 	len = get_int(&mesg, &maxsize);
364 	if (len)
365 		return len;
366 
367 	if (maxsize < NFS_FHSIZE)
368 		return -EINVAL;
369 	maxsize = min(maxsize, NFS3_FHSIZE);
370 
371 	if (qword_get(&mesg, mesg, size) > 0)
372 		return -EINVAL;
373 
374 	trace_nfsd_ctl_filehandle(netns(file), dname, path, maxsize);
375 
376 	/* we have all the words, they are in buf.. */
377 	dom = unix_domain_find(dname);
378 	if (!dom)
379 		return -ENOMEM;
380 
381 	len = exp_rootfh(netns(file), dom, path, &fh, maxsize);
382 	auth_domain_put(dom);
383 	if (len)
384 		return len;
385 
386 	mesg = buf;
387 	len = SIMPLE_TRANSACTION_LIMIT;
388 	qword_addhex(&mesg, &len, fh.fh_raw, fh.fh_size);
389 	mesg[-1] = '\n';
390 	return mesg - buf;
391 }
392 
393 /*
394  * write_threads - Start NFSD, or report the configured number of threads
395  *
396  * Input:
397  *			buf:		ignored
398  *			size:		zero
399  * Output:
400  *	On success:	passed-in buffer filled with '\n'-terminated C
401  *			string numeric value representing the configured
402  *			number of NFSD threads;
403  *			return code is the size in bytes of the string
404  *	On error:	return code is zero
405  *
406  * OR
407  *
408  * Input:
409  *			buf:		C string containing an unsigned
410  *					integer value representing the
411  *					number of NFSD threads to start
412  *			size:		non-zero length of C string in @buf
413  * Output:
414  *	On success:	NFS service is started;
415  *			passed-in buffer filled with '\n'-terminated C
416  *			string numeric value representing the configured
417  *			number of NFSD threads;
418  *			return code is the size in bytes of the string
419  *	On error:	return code is zero or a negative errno value
420  */
write_threads(struct file * file,char * buf,size_t size)421 static ssize_t write_threads(struct file *file, char *buf, size_t size)
422 {
423 	char *mesg = buf;
424 	int rv;
425 	struct net *net = netns(file);
426 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
427 
428 	if (size > 0) {
429 		int newthreads;
430 		rv = get_int(&mesg, &newthreads);
431 		if (rv)
432 			return rv;
433 		if (newthreads < 0)
434 			return -EINVAL;
435 		trace_nfsd_ctl_threads(net, newthreads);
436 		mutex_lock(&nfsd_mutex);
437 		if (newthreads > 0 || nn->nfsd_serv != NULL)
438 			rv = nfsd_svc(1, &newthreads, net, file->f_cred, NULL);
439 		else
440 			rv = 0;
441 		mutex_unlock(&nfsd_mutex);
442 		if (rv < 0)
443 			return rv;
444 	} else
445 		rv = nfsd_nrthreads(net);
446 
447 	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n", rv);
448 }
449 
450 /*
451  * write_pool_threads - Set or report the configured number of threads per pool
452  *
453  * Input:
454  *			buf:		ignored
455  *			size:		zero
456  *
457  * OR
458  *
459  * Input:
460  *			buf:		C string containing whitespace-
461  *					separated unsigned integer values
462  *					representing the number of NFSD
463  *					threads to start in each pool
464  *			size:		non-zero length of C string in @buf
465  * Output:
466  *	On success:	passed-in buffer filled with '\n'-terminated C
467  *			string containing integer values representing the
468  *			configured number of NFSD threads in each pool;
469  *			return code is the size in bytes of the string
470  *	On error:	return code is zero or a negative errno value
471  */
write_pool_threads(struct file * file,char * buf,size_t size)472 static ssize_t write_pool_threads(struct file *file, char *buf, size_t size)
473 {
474 	/* if size > 0, look for an array of number of threads per node
475 	 * and apply them  then write out number of threads per node as reply
476 	 */
477 	char *mesg = buf;
478 	int i;
479 	int rv;
480 	int len;
481 	int npools;
482 	int *nthreads;
483 	struct net *net = netns(file);
484 
485 	mutex_lock(&nfsd_mutex);
486 	npools = nfsd_nrpools(net);
487 	if (npools == 0) {
488 		/*
489 		 * NFS is shut down.  The admin can start it by
490 		 * writing to the threads file but NOT the pool_threads
491 		 * file, sorry.  Report zero threads.
492 		 */
493 		mutex_unlock(&nfsd_mutex);
494 		strcpy(buf, "0\n");
495 		return strlen(buf);
496 	}
497 
498 	nthreads = kzalloc_objs(int, npools);
499 	rv = -ENOMEM;
500 	if (nthreads == NULL)
501 		goto out_free;
502 
503 	if (size > 0) {
504 		for (i = 0; i < npools; i++) {
505 			rv = get_int(&mesg, &nthreads[i]);
506 			if (rv == -ENOENT)
507 				break;		/* fewer numbers than pools */
508 			if (rv)
509 				goto out_free;	/* syntax error */
510 			rv = -EINVAL;
511 			if (nthreads[i] < 0)
512 				goto out_free;
513 			trace_nfsd_ctl_pool_threads(net, i, nthreads[i]);
514 		}
515 
516 		/*
517 		 * There must always be a thread in pool 0; the admin
518 		 * can't shut down NFS completely using pool_threads.
519 		 */
520 		if (nthreads[0] == 0)
521 			nthreads[0] = 1;
522 
523 		rv = nfsd_set_nrthreads(i, nthreads, net);
524 		if (rv)
525 			goto out_free;
526 	}
527 
528 	rv = nfsd_get_nrthreads(npools, nthreads, net);
529 	if (rv)
530 		goto out_free;
531 
532 	mesg = buf;
533 	size = SIMPLE_TRANSACTION_LIMIT;
534 	for (i = 0; i < npools && size > 0; i++) {
535 		snprintf(mesg, size, "%d%c", nthreads[i], (i == npools-1 ? '\n' : ' '));
536 		len = strlen(mesg);
537 		size -= len;
538 		mesg += len;
539 	}
540 	rv = mesg - buf;
541 out_free:
542 	kfree(nthreads);
543 	mutex_unlock(&nfsd_mutex);
544 	return rv;
545 }
546 
547 static ssize_t
nfsd_print_version_support(struct nfsd_net * nn,char * buf,int remaining,const char * sep,unsigned vers,int minor)548 nfsd_print_version_support(struct nfsd_net *nn, char *buf, int remaining,
549 		const char *sep, unsigned vers, int minor)
550 {
551 	const char *format = minor < 0 ? "%s%c%u" : "%s%c%u.%u";
552 	bool supported = !!nfsd_vers(nn, vers, NFSD_TEST);
553 
554 	if (vers == 4 && minor >= 0 &&
555 	    !nfsd_minorversion(nn, minor, NFSD_TEST))
556 		supported = false;
557 	if (minor == 0 && supported)
558 		/*
559 		 * special case for backward compatability.
560 		 * +4.0 is never reported, it is implied by
561 		 * +4, unless -4.0 is present.
562 		 */
563 		return 0;
564 	return snprintf(buf, remaining, format, sep,
565 			supported ? '+' : '-', vers, minor);
566 }
567 
__write_versions(struct file * file,char * buf,size_t size)568 static ssize_t __write_versions(struct file *file, char *buf, size_t size)
569 {
570 	char *mesg = buf;
571 	char *vers, *minorp, sign;
572 	int len, num, remaining;
573 	ssize_t tlen = 0;
574 	char *sep;
575 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
576 
577 	if (size > 0) {
578 		if (nn->nfsd_serv)
579 			/* Cannot change versions without updating
580 			 * nn->nfsd_serv->sv_xdrsize, and reallocing
581 			 * rq_argp and rq_resp
582 			 */
583 			return -EBUSY;
584 		if (buf[size-1] != '\n')
585 			return -EINVAL;
586 		buf[size-1] = 0;
587 		trace_nfsd_ctl_version(netns(file), buf);
588 
589 		vers = mesg;
590 		len = qword_get(&mesg, vers, size);
591 		if (len <= 0) return -EINVAL;
592 		do {
593 			enum vers_op cmd;
594 			unsigned minor;
595 			sign = *vers;
596 			if (sign == '+' || sign == '-')
597 				num = simple_strtol((vers+1), &minorp, 0);
598 			else
599 				num = simple_strtol(vers, &minorp, 0);
600 			if (*minorp == '.') {
601 				if (num != 4)
602 					return -EINVAL;
603 				if (kstrtouint(minorp+1, 0, &minor) < 0)
604 					return -EINVAL;
605 			}
606 
607 			cmd = sign == '-' ? NFSD_CLEAR : NFSD_SET;
608 			switch(num) {
609 #ifdef CONFIG_NFSD_V2
610 			case 2:
611 #endif
612 			case 3:
613 				nfsd_vers(nn, num, cmd);
614 				break;
615 			case 4:
616 				if (*minorp == '.') {
617 					if (nfsd_minorversion(nn, minor, cmd) < 0)
618 						return -EINVAL;
619 				} else if ((cmd == NFSD_SET) != nfsd_vers(nn, num, NFSD_TEST)) {
620 					/*
621 					 * Either we have +4 and no minors are enabled,
622 					 * or we have -4 and at least one minor is enabled.
623 					 * In either case, propagate 'cmd' to all minors.
624 					 */
625 					minor = 0;
626 					while (nfsd_minorversion(nn, minor, cmd) >= 0)
627 						minor++;
628 				}
629 				break;
630 			default:
631 				/* Ignore requests to disable non-existent versions */
632 				if (cmd == NFSD_SET)
633 					return -EINVAL;
634 			}
635 			vers += len + 1;
636 		} while ((len = qword_get(&mesg, vers, size)) > 0);
637 		/* If all get turned off, turn them back on, as
638 		 * having no versions is BAD
639 		 */
640 		nfsd_reset_versions(nn);
641 	}
642 
643 	/* Now write current state into reply buffer */
644 	sep = "";
645 	remaining = SIMPLE_TRANSACTION_LIMIT;
646 	for (num=2 ; num <= 4 ; num++) {
647 		int minor;
648 		if (!nfsd_vers(nn, num, NFSD_AVAIL))
649 			continue;
650 
651 		minor = -1;
652 		do {
653 			len = nfsd_print_version_support(nn, buf, remaining,
654 					sep, num, minor);
655 			if (len >= remaining)
656 				goto out;
657 			remaining -= len;
658 			buf += len;
659 			tlen += len;
660 			minor++;
661 			if (len)
662 				sep = " ";
663 		} while (num == 4 && minor <= NFSD_SUPPORTED_MINOR_VERSION);
664 	}
665 out:
666 	len = snprintf(buf, remaining, "\n");
667 	if (len >= remaining)
668 		return -EINVAL;
669 	return tlen + len;
670 }
671 
672 /*
673  * write_versions - Set or report the available NFS protocol versions
674  *
675  * Input:
676  *			buf:		ignored
677  *			size:		zero
678  * Output:
679  *	On success:	passed-in buffer filled with '\n'-terminated C
680  *			string containing positive or negative integer
681  *			values representing the current status of each
682  *			protocol version;
683  *			return code is the size in bytes of the string
684  *	On error:	return code is zero or a negative errno value
685  *
686  * OR
687  *
688  * Input:
689  *			buf:		C string containing whitespace-
690  *					separated positive or negative
691  *					integer values representing NFS
692  *					protocol versions to enable ("+n")
693  *					or disable ("-n")
694  *			size:		non-zero length of C string in @buf
695  * Output:
696  *	On success:	status of zero or more protocol versions has
697  *			been updated; passed-in buffer filled with
698  *			'\n'-terminated C string containing positive
699  *			or negative integer values representing the
700  *			current status of each protocol version;
701  *			return code is the size in bytes of the string
702  *	On error:	return code is zero or a negative errno value
703  */
write_versions(struct file * file,char * buf,size_t size)704 static ssize_t write_versions(struct file *file, char *buf, size_t size)
705 {
706 	ssize_t rv;
707 
708 	mutex_lock(&nfsd_mutex);
709 	rv = __write_versions(file, buf, size);
710 	mutex_unlock(&nfsd_mutex);
711 	return rv;
712 }
713 
714 /*
715  * Zero-length write.  Return a list of NFSD's current listener
716  * transports.
717  */
__write_ports_names(char * buf,struct net * net)718 static ssize_t __write_ports_names(char *buf, struct net *net)
719 {
720 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
721 
722 	if (nn->nfsd_serv == NULL)
723 		return 0;
724 	return svc_xprt_names(nn->nfsd_serv, buf, SIMPLE_TRANSACTION_LIMIT);
725 }
726 
727 /*
728  * A single 'fd' number was written, in which case it must be for
729  * a socket of a supported family/protocol, and we use it as an
730  * nfsd listener.
731  */
__write_ports_addfd(char * buf,struct net * net,const struct cred * cred)732 static ssize_t __write_ports_addfd(char *buf, struct net *net, const struct cred *cred)
733 {
734 	char *mesg = buf;
735 	int fd, err;
736 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
737 	struct svc_serv *serv;
738 
739 	err = get_int(&mesg, &fd);
740 	if (err != 0 || fd < 0)
741 		return -EINVAL;
742 	trace_nfsd_ctl_ports_addfd(net, fd);
743 
744 	err = nfsd_create_serv(net);
745 	if (err != 0)
746 		return err;
747 
748 	serv = nn->nfsd_serv;
749 	err = svc_addsock(serv, net, fd, buf, SIMPLE_TRANSACTION_LIMIT, cred);
750 
751 	if (!serv->sv_nrthreads && list_empty(&nn->nfsd_serv->sv_permsocks))
752 		nfsd_destroy_serv(net);
753 
754 	return err;
755 }
756 
757 /*
758  * A transport listener is added by writing its transport name and
759  * a port number.
760  */
__write_ports_addxprt(char * buf,struct net * net,const struct cred * cred)761 static ssize_t __write_ports_addxprt(char *buf, struct net *net, const struct cred *cred)
762 {
763 	char transport[16];
764 	struct svc_xprt *xprt;
765 	int port, err;
766 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
767 	struct svc_serv *serv;
768 
769 	if (sscanf(buf, "%15s %5u", transport, &port) != 2)
770 		return -EINVAL;
771 
772 	if (port < 1 || port > USHRT_MAX)
773 		return -EINVAL;
774 	trace_nfsd_ctl_ports_addxprt(net, transport, port);
775 
776 	err = nfsd_create_serv(net);
777 	if (err != 0)
778 		return err;
779 
780 	serv = nn->nfsd_serv;
781 	err = svc_xprt_create(serv, transport, net,
782 			      PF_INET, port, SVC_SOCK_ANONYMOUS, cred);
783 	if (err < 0)
784 		goto out_err;
785 
786 	err = svc_xprt_create(serv, transport, net,
787 			      PF_INET6, port, SVC_SOCK_ANONYMOUS, cred);
788 	if (err < 0 && err != -EAFNOSUPPORT)
789 		goto out_close;
790 
791 	return 0;
792 out_close:
793 	xprt = svc_find_xprt(serv, transport, net, PF_INET, port);
794 	if (xprt != NULL) {
795 		svc_xprt_close(xprt);
796 		svc_xprt_put(xprt);
797 	}
798 out_err:
799 	if (!serv->sv_nrthreads && list_empty(&nn->nfsd_serv->sv_permsocks))
800 		nfsd_destroy_serv(net);
801 
802 	return err;
803 }
804 
__write_ports(struct file * file,char * buf,size_t size,struct net * net)805 static ssize_t __write_ports(struct file *file, char *buf, size_t size,
806 			     struct net *net)
807 {
808 	if (size == 0)
809 		return __write_ports_names(buf, net);
810 
811 	if (isdigit(buf[0]))
812 		return __write_ports_addfd(buf, net, file->f_cred);
813 
814 	if (isalpha(buf[0]))
815 		return __write_ports_addxprt(buf, net, file->f_cred);
816 
817 	return -EINVAL;
818 }
819 
820 /*
821  * write_ports - Pass a socket file descriptor or transport name to listen on
822  *
823  * Input:
824  *			buf:		ignored
825  *			size:		zero
826  * Output:
827  *	On success:	passed-in buffer filled with a '\n'-terminated C
828  *			string containing a whitespace-separated list of
829  *			named NFSD listeners;
830  *			return code is the size in bytes of the string
831  *	On error:	return code is zero or a negative errno value
832  *
833  * OR
834  *
835  * Input:
836  *			buf:		C string containing an unsigned
837  *					integer value representing a bound
838  *					but unconnected socket that is to be
839  *					used as an NFSD listener; listen(3)
840  *					must be called for a SOCK_STREAM
841  *					socket, otherwise it is ignored
842  *			size:		non-zero length of C string in @buf
843  * Output:
844  *	On success:	NFS service is started;
845  *			passed-in buffer filled with a '\n'-terminated C
846  *			string containing a unique alphanumeric name of
847  *			the listener;
848  *			return code is the size in bytes of the string
849  *	On error:	return code is a negative errno value
850  *
851  * OR
852  *
853  * Input:
854  *			buf:		C string containing a transport
855  *					name and an unsigned integer value
856  *					representing the port to listen on,
857  *					separated by whitespace
858  *			size:		non-zero length of C string in @buf
859  * Output:
860  *	On success:	returns zero; NFS service is started
861  *	On error:	return code is a negative errno value
862  */
write_ports(struct file * file,char * buf,size_t size)863 static ssize_t write_ports(struct file *file, char *buf, size_t size)
864 {
865 	ssize_t rv;
866 
867 	mutex_lock(&nfsd_mutex);
868 	rv = __write_ports(file, buf, size, netns(file));
869 	mutex_unlock(&nfsd_mutex);
870 	return rv;
871 }
872 
873 
874 int nfsd_max_blksize;
875 
876 /*
877  * write_maxblksize - Set or report the current NFS blksize
878  *
879  * Input:
880  *			buf:		ignored
881  *			size:		zero
882  *
883  * OR
884  *
885  * Input:
886  *			buf:		C string containing an unsigned
887  *					integer value representing the new
888  *					NFS blksize
889  *			size:		non-zero length of C string in @buf
890  * Output:
891  *	On success:	passed-in buffer filled with '\n'-terminated C string
892  *			containing numeric value of the current NFS blksize
893  *			setting;
894  *			return code is the size in bytes of the string
895  *	On error:	return code is zero or a negative errno value
896  */
write_maxblksize(struct file * file,char * buf,size_t size)897 static ssize_t write_maxblksize(struct file *file, char *buf, size_t size)
898 {
899 	char *mesg = buf;
900 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
901 
902 	if (size > 0) {
903 		int bsize;
904 		int rv = get_int(&mesg, &bsize);
905 		if (rv)
906 			return rv;
907 		trace_nfsd_ctl_maxblksize(netns(file), bsize);
908 
909 		/* force bsize into allowed range and
910 		 * required alignment.
911 		 */
912 		bsize = max_t(int, bsize, 1024);
913 		bsize = min_t(int, bsize, NFSSVC_MAXBLKSIZE);
914 		bsize &= ~(1024-1);
915 		mutex_lock(&nfsd_mutex);
916 		if (nn->nfsd_serv) {
917 			mutex_unlock(&nfsd_mutex);
918 			return -EBUSY;
919 		}
920 		nfsd_max_blksize = bsize;
921 		mutex_unlock(&nfsd_mutex);
922 	}
923 
924 	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%d\n",
925 							nfsd_max_blksize);
926 }
927 
928 #ifdef CONFIG_NFSD_V4
__nfsd4_write_time(struct file * file,char * buf,size_t size,time64_t * time,struct nfsd_net * nn)929 static ssize_t __nfsd4_write_time(struct file *file, char *buf, size_t size,
930 				  time64_t *time, struct nfsd_net *nn)
931 {
932 	struct dentry *dentry = file_dentry(file);
933 	char *mesg = buf;
934 	int rv, i;
935 
936 	if (size > 0) {
937 		if (nn->nfsd_serv)
938 			return -EBUSY;
939 		rv = get_int(&mesg, &i);
940 		if (rv)
941 			return rv;
942 		trace_nfsd_ctl_time(netns(file), dentry->d_name.name,
943 				    dentry->d_name.len, i);
944 
945 		/*
946 		 * Some sanity checking.  We don't have a reason for
947 		 * these particular numbers, but problems with the
948 		 * extremes are:
949 		 *	- Too short: the briefest network outage may
950 		 *	  cause clients to lose all their locks.  Also,
951 		 *	  the frequent polling may be wasteful.
952 		 *	- Too long: do you really want reboot recovery
953 		 *	  to take more than an hour?  Or to make other
954 		 *	  clients wait an hour before being able to
955 		 *	  revoke a dead client's locks?
956 		 */
957 		if (i < 10 || i > 3600)
958 			return -EINVAL;
959 		*time = i;
960 	}
961 
962 	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%lld\n", *time);
963 }
964 
nfsd4_write_time(struct file * file,char * buf,size_t size,time64_t * time,struct nfsd_net * nn)965 static ssize_t nfsd4_write_time(struct file *file, char *buf, size_t size,
966 				time64_t *time, struct nfsd_net *nn)
967 {
968 	ssize_t rv;
969 
970 	mutex_lock(&nfsd_mutex);
971 	rv = __nfsd4_write_time(file, buf, size, time, nn);
972 	mutex_unlock(&nfsd_mutex);
973 	return rv;
974 }
975 
976 /*
977  * write_leasetime - Set or report the current NFSv4 lease time
978  *
979  * Input:
980  *			buf:		ignored
981  *			size:		zero
982  *
983  * OR
984  *
985  * Input:
986  *			buf:		C string containing an unsigned
987  *					integer value representing the new
988  *					NFSv4 lease expiry time
989  *			size:		non-zero length of C string in @buf
990  * Output:
991  *	On success:	passed-in buffer filled with '\n'-terminated C
992  *			string containing unsigned integer value of the
993  *			current lease expiry time;
994  *			return code is the size in bytes of the string
995  *	On error:	return code is zero or a negative errno value
996  */
write_leasetime(struct file * file,char * buf,size_t size)997 static ssize_t write_leasetime(struct file *file, char *buf, size_t size)
998 {
999 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
1000 	return nfsd4_write_time(file, buf, size, &nn->nfsd4_lease, nn);
1001 }
1002 
1003 /*
1004  * write_gracetime - Set or report current NFSv4 grace period time
1005  *
1006  * As above, but sets the time of the NFSv4 grace period.
1007  *
1008  * Note this should never be set to less than the *previous*
1009  * lease-period time, but we don't try to enforce this.  (In the common
1010  * case (a new boot), we don't know what the previous lease time was
1011  * anyway.)
1012  */
write_gracetime(struct file * file,char * buf,size_t size)1013 static ssize_t write_gracetime(struct file *file, char *buf, size_t size)
1014 {
1015 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
1016 	return nfsd4_write_time(file, buf, size, &nn->nfsd4_grace, nn);
1017 }
1018 
1019 #ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING
__write_recoverydir(struct file * file,char * buf,size_t size,struct nfsd_net * nn)1020 static ssize_t __write_recoverydir(struct file *file, char *buf, size_t size,
1021 				   struct nfsd_net *nn)
1022 {
1023 	char *mesg = buf;
1024 	char *recdir;
1025 	int len, status;
1026 
1027 	if (size > 0) {
1028 		if (nn->nfsd_serv)
1029 			return -EBUSY;
1030 		if (size > PATH_MAX || buf[size-1] != '\n')
1031 			return -EINVAL;
1032 		buf[size-1] = 0;
1033 
1034 		recdir = mesg;
1035 		len = qword_get(&mesg, recdir, size);
1036 		if (len <= 0)
1037 			return -EINVAL;
1038 		trace_nfsd_ctl_recoverydir(netns(file), recdir);
1039 
1040 		status = nfs4_reset_recoverydir(recdir);
1041 		if (status)
1042 			return status;
1043 	}
1044 
1045 	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%s\n",
1046 							nfs4_recoverydir());
1047 }
1048 
1049 /*
1050  * write_recoverydir - Set or report the pathname of the recovery directory
1051  *
1052  * Input:
1053  *			buf:		ignored
1054  *			size:		zero
1055  *
1056  * OR
1057  *
1058  * Input:
1059  *			buf:		C string containing the pathname
1060  *					of the directory on a local file
1061  *					system containing permanent NFSv4
1062  *					recovery data
1063  *			size:		non-zero length of C string in @buf
1064  * Output:
1065  *	On success:	passed-in buffer filled with '\n'-terminated C string
1066  *			containing the current recovery pathname setting;
1067  *			return code is the size in bytes of the string
1068  *	On error:	return code is zero or a negative errno value
1069  */
write_recoverydir(struct file * file,char * buf,size_t size)1070 static ssize_t write_recoverydir(struct file *file, char *buf, size_t size)
1071 {
1072 	ssize_t rv;
1073 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
1074 
1075 	mutex_lock(&nfsd_mutex);
1076 	rv = __write_recoverydir(file, buf, size, nn);
1077 	mutex_unlock(&nfsd_mutex);
1078 	return rv;
1079 }
1080 #endif
1081 
1082 /*
1083  * write_v4_end_grace - release grace period for nfsd's v4.x lock manager
1084  *
1085  * Input:
1086  *			buf:		ignored
1087  *			size:		zero
1088  * OR
1089  *
1090  * Input:
1091  *			buf:		any value
1092  *			size:		non-zero length of C string in @buf
1093  * Output:
1094  *			passed-in buffer filled with "Y" or "N" with a newline
1095  *			and NULL-terminated C string. This indicates whether
1096  *			the grace period has ended in the current net
1097  *			namespace. Return code is the size in bytes of the
1098  *			string. Writing a string that starts with 'Y', 'y', or
1099  *			'1' to the file will end the grace period for nfsd's v4
1100  *			lock manager.
1101  */
write_v4_end_grace(struct file * file,char * buf,size_t size)1102 static ssize_t write_v4_end_grace(struct file *file, char *buf, size_t size)
1103 {
1104 	struct nfsd_net *nn = net_generic(netns(file), nfsd_net_id);
1105 
1106 	if (size > 0) {
1107 		switch(buf[0]) {
1108 		case 'Y':
1109 		case 'y':
1110 		case '1':
1111 			if (!nfsd4_force_end_grace(nn))
1112 				return -EBUSY;
1113 			trace_nfsd_end_grace(netns(file));
1114 			break;
1115 		default:
1116 			return -EINVAL;
1117 		}
1118 	}
1119 
1120 	return scnprintf(buf, SIMPLE_TRANSACTION_LIMIT, "%c\n",
1121 			 test_bit(NFSD_NET_GRACE_ENDED, &nn->flags) ? 'Y' : 'N');
1122 }
1123 
1124 #endif
1125 
1126 /*----------------------------------------------------------------------------*/
1127 /*
1128  *	populating the filesystem.
1129  */
1130 
nfsd_get_inode(struct super_block * sb,umode_t mode)1131 static struct inode *nfsd_get_inode(struct super_block *sb, umode_t mode)
1132 {
1133 	struct inode *inode = new_inode(sb);
1134 	if (inode) {
1135 		/* Following advice from simple_fill_super documentation: */
1136 		inode->i_ino = iunique(sb, NFSD_MaxReserved);
1137 		inode->i_mode = mode;
1138 		simple_inode_init_ts(inode);
1139 	}
1140 	return inode;
1141 }
1142 
nfsd_mkdir(struct dentry * parent,struct nfsdfs_client * ncl,char * name)1143 static struct dentry *nfsd_mkdir(struct dentry *parent, struct nfsdfs_client *ncl, char *name)
1144 {
1145 	struct inode *dir = parent->d_inode;
1146 	struct dentry *dentry;
1147 	struct inode *inode;
1148 
1149 	inode = nfsd_get_inode(parent->d_sb, S_IFDIR | 0600);
1150 	if (!inode)
1151 		return ERR_PTR(-ENOMEM);
1152 
1153 	dentry = simple_start_creating(parent, name);
1154 	if (IS_ERR(dentry)) {
1155 		iput(inode);
1156 		return dentry;
1157 	}
1158 	inode->i_fop = &simple_dir_operations;
1159 	inode->i_op = &simple_dir_inode_operations;
1160 	inc_nlink(inode);
1161 	if (ncl) {
1162 		inode->i_private = ncl;
1163 		kref_get(&ncl->cl_ref);
1164 	}
1165 	d_make_persistent(dentry, inode);
1166 	inc_nlink(dir);
1167 	fsnotify_mkdir(dir, dentry);
1168 	simple_done_creating(dentry);
1169 	return dentry;	// borrowed
1170 }
1171 
1172 #if IS_ENABLED(CONFIG_SUNRPC_GSS)
1173 /*
1174  * @content is assumed to be a NUL-terminated string that lives
1175  * longer than the symlink itself.
1176  */
_nfsd_symlink(struct dentry * parent,const char * name,const char * content)1177 static void _nfsd_symlink(struct dentry *parent, const char *name,
1178 			  const char *content)
1179 {
1180 	struct inode *dir = parent->d_inode;
1181 	struct inode *inode;
1182 	struct dentry *dentry;
1183 
1184 	inode = nfsd_get_inode(dir->i_sb, S_IFLNK | 0777);
1185 	if (!inode)
1186 		return;
1187 
1188 	dentry = simple_start_creating(parent, name);
1189 	if (IS_ERR(dentry)) {
1190 		iput(inode);
1191 		return;
1192 	}
1193 
1194 	inode->i_op = &simple_symlink_inode_operations;
1195 	inode->i_link = (char *)content;
1196 	inode->i_size = strlen(content);
1197 
1198 	d_make_persistent(dentry, inode);
1199 	fsnotify_create(dir, dentry);
1200 	simple_done_creating(dentry);
1201 }
1202 #else
_nfsd_symlink(struct dentry * parent,const char * name,const char * content)1203 static inline void _nfsd_symlink(struct dentry *parent, const char *name,
1204 				 const char *content)
1205 {
1206 }
1207 
1208 #endif
1209 
clear_ncl(struct dentry * dentry)1210 static void clear_ncl(struct dentry *dentry)
1211 {
1212 	struct inode *inode = d_inode(dentry);
1213 	struct nfsdfs_client *ncl = inode->i_private;
1214 
1215 	spin_lock(&inode->i_lock);
1216 	inode->i_private = NULL;
1217 	spin_unlock(&inode->i_lock);
1218 	kref_put(&ncl->cl_ref, ncl->cl_release);
1219 }
1220 
get_nfsdfs_client(struct inode * inode)1221 struct nfsdfs_client *get_nfsdfs_client(struct inode *inode)
1222 {
1223 	struct nfsdfs_client *nc;
1224 
1225 	spin_lock(&inode->i_lock);
1226 	nc = inode->i_private;
1227 	if (nc)
1228 		kref_get(&nc->cl_ref);
1229 	spin_unlock(&inode->i_lock);
1230 	return nc;
1231 }
1232 
1233 /* XXX: cut'n'paste from simple_fill_super; figure out if we could share
1234  * code instead. */
nfsdfs_create_files(struct dentry * root,const struct tree_descr * files,struct nfsdfs_client * ncl,struct dentry ** fdentries)1235 static int nfsdfs_create_files(struct dentry *root,
1236 				const struct tree_descr *files,
1237 				struct nfsdfs_client *ncl,
1238 				struct dentry **fdentries)
1239 {
1240 	struct inode *dir = d_inode(root);
1241 	struct dentry *dentry;
1242 
1243 	for (int i = 0; files->name && files->name[0]; i++, files++) {
1244 		struct inode *inode = nfsd_get_inode(root->d_sb,
1245 						     S_IFREG | files->mode);
1246 		if (!inode)
1247 			return -ENOMEM;
1248 		dentry = simple_start_creating(root, files->name);
1249 		if (IS_ERR(dentry)) {
1250 			iput(inode);
1251 			return PTR_ERR(dentry);
1252 		}
1253 		kref_get(&ncl->cl_ref);
1254 		inode->i_fop = files->ops;
1255 		inode->i_private = ncl;
1256 		d_make_persistent(dentry, inode);
1257 		fsnotify_create(dir, dentry);
1258 		if (fdentries)
1259 			fdentries[i] = dentry; // borrowed
1260 		simple_done_creating(dentry);
1261 	}
1262 	return 0;
1263 }
1264 
1265 /* on success, returns positive number unique to that client. */
nfsd_client_mkdir(struct nfsd_net * nn,struct nfsdfs_client * ncl,u32 id,const struct tree_descr * files,struct dentry ** fdentries)1266 struct dentry *nfsd_client_mkdir(struct nfsd_net *nn,
1267 				 struct nfsdfs_client *ncl, u32 id,
1268 				 const struct tree_descr *files,
1269 				 struct dentry **fdentries)
1270 {
1271 	struct dentry *dentry;
1272 	char name[11];
1273 	int ret;
1274 
1275 	sprintf(name, "%u", id);
1276 
1277 	dentry = nfsd_mkdir(nn->nfsd_client_dir, ncl, name);
1278 	if (IS_ERR(dentry)) /* XXX: tossing errors? */
1279 		return NULL;
1280 	ret = nfsdfs_create_files(dentry, files, ncl, fdentries);
1281 	if (ret) {
1282 		nfsd_client_rmdir(dentry);
1283 		return NULL;
1284 	}
1285 	return dentry;
1286 }
1287 
1288 /* Taken from __rpc_rmdir: */
nfsd_client_rmdir(struct dentry * dentry)1289 void nfsd_client_rmdir(struct dentry *dentry)
1290 {
1291 	simple_recursive_removal(dentry, clear_ncl);
1292 }
1293 
nfsd_fill_super(struct super_block * sb,struct fs_context * fc)1294 static int nfsd_fill_super(struct super_block *sb, struct fs_context *fc)
1295 {
1296 	struct nfsd_net *nn = net_generic(current->nsproxy->net_ns,
1297 							nfsd_net_id);
1298 	struct dentry *dentry;
1299 	int ret;
1300 
1301 	static const struct tree_descr nfsd_files[] = {
1302 		[NFSD_List] = {"exports", &exports_nfsd_operations, S_IRUGO},
1303 		/* Per-export io stats use same ops as exports file */
1304 		[NFSD_Export_Stats] = {"export_stats", &exports_nfsd_operations, S_IRUGO},
1305 		[NFSD_Export_features] = {"export_features",
1306 					&export_features_fops, S_IRUGO},
1307 		[NFSD_FO_UnlockIP] = {"unlock_ip",
1308 					&transaction_ops, S_IWUSR|S_IRUSR},
1309 		[NFSD_FO_UnlockFS] = {"unlock_filesystem",
1310 					&transaction_ops, S_IWUSR|S_IRUSR},
1311 		[NFSD_Fh] = {"filehandle", &transaction_ops, S_IWUSR|S_IRUSR},
1312 		[NFSD_Threads] = {"threads", &transaction_ops, S_IWUSR|S_IRUSR},
1313 		[NFSD_Pool_Threads] = {"pool_threads", &transaction_ops, S_IWUSR|S_IRUSR},
1314 		[NFSD_Pool_Stats] = {"pool_stats", &pool_stats_operations, S_IRUGO},
1315 		[NFSD_Reply_Cache_Stats] = {"reply_cache_stats",
1316 					&nfsd_reply_cache_stats_fops, S_IRUGO},
1317 		[NFSD_Versions] = {"versions", &transaction_ops, S_IWUSR|S_IRUSR},
1318 		[NFSD_Ports] = {"portlist", &transaction_ops, S_IWUSR|S_IRUGO},
1319 		[NFSD_MaxBlkSize] = {"max_block_size", &transaction_ops, S_IWUSR|S_IRUGO},
1320 		[NFSD_Filecache] = {"filecache", &nfsd_file_cache_stats_fops, S_IRUGO},
1321 #ifdef CONFIG_NFSD_V4
1322 		[NFSD_Leasetime] = {"nfsv4leasetime", &transaction_ops, S_IWUSR|S_IRUSR},
1323 		[NFSD_Gracetime] = {"nfsv4gracetime", &transaction_ops, S_IWUSR|S_IRUSR},
1324 #ifdef CONFIG_NFSD_LEGACY_CLIENT_TRACKING
1325 		[NFSD_RecoveryDir] = {"nfsv4recoverydir", &transaction_ops, S_IWUSR|S_IRUSR},
1326 #endif
1327 		[NFSD_V4EndGrace] = {"v4_end_grace", &transaction_ops, S_IWUSR|S_IRUGO},
1328 #endif
1329 		/* last one */ {""}
1330 	};
1331 
1332 	ret = simple_fill_super(sb, 0x6e667364, nfsd_files);
1333 	if (ret)
1334 		return ret;
1335 	_nfsd_symlink(sb->s_root, "supported_krb5_enctypes",
1336 		      "/proc/net/rpc/gss_krb5_enctypes");
1337 	dentry = nfsd_mkdir(sb->s_root, NULL, "clients");
1338 	if (IS_ERR(dentry))
1339 		return PTR_ERR(dentry);
1340 	nn->nfsd_client_dir = dentry;
1341 	return 0;
1342 }
1343 
nfsd_fs_get_tree(struct fs_context * fc)1344 static int nfsd_fs_get_tree(struct fs_context *fc)
1345 {
1346 	return get_tree_keyed(fc, nfsd_fill_super, get_net(fc->net_ns));
1347 }
1348 
nfsd_fs_free_fc(struct fs_context * fc)1349 static void nfsd_fs_free_fc(struct fs_context *fc)
1350 {
1351 	if (fc->s_fs_info)
1352 		put_net(fc->s_fs_info);
1353 }
1354 
1355 static const struct fs_context_operations nfsd_fs_context_ops = {
1356 	.free		= nfsd_fs_free_fc,
1357 	.get_tree	= nfsd_fs_get_tree,
1358 };
1359 
nfsd_init_fs_context(struct fs_context * fc)1360 static int nfsd_init_fs_context(struct fs_context *fc)
1361 {
1362 	put_user_ns(fc->user_ns);
1363 	fc->user_ns = get_user_ns(fc->net_ns->user_ns);
1364 	fc->ops = &nfsd_fs_context_ops;
1365 	return 0;
1366 }
1367 
nfsd_umount(struct super_block * sb)1368 static void nfsd_umount(struct super_block *sb)
1369 {
1370 	struct net *net = sb->s_fs_info;
1371 
1372 	nfsd_shutdown_threads(net);
1373 
1374 	kill_anon_super(sb);
1375 	put_net(net);
1376 }
1377 
1378 static struct file_system_type nfsd_fs_type = {
1379 	.owner		= THIS_MODULE,
1380 	.name		= "nfsd",
1381 	.init_fs_context = nfsd_init_fs_context,
1382 	.kill_sb	= nfsd_umount,
1383 };
1384 MODULE_ALIAS_FS("nfsd");
1385 
1386 #ifdef CONFIG_PROC_FS
1387 
exports_proc_open(struct inode * inode,struct file * file)1388 static int exports_proc_open(struct inode *inode, struct file *file)
1389 {
1390 	return exports_net_open(current->nsproxy->net_ns, file);
1391 }
1392 
1393 static const struct proc_ops exports_proc_ops = {
1394 	.proc_open	= exports_proc_open,
1395 	.proc_read	= seq_read,
1396 	.proc_lseek	= seq_lseek,
1397 	.proc_release	= exports_release,
1398 };
1399 
create_proc_exports_entry(void)1400 static int create_proc_exports_entry(void)
1401 {
1402 	struct proc_dir_entry *entry;
1403 
1404 	entry = proc_mkdir("fs/nfs", NULL);
1405 	if (!entry)
1406 		return -ENOMEM;
1407 	entry = proc_create("exports", 0, entry, &exports_proc_ops);
1408 	if (!entry) {
1409 		remove_proc_entry("fs/nfs", NULL);
1410 		return -ENOMEM;
1411 	}
1412 	return 0;
1413 }
1414 #else /* CONFIG_PROC_FS */
create_proc_exports_entry(void)1415 static int create_proc_exports_entry(void)
1416 {
1417 	return 0;
1418 }
1419 #endif
1420 
1421 unsigned int nfsd_net_id;
1422 
1423 struct nfsd_genl_rqstp {
1424 	struct sockaddr_storage	rq_daddr;
1425 	struct sockaddr_storage	rq_saddr;
1426 	unsigned long		rq_flags;
1427 	ktime_t			rq_stime;
1428 	__be32			rq_xid;
1429 	u32			rq_vers;
1430 	u32			rq_prog;
1431 	u32			rq_proc;
1432 
1433 	/* NFSv4 compound */
1434 	u32			rq_opcnt;
1435 	u32			rq_opnum[16];
1436 };
1437 
nfsd_genl_rpc_status_compose_msg(struct sk_buff * skb,struct netlink_callback * cb,struct nfsd_genl_rqstp * genl_rqstp)1438 static int nfsd_genl_rpc_status_compose_msg(struct sk_buff *skb,
1439 					    struct netlink_callback *cb,
1440 					    struct nfsd_genl_rqstp *genl_rqstp)
1441 {
1442 	void *hdr;
1443 	u32 i;
1444 
1445 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
1446 			  &nfsd_nl_family, 0, NFSD_CMD_RPC_STATUS_GET);
1447 	if (!hdr)
1448 		return -ENOBUFS;
1449 
1450 	if (nla_put_be32(skb, NFSD_A_RPC_STATUS_XID, genl_rqstp->rq_xid) ||
1451 	    nla_put_u32(skb, NFSD_A_RPC_STATUS_FLAGS, genl_rqstp->rq_flags) ||
1452 	    nla_put_u32(skb, NFSD_A_RPC_STATUS_PROG, genl_rqstp->rq_prog) ||
1453 	    nla_put_u32(skb, NFSD_A_RPC_STATUS_PROC, genl_rqstp->rq_proc) ||
1454 	    nla_put_u8(skb, NFSD_A_RPC_STATUS_VERSION, genl_rqstp->rq_vers) ||
1455 	    nla_put_s64(skb, NFSD_A_RPC_STATUS_SERVICE_TIME,
1456 			ktime_to_us(genl_rqstp->rq_stime),
1457 			NFSD_A_RPC_STATUS_PAD))
1458 		goto out_cancel;
1459 
1460 	switch (genl_rqstp->rq_saddr.ss_family) {
1461 	case AF_INET: {
1462 		const struct sockaddr_in *s_in, *d_in;
1463 
1464 		s_in = (const struct sockaddr_in *)&genl_rqstp->rq_saddr;
1465 		d_in = (const struct sockaddr_in *)&genl_rqstp->rq_daddr;
1466 		if (nla_put_in_addr(skb, NFSD_A_RPC_STATUS_SADDR4,
1467 				    s_in->sin_addr.s_addr) ||
1468 		    nla_put_in_addr(skb, NFSD_A_RPC_STATUS_DADDR4,
1469 				    d_in->sin_addr.s_addr) ||
1470 		    nla_put_be16(skb, NFSD_A_RPC_STATUS_SPORT,
1471 				 s_in->sin_port) ||
1472 		    nla_put_be16(skb, NFSD_A_RPC_STATUS_DPORT,
1473 				 d_in->sin_port))
1474 			goto out_cancel;
1475 		break;
1476 	}
1477 	case AF_INET6: {
1478 		const struct sockaddr_in6 *s_in, *d_in;
1479 
1480 		s_in = (const struct sockaddr_in6 *)&genl_rqstp->rq_saddr;
1481 		d_in = (const struct sockaddr_in6 *)&genl_rqstp->rq_daddr;
1482 		if (nla_put_in6_addr(skb, NFSD_A_RPC_STATUS_SADDR6,
1483 				     &s_in->sin6_addr) ||
1484 		    nla_put_in6_addr(skb, NFSD_A_RPC_STATUS_DADDR6,
1485 				     &d_in->sin6_addr) ||
1486 		    nla_put_be16(skb, NFSD_A_RPC_STATUS_SPORT,
1487 				 s_in->sin6_port) ||
1488 		    nla_put_be16(skb, NFSD_A_RPC_STATUS_DPORT,
1489 				 d_in->sin6_port))
1490 			goto out_cancel;
1491 		break;
1492 	}
1493 	}
1494 
1495 	for (i = 0; i < genl_rqstp->rq_opcnt; i++)
1496 		if (nla_put_u32(skb, NFSD_A_RPC_STATUS_COMPOUND_OPS,
1497 				genl_rqstp->rq_opnum[i]))
1498 			goto out_cancel;
1499 
1500 	genlmsg_end(skb, hdr);
1501 	return 0;
1502 
1503 out_cancel:
1504 	genlmsg_cancel(skb, hdr);
1505 	return -ENOBUFS;
1506 }
1507 
1508 /**
1509  * nfsd_nl_rpc_status_get_dumpit - Handle rpc_status_get dumpit
1510  * @skb: reply buffer
1511  * @cb: netlink metadata and command arguments
1512  *
1513  * Returns the size of the reply or a negative errno.
1514  */
nfsd_nl_rpc_status_get_dumpit(struct sk_buff * skb,struct netlink_callback * cb)1515 int nfsd_nl_rpc_status_get_dumpit(struct sk_buff *skb,
1516 				  struct netlink_callback *cb)
1517 {
1518 	int i, ret, rqstp_index = 0;
1519 	struct nfsd_net *nn;
1520 
1521 	mutex_lock(&nfsd_mutex);
1522 
1523 	nn = net_generic(sock_net(skb->sk), nfsd_net_id);
1524 	if (!nn->nfsd_serv) {
1525 		ret = -ENODEV;
1526 		goto out_unlock;
1527 	}
1528 
1529 	rcu_read_lock();
1530 
1531 	for (i = 0; i < svc_serv_nrpools(nn->nfsd_serv); i++) {
1532 		struct svc_rqst *rqstp;
1533 		long thread_skip = 0;
1534 
1535 		if (i < cb->args[0]) /* already consumed */
1536 			continue;
1537 
1538 		/*
1539 		 * The saved thread index only applies to the pool the dump
1540 		 * was resumed in. Subsequent pools must start from thread 0,
1541 		 * otherwise their first cb->args[1] threads are silently
1542 		 * skipped.
1543 		 */
1544 		if (i == cb->args[0])
1545 			thread_skip = cb->args[1];
1546 
1547 		rqstp_index = 0;
1548 		list_for_each_entry_rcu(rqstp,
1549 				&nn->nfsd_serv->sv_pools[i].sp_all_threads,
1550 				rq_all) {
1551 			struct nfsd_genl_rqstp genl_rqstp = {};
1552 			unsigned int status_counter;
1553 
1554 			if (rqstp_index++ < thread_skip) /* already consumed */
1555 				continue;
1556 			/*
1557 			 * Acquire rq_status_counter before parsing the rqst
1558 			 * fields. rq_status_counter is set to an odd value in
1559 			 * order to notify the consumers the rqstp fields are
1560 			 * meaningful.
1561 			 */
1562 			status_counter =
1563 				smp_load_acquire(&rqstp->rq_status_counter);
1564 			if (!(status_counter & 1))
1565 				continue;
1566 
1567 			genl_rqstp.rq_xid = rqstp->rq_xid;
1568 			genl_rqstp.rq_flags = rqstp->rq_flags;
1569 			genl_rqstp.rq_vers = rqstp->rq_vers;
1570 			genl_rqstp.rq_prog = rqstp->rq_prog;
1571 			genl_rqstp.rq_proc = rqstp->rq_proc;
1572 			genl_rqstp.rq_stime = rqstp->rq_stime;
1573 			genl_rqstp.rq_opcnt = 0;
1574 			memcpy(&genl_rqstp.rq_daddr, svc_daddr(rqstp),
1575 			       sizeof(struct sockaddr_storage));
1576 			memcpy(&genl_rqstp.rq_saddr, svc_addr(rqstp),
1577 			       sizeof(struct sockaddr_storage));
1578 
1579 #ifdef CONFIG_NFSD_V4
1580 			if (rqstp->rq_vers == NFS4_VERSION &&
1581 			    rqstp->rq_proc == NFSPROC4_COMPOUND) {
1582 				/* NFSv4 compound */
1583 				struct nfsd4_compoundargs *args;
1584 				int j;
1585 
1586 				args = rqstp->rq_argp;
1587 				genl_rqstp.rq_opcnt = min_t(u32, args->opcnt,
1588 							    ARRAY_SIZE(genl_rqstp.rq_opnum));
1589 				for (j = 0; j < genl_rqstp.rq_opcnt; j++)
1590 					genl_rqstp.rq_opnum[j] =
1591 						args->ops[j].opnum;
1592 			}
1593 #endif /* CONFIG_NFSD_V4 */
1594 
1595 			/*
1596 			 * Read-side load-load fence: order the field reads
1597 			 * above before the counter re-read below, mirroring
1598 			 * the smp_rmb() in the standard seqcount retry. The
1599 			 * begin-side smp_load_acquire() above pairs with the
1600 			 * smp_store_release() in nfsd_dispatch().
1601 			 */
1602 			smp_rmb();
1603 			if (READ_ONCE(rqstp->rq_status_counter) != status_counter)
1604 				continue;
1605 
1606 			ret = nfsd_genl_rpc_status_compose_msg(skb, cb,
1607 							       &genl_rqstp);
1608 			if (ret) {
1609 				if (skb->len) {
1610 					cb->args[0] = i;
1611 					cb->args[1] = rqstp_index - 1;
1612 					ret = skb->len;
1613 				}
1614 				goto out;
1615 			}
1616 		}
1617 	}
1618 
1619 	cb->args[0] = i;
1620 	cb->args[1] = rqstp_index;
1621 	ret = skb->len;
1622 out:
1623 	rcu_read_unlock();
1624 out_unlock:
1625 	mutex_unlock(&nfsd_mutex);
1626 
1627 	return ret;
1628 }
1629 
1630 /**
1631  * nfsd_nl_fh_key_set - helper to copy fh_key from userspace
1632  * @attr: nlattr NFSD_A_SERVER_FH_KEY
1633  * @nn: nfsd_net
1634  *
1635  * Callers should hold nfsd_mutex, returns 0 on success or negative errno.
1636  * Callers must ensure the server is shut down (sv_nrthreads == 0),
1637  * userspace documentation asserts the key may only be set when the server
1638  * is not running.
1639  */
nfsd_nl_fh_key_set(const struct nlattr * attr,struct nfsd_net * nn)1640 static int nfsd_nl_fh_key_set(const struct nlattr *attr, struct nfsd_net *nn)
1641 {
1642 	siphash_key_t *fh_key = nn->fh_key;
1643 	u64 k0, k1;
1644 	bool changed;
1645 
1646 	k0 = get_unaligned_le64(nla_data(attr));
1647 	k1 = get_unaligned_le64(nla_data(attr) + 8);
1648 
1649 	if (!fh_key) {
1650 		fh_key = kmalloc(sizeof(siphash_key_t), GFP_KERNEL);
1651 		if (!fh_key) {
1652 			trace_nfsd_ctl_fh_key_set(false, -ENOMEM);
1653 			return -ENOMEM;
1654 		}
1655 		nn->fh_key = fh_key;
1656 		changed = true;
1657 	} else {
1658 		changed = fh_key->key[0] != k0 || fh_key->key[1] != k1;
1659 	}
1660 
1661 	fh_key->key[0] = k0;
1662 	fh_key->key[1] = k1;
1663 	trace_nfsd_ctl_fh_key_set(changed, 0);
1664 	return 0;
1665 }
1666 
1667 /**
1668  * nfsd_nl_threads_set_doit - set the number of running threads
1669  * @skb: reply buffer
1670  * @info: netlink metadata and command arguments
1671  *
1672  * Return 0 on success or a negative errno.
1673  */
nfsd_nl_threads_set_doit(struct sk_buff * skb,struct genl_info * info)1674 int nfsd_nl_threads_set_doit(struct sk_buff *skb, struct genl_info *info)
1675 {
1676 	int *nthreads, nrpools = 0, i, ret = -EOPNOTSUPP, rem;
1677 	struct net *net = genl_info_net(info);
1678 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1679 	const struct nlattr *attr;
1680 	const char *scope = NULL;
1681 
1682 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_SERVER_THREADS))
1683 		return -EINVAL;
1684 
1685 	/* count number of SERVER_THREADS values */
1686 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_THREADS, info->nlhdr,
1687 				 GENL_HDRLEN, rem)
1688 		nrpools++;
1689 
1690 	mutex_lock(&nfsd_mutex);
1691 
1692 	nthreads = kzalloc_objs(int, nrpools);
1693 	if (!nthreads) {
1694 		ret = -ENOMEM;
1695 		goto out_unlock;
1696 	}
1697 
1698 	i = 0;
1699 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_THREADS, info->nlhdr,
1700 				 GENL_HDRLEN, rem) {
1701 		nthreads[i++] = nla_get_u32(attr);
1702 		if (i >= nrpools)
1703 			break;
1704 	}
1705 
1706 	if (info->attrs[NFSD_A_SERVER_GRACETIME] ||
1707 	    info->attrs[NFSD_A_SERVER_LEASETIME] ||
1708 	    info->attrs[NFSD_A_SERVER_SCOPE] ||
1709 	    info->attrs[NFSD_A_SERVER_FH_KEY]) {
1710 		ret = -EBUSY;
1711 		if (nn->nfsd_serv && nn->nfsd_serv->sv_nrthreads)
1712 			goto out_unlock;
1713 
1714 		ret = -EINVAL;
1715 		attr = info->attrs[NFSD_A_SERVER_GRACETIME];
1716 		if (attr) {
1717 			u32 gracetime = nla_get_u32(attr);
1718 
1719 			if (gracetime < 10 || gracetime > 3600)
1720 				goto out_unlock;
1721 
1722 			nn->nfsd4_grace = gracetime;
1723 		}
1724 
1725 		attr = info->attrs[NFSD_A_SERVER_LEASETIME];
1726 		if (attr) {
1727 			u32 leasetime = nla_get_u32(attr);
1728 
1729 			if (leasetime < 10 || leasetime > 3600)
1730 				goto out_unlock;
1731 
1732 			nn->nfsd4_lease = leasetime;
1733 		}
1734 
1735 		attr = info->attrs[NFSD_A_SERVER_SCOPE];
1736 		if (attr)
1737 			scope = nla_data(attr);
1738 
1739 		attr = info->attrs[NFSD_A_SERVER_FH_KEY];
1740 		if (attr) {
1741 			ret = nfsd_nl_fh_key_set(attr, nn);
1742 			if (ret)
1743 				goto out_unlock;
1744 		}
1745 	}
1746 
1747 	attr = info->attrs[NFSD_A_SERVER_MIN_THREADS];
1748 	if (attr)
1749 		nn->min_threads = nla_get_u32(attr);
1750 
1751 	ret = nfsd_svc(nrpools, nthreads, net, current_cred(), scope);
1752 	if (ret > 0)
1753 		ret = 0;
1754 out_unlock:
1755 	mutex_unlock(&nfsd_mutex);
1756 	kfree(nthreads);
1757 	return ret;
1758 }
1759 
1760 /**
1761  * nfsd_nl_threads_get_doit - get the maximum number of running threads
1762  * @skb: reply buffer
1763  * @info: netlink metadata and command arguments
1764  *
1765  * Return 0 on success or a negative errno.
1766  */
nfsd_nl_threads_get_doit(struct sk_buff * skb,struct genl_info * info)1767 int nfsd_nl_threads_get_doit(struct sk_buff *skb, struct genl_info *info)
1768 {
1769 	struct net *net = genl_info_net(info);
1770 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
1771 	void *hdr;
1772 	int err;
1773 
1774 	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
1775 	if (!skb)
1776 		return -ENOMEM;
1777 
1778 	hdr = genlmsg_iput(skb, info);
1779 	if (!hdr) {
1780 		err = -EMSGSIZE;
1781 		goto err_free_msg;
1782 	}
1783 
1784 	mutex_lock(&nfsd_mutex);
1785 
1786 	err = nla_put_u32(skb, NFSD_A_SERVER_GRACETIME,
1787 			  nn->nfsd4_grace) ||
1788 	      nla_put_u32(skb, NFSD_A_SERVER_LEASETIME,
1789 			  nn->nfsd4_lease) ||
1790 	      nla_put_u32(skb, NFSD_A_SERVER_MIN_THREADS,
1791 			  nn->min_threads) ||
1792 	      nla_put_string(skb, NFSD_A_SERVER_SCOPE,
1793 			  nn->nfsd_name);
1794 	if (err)
1795 		goto err_unlock;
1796 
1797 	if (nn->nfsd_serv) {
1798 		int i;
1799 
1800 		for (i = 0; i < nfsd_nrpools(net); ++i) {
1801 			struct svc_pool *sp = &nn->nfsd_serv->sv_pools[i];
1802 
1803 			err = nla_put_u32(skb, NFSD_A_SERVER_THREADS,
1804 					  sp->sp_nrthrmax);
1805 			if (err)
1806 				goto err_unlock;
1807 		}
1808 	} else {
1809 		err = nla_put_u32(skb, NFSD_A_SERVER_THREADS, 0);
1810 		if (err)
1811 			goto err_unlock;
1812 	}
1813 
1814 	mutex_unlock(&nfsd_mutex);
1815 
1816 	genlmsg_end(skb, hdr);
1817 
1818 	return genlmsg_reply(skb, info);
1819 
1820 err_unlock:
1821 	mutex_unlock(&nfsd_mutex);
1822 err_free_msg:
1823 	nlmsg_free(skb);
1824 
1825 	return err;
1826 }
1827 
1828 /**
1829  * nfsd_nl_version_set_doit - set the nfs enabled versions
1830  * @skb: reply buffer
1831  * @info: netlink metadata and command arguments
1832  *
1833  * Return 0 on success or a negative errno.
1834  */
nfsd_nl_version_set_doit(struct sk_buff * skb,struct genl_info * info)1835 int nfsd_nl_version_set_doit(struct sk_buff *skb, struct genl_info *info)
1836 {
1837 	const struct nlattr *attr;
1838 	struct nfsd_net *nn;
1839 	int i, rem;
1840 
1841 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_SERVER_PROTO_VERSION))
1842 		return -EINVAL;
1843 
1844 	mutex_lock(&nfsd_mutex);
1845 
1846 	nn = net_generic(genl_info_net(info), nfsd_net_id);
1847 	if (nn->nfsd_serv) {
1848 		mutex_unlock(&nfsd_mutex);
1849 		return -EBUSY;
1850 	}
1851 
1852 	/* clear current supported versions. */
1853 	nfsd_vers(nn, 2, NFSD_CLEAR);
1854 	nfsd_vers(nn, 3, NFSD_CLEAR);
1855 	for (i = 0; i <= NFSD_SUPPORTED_MINOR_VERSION; i++)
1856 		nfsd_minorversion(nn, i, NFSD_CLEAR);
1857 
1858 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_PROTO_VERSION, info->nlhdr,
1859 				 GENL_HDRLEN, rem) {
1860 		struct nlattr *tb[NFSD_A_VERSION_MAX + 1];
1861 		u32 major, minor = 0;
1862 		bool enabled;
1863 
1864 		if (nla_parse_nested(tb, NFSD_A_VERSION_MAX, attr,
1865 				     nfsd_version_nl_policy, info->extack) < 0)
1866 			continue;
1867 
1868 		if (!tb[NFSD_A_VERSION_MAJOR])
1869 			continue;
1870 
1871 		major = nla_get_u32(tb[NFSD_A_VERSION_MAJOR]);
1872 		if (tb[NFSD_A_VERSION_MINOR])
1873 			minor = nla_get_u32(tb[NFSD_A_VERSION_MINOR]);
1874 
1875 		enabled = nla_get_flag(tb[NFSD_A_VERSION_ENABLED]);
1876 
1877 		switch (major) {
1878 		case 4:
1879 			nfsd_minorversion(nn, minor, enabled ? NFSD_SET : NFSD_CLEAR);
1880 			break;
1881 		case 3:
1882 		case 2:
1883 			if (!minor)
1884 				nfsd_vers(nn, major, enabled ? NFSD_SET : NFSD_CLEAR);
1885 			break;
1886 		default:
1887 			break;
1888 		}
1889 	}
1890 
1891 	mutex_unlock(&nfsd_mutex);
1892 
1893 	return 0;
1894 }
1895 
1896 /**
1897  * nfsd_nl_version_get_doit - get the enabled status for all supported nfs versions
1898  * @skb: reply buffer
1899  * @info: netlink metadata and command arguments
1900  *
1901  * Return 0 on success or a negative errno.
1902  */
nfsd_nl_version_get_doit(struct sk_buff * skb,struct genl_info * info)1903 int nfsd_nl_version_get_doit(struct sk_buff *skb, struct genl_info *info)
1904 {
1905 	struct nfsd_net *nn;
1906 	int i, err;
1907 	void *hdr;
1908 
1909 	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
1910 	if (!skb)
1911 		return -ENOMEM;
1912 
1913 	hdr = genlmsg_iput(skb, info);
1914 	if (!hdr) {
1915 		err = -EMSGSIZE;
1916 		goto err_free_msg;
1917 	}
1918 
1919 	mutex_lock(&nfsd_mutex);
1920 	nn = net_generic(genl_info_net(info), nfsd_net_id);
1921 
1922 	for (i = 2; i <= 4; i++) {
1923 		int j;
1924 
1925 		for (j = 0; j <= NFSD_SUPPORTED_MINOR_VERSION; j++) {
1926 			struct nlattr *attr;
1927 
1928 			/* Don't record any versions the kernel doesn't have
1929 			 * compiled in
1930 			 */
1931 			if (!nfsd_support_version(i))
1932 				continue;
1933 
1934 			/* NFSv{2,3} does not support minor numbers */
1935 			if (i < 4 && j)
1936 				continue;
1937 
1938 			attr = nla_nest_start(skb,
1939 					      NFSD_A_SERVER_PROTO_VERSION);
1940 			if (!attr) {
1941 				err = -EINVAL;
1942 				goto err_nfsd_unlock;
1943 			}
1944 
1945 			if (nla_put_u32(skb, NFSD_A_VERSION_MAJOR, i) ||
1946 			    nla_put_u32(skb, NFSD_A_VERSION_MINOR, j)) {
1947 				err = -EINVAL;
1948 				goto err_nfsd_unlock;
1949 			}
1950 
1951 			/* Set the enabled flag if the version is enabled */
1952 			if (nfsd_vers(nn, i, NFSD_TEST) &&
1953 			    (i < 4 || nfsd_minorversion(nn, j, NFSD_TEST)) &&
1954 			    nla_put_flag(skb, NFSD_A_VERSION_ENABLED)) {
1955 				err = -EINVAL;
1956 				goto err_nfsd_unlock;
1957 			}
1958 
1959 			nla_nest_end(skb, attr);
1960 		}
1961 	}
1962 
1963 	mutex_unlock(&nfsd_mutex);
1964 	genlmsg_end(skb, hdr);
1965 
1966 	return genlmsg_reply(skb, info);
1967 
1968 err_nfsd_unlock:
1969 	mutex_unlock(&nfsd_mutex);
1970 err_free_msg:
1971 	nlmsg_free(skb);
1972 
1973 	return err;
1974 }
1975 
1976 /**
1977  * nfsd_nl_validate_listeners - sanity-check the listener list from userland
1978  * @info: netlink metadata and command arguments
1979  *
1980  * Walk every NFSD_A_SERVER_SOCK_ADDR attribute and confirm that each entry
1981  * is well-formed: it parses against the policy, carries both an address and
1982  * a transport name, and the address is long enough for its family. Doing
1983  * this up front lets the callers below assume every entry is valid and
1984  * guarantees we make no changes when the request is malformed.
1985  *
1986  * Return: 0 if every entry is valid, or a negative errno otherwise.
1987  */
nfsd_nl_validate_listeners(struct genl_info * info)1988 static int nfsd_nl_validate_listeners(struct genl_info *info)
1989 {
1990 	const struct nlattr *attr;
1991 	int rem;
1992 
1993 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_SOCK_ADDR, info->nlhdr,
1994 				 GENL_HDRLEN, rem) {
1995 		struct nlattr *tb[NFSD_A_SOCK_MAX + 1];
1996 		struct sockaddr *sa;
1997 		int err;
1998 
1999 		err = nla_parse_nested(tb, NFSD_A_SOCK_MAX, attr,
2000 				       nfsd_sock_nl_policy, info->extack);
2001 		if (err < 0)
2002 			return err;
2003 
2004 		if (!tb[NFSD_A_SOCK_ADDR] || !tb[NFSD_A_SOCK_TRANSPORT_NAME])
2005 			return -EINVAL;
2006 
2007 		sa = nla_data(tb[NFSD_A_SOCK_ADDR]);
2008 		if (nla_len(tb[NFSD_A_SOCK_ADDR]) < sizeof(sa->sa_family))
2009 			return -EINVAL;
2010 
2011 		switch (sa->sa_family) {
2012 		case AF_INET:
2013 			if (nla_len(tb[NFSD_A_SOCK_ADDR]) <
2014 			    sizeof(struct sockaddr_in))
2015 				return -EINVAL;
2016 			break;
2017 		case AF_INET6:
2018 			if (nla_len(tb[NFSD_A_SOCK_ADDR]) <
2019 			    sizeof(struct sockaddr_in6))
2020 				return -EINVAL;
2021 			break;
2022 		default:
2023 			return -EAFNOSUPPORT;
2024 		}
2025 	}
2026 
2027 	return 0;
2028 }
2029 
2030 /**
2031  * nfsd_nl_listener_set_doit - set the nfs running sockets
2032  * @skb: reply buffer
2033  * @info: netlink metadata and command arguments
2034  *
2035  * Return 0 on success or a negative errno.
2036  */
nfsd_nl_listener_set_doit(struct sk_buff * skb,struct genl_info * info)2037 int nfsd_nl_listener_set_doit(struct sk_buff *skb, struct genl_info *info)
2038 {
2039 	struct net *net = genl_info_net(info);
2040 	struct svc_xprt *xprt, *tmp;
2041 	const struct nlattr *attr;
2042 	struct svc_serv *serv;
2043 	LIST_HEAD(permsocks);
2044 	struct nfsd_net *nn;
2045 	bool delete = false;
2046 	int err, rem;
2047 
2048 	/*
2049 	 * Validate the entire listener list before making any changes, so a
2050 	 * malformed request fails cleanly without creating a serv or touching
2051 	 * the existing listeners.
2052 	 */
2053 	err = nfsd_nl_validate_listeners(info);
2054 	if (err)
2055 		return err;
2056 
2057 	mutex_lock(&nfsd_mutex);
2058 
2059 	err = nfsd_create_serv(net);
2060 	if (err) {
2061 		mutex_unlock(&nfsd_mutex);
2062 		return err;
2063 	}
2064 
2065 	nn = net_generic(net, nfsd_net_id);
2066 	serv = nn->nfsd_serv;
2067 
2068 	spin_lock_bh(&serv->sv_lock);
2069 
2070 	/* Move all of the old listener sockets to a temp list */
2071 	list_splice_init(&serv->sv_permsocks, &permsocks);
2072 
2073 	/*
2074 	 * Walk the list of server_socks from userland and move any that match
2075 	 * back to sv_permsocks
2076 	 */
2077 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_SOCK_ADDR, info->nlhdr,
2078 				 GENL_HDRLEN, rem) {
2079 		struct nlattr *tb[NFSD_A_SOCK_MAX + 1];
2080 		const char *xcl_name;
2081 		struct sockaddr *sa;
2082 
2083 		/* validated up front in nfsd_nl_validate_listeners() */
2084 		if (nla_parse_nested(tb, NFSD_A_SOCK_MAX, attr,
2085 				     nfsd_sock_nl_policy, info->extack) < 0)
2086 			continue;
2087 
2088 		xcl_name = nla_data(tb[NFSD_A_SOCK_TRANSPORT_NAME]);
2089 		sa = nla_data(tb[NFSD_A_SOCK_ADDR]);
2090 
2091 		/* Put back any matching sockets */
2092 		list_for_each_entry_safe(xprt, tmp, &permsocks, xpt_list) {
2093 			/* This shouldn't be possible */
2094 			if (WARN_ON_ONCE(xprt->xpt_net != net)) {
2095 				list_move(&xprt->xpt_list, &serv->sv_permsocks);
2096 				continue;
2097 			}
2098 
2099 			/* If everything matches, put it back */
2100 			if (!strcmp(xprt->xpt_class->xcl_name, xcl_name) &&
2101 			    rpc_cmp_addr_port(sa, (struct sockaddr *)&xprt->xpt_local)) {
2102 				list_move(&xprt->xpt_list, &serv->sv_permsocks);
2103 				break;
2104 			}
2105 		}
2106 	}
2107 
2108 	/*
2109 	 * If there are listener transports remaining on the permsocks list,
2110 	 * it means we were asked to remove a listener.
2111 	 */
2112 	if (!list_empty(&permsocks)) {
2113 		list_splice_init(&permsocks, &serv->sv_permsocks);
2114 		delete = true;
2115 	}
2116 	spin_unlock_bh(&serv->sv_lock);
2117 
2118 	/* Do not remove listeners while there are active threads. */
2119 	if (serv->sv_nrthreads) {
2120 		err = -EBUSY;
2121 		goto out_unlock_mtx;
2122 	}
2123 
2124 	/*
2125 	 * Since we can't delete an arbitrary llist entry, destroy the
2126 	 * remaining listeners and recreate the list.
2127 	 */
2128 	if (delete)
2129 		svc_xprt_destroy_all(serv, net, false);
2130 
2131 	/* walk list of addrs again, open any that still don't exist */
2132 	nlmsg_for_each_attr_type(attr, NFSD_A_SERVER_SOCK_ADDR, info->nlhdr,
2133 				 GENL_HDRLEN, rem) {
2134 		struct nlattr *tb[NFSD_A_SOCK_MAX + 1];
2135 		const char *xcl_name;
2136 		struct sockaddr *sa;
2137 		int ret;
2138 
2139 		/* validated up front in nfsd_nl_validate_listeners() */
2140 		if (nla_parse_nested(tb, NFSD_A_SOCK_MAX, attr,
2141 				     nfsd_sock_nl_policy, info->extack) < 0)
2142 			continue;
2143 
2144 		xcl_name = nla_data(tb[NFSD_A_SOCK_TRANSPORT_NAME]);
2145 		sa = nla_data(tb[NFSD_A_SOCK_ADDR]);
2146 
2147 		xprt = svc_find_listener(serv, xcl_name, net, sa);
2148 		if (xprt) {
2149 			if (delete)
2150 				WARN_ONCE(1, "Transport type=%s already exists\n",
2151 					  xcl_name);
2152 			svc_xprt_put(xprt);
2153 			continue;
2154 		}
2155 
2156 		ret = svc_xprt_create_from_sa(serv, xcl_name, net, sa, 0,
2157 					      current_cred());
2158 		/* always save the latest error */
2159 		if (ret < 0)
2160 			err = ret;
2161 	}
2162 
2163 	if (!serv->sv_nrthreads && list_empty(&nn->nfsd_serv->sv_permsocks))
2164 		nfsd_destroy_serv(net);
2165 
2166 out_unlock_mtx:
2167 	mutex_unlock(&nfsd_mutex);
2168 
2169 	return err;
2170 }
2171 
2172 /**
2173  * nfsd_nl_listener_get_doit - get the nfs running listeners
2174  * @skb: reply buffer
2175  * @info: netlink metadata and command arguments
2176  *
2177  * Return 0 on success or a negative errno.
2178  */
nfsd_nl_listener_get_doit(struct sk_buff * skb,struct genl_info * info)2179 int nfsd_nl_listener_get_doit(struct sk_buff *skb, struct genl_info *info)
2180 {
2181 	struct svc_xprt *xprt;
2182 	struct svc_serv *serv;
2183 	struct nfsd_net *nn;
2184 	void *hdr;
2185 	int err;
2186 
2187 	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
2188 	if (!skb)
2189 		return -ENOMEM;
2190 
2191 	hdr = genlmsg_iput(skb, info);
2192 	if (!hdr) {
2193 		err = -EMSGSIZE;
2194 		goto err_free_msg;
2195 	}
2196 
2197 	mutex_lock(&nfsd_mutex);
2198 	nn = net_generic(genl_info_net(info), nfsd_net_id);
2199 
2200 	/* no nfs server? Just send empty socket list */
2201 	if (!nn->nfsd_serv)
2202 		goto out_unlock_mtx;
2203 
2204 	serv = nn->nfsd_serv;
2205 	spin_lock_bh(&serv->sv_lock);
2206 	list_for_each_entry(xprt, &serv->sv_permsocks, xpt_list) {
2207 		struct nlattr *attr;
2208 
2209 		attr = nla_nest_start(skb, NFSD_A_SERVER_SOCK_ADDR);
2210 		if (!attr) {
2211 			err = -EINVAL;
2212 			goto err_serv_unlock;
2213 		}
2214 
2215 		if (nla_put_string(skb, NFSD_A_SOCK_TRANSPORT_NAME,
2216 				   xprt->xpt_class->xcl_name) ||
2217 		    nla_put(skb, NFSD_A_SOCK_ADDR,
2218 			    sizeof(struct sockaddr_storage),
2219 			    &xprt->xpt_local)) {
2220 			err = -EINVAL;
2221 			goto err_serv_unlock;
2222 		}
2223 
2224 		nla_nest_end(skb, attr);
2225 	}
2226 	spin_unlock_bh(&serv->sv_lock);
2227 out_unlock_mtx:
2228 	mutex_unlock(&nfsd_mutex);
2229 	genlmsg_end(skb, hdr);
2230 
2231 	return genlmsg_reply(skb, info);
2232 
2233 err_serv_unlock:
2234 	spin_unlock_bh(&serv->sv_lock);
2235 	mutex_unlock(&nfsd_mutex);
2236 err_free_msg:
2237 	nlmsg_free(skb);
2238 
2239 	return err;
2240 }
2241 
2242 /**
2243  * nfsd_nl_pool_mode_set_doit - set the number of running threads
2244  * @skb: reply buffer
2245  * @info: netlink metadata and command arguments
2246  *
2247  * Return 0 on success or a negative errno.
2248  */
nfsd_nl_pool_mode_set_doit(struct sk_buff * skb,struct genl_info * info)2249 int nfsd_nl_pool_mode_set_doit(struct sk_buff *skb, struct genl_info *info)
2250 {
2251 	const struct nlattr *attr;
2252 
2253 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_POOL_MODE_MODE))
2254 		return -EINVAL;
2255 
2256 	attr = info->attrs[NFSD_A_POOL_MODE_MODE];
2257 	return sunrpc_set_pool_mode(nla_data(attr));
2258 }
2259 
2260 /**
2261  * nfsd_nl_pool_mode_get_doit - get info about pool_mode
2262  * @skb: reply buffer
2263  * @info: netlink metadata and command arguments
2264  *
2265  * Return 0 on success or a negative errno.
2266  */
nfsd_nl_pool_mode_get_doit(struct sk_buff * skb,struct genl_info * info)2267 int nfsd_nl_pool_mode_get_doit(struct sk_buff *skb, struct genl_info *info)
2268 {
2269 	struct net *net = genl_info_net(info);
2270 	char buf[16];
2271 	void *hdr;
2272 	int err;
2273 
2274 	if (sunrpc_get_pool_mode(buf, ARRAY_SIZE(buf)) >= ARRAY_SIZE(buf))
2275 		return -ERANGE;
2276 
2277 	skb = genlmsg_new(GENLMSG_DEFAULT_SIZE, GFP_KERNEL);
2278 	if (!skb)
2279 		return -ENOMEM;
2280 
2281 	err = -EMSGSIZE;
2282 	hdr = genlmsg_iput(skb, info);
2283 	if (!hdr)
2284 		goto err_free_msg;
2285 
2286 	err = nla_put_string(skb, NFSD_A_POOL_MODE_MODE, buf) |
2287 	      nla_put_u32(skb, NFSD_A_POOL_MODE_NPOOLS, nfsd_nrpools(net));
2288 	if (err)
2289 		goto err_free_msg;
2290 
2291 	genlmsg_end(skb, hdr);
2292 	return genlmsg_reply(skb, info);
2293 
2294 err_free_msg:
2295 	nlmsg_free(skb);
2296 	return err;
2297 }
2298 
2299 /**
2300  * nfsd_nl_cache_flush_doit - flush nfsd caches via netlink
2301  * @skb: reply buffer
2302  * @info: netlink metadata and command arguments
2303  *
2304  * Flush the svc_export and/or expkey caches. If NFSD_A_CACHE_FLUSH_MASK
2305  * is provided, only flush the caches indicated by the bitmask (bit 0 =
2306  * svc_export, bit 1 = expkey). If omitted, flush both.
2307  *
2308  * Return 0 on success or a negative errno.
2309  */
nfsd_nl_cache_flush_doit(struct sk_buff * skb,struct genl_info * info)2310 int nfsd_nl_cache_flush_doit(struct sk_buff *skb, struct genl_info *info)
2311 {
2312 	struct net *net = genl_info_net(info);
2313 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2314 	u32 mask = ~0U;
2315 
2316 	if (info->attrs[NFSD_A_CACHE_FLUSH_MASK])
2317 		mask = nla_get_u32(info->attrs[NFSD_A_CACHE_FLUSH_MASK]);
2318 
2319 	mutex_lock(&nfsd_mutex);
2320 
2321 	if ((mask & NFSD_CACHE_TYPE_SVC_EXPORT) &&
2322 	    nn->svc_export_cache)
2323 		cache_purge(nn->svc_export_cache);
2324 
2325 	if ((mask & NFSD_CACHE_TYPE_EXPKEY) &&
2326 	    nn->svc_expkey_cache)
2327 		cache_purge(nn->svc_expkey_cache);
2328 
2329 	mutex_unlock(&nfsd_mutex);
2330 
2331 	return 0;
2332 }
2333 
2334 /* Emit a single server-proc-entry nest: { op, count }. */
nfsd_nl_put_proc_entry(struct sk_buff * skb,int attr,u32 op,u64 count)2335 static int nfsd_nl_put_proc_entry(struct sk_buff *skb, int attr,
2336 				  u32 op, u64 count)
2337 {
2338 	struct nlattr *nest;
2339 
2340 	nest = nla_nest_start(skb, attr);
2341 	if (!nest)
2342 		return -EMSGSIZE;
2343 	if (nla_put_u32(skb, NFSD_A_SERVER_PROC_ENTRY_OP, op) ||
2344 	    nla_put_u64_64bit(skb, NFSD_A_SERVER_PROC_ENTRY_COUNT,
2345 			      count, NFSD_A_SERVER_PROC_ENTRY_PAD)) {
2346 		nla_nest_cancel(skb, nest);
2347 		return -EMSGSIZE;
2348 	}
2349 	nla_nest_end(skb, nest);
2350 	return 0;
2351 }
2352 
2353 /* Emit the scalar server-stats counters. Only ever called on a fresh skb. */
nfsd_nl_server_stats_scalars(struct sk_buff * skb,struct nfsd_net * nn,struct svc_stat * statp)2354 static int nfsd_nl_server_stats_scalars(struct sk_buff *skb,
2355 					struct nfsd_net *nn,
2356 					struct svc_stat *statp)
2357 {
2358 	if (nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_RC_HITS,
2359 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_RC_HITS]),
2360 			NFSD_A_SERVER_STATS_PAD) ||
2361 	    nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_RC_MISSES,
2362 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_RC_MISSES]),
2363 			NFSD_A_SERVER_STATS_PAD) ||
2364 	    nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_RC_NOCACHE,
2365 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_RC_NOCACHE]),
2366 			NFSD_A_SERVER_STATS_PAD))
2367 		return -EMSGSIZE;
2368 
2369 	if (nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_FH_STALE,
2370 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_FH_STALE]),
2371 			NFSD_A_SERVER_STATS_PAD))
2372 		return -EMSGSIZE;
2373 
2374 	if (nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_IO_READ,
2375 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_IO_READ]),
2376 			NFSD_A_SERVER_STATS_PAD) ||
2377 	    nla_put_u64_64bit(skb, NFSD_A_SERVER_STATS_IO_WRITE,
2378 			percpu_counter_sum_positive(&nn->counter[NFSD_STATS_IO_WRITE]),
2379 			NFSD_A_SERVER_STATS_PAD))
2380 		return -EMSGSIZE;
2381 
2382 	if (nla_put_u32(skb, NFSD_A_SERVER_STATS_NETCNT, statp->netcnt) ||
2383 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_NETUDPCNT, statp->netudpcnt) ||
2384 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_NETTCPCNT, statp->nettcpcnt) ||
2385 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_NETTCPCONN, statp->nettcpconn))
2386 		return -EMSGSIZE;
2387 
2388 	if (nla_put_u32(skb, NFSD_A_SERVER_STATS_RPCCNT, statp->rpccnt) ||
2389 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_RPCBADFMT, statp->rpcbadfmt) ||
2390 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_RPCBADAUTH, statp->rpcbadauth) ||
2391 	    nla_put_u32(skb, NFSD_A_SERVER_STATS_RPCBADCLNT, statp->rpcbadclnt))
2392 		return -EMSGSIZE;
2393 
2394 	return 0;
2395 }
2396 
2397 /*
2398  * Emit per-version procedure counts for one NFS version, resuming at *idx.
2399  * Returns 0 when the version has been fully emitted (or is not present), or
2400  * -EMSGSIZE when @skb filled up, leaving *idx at the entry still to emit.
2401  */
nfsd_nl_server_stats_proc(struct sk_buff * skb,struct svc_stat * statp,struct svc_program * prog,unsigned int ver,int attr,int * idx)2402 static int nfsd_nl_server_stats_proc(struct sk_buff *skb,
2403 				     struct svc_stat *statp,
2404 				     struct svc_program *prog,
2405 				     unsigned int ver, int attr, int *idx)
2406 {
2407 	unsigned long __percpu *counts;
2408 	unsigned int nproc;
2409 
2410 	if (!statp->vs_count || ver >= prog->pg_nvers ||
2411 	    !prog->pg_vers[ver] || !statp->vs_count[ver])
2412 		return 0;
2413 
2414 	counts = statp->vs_count[ver];
2415 	nproc = prog->pg_vers[ver]->vs_nproc;
2416 
2417 	for (; *idx < nproc; (*idx)++) {
2418 		unsigned long count = 0;
2419 		int cpu;
2420 
2421 		for_each_possible_cpu(cpu)
2422 			count += per_cpu(counts[*idx], cpu);
2423 
2424 		if (!count)
2425 			continue;
2426 		if (nfsd_nl_put_proc_entry(skb, attr, *idx, count))
2427 			return -EMSGSIZE;
2428 	}
2429 
2430 	return 0;
2431 }
2432 
2433 #ifdef CONFIG_NFSD_V4
2434 /*
2435  * Emit NFSv4 per-operation counts, resuming at *idx. Same return convention
2436  * as nfsd_nl_server_stats_proc().
2437  */
nfsd_nl_server_stats_nfs4ops(struct sk_buff * skb,struct nfsd_net * nn,int * idx)2438 static int nfsd_nl_server_stats_nfs4ops(struct sk_buff *skb,
2439 					struct nfsd_net *nn, int *idx)
2440 {
2441 	for (; *idx <= LAST_NFS4_OP; (*idx)++) {
2442 		u64 cnt = percpu_counter_sum_positive(
2443 				&nn->counter[NFSD_STATS_NFS4_OP(*idx)]);
2444 
2445 		if (!cnt)
2446 			continue;
2447 		if (nfsd_nl_put_proc_entry(skb, NFSD_A_SERVER_STATS_PROC4OPS_OPS,
2448 					   *idx, cnt))
2449 			return -EMSGSIZE;
2450 	}
2451 
2452 	return 0;
2453 }
2454 
2455 /*
2456  * Emit NFSv4 callback (backchannel) per-operation counts, resuming at *idx,
2457  * which counts from OP_CB_GETATTR. Same return convention as
2458  * nfsd_nl_server_stats_proc().
2459  */
nfsd_nl_server_stats_cbops(struct sk_buff * skb,struct nfsd_net * nn,int * idx)2460 static int nfsd_nl_server_stats_cbops(struct sk_buff *skb,
2461 				      struct nfsd_net *nn, int *idx)
2462 {
2463 	int op;
2464 
2465 	for (op = OP_CB_GETATTR + *idx; op <= OP_CB_OFFLOAD; op++, (*idx)++) {
2466 		u64 cnt = percpu_counter_sum_positive(&nn->cb_counter[op]);
2467 
2468 		if (!cnt)
2469 			continue;
2470 		if (nfsd_nl_put_proc_entry(skb, NFSD_A_SERVER_STATS_PROC4CB_OPS,
2471 					   op, cnt))
2472 			return -EMSGSIZE;
2473 	}
2474 
2475 	return 0;
2476 }
2477 #endif
2478 
2479 /* Sections of the server-stats dump, emitted in order across messages. */
2480 enum {
2481 	NFSD_SERVER_STATS_SCALARS = 0,
2482 	NFSD_SERVER_STATS_PROC2,
2483 	NFSD_SERVER_STATS_PROC3,
2484 	NFSD_SERVER_STATS_PROC4,
2485 	NFSD_SERVER_STATS_PROC4CB,
2486 	NFSD_SERVER_STATS_PROC4OPS,
2487 	NFSD_SERVER_STATS_DONE,
2488 };
2489 
2490 /**
2491  * nfsd_nl_server_stats_get_dumpit - dump NFS server statistics
2492  * @skb: reply buffer
2493  * @cb: netlink metadata and command arguments
2494  *
2495  * The server-stats object is emitted across one or more netlink messages.
2496  * cb->args[0] tracks the current section and cb->args[1] the entry index
2497  * within it, so a section that does not fit in the current message is resumed
2498  * in the next one. The scalar counters are small and emitted once, in the
2499  * first message; userspace merges the attributes from every message.
2500  *
2501  * Returns the size of the reply or a negative errno.
2502  */
nfsd_nl_server_stats_get_dumpit(struct sk_buff * skb,struct netlink_callback * cb)2503 int nfsd_nl_server_stats_get_dumpit(struct sk_buff *skb,
2504 				    struct netlink_callback *cb)
2505 {
2506 	struct net *net = sock_net(skb->sk);
2507 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2508 	struct svc_stat *statp = &nn->nfsd_svcstats;
2509 	struct svc_program *prog = statp->program;
2510 	int section = cb->args[0];
2511 	int idx = cb->args[1];
2512 	void *hdr;
2513 
2514 	if (section >= NFSD_SERVER_STATS_DONE)
2515 		return 0;
2516 
2517 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid,
2518 			  cb->nlh->nlmsg_seq, &nfsd_nl_family,
2519 			  NLM_F_MULTI, NFSD_CMD_SERVER_STATS_GET);
2520 	if (!hdr)
2521 		return -ENOBUFS;
2522 
2523 	/* Scalar stats fit easily and are emitted in the first message. */
2524 	if (section == NFSD_SERVER_STATS_SCALARS) {
2525 		if (nfsd_nl_server_stats_scalars(skb, nn, statp))
2526 			goto err_cancel;
2527 		section = NFSD_SERVER_STATS_PROC2;
2528 		idx = 0;
2529 	}
2530 
2531 	/*
2532 	 * Emit as many of the remaining sections as fit. A section returning
2533 	 * -EMSGSIZE means the message is full: close it and resume from the
2534 	 * same section/index on the next call with a fresh skb. Each entry is
2535 	 * small enough to fit in a fresh skb, so forward progress is assured.
2536 	 */
2537 	while (section < NFSD_SERVER_STATS_DONE) {
2538 		int ret = 0;
2539 
2540 		switch (section) {
2541 		case NFSD_SERVER_STATS_PROC2:
2542 			ret = nfsd_nl_server_stats_proc(skb, statp, prog, 2,
2543 					NFSD_A_SERVER_STATS_PROC2_OPS, &idx);
2544 			break;
2545 		case NFSD_SERVER_STATS_PROC3:
2546 			ret = nfsd_nl_server_stats_proc(skb, statp, prog, 3,
2547 					NFSD_A_SERVER_STATS_PROC3_OPS, &idx);
2548 			break;
2549 		case NFSD_SERVER_STATS_PROC4:
2550 			ret = nfsd_nl_server_stats_proc(skb, statp, prog, 4,
2551 					NFSD_A_SERVER_STATS_PROC4_OPS, &idx);
2552 			break;
2553 #ifdef CONFIG_NFSD_V4
2554 		case NFSD_SERVER_STATS_PROC4CB:
2555 			ret = nfsd_nl_server_stats_cbops(skb, nn, &idx);
2556 			break;
2557 		case NFSD_SERVER_STATS_PROC4OPS:
2558 			ret = nfsd_nl_server_stats_nfs4ops(skb, nn, &idx);
2559 			break;
2560 #endif
2561 		}
2562 
2563 		if (ret == -EMSGSIZE)
2564 			goto out;
2565 		if (ret)
2566 			goto err_cancel;
2567 
2568 		section++;
2569 		idx = 0;
2570 	}
2571 
2572 out:
2573 	genlmsg_end(skb, hdr);
2574 	cb->args[0] = section;
2575 	cb->args[1] = idx;
2576 	return skb->len;
2577 
2578 err_cancel:
2579 	genlmsg_cancel(skb, hdr);
2580 	return -EMSGSIZE;
2581 }
2582 
nfsd_cache_notify(struct cache_detail * cd,struct cache_head * h,u32 cache_type)2583 int nfsd_cache_notify(struct cache_detail *cd, struct cache_head *h, u32 cache_type)
2584 {
2585 	struct genlmsghdr *hdr;
2586 	struct sk_buff *msg;
2587 
2588 	if (!genl_has_listeners(&nfsd_nl_family, cd->net, NFSD_NLGRP_EXPORTD))
2589 		return -ENOLINK;
2590 
2591 	msg = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2592 	if (!msg)
2593 		return -ENOMEM;
2594 
2595 	hdr = genlmsg_put(msg, 0, 0, &nfsd_nl_family, 0, NFSD_CMD_CACHE_NOTIFY);
2596 	if (!hdr) {
2597 		nlmsg_free(msg);
2598 		return -ENOMEM;
2599 	}
2600 
2601 	if (nla_put_u32(msg, NFSD_A_CACHE_NOTIFY_CACHE_TYPE, cache_type)) {
2602 		nlmsg_free(msg);
2603 		return -ENOMEM;
2604 	}
2605 
2606 	genlmsg_end(msg, hdr);
2607 	return genlmsg_multicast_netns(&nfsd_nl_family, cd->net, msg, 0,
2608 				       NFSD_NLGRP_EXPORTD, GFP_KERNEL);
2609 }
2610 
2611 /**
2612  * nfsd_nl_unlock_ip_doit - release NLM locks held by an IP address
2613  * @skb: reply buffer
2614  * @info: netlink metadata and command arguments
2615  *
2616  * Return: 0 on success or a negative errno.
2617  */
nfsd_nl_unlock_ip_doit(struct sk_buff * skb,struct genl_info * info)2618 int nfsd_nl_unlock_ip_doit(struct sk_buff *skb, struct genl_info *info)
2619 {
2620 	struct sockaddr *sap;
2621 
2622 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_UNLOCK_IP_ADDRESS))
2623 		return -EINVAL;
2624 	sap = nla_data(info->attrs[NFSD_A_UNLOCK_IP_ADDRESS]);
2625 	switch (sap->sa_family) {
2626 	case AF_INET:
2627 		if (nla_len(info->attrs[NFSD_A_UNLOCK_IP_ADDRESS]) <
2628 		    sizeof(struct sockaddr_in))
2629 			return -EINVAL;
2630 		break;
2631 	case AF_INET6:
2632 		if (nla_len(info->attrs[NFSD_A_UNLOCK_IP_ADDRESS]) <
2633 		    sizeof(struct sockaddr_in6))
2634 			return -EINVAL;
2635 		break;
2636 	default:
2637 		return -EAFNOSUPPORT;
2638 	}
2639 	/*
2640 	 * nlmsvc_unlock_all_by_ip() releases matching locks
2641 	 * across all network namespaces because lockd operates
2642 	 * a single global instance.
2643 	 */
2644 	trace_nfsd_ctl_unlock_ip(genl_info_net(info), sap,
2645 				 svc_addr_len(sap));
2646 	return nlmsvc_unlock_all_by_ip(sap);
2647 }
2648 
2649 /**
2650  * nfsd_nl_unlock_filesystem_doit - revoke NFS state under a filesystem path
2651  * @skb: reply buffer
2652  * @info: netlink metadata and command arguments
2653  *
2654  * Return: 0 on success or a negative errno.
2655  */
nfsd_nl_unlock_filesystem_doit(struct sk_buff * skb,struct genl_info * info)2656 int nfsd_nl_unlock_filesystem_doit(struct sk_buff *skb,
2657 				   struct genl_info *info)
2658 {
2659 	struct net *net = genl_info_net(info);
2660 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2661 	struct path path;
2662 	int error;
2663 
2664 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_UNLOCK_FILESYSTEM_PATH))
2665 		return -EINVAL;
2666 
2667 	trace_nfsd_ctl_unlock_fs(net,
2668 			nla_data(info->attrs[NFSD_A_UNLOCK_FILESYSTEM_PATH]));
2669 	error = kern_path(
2670 			nla_data(info->attrs[NFSD_A_UNLOCK_FILESYSTEM_PATH]),
2671 			0, &path);
2672 	if (error)
2673 		return error;
2674 
2675 	error = nlmsvc_unlock_all_by_sb(path.dentry->d_sb);
2676 
2677 	mutex_lock(&nfsd_mutex);
2678 	if (test_bit(NFSD_NET_UP, &nn->flags)) {
2679 		nfsd4_cancel_copy_by_sb(net, path.dentry->d_sb);
2680 		nfsd4_revoke_states(nn, path.dentry->d_sb);
2681 	} else {
2682 		error = -EINVAL;
2683 	}
2684 	mutex_unlock(&nfsd_mutex);
2685 
2686 	path_put(&path);
2687 	return error;
2688 }
2689 
2690 /**
2691  * nfsd_nl_unlock_export_doit - revoke NFSv4 state for an export path
2692  * @skb: reply buffer
2693  * @info: netlink metadata and command arguments
2694  *
2695  * Revokes all NFSv4 state (opens, locks, delegations, layouts) acquired
2696  * through any export of the given path, regardless of which client holds
2697  * the state.  Userspace (exportfs -u) sends this after removing the last
2698  * client for a path so the underlying filesystem can be unmounted.
2699  *
2700  * Unlike NFSD_CMD_UNLOCK_FILESYSTEM, which operates at superblock
2701  * granularity, this command revokes only the state associated with
2702  * exports of a specific path.
2703  *
2704  * Return: 0 on success or a negative errno.
2705  */
nfsd_nl_unlock_export_doit(struct sk_buff * skb,struct genl_info * info)2706 int nfsd_nl_unlock_export_doit(struct sk_buff *skb, struct genl_info *info)
2707 {
2708 	struct net *net = genl_info_net(info);
2709 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2710 	struct path path;
2711 	int error;
2712 
2713 	if (GENL_REQ_ATTR_CHECK(info, NFSD_A_UNLOCK_EXPORT_PATH))
2714 		return -EINVAL;
2715 
2716 	trace_nfsd_ctl_unlock_export(net,
2717 			nla_data(info->attrs[NFSD_A_UNLOCK_EXPORT_PATH]));
2718 	error = kern_path(
2719 			nla_data(info->attrs[NFSD_A_UNLOCK_EXPORT_PATH]),
2720 			0, &path);
2721 	if (error)
2722 		return error;
2723 
2724 	mutex_lock(&nfsd_mutex);
2725 	if (test_bit(NFSD_NET_UP, &nn->flags)) {
2726 		nfsd_file_close_export(net, &path);
2727 		nfsd4_revoke_export_states(nn, &path);
2728 	} else
2729 		error = -EINVAL;
2730 	mutex_unlock(&nfsd_mutex);
2731 
2732 	path_put(&path);
2733 	return error;
2734 }
2735 
2736 /**
2737  * nfsd_net_init - Prepare the nfsd_net portion of a new net namespace
2738  * @net: a freshly-created network namespace
2739  *
2740  * This information stays around as long as the network namespace is
2741  * alive whether or not there is an NFSD instance running in the
2742  * namespace.
2743  *
2744  * Returns zero on success, or a negative errno otherwise.
2745  */
nfsd_net_init(struct net * net)2746 static __net_init int nfsd_net_init(struct net *net)
2747 {
2748 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2749 	int retval;
2750 	int i;
2751 
2752 	retval = nfsd_net_cb_init(nn);
2753 	if (retval)
2754 		return retval;
2755 	retval = nfsd_export_init(net);
2756 	if (retval)
2757 		goto out_export_error;
2758 	retval = nfsd_idmap_init(net);
2759 	if (retval)
2760 		goto out_idmap_error;
2761 	retval = percpu_counter_init_many(nn->counter, 0, GFP_KERNEL,
2762 					  NFSD_STATS_COUNTERS_NUM);
2763 	if (retval)
2764 		goto out_repcache_error;
2765 
2766 #ifdef CONFIG_NFSD_V4
2767 	retval = percpu_counter_init_many(nn->cb_counter, 0, GFP_KERNEL,
2768 					  NFSD_STATS_CB_OPS_NUM);
2769 	if (retval)
2770 		goto out_cb_counter_error;
2771 #endif
2772 
2773 	memset(&nn->nfsd_svcstats, 0, sizeof(nn->nfsd_svcstats));
2774 	nn->nfsd_svcstats.program = &nfsd_programs[0];
2775 	retval = svc_stat_alloc_counts(&nn->nfsd_svcstats);
2776 	if (retval)
2777 		goto out_proc_error;
2778 	if (!nfsd_proc_stat_init(net)) {
2779 		retval = -ENOMEM;
2780 		goto out_svcstats_error;
2781 	}
2782 
2783 	for (i = 0; i < sizeof(nn->nfsd_versions); i++)
2784 		nn->nfsd_versions[i] = nfsd_support_version(i);
2785 	for (i = 0; i < sizeof(nn->nfsd4_minorversions); i++)
2786 		nn->nfsd4_minorversions[i] = nfsd_support_version(4);
2787 	nn->nfsd_info.mutex = &nfsd_mutex;
2788 	nn->nfsd_serv = NULL;
2789 	nfsd4_init_leases_net(nn);
2790 	get_random_bytes(&nn->siphash_key, sizeof(nn->siphash_key));
2791 	seqlock_init(&nn->writeverf_lock);
2792 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
2793 	spin_lock_init(&nn->local_clients_lock);
2794 	INIT_LIST_HEAD(&nn->local_clients);
2795 #endif
2796 	return 0;
2797 
2798 out_svcstats_error:
2799 	svc_stat_free_counts(&nn->nfsd_svcstats);
2800 out_proc_error:
2801 #ifdef CONFIG_NFSD_V4
2802 	percpu_counter_destroy_many(nn->cb_counter, NFSD_STATS_CB_OPS_NUM);
2803 out_cb_counter_error:
2804 #endif
2805 	percpu_counter_destroy_many(nn->counter, NFSD_STATS_COUNTERS_NUM);
2806 out_repcache_error:
2807 	nfsd_idmap_shutdown(net);
2808 out_idmap_error:
2809 	nfsd_export_shutdown(net);
2810 out_export_error:
2811 	nfsd_net_cb_shutdown(nn);
2812 	return retval;
2813 }
2814 
2815 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
2816 /**
2817  * nfsd_net_pre_exit - Disconnect localio clients from net namespace
2818  * @net: a network namespace that is about to be destroyed
2819  *
2820  * This invalidates ->net pointers held by localio clients
2821  * while they can still safely access nn->counter.
2822  */
nfsd_net_pre_exit(struct net * net)2823 static __net_exit void nfsd_net_pre_exit(struct net *net)
2824 {
2825 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2826 
2827 	nfs_localio_invalidate_clients(&nn->local_clients,
2828 				       &nn->local_clients_lock);
2829 }
2830 #endif
2831 
2832 /**
2833  * nfsd_net_exit - Release the nfsd_net portion of a net namespace
2834  * @net: a network namespace that is about to be destroyed
2835  *
2836  */
nfsd_net_exit(struct net * net)2837 static __net_exit void nfsd_net_exit(struct net *net)
2838 {
2839 	struct nfsd_net *nn = net_generic(net, nfsd_net_id);
2840 
2841 	kfree_sensitive(nn->fh_key);
2842 	nfsd_net_cb_shutdown(nn);
2843 	nfsd_proc_stat_shutdown(net);
2844 	svc_stat_free_counts(&nn->nfsd_svcstats);
2845 #ifdef CONFIG_NFSD_V4
2846 	percpu_counter_destroy_many(nn->cb_counter, NFSD_STATS_CB_OPS_NUM);
2847 #endif
2848 	percpu_counter_destroy_many(nn->counter, NFSD_STATS_COUNTERS_NUM);
2849 	nfsd_idmap_shutdown(net);
2850 	nfsd_export_shutdown(net);
2851 }
2852 
2853 static struct pernet_operations nfsd_net_ops = {
2854 	.init = nfsd_net_init,
2855 #if IS_ENABLED(CONFIG_NFS_LOCALIO)
2856 	.pre_exit = nfsd_net_pre_exit,
2857 #endif
2858 	.exit = nfsd_net_exit,
2859 	.id   = &nfsd_net_id,
2860 	.size = sizeof(struct nfsd_net),
2861 };
2862 
init_nfsd(void)2863 static int __init init_nfsd(void)
2864 {
2865 	int retval;
2866 
2867 	retval = nfsd4_init_slabs();
2868 	if (retval)
2869 		return retval;
2870 
2871 	nfsd_debugfs_init();
2872 
2873 	retval = nfsd4_init_pnfs();
2874 	if (retval)
2875 		goto out_free_slabs;
2876 	retval = nfsd_drc_slab_create();
2877 	if (retval)
2878 		goto out_free_pnfs;
2879 	nfsd_lockd_init();	/* lockd->nfsd callbacks */
2880 	retval = register_pernet_subsys(&nfsd_net_ops);
2881 	if (retval < 0)
2882 		goto out_free_lockd;
2883 	retval = register_cld_notifier();
2884 	if (retval)
2885 		goto out_free_subsys;
2886 	retval = nfsd4_create_laundry_wq();
2887 	if (retval)
2888 		goto out_free_cld;
2889 	retval = register_filesystem(&nfsd_fs_type);
2890 	if (retval)
2891 		goto out_free_nfsd4;
2892 	retval = genl_register_family(&nfsd_nl_family);
2893 	if (retval)
2894 		goto out_free_filesystem;
2895 	retval = create_proc_exports_entry();
2896 	if (retval)
2897 		goto out_free_all;
2898 	nfsd_localio_ops_init();
2899 
2900 	return 0;
2901 out_free_all:
2902 	genl_unregister_family(&nfsd_nl_family);
2903 out_free_filesystem:
2904 	unregister_filesystem(&nfsd_fs_type);
2905 out_free_nfsd4:
2906 	nfsd4_destroy_laundry_wq();
2907 out_free_cld:
2908 	unregister_cld_notifier();
2909 out_free_subsys:
2910 	unregister_pernet_subsys(&nfsd_net_ops);
2911 out_free_lockd:
2912 	nfsd_lockd_shutdown();
2913 	nfsd_drc_slab_free();
2914 out_free_pnfs:
2915 	nfsd4_exit_pnfs();
2916 out_free_slabs:
2917 	nfsd_debugfs_exit();
2918 	nfsd4_free_slabs();
2919 	return retval;
2920 }
2921 
exit_nfsd(void)2922 static void __exit exit_nfsd(void)
2923 {
2924 	remove_proc_entry("fs/nfs/exports", NULL);
2925 	remove_proc_entry("fs/nfs", NULL);
2926 	genl_unregister_family(&nfsd_nl_family);
2927 	unregister_filesystem(&nfsd_fs_type);
2928 	nfsd4_destroy_laundry_wq();
2929 	unregister_cld_notifier();
2930 	unregister_pernet_subsys(&nfsd_net_ops);
2931 	nfsd_drc_slab_free();
2932 	nfsd_lockd_shutdown();
2933 	nfsd4_exit_pnfs();
2934 	nfsd_debugfs_exit();
2935 	nfsd4_free_slabs();
2936 }
2937 
2938 MODULE_AUTHOR("Olaf Kirch <okir@monad.swb.de>");
2939 MODULE_DESCRIPTION("In-kernel NFS server");
2940 MODULE_LICENSE("GPL");
2941 module_init(init_nfsd)
2942 module_exit(exit_nfsd)
2943