xref: /linux/net/sunrpc/svc.c (revision 893a68af6a2e06fb6cb5373d9370197405552f65)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * linux/net/sunrpc/svc.c
4  *
5  * High-level RPC service routines
6  *
7  * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
8  *
9  * Multiple threads pools and NUMAisation
10  * Copyright (c) 2006 Silicon Graphics, Inc.
11  * by Greg Banks <gnb@melbourne.sgi.com>
12  */
13 
14 #include <linux/linkage.h>
15 #include <linux/sched/signal.h>
16 #include <linux/errno.h>
17 #include <linux/net.h>
18 #include <linux/in.h>
19 #include <linux/mm.h>
20 #include <linux/interrupt.h>
21 #include <linux/module.h>
22 #include <linux/kthread.h>
23 #include <linux/slab.h>
24 
25 #include <linux/sunrpc/types.h>
26 #include <linux/sunrpc/xdr.h>
27 #include <linux/sunrpc/stats.h>
28 #include <linux/sunrpc/svcsock.h>
29 #include <linux/sunrpc/clnt.h>
30 #include <linux/sunrpc/bc_xprt.h>
31 
32 #include <trace/events/sunrpc.h>
33 
34 #include "fail.h"
35 #include "sunrpc.h"
36 
37 #define RPCDBG_FACILITY	RPCDBG_SVCDSP
38 
39 static void svc_unregister(const struct svc_serv *serv, struct net *net);
40 
41 /*
42  * Structure for mapping nodes to pools and vice versa.
43  * Setup once during sunrpc initialisation.
44  */
45 
46 struct svc_pool_map {
47 	int count;			/* How many svc_servs use us */
48 	unsigned int npools;
49 	unsigned int *pool_to;		/* maps pool id to node */
50 	unsigned int *to_pool;		/* maps node to pool id */
51 };
52 
53 static struct svc_pool_map svc_pool_map;
54 
55 static DEFINE_MUTEX(svc_pool_map_mutex);/* protects svc_pool_map.count only */
56 
57 /*
58  * Pool modes that were historically accepted. They no longer select
59  * anything: the pool mode is always pernode. The names are retained
60  * only so that writing a previously-valid value still succeeds.
61  */
62 static const char * const pool_mode_names[] = {
63 	"auto", "global", "percpu", "pernode",
64 };
65 
66 int sunrpc_set_pool_mode(const char *val)
67 {
68 	int idx = sysfs_match_string(pool_mode_names, val);
69 
70 	return idx < 0 ? idx : 0;
71 }
72 EXPORT_SYMBOL(sunrpc_set_pool_mode);
73 
74 /**
75  * sunrpc_get_pool_mode - get the current pool_mode for the host
76  * @buf: where to write the current pool_mode
77  * @size: size of @buf
78  *
79  * Write the pool_mode string to @buf. Returns the number of characters
80  * written to @buf (a'la snprintf()).
81  */
82 int
83 sunrpc_get_pool_mode(char *buf, size_t size)
84 {
85 	return snprintf(buf, size, "pernode");
86 }
87 EXPORT_SYMBOL(sunrpc_get_pool_mode);
88 
89 static int
90 param_set_pool_mode(const char *val, const struct kernel_param *kp)
91 {
92 	pr_notice_once("sunrpc: the pool_mode module parameter is deprecated and no longer has any effect; the pool mode is always 'pernode'\n");
93 	return sunrpc_set_pool_mode(val);
94 }
95 
96 static int
97 param_get_pool_mode(char *buf, const struct kernel_param *kp)
98 {
99 	return sysfs_emit(buf, "pernode\n");
100 }
101 
102 module_param_call(pool_mode, param_set_pool_mode, param_get_pool_mode,
103 		  NULL, 0644);
104 
105 /*
106  * Allocate the to_pool[] and pool_to[] arrays.
107  * Returns 0 on success or an errno.
108  */
109 static int
110 svc_pool_map_alloc_arrays(struct svc_pool_map *m, unsigned int maxpools)
111 {
112 	m->to_pool = kcalloc(maxpools, sizeof(unsigned int), GFP_KERNEL);
113 	if (!m->to_pool)
114 		goto fail;
115 	m->pool_to = kcalloc(maxpools, sizeof(unsigned int), GFP_KERNEL);
116 	if (!m->pool_to)
117 		goto fail_free;
118 
119 	return 0;
120 
121 fail_free:
122 	kfree(m->to_pool);
123 	m->to_pool = NULL;
124 fail:
125 	return -ENOMEM;
126 }
127 
128 /*
129  * Initialise the pool map for one pool per NUMA node.
130  * Returns number of pools or <0 on error.
131  */
132 static int
133 svc_pool_map_init_pernode(struct svc_pool_map *m)
134 {
135 	unsigned int maxpools = nr_node_ids;
136 	unsigned int pidx = 0;
137 	unsigned int node;
138 	int err;
139 
140 	err = svc_pool_map_alloc_arrays(m, maxpools);
141 	if (err)
142 		return err;
143 
144 	for_each_node_with_cpus(node) {
145 		/* some architectures (e.g. SN2) have cpuless nodes */
146 		BUG_ON(pidx > maxpools);
147 		m->to_pool[node] = pidx;
148 		m->pool_to[pidx] = node;
149 		pidx++;
150 	}
151 	/* nodes brought online later all get mapped to pool0, sorry */
152 
153 	return pidx;
154 }
155 
156 
157 /*
158  * Add a reference to the global map of nodes to pools (and
159  * vice versa) if pools are in use.
160  * Initialise the map if we're the first user.
161  * Returns the number of pools, or 0 on failure.
162  */
163 static unsigned int
164 svc_pool_map_get(void)
165 {
166 	struct svc_pool_map *m = &svc_pool_map;
167 	int npools;
168 
169 	mutex_lock(&svc_pool_map_mutex);
170 	if (m->count++) {
171 		mutex_unlock(&svc_pool_map_mutex);
172 		return m->npools;
173 	}
174 
175 	npools = svc_pool_map_init_pernode(m);
176 	if (npools <= 0) {
177 		m->count = 0;
178 		mutex_unlock(&svc_pool_map_mutex);
179 		return 0;
180 	}
181 	m->npools = npools;
182 	mutex_unlock(&svc_pool_map_mutex);
183 	return npools;
184 }
185 
186 /*
187  * Drop a reference to the global map of nodes to pools.
188  * When the last reference is dropped, the map data is
189  * freed; this allows the sysadmin to change the pool.
190  */
191 static void
192 svc_pool_map_put(void)
193 {
194 	struct svc_pool_map *m = &svc_pool_map;
195 
196 	mutex_lock(&svc_pool_map_mutex);
197 	if (!--m->count) {
198 		kfree(m->to_pool);
199 		m->to_pool = NULL;
200 		kfree(m->pool_to);
201 		m->pool_to = NULL;
202 		m->npools = 0;
203 	}
204 	mutex_unlock(&svc_pool_map_mutex);
205 }
206 
207 static int svc_pool_map_get_node(unsigned int pidx)
208 {
209 	const struct svc_pool_map *m = &svc_pool_map;
210 
211 	return m->pool_to[pidx];
212 }
213 
214 /*
215  * Set the given thread's cpus_allowed mask so that it
216  * will only run on cpus in the given pool.
217  */
218 static inline void
219 svc_pool_map_set_cpumask(struct task_struct *task, unsigned int pidx)
220 {
221 	struct svc_pool_map *m = &svc_pool_map;
222 	unsigned int node = m->pool_to[pidx];
223 
224 	/*
225 	 * The caller checks for more than one pool, which
226 	 * implies that we've been initialized.
227 	 */
228 	WARN_ON_ONCE(m->count == 0);
229 	if (m->count == 0)
230 		return;
231 
232 	set_cpus_allowed_ptr(task, cpumask_of_node(node));
233 }
234 
235 /**
236  * svc_serv_nrpools - number of thread pools backing a service
237  * @serv: An RPC service
238  *
239  * Pooled services all share the global svc_pool_map, so their pool count
240  * is svc_pool_map.npools. Unpooled services have a single pool. Reading
241  * npools without svc_pool_map_mutex is safe: a pooled service holds a map
242  * reference for its whole lifetime, so npools is stable once set.
243  *
244  * Return value:
245  *   The number of pools in @serv
246  */
247 unsigned int svc_serv_nrpools(const struct svc_serv *serv)
248 {
249 	return serv->sv_is_pooled ? svc_pool_map.npools : 1;
250 }
251 EXPORT_SYMBOL_GPL(svc_serv_nrpools);
252 
253 /**
254  * svc_pool_for_cpu - Select pool to run a thread on this cpu
255  * @serv: An RPC service
256  *
257  * Use the active CPU and the svc_pool_map to select the svc thread
258  * pool to use. Once initialized, the svc_pool_map does not change.
259  *
260  * Return value:
261  *   A pointer to an svc_pool
262  */
263 struct svc_pool *svc_pool_for_cpu(struct svc_serv *serv)
264 {
265 	unsigned int nrpools = svc_serv_nrpools(serv);
266 	struct svc_pool_map *m = &svc_pool_map;
267 	unsigned int pidx, i;
268 
269 	if (nrpools <= 1)
270 		return serv->sv_pools;
271 
272 	/*
273 	 * It's possible to have a pool with no threads. Userland can just set
274 	 * things up this way directly. Also, when threads are autodistributed
275 	 * they are spread evenly across the pools, but when there are fewer
276 	 * threads than pools some pools can end up with none.
277 	 *
278 	 * A transport enqueued on a threadless pool would never be picked up,
279 	 * since each thread only services its own pool. Fall back to the next
280 	 * populated pool, trading NUMA locality for a guarantee that the
281 	 * transport is serviced.
282 	 */
283 	pidx = m->to_pool[cpu_to_node(raw_smp_processor_id())];
284 	for (i = 0; i < nrpools; i++) {
285 		struct svc_pool *pool = &serv->sv_pools[pidx];
286 
287 		/* This is set under the service mutex and rarely ever
288 		 * changes. A data race here is harmless.
289 		 */
290 		if (data_race(pool->sp_nrthreads))
291 			return pool;
292 
293 		if (++pidx >= nrpools)
294 			pidx = 0;
295 	}
296 
297 	/* No pool has any threads; nothing can service the transport. */
298 	return &serv->sv_pools[pidx];
299 }
300 
301 static int svc_rpcb_setup(struct svc_serv *serv, struct net *net)
302 {
303 	int err;
304 
305 	err = rpcb_create_local(net);
306 	if (err)
307 		return err;
308 
309 	/* Remove any stale portmap registrations */
310 	svc_unregister(serv, net);
311 	return 0;
312 }
313 
314 void svc_rpcb_cleanup(struct svc_serv *serv, struct net *net)
315 {
316 	svc_unregister(serv, net);
317 	rpcb_put_local(net);
318 }
319 
320 static int svc_uses_rpcbind(struct svc_serv *serv)
321 {
322 	unsigned int		p, i;
323 
324 	for (p = 0; p < serv->sv_nprogs; p++) {
325 		struct svc_program *progp = &serv->sv_programs[p];
326 
327 		for (i = 0; i < progp->pg_nvers; i++) {
328 			if (progp->pg_vers[i] == NULL)
329 				continue;
330 			if (!progp->pg_vers[i]->vs_hidden)
331 				return 1;
332 		}
333 	}
334 
335 	return 0;
336 }
337 
338 int svc_bind(struct svc_serv *serv, struct net *net)
339 {
340 	if (serv->sv_no_rpcbind)
341 		return 0;
342 	if (!svc_uses_rpcbind(serv))
343 		return 0;
344 	return svc_rpcb_setup(serv, net);
345 }
346 EXPORT_SYMBOL_GPL(svc_bind);
347 
348 #if defined(CONFIG_SUNRPC_BACKCHANNEL)
349 static void
350 __svc_init_bc(struct svc_serv *serv)
351 {
352 	lwq_init(&serv->sv_cb_list);
353 }
354 #else
355 static void
356 __svc_init_bc(struct svc_serv *serv)
357 {
358 }
359 #endif
360 
361 static int svc_pool_init_counters(struct svc_pool *pool)
362 {
363 	int err;
364 
365 	err = percpu_counter_init(&pool->sp_messages_arrived, 0, GFP_KERNEL);
366 	if (err)
367 		return err;
368 	err = percpu_counter_init(&pool->sp_sockets_queued, 0, GFP_KERNEL);
369 	if (err)
370 		goto err_sockets;
371 	err = percpu_counter_init(&pool->sp_threads_woken, 0, GFP_KERNEL);
372 	if (err)
373 		goto err_threads;
374 	return 0;
375 
376 err_threads:
377 	percpu_counter_destroy(&pool->sp_sockets_queued);
378 err_sockets:
379 	percpu_counter_destroy(&pool->sp_messages_arrived);
380 	return err;
381 }
382 
383 static void svc_pool_destroy_counters(struct svc_pool *pool)
384 {
385 	percpu_counter_destroy(&pool->sp_messages_arrived);
386 	percpu_counter_destroy(&pool->sp_sockets_queued);
387 	percpu_counter_destroy(&pool->sp_threads_woken);
388 }
389 
390 /*
391  * Create an RPC service
392  */
393 static struct svc_serv *
394 __svc_create(struct svc_program *prog, int nprogs, struct svc_stat *stats,
395 	     unsigned int bufsize, int npools, int (*threadfn)(void *data))
396 {
397 	struct svc_serv	*serv;
398 	unsigned int vers;
399 	unsigned int xdrsize;
400 	unsigned int i;
401 
402 	if (!(serv = kzalloc_obj(*serv)))
403 		return NULL;
404 	serv->sv_name      = prog->pg_name;
405 	serv->sv_programs  = prog;
406 	serv->sv_nprogs    = nprogs;
407 	serv->sv_stats     = stats;
408 	if (bufsize > RPCSVC_MAXPAYLOAD)
409 		bufsize = RPCSVC_MAXPAYLOAD;
410 	serv->sv_max_payload = bufsize? bufsize : 4096;
411 	serv->sv_max_mesg  = roundup(serv->sv_max_payload + PAGE_SIZE, PAGE_SIZE);
412 	serv->sv_threadfn = threadfn;
413 	xdrsize = 0;
414 	for (i = 0; i < nprogs; i++) {
415 		struct svc_program *progp = &prog[i];
416 
417 		progp->pg_lovers = progp->pg_nvers-1;
418 		for (vers = 0; vers < progp->pg_nvers ; vers++)
419 			if (progp->pg_vers[vers]) {
420 				progp->pg_hivers = vers;
421 				if (progp->pg_lovers > vers)
422 					progp->pg_lovers = vers;
423 				if (progp->pg_vers[vers]->vs_xdrsize > xdrsize)
424 					xdrsize = progp->pg_vers[vers]->vs_xdrsize;
425 			}
426 	}
427 	serv->sv_xdrsize   = xdrsize;
428 	INIT_LIST_HEAD(&serv->sv_tempsocks);
429 	INIT_LIST_HEAD(&serv->sv_permsocks);
430 	timer_setup(&serv->sv_temptimer, NULL, 0);
431 	spin_lock_init(&serv->sv_lock);
432 
433 	__svc_init_bc(serv);
434 
435 	serv->sv_pools = kzalloc_objs(struct svc_pool, npools);
436 	if (!serv->sv_pools) {
437 		kfree(serv);
438 		return NULL;
439 	}
440 
441 	for (i = 0; i < npools; i++) {
442 		struct svc_pool *pool = &serv->sv_pools[i];
443 
444 		dprintk("svc: initialising pool %u for %s\n",
445 				i, serv->sv_name);
446 
447 		pool->sp_id = i;
448 		lwq_init(&pool->sp_xprts);
449 		INIT_LIST_HEAD(&pool->sp_all_threads);
450 		init_llist_head(&pool->sp_idle_threads);
451 
452 		if (svc_pool_init_counters(pool))
453 			goto out_err;
454 	}
455 
456 	return serv;
457 
458 out_err:
459 	while (i--)
460 		svc_pool_destroy_counters(&serv->sv_pools[i]);
461 	kfree(serv->sv_pools);
462 	kfree(serv);
463 	return NULL;
464 }
465 
466 /**
467  * svc_create - Create an RPC service
468  * @prog: the RPC program the new service will handle
469  * @bufsize: maximum message size for @prog
470  * @threadfn: a function to service RPC requests for @prog
471  *
472  * Returns an instantiated struct svc_serv object or NULL.
473  */
474 struct svc_serv *svc_create(struct svc_program *prog, unsigned int bufsize,
475 			    int (*threadfn)(void *data))
476 {
477 	return __svc_create(prog, 1, NULL, bufsize, 1, threadfn);
478 }
479 EXPORT_SYMBOL_GPL(svc_create);
480 
481 /**
482  * svc_create_pooled - Create an RPC service with pooled threads
483  * @prog:  Array of RPC programs the new service will handle
484  * @nprogs: Number of programs in the array
485  * @stats: the stats struct if desired
486  * @bufsize: maximum message size for @prog
487  * @threadfn: a function to service RPC requests for @prog
488  *
489  * Returns an instantiated struct svc_serv object or NULL.
490  */
491 struct svc_serv *svc_create_pooled(struct svc_program *prog,
492 				   unsigned int nprogs,
493 				   struct svc_stat *stats,
494 				   unsigned int bufsize,
495 				   int (*threadfn)(void *data))
496 {
497 	struct svc_serv *serv;
498 	unsigned int npools = svc_pool_map_get();
499 
500 	if (!npools)
501 		return NULL;
502 
503 	serv = __svc_create(prog, nprogs, stats, bufsize, npools, threadfn);
504 	if (!serv)
505 		goto out_err;
506 	serv->sv_is_pooled = true;
507 	return serv;
508 out_err:
509 	svc_pool_map_put();
510 	return NULL;
511 }
512 EXPORT_SYMBOL_GPL(svc_create_pooled);
513 
514 /*
515  * Destroy an RPC service. Should be called with appropriate locking to
516  * protect sv_permsocks and sv_tempsocks.
517  */
518 void
519 svc_destroy(struct svc_serv **servp)
520 {
521 	struct svc_serv *serv = *servp;
522 	unsigned int i;
523 
524 	*servp = NULL;
525 
526 	dprintk("svc: svc_destroy(%s)\n", serv->sv_programs->pg_name);
527 	timer_shutdown_sync(&serv->sv_temptimer);
528 
529 	/*
530 	 * Remaining transports at this point are not expected.
531 	 */
532 	WARN_ONCE(!list_empty(&serv->sv_permsocks),
533 		  "SVC: permsocks remain for %s\n", serv->sv_programs->pg_name);
534 	WARN_ONCE(!list_empty(&serv->sv_tempsocks),
535 		  "SVC: tempsocks remain for %s\n", serv->sv_programs->pg_name);
536 
537 	cache_clean_deferred(serv);
538 
539 	for (i = 0; i < svc_serv_nrpools(serv); i++) {
540 		struct svc_pool *pool = &serv->sv_pools[i];
541 
542 		svc_pool_destroy_counters(pool);
543 	}
544 
545 	if (serv->sv_is_pooled)
546 		svc_pool_map_put();
547 
548 	kfree(serv->sv_pools);
549 	kfree(serv);
550 }
551 EXPORT_SYMBOL_GPL(svc_destroy);
552 
553 static bool
554 svc_init_buffer(struct svc_rqst *rqstp, const struct svc_serv *serv, int node)
555 {
556 	rqstp->rq_maxpages = svc_serv_maxpages(serv);
557 
558 	/* +1 for a NULL sentinel readable by nfsd_splice_actor() */
559 	rqstp->rq_pages = kcalloc_node(rqstp->rq_maxpages + 1,
560 				       sizeof(struct page *),
561 				       GFP_KERNEL, node);
562 	if (!rqstp->rq_pages)
563 		return false;
564 
565 	/* +1 for a NULL sentinel at rq_page_end (see svc_rqst_replace_page) */
566 	rqstp->rq_respages = kcalloc_node(rqstp->rq_maxpages + 1,
567 					  sizeof(struct page *),
568 					  GFP_KERNEL, node);
569 	if (!rqstp->rq_respages) {
570 		kfree(rqstp->rq_pages);
571 		rqstp->rq_pages = NULL;
572 		return false;
573 	}
574 
575 	rqstp->rq_pages_nfree = rqstp->rq_maxpages;
576 	rqstp->rq_next_page = rqstp->rq_respages + rqstp->rq_maxpages;
577 	return true;
578 }
579 
580 /*
581  * Release an RPC server buffer
582  */
583 static void
584 svc_release_buffer(struct svc_rqst *rqstp)
585 {
586 	unsigned long i;
587 
588 	if (rqstp->rq_pages) {
589 		for (i = 0; i < rqstp->rq_maxpages; i++)
590 			if (rqstp->rq_pages[i])
591 				put_page(rqstp->rq_pages[i]);
592 		kfree(rqstp->rq_pages);
593 	}
594 
595 	if (rqstp->rq_respages) {
596 		for (i = 0; i < rqstp->rq_maxpages; i++)
597 			if (rqstp->rq_respages[i])
598 				put_page(rqstp->rq_respages[i]);
599 		kfree(rqstp->rq_respages);
600 	}
601 }
602 
603 static void svc_rqst_free_rcu(struct rcu_head *head)
604 {
605 	struct svc_rqst *rqstp = container_of(head, struct svc_rqst, rq_rcu_head);
606 
607 	kfree(rqstp->rq_resp);
608 	kfree(rqstp->rq_argp);
609 	kfree(rqstp);
610 }
611 
612 static void
613 svc_rqst_free(struct svc_rqst *rqstp)
614 {
615 	folio_batch_release(&rqstp->rq_fbatch);
616 	kfree(rqstp->rq_bvec);
617 	svc_release_buffer(rqstp);
618 	if (rqstp->rq_scratch_folio)
619 		folio_put(rqstp->rq_scratch_folio);
620 	kfree(rqstp->rq_auth_data);
621 	call_rcu(&rqstp->rq_rcu_head, svc_rqst_free_rcu);
622 }
623 
624 static struct svc_rqst *
625 svc_prepare_thread(struct svc_serv *serv, struct svc_pool *pool, int node)
626 {
627 	struct svc_rqst	*rqstp;
628 
629 	rqstp = kzalloc_node(sizeof(*rqstp), GFP_KERNEL, node);
630 	if (!rqstp)
631 		return rqstp;
632 
633 	folio_batch_init(&rqstp->rq_fbatch);
634 
635 	rqstp->rq_server = serv;
636 	rqstp->rq_pool = pool;
637 
638 	rqstp->rq_scratch_folio = __folio_alloc_node(GFP_KERNEL, 0,
639 						     node == NUMA_NO_NODE ?
640 						     numa_mem_id() : node);
641 	if (!rqstp->rq_scratch_folio)
642 		goto out_enomem;
643 
644 	rqstp->rq_argp = kmalloc_node(serv->sv_xdrsize, GFP_KERNEL, node);
645 	if (!rqstp->rq_argp)
646 		goto out_enomem;
647 
648 	rqstp->rq_resp = kmalloc_node(serv->sv_xdrsize, GFP_KERNEL, node);
649 	if (!rqstp->rq_resp)
650 		goto out_enomem;
651 
652 	if (!svc_init_buffer(rqstp, serv, node))
653 		goto out_enomem;
654 
655 	rqstp->rq_bvec = kcalloc_node(rqstp->rq_maxpages,
656 				      sizeof(struct bio_vec),
657 				      GFP_KERNEL, node);
658 	if (!rqstp->rq_bvec)
659 		goto out_enomem;
660 
661 	rqstp->rq_err = -EAGAIN; /* No error yet */
662 
663 	serv->sv_nrthreads += 1;
664 	pool->sp_nrthreads += 1;
665 
666 	/* Protected by whatever lock the service uses when calling
667 	 * svc_set_num_threads()
668 	 */
669 	list_add_rcu(&rqstp->rq_all, &pool->sp_all_threads);
670 
671 	return rqstp;
672 
673 out_enomem:
674 	svc_rqst_free(rqstp);
675 	return NULL;
676 }
677 
678 /**
679  * svc_pool_wake_idle_thread - Awaken an idle thread in @pool
680  * @pool: service thread pool
681  *
682  * Can be called from soft IRQ or process context. Finding an idle
683  * service thread and marking it BUSY is atomic with respect to
684  * other calls to svc_pool_wake_idle_thread().
685  *
686  */
687 void svc_pool_wake_idle_thread(struct svc_pool *pool)
688 {
689 	struct svc_rqst	*rqstp;
690 	struct llist_node *ln;
691 
692 	rcu_read_lock();
693 	ln = READ_ONCE(pool->sp_idle_threads.first);
694 	if (ln) {
695 		rqstp = llist_entry(ln, struct svc_rqst, rq_idle);
696 		WRITE_ONCE(rqstp->rq_qtime, ktime_get());
697 		if (!task_is_running(rqstp->rq_task)) {
698 			wake_up_process(rqstp->rq_task);
699 			trace_svc_pool_thread_wake(pool, rqstp->rq_task->pid);
700 			percpu_counter_inc(&pool->sp_threads_woken);
701 		} else {
702 			trace_svc_pool_thread_running(pool, rqstp->rq_task->pid);
703 		}
704 		rcu_read_unlock();
705 		return;
706 	}
707 	rcu_read_unlock();
708 	trace_svc_pool_thread_noidle(pool, 0);
709 }
710 EXPORT_SYMBOL_GPL(svc_pool_wake_idle_thread);
711 
712 /**
713  * svc_new_thread - spawn a new thread in the given pool
714  * @serv: the serv to which the pool belongs
715  * @pool: pool in which thread should be spawned
716  *
717  * Create a new thread inside @pool, which is a part of @serv.
718  * Caller must hold the service mutex.
719  *
720  * Returns 0 on success, or -errno on failure.
721  */
722 int svc_new_thread(struct svc_serv *serv, struct svc_pool *pool)
723 {
724 	struct svc_rqst	*rqstp;
725 	struct task_struct *task;
726 	int node;
727 	int err = 0;
728 
729 	/*
730 	 * Only pooled services hold a reference to the pool map, so only they
731 	 * may consult it. Unpooled services (e.g. lockd, the NFS callback)
732 	 * leave placement to the allocator.
733 	 */
734 	if (serv->sv_is_pooled)
735 		node = svc_pool_map_get_node(pool->sp_id);
736 	else
737 		node = NUMA_NO_NODE;
738 
739 	rqstp = svc_prepare_thread(serv, pool, node);
740 	if (!rqstp)
741 		return -ENOMEM;
742 	task = kthread_create_on_node(serv->sv_threadfn, rqstp,
743 				      node, "%s", serv->sv_name);
744 	if (IS_ERR(task)) {
745 		err = PTR_ERR(task);
746 		goto out;
747 	}
748 
749 	rqstp->rq_task = task;
750 	if (svc_serv_nrpools(serv) > 1)
751 		svc_pool_map_set_cpumask(task, pool->sp_id);
752 
753 	svc_sock_update_bufs(serv);
754 	wake_up_process(task);
755 
756 	/* Wait for the thread to signal initialization status */
757 	wait_var_event(&rqstp->rq_err, rqstp->rq_err != -EAGAIN);
758 	err = rqstp->rq_err;
759 out:
760 	if (err)
761 		svc_exit_thread(rqstp);
762 	return err;
763 }
764 EXPORT_SYMBOL_GPL(svc_new_thread);
765 
766 static int
767 svc_start_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
768 {
769 	int err = 0;
770 
771 	while (!err && nrservs--)
772 		err = svc_new_thread(serv, pool);
773 
774 	return err;
775 }
776 
777 static int
778 svc_stop_kthreads(struct svc_serv *serv, struct svc_pool *pool, int nrservs)
779 {
780 	do {
781 		set_bit(SP_VICTIM_REMAINS, &pool->sp_flags);
782 		set_bit(SP_NEED_VICTIM, &pool->sp_flags);
783 		svc_pool_wake_idle_thread(pool);
784 		wait_on_bit(&pool->sp_flags, SP_VICTIM_REMAINS, TASK_IDLE);
785 		nrservs++;
786 	} while (nrservs < 0);
787 	return 0;
788 }
789 
790 /**
791  * svc_set_pool_threads - adjust number of threads per pool
792  * @serv: RPC service to adjust
793  * @pool: Specific pool from which to choose threads
794  * @min_threads: min number of threads to run in @pool
795  * @max_threads: max number of threads in @pool (0 means kill all threads)
796  *
797  * Create or destroy threads in @pool to bring it into an acceptable range
798  * between @min_threads and @max_threads.
799  *
800  * If @min_threads is 0 or larger than @max_threads, then it is ignored and
801  * the pool will be set to run a static @max_threads number of threads.
802  *
803  * Caller must ensure mutual exclusion between this and server startup or
804  * shutdown.
805  *
806  * Returns zero on success or a negative errno if an error occurred while
807  * starting a thread.
808  */
809 int
810 svc_set_pool_threads(struct svc_serv *serv, struct svc_pool *pool,
811 		     unsigned int min_threads, unsigned int max_threads)
812 {
813 	int delta;
814 
815 	if (!pool)
816 		return -EINVAL;
817 
818 	/* clamp min threads to the max */
819 	if (min_threads > max_threads)
820 		min_threads = max_threads;
821 
822 	pool->sp_nrthrmin = min_threads;
823 	pool->sp_nrthrmax = max_threads;
824 
825 	/*
826 	 * When min_threads is set, then only change the number of
827 	 * threads to bring it within an acceptable range.
828 	 */
829 	if (min_threads) {
830 		if (pool->sp_nrthreads > max_threads)
831 			delta = max_threads;
832 		else if (pool->sp_nrthreads < min_threads)
833 			delta = min_threads;
834 		else
835 			return 0;
836 	} else {
837 		delta = max_threads;
838 	}
839 
840 	delta -= pool->sp_nrthreads;
841 	if (delta > 0)
842 		return svc_start_kthreads(serv, pool, delta);
843 	if (delta < 0)
844 		return svc_stop_kthreads(serv, pool, delta);
845 	return 0;
846 }
847 EXPORT_SYMBOL_GPL(svc_set_pool_threads);
848 
849 /**
850  * svc_set_num_threads - adjust number of threads in serv
851  * @serv: RPC service to adjust
852  * @min_threads: min number of threads to run per pool
853  * @nrservs: New number of threads for @serv (0 means kill all threads)
854  *
855  * Create or destroy threads in @serv to bring it to @nrservs. If there
856  * are multiple pools then the new threads or victims will be distributed
857  * evenly among them.
858  *
859  * When @nrservs is non-zero but smaller than the number of pools, even
860  * distribution would leave some pools empty. Since each pool maps to a
861  * NUMA node and only services transports steered to that node, every
862  * pool is instead guaranteed at least one thread. The resulting total
863  * may therefore exceed @nrservs.
864  *
865  * Caller must ensure mutual exclusion between this and server startup or
866  * shutdown.
867  *
868  * Returns zero on success or a negative errno if an error occurred while
869  * starting a thread. On failure, some pools may have already been
870  * adjusted; the caller is responsible for recovery.
871  */
872 int
873 svc_set_num_threads(struct svc_serv *serv, unsigned int min_threads,
874 		    unsigned int nrservs)
875 {
876 	unsigned int nrpools = svc_serv_nrpools(serv);
877 	unsigned int base = nrservs / nrpools;
878 	unsigned int remain = nrservs % nrpools;
879 	int i, err = 0;
880 
881 	/*
882 	 * Don't let a pool sit empty while threads are being
883 	 * auto-distributed: a transport steered to its node would have
884 	 * nothing to service it. Every pool maps to a CPU-bearing node,
885 	 * so hand each one a thread. This may push the total above
886 	 * @nrservs.
887 	 */
888 	if (base == 0 && nrservs != 0)
889 		remain = nrpools;
890 
891 	for (i = 0; i < nrpools; ++i) {
892 		struct svc_pool *pool = &serv->sv_pools[i];
893 		int threads = base;
894 
895 		if (remain) {
896 			++threads;
897 			--remain;
898 		}
899 
900 		err = svc_set_pool_threads(serv, pool, min_threads, threads);
901 		if (err)
902 			break;
903 	}
904 	return err;
905 }
906 EXPORT_SYMBOL_GPL(svc_set_num_threads);
907 
908 /**
909  * svc_serv_maxthreads - report a service's configured thread ceiling
910  * @serv: RPC service to query
911  *
912  * A pooled service sizes its threads dynamically, so the number of
913  * threads running at any moment tracks recent load rather than the
914  * service's capacity. The per-pool maximum is the stable figure a
915  * consumer should size against.
916  *
917  * The caller must keep @serv valid for the duration of the call.
918  *
919  * Return: the sum of every pool's maximum thread count.
920  */
921 unsigned int svc_serv_maxthreads(const struct svc_serv *serv)
922 {
923 	unsigned int i, max = 0;
924 
925 	for (i = 0; i < svc_serv_nrpools(serv); i++)
926 		max += data_race(serv->sv_pools[i].sp_nrthrmax);
927 	return max;
928 }
929 EXPORT_SYMBOL_GPL(svc_serv_maxthreads);
930 
931 /**
932  * svc_rqst_replace_page - Replace one page in rq_respages[]
933  * @rqstp: svc_rqst with pages to replace
934  * @page: replacement page
935  *
936  * When replacing a page in rq_respages, batch the release of the
937  * replaced pages to avoid hammering the page allocator.
938  *
939  * Return values:
940  *   %true: page replaced
941  *   %false: array bounds checking failed
942  */
943 bool svc_rqst_replace_page(struct svc_rqst *rqstp, struct page *page)
944 {
945 	struct page **begin = rqstp->rq_respages;
946 	struct page **end = rqstp->rq_page_end;
947 
948 	if (unlikely(rqstp->rq_next_page < begin || rqstp->rq_next_page > end)) {
949 		trace_svc_replace_page_err(rqstp);
950 		return false;
951 	}
952 
953 	if (*rqstp->rq_next_page)
954 		svc_rqst_page_release(rqstp, *rqstp->rq_next_page);
955 
956 	get_page(page);
957 	*(rqstp->rq_next_page++) = page;
958 	return true;
959 }
960 EXPORT_SYMBOL_GPL(svc_rqst_replace_page);
961 
962 /**
963  * svc_rqst_release_pages - Release Reply buffer pages
964  * @rqstp: RPC transaction context
965  *
966  * Release response pages in the range [rq_respages, rq_next_page).
967  * NULL entries in this range are skipped, allowing transports to
968  * transfer pages to a send context before this function runs.
969  */
970 void svc_rqst_release_pages(struct svc_rqst *rqstp)
971 {
972 	struct page **pp;
973 
974 	for (pp = rqstp->rq_respages; pp < rqstp->rq_next_page; pp++) {
975 		if (*pp) {
976 			if (!folio_batch_add(&rqstp->rq_fbatch,
977 					     page_folio(*pp)))
978 				__folio_batch_release(&rqstp->rq_fbatch);
979 			*pp = NULL;
980 		}
981 	}
982 	if (rqstp->rq_fbatch.nr)
983 		__folio_batch_release(&rqstp->rq_fbatch);
984 }
985 
986 /**
987  * svc_exit_thread - finalise the termination of a sunrpc server thread
988  * @rqstp: the svc_rqst which represents the thread.
989  *
990  * When a thread started with svc_new_thread() exits it must call
991  * svc_exit_thread() as its last act.  This must be done with the
992  * service mutex held.  Normally this is held by a DIFFERENT thread, the
993  * one that is calling svc_set_num_threads() and which will wait for
994  * SP_VICTIM_REMAINS to be cleared before dropping the mutex.  If the
995  * thread exits for any reason other than svc_thread_should_stop()
996  * returning %true (which indicated that svc_set_num_threads() is
997  * waiting for it to exit), then it must take the service mutex itself,
998  * which can only safely be done using mutex_try_lock().
999  */
1000 void
1001 svc_exit_thread(struct svc_rqst *rqstp)
1002 {
1003 	struct svc_serv	*serv = rqstp->rq_server;
1004 	struct svc_pool	*pool = rqstp->rq_pool;
1005 
1006 	list_del_rcu(&rqstp->rq_all);
1007 
1008 	pool->sp_nrthreads -= 1;
1009 	serv->sv_nrthreads -= 1;
1010 	svc_sock_update_bufs(serv);
1011 
1012 	svc_rqst_free(rqstp);
1013 
1014 	clear_and_wake_up_bit(SP_VICTIM_REMAINS, &pool->sp_flags);
1015 }
1016 EXPORT_SYMBOL_GPL(svc_exit_thread);
1017 
1018 /*
1019  * Register an "inet" protocol family netid with the local
1020  * rpcbind daemon via an rpcbind v4 SET request.
1021  *
1022  * No netconfig infrastructure is available in the kernel, so
1023  * we map IP_ protocol numbers to netids by hand.
1024  *
1025  * Returns zero on success; a negative errno value is returned
1026  * if any error occurs.
1027  */
1028 static int __svc_rpcb_register4(struct net *net, const u32 program,
1029 				const u32 version,
1030 				const unsigned short protocol,
1031 				const unsigned short port)
1032 {
1033 	const struct sockaddr_in sin = {
1034 		.sin_family		= AF_INET,
1035 		.sin_addr.s_addr	= htonl(INADDR_ANY),
1036 		.sin_port		= htons(port),
1037 	};
1038 	const char *netid;
1039 	int error;
1040 
1041 	switch (protocol) {
1042 	case IPPROTO_UDP:
1043 		netid = RPCBIND_NETID_UDP;
1044 		break;
1045 	case IPPROTO_TCP:
1046 		netid = RPCBIND_NETID_TCP;
1047 		break;
1048 	default:
1049 		return -ENOPROTOOPT;
1050 	}
1051 
1052 	error = rpcb_v4_register(net, program, version,
1053 					(const struct sockaddr *)&sin, netid);
1054 
1055 	/*
1056 	 * User space didn't support rpcbind v4, so retry this
1057 	 * registration request with the legacy rpcbind v2 protocol.
1058 	 */
1059 	if (error == -EPROTONOSUPPORT)
1060 		error = rpcb_register(net, program, version, protocol, port);
1061 
1062 	return error;
1063 }
1064 
1065 #if IS_ENABLED(CONFIG_IPV6)
1066 /*
1067  * Register an "inet6" protocol family netid with the local
1068  * rpcbind daemon via an rpcbind v4 SET request.
1069  *
1070  * No netconfig infrastructure is available in the kernel, so
1071  * we map IP_ protocol numbers to netids by hand.
1072  *
1073  * Returns zero on success; a negative errno value is returned
1074  * if any error occurs.
1075  */
1076 static int __svc_rpcb_register6(struct net *net, const u32 program,
1077 				const u32 version,
1078 				const unsigned short protocol,
1079 				const unsigned short port)
1080 {
1081 	const struct sockaddr_in6 sin6 = {
1082 		.sin6_family		= AF_INET6,
1083 		.sin6_addr		= IN6ADDR_ANY_INIT,
1084 		.sin6_port		= htons(port),
1085 	};
1086 	const char *netid;
1087 	int error;
1088 
1089 	switch (protocol) {
1090 	case IPPROTO_UDP:
1091 		netid = RPCBIND_NETID_UDP6;
1092 		break;
1093 	case IPPROTO_TCP:
1094 		netid = RPCBIND_NETID_TCP6;
1095 		break;
1096 	default:
1097 		return -ENOPROTOOPT;
1098 	}
1099 
1100 	error = rpcb_v4_register(net, program, version,
1101 					(const struct sockaddr *)&sin6, netid);
1102 
1103 	/*
1104 	 * User space didn't support rpcbind version 4, so we won't
1105 	 * use a PF_INET6 listener.
1106 	 */
1107 	if (error == -EPROTONOSUPPORT)
1108 		error = -EAFNOSUPPORT;
1109 
1110 	return error;
1111 }
1112 #endif	/* IS_ENABLED(CONFIG_IPV6) */
1113 
1114 /*
1115  * Register a kernel RPC service via rpcbind version 4.
1116  *
1117  * Returns zero on success; a negative errno value is returned
1118  * if any error occurs.
1119  */
1120 static int __svc_register(struct net *net, const char *progname,
1121 			  const u32 program, const u32 version,
1122 			  const int family,
1123 			  const unsigned short protocol,
1124 			  const unsigned short port)
1125 {
1126 	int error = -EAFNOSUPPORT;
1127 
1128 	switch (family) {
1129 	case PF_INET:
1130 		error = __svc_rpcb_register4(net, program, version,
1131 						protocol, port);
1132 		break;
1133 #if IS_ENABLED(CONFIG_IPV6)
1134 	case PF_INET6:
1135 		error = __svc_rpcb_register6(net, program, version,
1136 						protocol, port);
1137 #endif
1138 	}
1139 
1140 	trace_svc_register(progname, version, family, protocol, port, error);
1141 	return error;
1142 }
1143 
1144 static
1145 int svc_rpcbind_set_version(struct net *net,
1146 			    const struct svc_program *progp,
1147 			    u32 version, int family,
1148 			    unsigned short proto,
1149 			    unsigned short port)
1150 {
1151 	return __svc_register(net, progp->pg_name, progp->pg_prog,
1152 				version, family, proto, port);
1153 
1154 }
1155 
1156 int svc_generic_rpcbind_set(struct net *net,
1157 			    const struct svc_program *progp,
1158 			    u32 version, int family,
1159 			    unsigned short proto,
1160 			    unsigned short port)
1161 {
1162 	const struct svc_version *vers = progp->pg_vers[version];
1163 	int error;
1164 
1165 	if (vers == NULL)
1166 		return 0;
1167 
1168 	if (vers->vs_hidden) {
1169 		trace_svc_noregister(progp->pg_name, version, proto,
1170 				     port, family, 0);
1171 		return 0;
1172 	}
1173 
1174 	/*
1175 	 * Don't register a UDP port if we need congestion
1176 	 * control.
1177 	 */
1178 	if (vers->vs_need_cong_ctrl && proto == IPPROTO_UDP)
1179 		return 0;
1180 
1181 	error = svc_rpcbind_set_version(net, progp, version,
1182 					family, proto, port);
1183 
1184 	/* -EIO means no answer, not a refusal, so vs_rpcb_optnl must keep it. */
1185 	if (error == -EIO)
1186 		return error;
1187 
1188 	return (vers->vs_rpcb_optnl) ? 0 : error;
1189 }
1190 EXPORT_SYMBOL_GPL(svc_generic_rpcbind_set);
1191 
1192 /**
1193  * svc_rpcb_failure_count - local rpcbind calls for @serv that got no answer
1194  * @serv: RPC service to query
1195  *
1196  * svc_register() adds one for each of its calls that got no answer. A reply
1197  * that refuses one entry does not count, because rpcbind answered and the
1198  * next entry may still succeed.
1199  *
1200  * The count is kept per serv rather than per net. The local rpcbind client
1201  * is per-net and lockd shares it, but a count that another service can move
1202  * says nothing about this serv's own calls.
1203  *
1204  * This is for callers that cannot see the svc_register() return, because a
1205  * transport class sits in between. Such a caller reads the count before it
1206  * starts and compares as it goes, so there is no state to reset between
1207  * operations. The count never resets, and callers must not attach meaning
1208  * to the value itself.
1209  *
1210  * Return: the number of unanswered calls since this serv was created.
1211  */
1212 unsigned int svc_rpcb_failure_count(struct svc_serv *serv)
1213 {
1214 	return atomic_read(&serv->sv_rpcb_failures);
1215 }
1216 EXPORT_SYMBOL_GPL(svc_rpcb_failure_count);
1217 
1218 /**
1219  * svc_register - register an RPC service with the local portmapper
1220  * @serv: svc_serv struct for the service to register
1221  * @net: net namespace for the service to register
1222  * @family: protocol family of service's listener socket
1223  * @proto: transport protocol number to advertise
1224  * @port: port to advertise
1225  *
1226  * Service is registered for any address in the passed-in protocol family
1227  */
1228 int svc_register(struct svc_serv *serv, struct net *net,
1229 		 const int family, const unsigned short proto,
1230 		 const unsigned short port)
1231 {
1232 	bool			noanswer = false;
1233 	unsigned int		p, i;
1234 	int			error = 0;
1235 
1236 	WARN_ON_ONCE(proto == 0 && port == 0);
1237 	if (proto == 0 && port == 0)
1238 		return -EINVAL;
1239 
1240 	if (serv->sv_no_rpcbind)
1241 		return 0;
1242 
1243 	for (p = 0; p < serv->sv_nprogs; p++) {
1244 		struct svc_program *progp = &serv->sv_programs[p];
1245 
1246 		for (i = 0; i < progp->pg_nvers; i++) {
1247 			const struct svc_version *vers = progp->pg_vers[i];
1248 			int ret;
1249 
1250 			ret = progp->pg_rpcbind_set(net, progp, i,
1251 					family, proto, port);
1252 			if (ret == -EIO) {
1253 				noanswer = true;
1254 				if (vers && vers->vs_rpcb_optnl)
1255 					ret = 0;
1256 			}
1257 			if (ret < 0) {
1258 				printk(KERN_WARNING "svc: failed to register "
1259 					"%sv%u RPC service (errno %d).\n",
1260 					progp->pg_name, i, -ret);
1261 				if (!error)
1262 					error = ret;
1263 				break;
1264 			}
1265 			if (noanswer)
1266 				break;
1267 		}
1268 
1269 		/* Give up on trying to register anything if it didn't respond */
1270 		if (noanswer)
1271 			break;
1272 	}
1273 
1274 	if (noanswer)
1275 		atomic_inc(&serv->sv_rpcb_failures);
1276 
1277 	return error;
1278 }
1279 
1280 /*
1281  * If user space is running rpcbind, it should take the v4 UNSET
1282  * and clear everything for this [program, version].  If user space
1283  * is running portmap, it will reject the v4 UNSET, but won't have
1284  * any "inet6" entries anyway.  So a PMAP_UNSET should be sufficient
1285  * in this case to clear all existing entries for [program, version].
1286  */
1287 static int __svc_unregister(struct net *net, const u32 program, const u32 version,
1288 			    const char *progname)
1289 {
1290 	int error;
1291 
1292 	error = rpcb_v4_register(net, program, version, NULL, "");
1293 
1294 	/*
1295 	 * User space didn't support rpcbind v4, so retry this
1296 	 * request with the legacy rpcbind v2 protocol.
1297 	 */
1298 	if (error == -EPROTONOSUPPORT)
1299 		error = rpcb_register(net, program, version, 0, 0);
1300 
1301 	trace_svc_unregister(progname, version, error);
1302 	return error;
1303 }
1304 
1305 /*
1306  * All netids, bind addresses and ports registered for [program, version]
1307  * are removed from the local rpcbind database (if the service is not
1308  * hidden) to make way for a new instance of the service.
1309  *
1310  * The result of unregistration is reported via dprintk for those who want
1311  * verification of the result, but is otherwise not important.
1312  */
1313 static void svc_unregister(const struct svc_serv *serv, struct net *net)
1314 {
1315 	struct sighand_struct *sighand;
1316 	unsigned long flags;
1317 	unsigned int p, i;
1318 
1319 	clear_thread_flag(TIF_SIGPENDING);
1320 
1321 	for (p = 0; p < serv->sv_nprogs; p++) {
1322 		struct svc_program *progp = &serv->sv_programs[p];
1323 
1324 		for (i = 0; i < progp->pg_nvers; i++) {
1325 			if (progp->pg_vers[i] == NULL)
1326 				continue;
1327 			if (progp->pg_vers[i]->vs_hidden)
1328 				continue;
1329 			if (__svc_unregister(net, progp->pg_prog, i,
1330 					     progp->pg_name) == -EIO)
1331 				goto out;
1332 		}
1333 	}
1334 
1335 out:
1336 	rcu_read_lock();
1337 	sighand = rcu_dereference(current->sighand);
1338 	spin_lock_irqsave(&sighand->siglock, flags);
1339 	recalc_sigpending();
1340 	spin_unlock_irqrestore(&sighand->siglock, flags);
1341 	rcu_read_unlock();
1342 }
1343 
1344 /*
1345  * dprintk the given error with the address of the client that caused it.
1346  */
1347 #if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
1348 static __printf(2, 3)
1349 void svc_printk(struct svc_rqst *rqstp, const char *fmt, ...)
1350 {
1351 	struct va_format vaf;
1352 	va_list args;
1353 	char 	buf[RPC_MAX_ADDRBUFLEN];
1354 
1355 	va_start(args, fmt);
1356 
1357 	vaf.fmt = fmt;
1358 	vaf.va = &args;
1359 
1360 	dprintk("svc: %s: %pV", svc_print_addr(rqstp, buf, sizeof(buf)), &vaf);
1361 
1362 	va_end(args);
1363 }
1364 #else
1365 static __printf(2,3) void svc_printk(struct svc_rqst *rqstp, const char *fmt, ...) {}
1366 #endif
1367 
1368 __be32
1369 svc_generic_init_request(struct svc_rqst *rqstp,
1370 		const struct svc_program *progp,
1371 		struct svc_process_info *ret)
1372 {
1373 	const struct svc_version *versp = NULL;	/* compiler food */
1374 	const struct svc_procedure *procp = NULL;
1375 
1376 	if (rqstp->rq_vers >= progp->pg_nvers )
1377 		goto err_bad_vers;
1378 	versp = progp->pg_vers[rqstp->rq_vers];
1379 	if (!versp)
1380 		goto err_bad_vers;
1381 
1382 	/*
1383 	 * Some protocol versions (namely NFSv4) require some form of
1384 	 * congestion control.  (See RFC 7530 section 3.1 paragraph 2)
1385 	 * In other words, UDP is not allowed. We mark those when setting
1386 	 * up the svc_xprt, and verify that here.
1387 	 *
1388 	 * The spec is not very clear about what error should be returned
1389 	 * when someone tries to access a server that is listening on UDP
1390 	 * for lower versions. RPC_PROG_MISMATCH seems to be the closest
1391 	 * fit.
1392 	 */
1393 	if (versp->vs_need_cong_ctrl && rqstp->rq_xprt &&
1394 	    !test_bit(XPT_CONG_CTRL, &rqstp->rq_xprt->xpt_flags))
1395 		goto err_bad_vers;
1396 
1397 	if (rqstp->rq_proc >= versp->vs_nproc)
1398 		goto err_bad_proc;
1399 	rqstp->rq_procinfo = procp = &versp->vs_proc[rqstp->rq_proc];
1400 
1401 	/* Initialize storage for argp and resp */
1402 	memset(rqstp->rq_argp, 0, procp->pc_argzero);
1403 	memset(rqstp->rq_resp, 0, procp->pc_ressize);
1404 
1405 	/* Bump per-net per-procedure stats counter */
1406 	if (rqstp->rq_server->sv_stats &&
1407 	    rqstp->rq_server->sv_stats->program == progp &&
1408 	    rqstp->rq_server->sv_stats->vs_count &&
1409 	    rqstp->rq_server->sv_stats->vs_count[rqstp->rq_vers])
1410 		this_cpu_inc(rqstp->rq_server->sv_stats->vs_count
1411 				[rqstp->rq_vers][rqstp->rq_proc]);
1412 
1413 	ret->dispatch = versp->vs_dispatch;
1414 	return rpc_success;
1415 err_bad_vers:
1416 	ret->mismatch.lovers = progp->pg_lovers;
1417 	ret->mismatch.hivers = progp->pg_hivers;
1418 	return rpc_prog_mismatch;
1419 err_bad_proc:
1420 	return rpc_proc_unavail;
1421 }
1422 EXPORT_SYMBOL_GPL(svc_generic_init_request);
1423 
1424 /**
1425  * svc_stat_alloc_counts - allocate per-netns per-version call count arrays
1426  * @statp: svc_stat whose vs_count arrays should be allocated
1427  *
1428  * statp->program must be set before calling this.
1429  *
1430  * Returns zero on success, or a negative errno otherwise.
1431  */
1432 int svc_stat_alloc_counts(struct svc_stat *statp)
1433 {
1434 	struct svc_program *prog = statp->program;
1435 	unsigned int i;
1436 
1437 	statp->vs_count = kcalloc(prog->pg_nvers,
1438 				  sizeof(unsigned long __percpu *),
1439 				  GFP_KERNEL);
1440 	if (!statp->vs_count)
1441 		return -ENOMEM;
1442 
1443 	for (i = 0; i < prog->pg_nvers; i++) {
1444 		if (!prog->pg_vers[i])
1445 			continue;
1446 		statp->vs_count[i] = __alloc_percpu(prog->pg_vers[i]->vs_nproc *
1447 					    sizeof(unsigned long),
1448 					    sizeof(unsigned long));
1449 		if (!statp->vs_count[i])
1450 			goto err;
1451 	}
1452 	return 0;
1453 err:
1454 	svc_stat_free_counts(statp);
1455 	return -ENOMEM;
1456 }
1457 EXPORT_SYMBOL_GPL(svc_stat_alloc_counts);
1458 
1459 /**
1460  * svc_stat_free_counts - free per-netns per-version call count arrays
1461  * @statp: svc_stat whose vs_count arrays should be freed
1462  */
1463 void svc_stat_free_counts(struct svc_stat *statp)
1464 {
1465 	struct svc_program *prog = statp->program;
1466 	unsigned int i;
1467 
1468 	if (!statp->vs_count)
1469 		return;
1470 
1471 	for (i = 0; i < prog->pg_nvers; i++)
1472 		free_percpu(statp->vs_count[i]);
1473 	kfree(statp->vs_count);
1474 	statp->vs_count = NULL;
1475 }
1476 EXPORT_SYMBOL_GPL(svc_stat_free_counts);
1477 
1478 /*
1479  * Common routine for processing the RPC request.
1480  */
1481 static int
1482 svc_process_common(struct svc_rqst *rqstp)
1483 {
1484 	struct xdr_stream	*xdr = &rqstp->rq_res_stream;
1485 	struct svc_program	*progp = NULL;
1486 	const struct svc_procedure *procp = NULL;
1487 	struct svc_serv		*serv = rqstp->rq_server;
1488 	struct svc_process_info process;
1489 	enum svc_auth_status	auth_res;
1490 	unsigned int		aoffset;
1491 	int			pr, rc;
1492 	__be32			*p;
1493 
1494 	/* Reset the accept_stat for the RPC */
1495 	rqstp->rq_accept_statp = NULL;
1496 
1497 	/* Will be turned off only when NFSv4 Sessions are used */
1498 	set_bit(RQ_USEDEFERRAL, &rqstp->rq_flags);
1499 	clear_bit(RQ_DROPME, &rqstp->rq_flags);
1500 
1501 	/* Construct the first words of the reply: */
1502 	svcxdr_init_encode(rqstp);
1503 	xdr_stream_encode_be32(xdr, rqstp->rq_xid);
1504 	xdr_stream_encode_be32(xdr, rpc_reply);
1505 
1506 	p = xdr_inline_decode(&rqstp->rq_arg_stream, XDR_UNIT * 4);
1507 	if (unlikely(!p))
1508 		goto err_short_len;
1509 	if (*p++ != cpu_to_be32(RPC_VERSION))
1510 		goto err_bad_rpc;
1511 
1512 	xdr_stream_encode_be32(xdr, rpc_msg_accepted);
1513 
1514 	rqstp->rq_prog = be32_to_cpup(p++);
1515 	rqstp->rq_vers = be32_to_cpup(p++);
1516 	rqstp->rq_proc = be32_to_cpup(p);
1517 
1518 	for (pr = 0; pr < serv->sv_nprogs; pr++)
1519 		if (rqstp->rq_prog == serv->sv_programs[pr].pg_prog)
1520 			progp = &serv->sv_programs[pr];
1521 
1522 	/*
1523 	 * Decode auth data, and add verifier to reply buffer.
1524 	 * We do this before anything else in order to get a decent
1525 	 * auth verifier.
1526 	 */
1527 	auth_res = svc_authenticate(rqstp);
1528 	/* Also give the program a chance to reject this call: */
1529 	if (auth_res == SVC_OK && progp)
1530 		auth_res = progp->pg_authenticate(rqstp);
1531 	trace_svc_authenticate(rqstp, auth_res);
1532 	switch (auth_res) {
1533 	case SVC_OK:
1534 		break;
1535 	case SVC_GARBAGE:
1536 		rqstp->rq_auth_stat = rpc_autherr_badcred;
1537 		goto err_bad_auth;
1538 	case SVC_DENIED:
1539 		goto err_bad_auth;
1540 	case SVC_CLOSE:
1541 		goto close;
1542 	case SVC_DROP:
1543 		goto dropit;
1544 	case SVC_COMPLETE:
1545 		goto sendit;
1546 	default:
1547 		pr_warn_once("Unexpected svc_auth_status (%d)\n", auth_res);
1548 		rqstp->rq_auth_stat = rpc_autherr_failed;
1549 		goto err_bad_auth;
1550 	}
1551 
1552 	if (progp == NULL)
1553 		goto err_bad_prog;
1554 
1555 	switch (progp->pg_init_request(rqstp, progp, &process)) {
1556 	case rpc_success:
1557 		break;
1558 	case rpc_prog_unavail:
1559 		goto err_bad_prog;
1560 	case rpc_prog_mismatch:
1561 		goto err_bad_vers;
1562 	case rpc_proc_unavail:
1563 		goto err_bad_proc;
1564 	}
1565 
1566 	procp = rqstp->rq_procinfo;
1567 	/* Should this check go into the dispatcher? */
1568 	if (!procp || !procp->pc_func)
1569 		goto err_bad_proc;
1570 
1571 	/* Syntactic check complete */
1572 	if (serv->sv_stats)
1573 		serv->sv_stats->rpccnt++;
1574 	trace_svc_process(rqstp, progp->pg_name);
1575 
1576 	aoffset = xdr_stream_pos(xdr);
1577 
1578 	/* un-reserve some of the out-queue now that we have a
1579 	 * better idea of reply size
1580 	 */
1581 	if (procp->pc_xdrressize)
1582 		svc_reserve_auth(rqstp, procp->pc_xdrressize<<2);
1583 
1584 	/* Call the function that processes the request. */
1585 	rc = process.dispatch(rqstp);
1586 	xdr_finish_decode(xdr);
1587 
1588 	if (!rc)
1589 		goto dropit;
1590 	if (rqstp->rq_auth_stat != rpc_auth_ok)
1591 		goto err_bad_auth;
1592 
1593 	if (*rqstp->rq_accept_statp != rpc_success)
1594 		xdr_truncate_encode(xdr, aoffset);
1595 
1596 	if (procp->pc_encode == NULL)
1597 		goto dropit;
1598 
1599  sendit:
1600 	if (svc_authorise(rqstp))
1601 		goto close_xprt;
1602 	return 1;		/* Caller can now send it */
1603 
1604  dropit:
1605 	svc_authorise(rqstp);	/* doesn't hurt to call this twice */
1606 	dprintk("svc: svc_process dropit\n");
1607 	return 0;
1608 
1609  close:
1610 	svc_authorise(rqstp);
1611 close_xprt:
1612 	if (rqstp->rq_xprt && test_bit(XPT_TEMP, &rqstp->rq_xprt->xpt_flags))
1613 		svc_xprt_close(rqstp->rq_xprt);
1614 	dprintk("svc: svc_process close\n");
1615 	return 0;
1616 
1617 err_short_len:
1618 	svc_printk(rqstp, "short len %u, dropping request\n",
1619 		   rqstp->rq_arg.len);
1620 	goto close_xprt;
1621 
1622 err_bad_rpc:
1623 	if (serv->sv_stats)
1624 		serv->sv_stats->rpcbadfmt++;
1625 	xdr_stream_encode_u32(xdr, RPC_MSG_DENIED);
1626 	xdr_stream_encode_u32(xdr, RPC_MISMATCH);
1627 	/* Only RPCv2 supported */
1628 	xdr_stream_encode_u32(xdr, RPC_VERSION);
1629 	xdr_stream_encode_u32(xdr, RPC_VERSION);
1630 	return 1;	/* don't wrap */
1631 
1632 err_bad_auth:
1633 	dprintk("svc: authentication failed (%d)\n",
1634 		be32_to_cpu(rqstp->rq_auth_stat));
1635 	if (serv->sv_stats)
1636 		serv->sv_stats->rpcbadauth++;
1637 	/* Restore write pointer to location of reply status: */
1638 	xdr_truncate_encode(xdr, XDR_UNIT * 2);
1639 	xdr_stream_encode_u32(xdr, RPC_MSG_DENIED);
1640 	xdr_stream_encode_u32(xdr, RPC_AUTH_ERROR);
1641 	xdr_stream_encode_be32(xdr, rqstp->rq_auth_stat);
1642 	goto sendit;
1643 
1644 err_bad_prog:
1645 	dprintk("svc: unknown program %d\n", rqstp->rq_prog);
1646 	if (serv->sv_stats)
1647 		serv->sv_stats->rpcbadfmt++;
1648 	*rqstp->rq_accept_statp = rpc_prog_unavail;
1649 	goto sendit;
1650 
1651 err_bad_vers:
1652 	svc_printk(rqstp, "unknown version (%d for prog %d, %s)\n",
1653 		       rqstp->rq_vers, rqstp->rq_prog, progp->pg_name);
1654 
1655 	if (serv->sv_stats)
1656 		serv->sv_stats->rpcbadfmt++;
1657 	*rqstp->rq_accept_statp = rpc_prog_mismatch;
1658 
1659 	/*
1660 	 * svc_authenticate() has already added the verifier and
1661 	 * advanced the stream just past rq_accept_statp.
1662 	 */
1663 	xdr_stream_encode_u32(xdr, process.mismatch.lovers);
1664 	xdr_stream_encode_u32(xdr, process.mismatch.hivers);
1665 	goto sendit;
1666 
1667 err_bad_proc:
1668 	svc_printk(rqstp, "unknown procedure (%d)\n", rqstp->rq_proc);
1669 
1670 	if (serv->sv_stats)
1671 		serv->sv_stats->rpcbadfmt++;
1672 	*rqstp->rq_accept_statp = rpc_proc_unavail;
1673 	goto sendit;
1674 }
1675 
1676 /*
1677  * Drop request
1678  */
1679 static void svc_drop(struct svc_rqst *rqstp)
1680 {
1681 	trace_svc_drop(rqstp);
1682 }
1683 
1684 static void svc_release_rqst(struct svc_rqst *rqstp)
1685 {
1686 	const struct svc_procedure *procp = rqstp->rq_procinfo;
1687 
1688 	if (procp && procp->pc_release)
1689 		procp->pc_release(rqstp);
1690 
1691 	/*
1692 	 * A subsequent svc_release_rqst() on this rqstp must not
1693 	 * re-invoke pc_release against released state.
1694 	 */
1695 	rqstp->rq_procinfo = NULL;
1696 }
1697 
1698 /**
1699  * svc_process - Execute one RPC transaction
1700  * @rqstp: RPC transaction context
1701  *
1702  */
1703 void svc_process(struct svc_rqst *rqstp)
1704 {
1705 	struct kvec		*resv = &rqstp->rq_res.head[0];
1706 	__be32 *p;
1707 
1708 #if IS_ENABLED(CONFIG_FAIL_SUNRPC)
1709 	if (!fail_sunrpc.ignore_server_disconnect &&
1710 	    should_fail(&fail_sunrpc.attr, 1))
1711 		svc_xprt_deferred_close(rqstp->rq_xprt);
1712 #endif
1713 
1714 	/* Discard a stale release hook from a previous RPC. */
1715 	rqstp->rq_procinfo = NULL;
1716 
1717 	/*
1718 	 * Setup response xdr_buf.
1719 	 * Initially it has just one page
1720 	 */
1721 	rqstp->rq_next_page = &rqstp->rq_respages[1];
1722 	resv->iov_base = page_address(rqstp->rq_respages[0]);
1723 	resv->iov_len = 0;
1724 	rqstp->rq_res.pages = rqstp->rq_next_page;
1725 	rqstp->rq_res.len = 0;
1726 	rqstp->rq_res.page_base = 0;
1727 	rqstp->rq_res.page_len = 0;
1728 	rqstp->rq_res.buflen = PAGE_SIZE;
1729 	rqstp->rq_res.tail[0].iov_base = NULL;
1730 	rqstp->rq_res.tail[0].iov_len = 0;
1731 
1732 	svcxdr_init_decode(rqstp);
1733 	p = xdr_inline_decode(&rqstp->rq_arg_stream, XDR_UNIT * 2);
1734 	if (unlikely(!p))
1735 		goto out_drop;
1736 	rqstp->rq_xid = *p++;
1737 	if (unlikely(*p != rpc_call))
1738 		goto out_baddir;
1739 
1740 	if (!svc_process_common(rqstp)) {
1741 		svc_release_rqst(rqstp);
1742 		goto out_drop;
1743 	}
1744 	svc_send(rqstp);
1745 	svc_release_rqst(rqstp);
1746 	return;
1747 
1748 out_baddir:
1749 	svc_printk(rqstp, "bad direction 0x%08x, dropping request\n",
1750 		   be32_to_cpu(*p));
1751 	if (rqstp->rq_server->sv_stats)
1752 		rqstp->rq_server->sv_stats->rpcbadfmt++;
1753 out_drop:
1754 	svc_drop(rqstp);
1755 }
1756 
1757 #if defined(CONFIG_SUNRPC_BACKCHANNEL)
1758 /**
1759  * svc_process_bc - process a reverse-direction RPC request
1760  * @req: RPC request to be used for client-side processing
1761  * @rqstp: server-side execution context
1762  *
1763  */
1764 void svc_process_bc(struct rpc_rqst *req, struct svc_rqst *rqstp)
1765 {
1766 	struct rpc_timeout timeout = {
1767 		.to_increment		= 0,
1768 	};
1769 	struct rpc_task *task;
1770 	int proc_error;
1771 
1772 	/* Build the svc_rqst used by the common processing routine */
1773 	rqstp->rq_procinfo = NULL;
1774 	rqstp->rq_xid = req->rq_xid;
1775 	rqstp->rq_prot = req->rq_xprt->prot;
1776 	rqstp->rq_bc_net = req->rq_xprt->xprt_net;
1777 
1778 	rqstp->rq_addrlen = sizeof(req->rq_xprt->addr);
1779 	memcpy(&rqstp->rq_addr, &req->rq_xprt->addr, rqstp->rq_addrlen);
1780 	memcpy(&rqstp->rq_arg, &req->rq_rcv_buf, sizeof(rqstp->rq_arg));
1781 	memcpy(&rqstp->rq_res, &req->rq_snd_buf, sizeof(rqstp->rq_res));
1782 
1783 	/* Adjust the argument buffer length */
1784 	rqstp->rq_arg.len = req->rq_private_buf.len;
1785 	if (rqstp->rq_arg.len <= rqstp->rq_arg.head[0].iov_len) {
1786 		rqstp->rq_arg.head[0].iov_len = rqstp->rq_arg.len;
1787 		rqstp->rq_arg.page_len = 0;
1788 	} else if (rqstp->rq_arg.len <= rqstp->rq_arg.head[0].iov_len +
1789 			rqstp->rq_arg.page_len)
1790 		rqstp->rq_arg.page_len = rqstp->rq_arg.len -
1791 			rqstp->rq_arg.head[0].iov_len;
1792 	else
1793 		rqstp->rq_arg.len = rqstp->rq_arg.head[0].iov_len +
1794 			rqstp->rq_arg.page_len;
1795 
1796 	/* Reset the response buffer */
1797 	rqstp->rq_res.head[0].iov_len = 0;
1798 
1799 	/*
1800 	 * Skip the XID and calldir fields because they've already
1801 	 * been processed by the caller.
1802 	 */
1803 	svcxdr_init_decode(rqstp);
1804 	if (!xdr_inline_decode(&rqstp->rq_arg_stream, XDR_UNIT * 2))
1805 		return;
1806 
1807 	/* Parse and execute the bc call */
1808 	proc_error = svc_process_common(rqstp);
1809 
1810 	atomic_dec(&req->rq_xprt->bc_slot_count);
1811 	if (!proc_error) {
1812 		/* Processing error: drop the request */
1813 		xprt_free_bc_request(req);
1814 		svc_release_rqst(rqstp);
1815 		return;
1816 	}
1817 	/* Finally, send the reply synchronously */
1818 	if (rqstp->bc_to_initval > 0) {
1819 		timeout.to_initval = rqstp->bc_to_initval;
1820 		timeout.to_retries = rqstp->bc_to_retries;
1821 	} else {
1822 		timeout.to_initval = req->rq_xprt->timeout->to_initval;
1823 		timeout.to_retries = req->rq_xprt->timeout->to_retries;
1824 	}
1825 	timeout.to_maxval = timeout.to_initval;
1826 	memcpy(&req->rq_snd_buf, &rqstp->rq_res, sizeof(req->rq_snd_buf));
1827 	task = rpc_run_bc_task(req, &timeout);
1828 	svc_release_rqst(rqstp);
1829 
1830 	if (IS_ERR(task))
1831 		return;
1832 
1833 	WARN_ON_ONCE(atomic_read(&task->tk_count) != 1);
1834 	rpc_put_task(task);
1835 }
1836 #endif /* CONFIG_SUNRPC_BACKCHANNEL */
1837 
1838 /**
1839  * svc_max_payload - Return transport-specific limit on the RPC payload
1840  * @rqstp: RPC transaction context
1841  *
1842  * Returns the maximum number of payload bytes the current transport
1843  * allows.
1844  */
1845 u32 svc_max_payload(const struct svc_rqst *rqstp)
1846 {
1847 	u32 max = rqstp->rq_xprt->xpt_class->xcl_max_payload;
1848 
1849 	if (rqstp->rq_server->sv_max_payload < max)
1850 		max = rqstp->rq_server->sv_max_payload;
1851 	return max;
1852 }
1853 EXPORT_SYMBOL_GPL(svc_max_payload);
1854 
1855 /**
1856  * svc_proc_name - Return RPC procedure name in string form
1857  * @rqstp: svc_rqst to operate on
1858  *
1859  * Return value:
1860  *   Pointer to a NUL-terminated string
1861  */
1862 const char *svc_proc_name(const struct svc_rqst *rqstp)
1863 {
1864 	if (rqstp && rqstp->rq_procinfo)
1865 		return rqstp->rq_procinfo->pc_name;
1866 	return "unknown";
1867 }
1868 
1869 
1870 /**
1871  * svc_encode_result_payload - mark a range of bytes as a result payload
1872  * @rqstp: svc_rqst to operate on
1873  * @offset: payload's byte offset in rqstp->rq_res
1874  * @length: size of payload, in bytes
1875  *
1876  * Returns zero on success, or a negative errno if a permanent
1877  * error occurred.
1878  */
1879 int svc_encode_result_payload(struct svc_rqst *rqstp, unsigned int offset,
1880 			      unsigned int length)
1881 {
1882 	return rqstp->rq_xprt->xpt_ops->xpo_result_payload(rqstp, offset,
1883 							   length);
1884 }
1885 EXPORT_SYMBOL_GPL(svc_encode_result_payload);
1886 
1887 /**
1888  * svc_fill_symlink_pathname - Construct pathname argument for VFS symlink call
1889  * @rqstp: svc_rqst to operate on
1890  * @first: buffer containing first section of pathname
1891  * @p: buffer containing remaining section of pathname
1892  * @total: total length of the pathname argument
1893  *
1894  * The VFS symlink API demands a NUL-terminated pathname in mapped memory.
1895  * Returns pointer to a NUL-terminated string, or an ERR_PTR. Caller must free
1896  * the returned string.
1897  */
1898 char *svc_fill_symlink_pathname(struct svc_rqst *rqstp, struct kvec *first,
1899 				void *p, size_t total)
1900 {
1901 	size_t len, remaining;
1902 	char *result, *dst;
1903 
1904 	result = kmalloc(total + 1, GFP_KERNEL);
1905 	if (!result)
1906 		return ERR_PTR(-ESERVERFAULT);
1907 
1908 	dst = result;
1909 	remaining = total;
1910 
1911 	len = min_t(size_t, total, first->iov_len);
1912 	if (len) {
1913 		memcpy(dst, first->iov_base, len);
1914 		dst += len;
1915 		remaining -= len;
1916 	}
1917 
1918 	if (remaining) {
1919 		len = min_t(size_t, remaining, PAGE_SIZE);
1920 		memcpy(dst, p, len);
1921 		dst += len;
1922 	}
1923 
1924 	*dst = '\0';
1925 
1926 	/* Sanity check: Linux doesn't allow the pathname argument to
1927 	 * contain a NUL byte.
1928 	 */
1929 	if (strlen(result) != total) {
1930 		kfree(result);
1931 		return ERR_PTR(-EINVAL);
1932 	}
1933 	return result;
1934 }
1935 EXPORT_SYMBOL_GPL(svc_fill_symlink_pathname);
1936