1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2010, 2012, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36 
37 #define DEBUG_SUBSYSTEM S_RPC
38 #include "../include/obd_support.h"
39 #include "../include/obd_class.h"
40 #include "../include/lustre_net.h"
41 #include "../include/lu_object.h"
42 #include "../../include/linux/lnet/types.h"
43 #include "ptlrpc_internal.h"
44 
45 /* The following are visible and mutable through /sys/module/ptlrpc */
46 int test_req_buffer_pressure;
47 module_param(test_req_buffer_pressure, int, 0444);
48 MODULE_PARM_DESC(test_req_buffer_pressure, "set non-zero to put pressure on request buffer pools");
49 module_param(at_min, int, 0644);
50 MODULE_PARM_DESC(at_min, "Adaptive timeout minimum (sec)");
51 module_param(at_max, int, 0644);
52 MODULE_PARM_DESC(at_max, "Adaptive timeout maximum (sec)");
53 module_param(at_history, int, 0644);
54 MODULE_PARM_DESC(at_history,
55 		 "Adaptive timeouts remember the slowest event that took place within this period (sec)");
56 module_param(at_early_margin, int, 0644);
57 MODULE_PARM_DESC(at_early_margin, "How soon before an RPC deadline to send an early reply");
58 module_param(at_extra, int, 0644);
59 MODULE_PARM_DESC(at_extra, "How much extra time to give with each early reply");
60 
61 /* forward ref */
62 static int ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt);
63 static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req);
64 static void ptlrpc_at_remove_timed(struct ptlrpc_request *req);
65 
66 /** Holds a list of all PTLRPC services */
67 LIST_HEAD(ptlrpc_all_services);
68 /** Used to protect the \e ptlrpc_all_services list */
69 struct mutex ptlrpc_all_services_mutex;
70 
71 static struct ptlrpc_request_buffer_desc *
ptlrpc_alloc_rqbd(struct ptlrpc_service_part * svcpt)72 ptlrpc_alloc_rqbd(struct ptlrpc_service_part *svcpt)
73 {
74 	struct ptlrpc_service *svc = svcpt->scp_service;
75 	struct ptlrpc_request_buffer_desc *rqbd;
76 
77 	rqbd = kzalloc_node(sizeof(*rqbd), GFP_NOFS,
78 			    cfs_cpt_spread_node(svc->srv_cptable,
79 						svcpt->scp_cpt));
80 	if (rqbd == NULL)
81 		return NULL;
82 
83 	rqbd->rqbd_svcpt = svcpt;
84 	rqbd->rqbd_refcount = 0;
85 	rqbd->rqbd_cbid.cbid_fn = request_in_callback;
86 	rqbd->rqbd_cbid.cbid_arg = rqbd;
87 	INIT_LIST_HEAD(&rqbd->rqbd_reqs);
88 	rqbd->rqbd_buffer = libcfs_kvzalloc_cpt(svc->srv_cptable,
89 						svcpt->scp_cpt,
90 						svc->srv_buf_size,
91 						GFP_KERNEL);
92 	if (rqbd->rqbd_buffer == NULL) {
93 		kfree(rqbd);
94 		return NULL;
95 	}
96 
97 	spin_lock(&svcpt->scp_lock);
98 	list_add(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
99 	svcpt->scp_nrqbds_total++;
100 	spin_unlock(&svcpt->scp_lock);
101 
102 	return rqbd;
103 }
104 
105 static void
ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc * rqbd)106 ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
107 {
108 	struct ptlrpc_service_part *svcpt = rqbd->rqbd_svcpt;
109 
110 	LASSERT(rqbd->rqbd_refcount == 0);
111 	LASSERT(list_empty(&rqbd->rqbd_reqs));
112 
113 	spin_lock(&svcpt->scp_lock);
114 	list_del(&rqbd->rqbd_list);
115 	svcpt->scp_nrqbds_total--;
116 	spin_unlock(&svcpt->scp_lock);
117 
118 	kvfree(rqbd->rqbd_buffer);
119 	kfree(rqbd);
120 }
121 
122 static int
ptlrpc_grow_req_bufs(struct ptlrpc_service_part * svcpt,int post)123 ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
124 {
125 	struct ptlrpc_service *svc = svcpt->scp_service;
126 	struct ptlrpc_request_buffer_desc *rqbd;
127 	int rc = 0;
128 	int i;
129 
130 	if (svcpt->scp_rqbd_allocating)
131 		goto try_post;
132 
133 	spin_lock(&svcpt->scp_lock);
134 	/* check again with lock */
135 	if (svcpt->scp_rqbd_allocating) {
136 		/* NB: we might allow more than one thread in the future */
137 		LASSERT(svcpt->scp_rqbd_allocating == 1);
138 		spin_unlock(&svcpt->scp_lock);
139 		goto try_post;
140 	}
141 
142 	svcpt->scp_rqbd_allocating++;
143 	spin_unlock(&svcpt->scp_lock);
144 
145 	for (i = 0; i < svc->srv_nbuf_per_group; i++) {
146 		/* NB: another thread might have recycled enough rqbds, we
147 		 * need to make sure it wouldn't over-allocate, see LU-1212. */
148 		if (svcpt->scp_nrqbds_posted >= svc->srv_nbuf_per_group)
149 			break;
150 
151 		rqbd = ptlrpc_alloc_rqbd(svcpt);
152 
153 		if (rqbd == NULL) {
154 			CERROR("%s: Can't allocate request buffer\n",
155 			       svc->srv_name);
156 			rc = -ENOMEM;
157 			break;
158 		}
159 	}
160 
161 	spin_lock(&svcpt->scp_lock);
162 
163 	LASSERT(svcpt->scp_rqbd_allocating == 1);
164 	svcpt->scp_rqbd_allocating--;
165 
166 	spin_unlock(&svcpt->scp_lock);
167 
168 	CDEBUG(D_RPCTRACE,
169 	       "%s: allocate %d new %d-byte reqbufs (%d/%d left), rc = %d\n",
170 	       svc->srv_name, i, svc->srv_buf_size, svcpt->scp_nrqbds_posted,
171 	       svcpt->scp_nrqbds_total, rc);
172 
173  try_post:
174 	if (post && rc == 0)
175 		rc = ptlrpc_server_post_idle_rqbds(svcpt);
176 
177 	return rc;
178 }
179 
180 struct ptlrpc_hr_partition;
181 
182 struct ptlrpc_hr_thread {
183 	int				hrt_id;		/* thread ID */
184 	spinlock_t			hrt_lock;
185 	wait_queue_head_t			hrt_waitq;
186 	struct list_head			hrt_queue;	/* RS queue */
187 	struct ptlrpc_hr_partition	*hrt_partition;
188 };
189 
190 struct ptlrpc_hr_partition {
191 	/* # of started threads */
192 	atomic_t			hrp_nstarted;
193 	/* # of stopped threads */
194 	atomic_t			hrp_nstopped;
195 	/* cpu partition id */
196 	int				hrp_cpt;
197 	/* round-robin rotor for choosing thread */
198 	int				hrp_rotor;
199 	/* total number of threads on this partition */
200 	int				hrp_nthrs;
201 	/* threads table */
202 	struct ptlrpc_hr_thread		*hrp_thrs;
203 };
204 
205 #define HRT_RUNNING 0
206 #define HRT_STOPPING 1
207 
208 struct ptlrpc_hr_service {
209 	/* CPU partition table, it's just cfs_cpt_table for now */
210 	struct cfs_cpt_table		*hr_cpt_table;
211 	/** controller sleep waitq */
212 	wait_queue_head_t			hr_waitq;
213 	unsigned int			hr_stopping;
214 	/** roundrobin rotor for non-affinity service */
215 	unsigned int			hr_rotor;
216 	/* partition data */
217 	struct ptlrpc_hr_partition	**hr_partitions;
218 };
219 
220 /** reply handling service. */
221 static struct ptlrpc_hr_service		ptlrpc_hr;
222 
223 /**
224  * Choose an hr thread to dispatch requests to.
225  */
226 static struct ptlrpc_hr_thread *
ptlrpc_hr_select(struct ptlrpc_service_part * svcpt)227 ptlrpc_hr_select(struct ptlrpc_service_part *svcpt)
228 {
229 	struct ptlrpc_hr_partition *hrp;
230 	unsigned int rotor;
231 
232 	if (svcpt->scp_cpt >= 0 &&
233 	    svcpt->scp_service->srv_cptable == ptlrpc_hr.hr_cpt_table) {
234 		/* directly match partition */
235 		hrp = ptlrpc_hr.hr_partitions[svcpt->scp_cpt];
236 
237 	} else {
238 		rotor = ptlrpc_hr.hr_rotor++;
239 		rotor %= cfs_cpt_number(ptlrpc_hr.hr_cpt_table);
240 
241 		hrp = ptlrpc_hr.hr_partitions[rotor];
242 	}
243 
244 	rotor = hrp->hrp_rotor++;
245 	return &hrp->hrp_thrs[rotor % hrp->hrp_nthrs];
246 }
247 
248 /**
249  * Put reply state into a queue for processing because we received
250  * ACK from the client
251  */
ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state * rs)252 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
253 {
254 	struct ptlrpc_hr_thread *hrt;
255 
256 	LASSERT(list_empty(&rs->rs_list));
257 
258 	hrt = ptlrpc_hr_select(rs->rs_svcpt);
259 
260 	spin_lock(&hrt->hrt_lock);
261 	list_add_tail(&rs->rs_list, &hrt->hrt_queue);
262 	spin_unlock(&hrt->hrt_lock);
263 
264 	wake_up(&hrt->hrt_waitq);
265 }
266 
267 void
ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state * rs)268 ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs)
269 {
270 	assert_spin_locked(&rs->rs_svcpt->scp_rep_lock);
271 	assert_spin_locked(&rs->rs_lock);
272 	LASSERT(rs->rs_difficult);
273 	rs->rs_scheduled_ever = 1;  /* flag any notification attempt */
274 
275 	if (rs->rs_scheduled) {     /* being set up or already notified */
276 		return;
277 	}
278 
279 	rs->rs_scheduled = 1;
280 	list_del_init(&rs->rs_list);
281 	ptlrpc_dispatch_difficult_reply(rs);
282 }
283 EXPORT_SYMBOL(ptlrpc_schedule_difficult_reply);
284 
285 static int
ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part * svcpt)286 ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
287 {
288 	struct ptlrpc_request_buffer_desc *rqbd;
289 	int rc;
290 	int posted = 0;
291 
292 	for (;;) {
293 		spin_lock(&svcpt->scp_lock);
294 
295 		if (list_empty(&svcpt->scp_rqbd_idle)) {
296 			spin_unlock(&svcpt->scp_lock);
297 			return posted;
298 		}
299 
300 		rqbd = list_entry(svcpt->scp_rqbd_idle.next,
301 				      struct ptlrpc_request_buffer_desc,
302 				      rqbd_list);
303 		list_del(&rqbd->rqbd_list);
304 
305 		/* assume we will post successfully */
306 		svcpt->scp_nrqbds_posted++;
307 		list_add(&rqbd->rqbd_list, &svcpt->scp_rqbd_posted);
308 
309 		spin_unlock(&svcpt->scp_lock);
310 
311 		rc = ptlrpc_register_rqbd(rqbd);
312 		if (rc != 0)
313 			break;
314 
315 		posted = 1;
316 	}
317 
318 	spin_lock(&svcpt->scp_lock);
319 
320 	svcpt->scp_nrqbds_posted--;
321 	list_del(&rqbd->rqbd_list);
322 	list_add_tail(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
323 
324 	/* Don't complain if no request buffers are posted right now; LNET
325 	 * won't drop requests because we set the portal lazy! */
326 
327 	spin_unlock(&svcpt->scp_lock);
328 
329 	return -1;
330 }
331 
ptlrpc_at_timer(unsigned long castmeharder)332 static void ptlrpc_at_timer(unsigned long castmeharder)
333 {
334 	struct ptlrpc_service_part *svcpt;
335 
336 	svcpt = (struct ptlrpc_service_part *)castmeharder;
337 
338 	svcpt->scp_at_check = 1;
339 	svcpt->scp_at_checktime = cfs_time_current();
340 	wake_up(&svcpt->scp_waitq);
341 }
342 
343 static void
ptlrpc_server_nthreads_check(struct ptlrpc_service * svc,struct ptlrpc_service_conf * conf)344 ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
345 			     struct ptlrpc_service_conf *conf)
346 {
347 	struct ptlrpc_service_thr_conf *tc = &conf->psc_thr;
348 	unsigned init;
349 	unsigned total;
350 	unsigned nthrs;
351 	int weight;
352 
353 	/*
354 	 * Common code for estimating & validating threads number.
355 	 * CPT affinity service could have percpt thread-pool instead
356 	 * of a global thread-pool, which means user might not always
357 	 * get the threads number they give it in conf::tc_nthrs_user
358 	 * even they did set. It's because we need to validate threads
359 	 * number for each CPT to guarantee each pool will have enough
360 	 * threads to keep the service healthy.
361 	 */
362 	init = PTLRPC_NTHRS_INIT + (svc->srv_ops.so_hpreq_handler != NULL);
363 	init = max_t(int, init, tc->tc_nthrs_init);
364 
365 	/* NB: please see comments in lustre_lnet.h for definition
366 	 * details of these members */
367 	LASSERT(tc->tc_nthrs_max != 0);
368 
369 	if (tc->tc_nthrs_user != 0) {
370 		/* In case there is a reason to test a service with many
371 		 * threads, we give a less strict check here, it can
372 		 * be up to 8 * nthrs_max */
373 		total = min(tc->tc_nthrs_max * 8, tc->tc_nthrs_user);
374 		nthrs = total / svc->srv_ncpts;
375 		init = max(init, nthrs);
376 		goto out;
377 	}
378 
379 	total = tc->tc_nthrs_max;
380 	if (tc->tc_nthrs_base == 0) {
381 		/* don't care about base threads number per partition,
382 		 * this is most for non-affinity service */
383 		nthrs = total / svc->srv_ncpts;
384 		goto out;
385 	}
386 
387 	nthrs = tc->tc_nthrs_base;
388 	if (svc->srv_ncpts == 1) {
389 		int i;
390 
391 		/* NB: Increase the base number if it's single partition
392 		 * and total number of cores/HTs is larger or equal to 4.
393 		 * result will always < 2 * nthrs_base */
394 		weight = cfs_cpt_weight(svc->srv_cptable, CFS_CPT_ANY);
395 		for (i = 1; (weight >> (i + 1)) != 0 && /* >= 4 cores/HTs */
396 			    (tc->tc_nthrs_base >> i) != 0; i++)
397 			nthrs += tc->tc_nthrs_base >> i;
398 	}
399 
400 	if (tc->tc_thr_factor != 0) {
401 		int factor = tc->tc_thr_factor;
402 		const int fade = 4;
403 
404 		/*
405 		 * User wants to increase number of threads with for
406 		 * each CPU core/HT, most likely the factor is larger then
407 		 * one thread/core because service threads are supposed to
408 		 * be blocked by lock or wait for IO.
409 		 */
410 		/*
411 		 * Amdahl's law says that adding processors wouldn't give
412 		 * a linear increasing of parallelism, so it's nonsense to
413 		 * have too many threads no matter how many cores/HTs
414 		 * there are.
415 		 */
416 		/* weight is # of HTs */
417 		if (cpumask_weight(topology_sibling_cpumask(0)) > 1) {
418 			/* depress thread factor for hyper-thread */
419 			factor = factor - (factor >> 1) + (factor >> 3);
420 		}
421 
422 		weight = cfs_cpt_weight(svc->srv_cptable, 0);
423 		LASSERT(weight > 0);
424 
425 		for (; factor > 0 && weight > 0; factor--, weight -= fade)
426 			nthrs += min(weight, fade) * factor;
427 	}
428 
429 	if (nthrs * svc->srv_ncpts > tc->tc_nthrs_max) {
430 		nthrs = max(tc->tc_nthrs_base,
431 			    tc->tc_nthrs_max / svc->srv_ncpts);
432 	}
433  out:
434 	nthrs = max(nthrs, tc->tc_nthrs_init);
435 	svc->srv_nthrs_cpt_limit = nthrs;
436 	svc->srv_nthrs_cpt_init = init;
437 
438 	if (nthrs * svc->srv_ncpts > tc->tc_nthrs_max) {
439 		CDEBUG(D_OTHER, "%s: This service may have more threads (%d) than the given soft limit (%d)\n",
440 		       svc->srv_name, nthrs * svc->srv_ncpts,
441 		       tc->tc_nthrs_max);
442 	}
443 }
444 
445 /**
446  * Initialize percpt data for a service
447  */
448 static int
ptlrpc_service_part_init(struct ptlrpc_service * svc,struct ptlrpc_service_part * svcpt,int cpt)449 ptlrpc_service_part_init(struct ptlrpc_service *svc,
450 			 struct ptlrpc_service_part *svcpt, int cpt)
451 {
452 	struct ptlrpc_at_array	*array;
453 	int size;
454 	int index;
455 	int rc;
456 
457 	svcpt->scp_cpt = cpt;
458 	INIT_LIST_HEAD(&svcpt->scp_threads);
459 
460 	/* rqbd and incoming request queue */
461 	spin_lock_init(&svcpt->scp_lock);
462 	INIT_LIST_HEAD(&svcpt->scp_rqbd_idle);
463 	INIT_LIST_HEAD(&svcpt->scp_rqbd_posted);
464 	INIT_LIST_HEAD(&svcpt->scp_req_incoming);
465 	init_waitqueue_head(&svcpt->scp_waitq);
466 	/* history request & rqbd list */
467 	INIT_LIST_HEAD(&svcpt->scp_hist_reqs);
468 	INIT_LIST_HEAD(&svcpt->scp_hist_rqbds);
469 
470 	/* active requests and hp requests */
471 	spin_lock_init(&svcpt->scp_req_lock);
472 
473 	/* reply states */
474 	spin_lock_init(&svcpt->scp_rep_lock);
475 	INIT_LIST_HEAD(&svcpt->scp_rep_active);
476 	INIT_LIST_HEAD(&svcpt->scp_rep_idle);
477 	init_waitqueue_head(&svcpt->scp_rep_waitq);
478 	atomic_set(&svcpt->scp_nreps_difficult, 0);
479 
480 	/* adaptive timeout */
481 	spin_lock_init(&svcpt->scp_at_lock);
482 	array = &svcpt->scp_at_array;
483 
484 	size = at_est2timeout(at_max);
485 	array->paa_size = size;
486 	array->paa_count = 0;
487 	array->paa_deadline = -1;
488 
489 	/* allocate memory for scp_at_array (ptlrpc_at_array) */
490 	array->paa_reqs_array =
491 		kzalloc_node(sizeof(struct list_head) * size, GFP_NOFS,
492 			     cfs_cpt_spread_node(svc->srv_cptable, cpt));
493 	if (array->paa_reqs_array == NULL)
494 		return -ENOMEM;
495 
496 	for (index = 0; index < size; index++)
497 		INIT_LIST_HEAD(&array->paa_reqs_array[index]);
498 
499 	array->paa_reqs_count =
500 		kzalloc_node(sizeof(__u32) * size, GFP_NOFS,
501 			     cfs_cpt_spread_node(svc->srv_cptable, cpt));
502 	if (array->paa_reqs_count == NULL)
503 		goto free_reqs_array;
504 
505 	setup_timer(&svcpt->scp_at_timer, ptlrpc_at_timer,
506 		    (unsigned long)svcpt);
507 
508 	/* At SOW, service time should be quick; 10s seems generous. If client
509 	 * timeout is less than this, we'll be sending an early reply. */
510 	at_init(&svcpt->scp_at_estimate, 10, 0);
511 
512 	/* assign this before call ptlrpc_grow_req_bufs */
513 	svcpt->scp_service = svc;
514 	/* Now allocate the request buffers, but don't post them now */
515 	rc = ptlrpc_grow_req_bufs(svcpt, 0);
516 	/* We shouldn't be under memory pressure at startup, so
517 	 * fail if we can't allocate all our buffers at this time. */
518 	if (rc != 0)
519 		goto free_reqs_count;
520 
521 	return 0;
522 
523 free_reqs_count:
524 	kfree(array->paa_reqs_count);
525 	array->paa_reqs_count = NULL;
526 free_reqs_array:
527 	kfree(array->paa_reqs_array);
528 	array->paa_reqs_array = NULL;
529 
530 	return -ENOMEM;
531 }
532 
533 /**
534  * Initialize service on a given portal.
535  * This includes starting serving threads , allocating and posting rqbds and
536  * so on.
537  */
538 struct ptlrpc_service *
ptlrpc_register_service(struct ptlrpc_service_conf * conf,struct kset * parent,struct dentry * debugfs_entry)539 ptlrpc_register_service(struct ptlrpc_service_conf *conf,
540 			struct kset *parent,
541 			struct dentry *debugfs_entry)
542 {
543 	struct ptlrpc_service_cpt_conf *cconf = &conf->psc_cpt;
544 	struct ptlrpc_service *service;
545 	struct ptlrpc_service_part *svcpt;
546 	struct cfs_cpt_table *cptable;
547 	__u32 *cpts = NULL;
548 	int ncpts;
549 	int cpt;
550 	int rc;
551 	int i;
552 
553 	LASSERT(conf->psc_buf.bc_nbufs > 0);
554 	LASSERT(conf->psc_buf.bc_buf_size >=
555 		conf->psc_buf.bc_req_max_size + SPTLRPC_MAX_PAYLOAD);
556 	LASSERT(conf->psc_thr.tc_ctx_tags != 0);
557 
558 	cptable = cconf->cc_cptable;
559 	if (cptable == NULL)
560 		cptable = cfs_cpt_table;
561 
562 	if (!conf->psc_thr.tc_cpu_affinity) {
563 		ncpts = 1;
564 	} else {
565 		ncpts = cfs_cpt_number(cptable);
566 		if (cconf->cc_pattern != NULL) {
567 			struct cfs_expr_list *el;
568 
569 			rc = cfs_expr_list_parse(cconf->cc_pattern,
570 						 strlen(cconf->cc_pattern),
571 						 0, ncpts - 1, &el);
572 			if (rc != 0) {
573 				CERROR("%s: invalid CPT pattern string: %s",
574 				       conf->psc_name, cconf->cc_pattern);
575 				return ERR_PTR(-EINVAL);
576 			}
577 
578 			rc = cfs_expr_list_values(el, ncpts, &cpts);
579 			cfs_expr_list_free(el);
580 			if (rc <= 0) {
581 				CERROR("%s: failed to parse CPT array %s: %d\n",
582 				       conf->psc_name, cconf->cc_pattern, rc);
583 				kfree(cpts);
584 				return ERR_PTR(rc < 0 ? rc : -EINVAL);
585 			}
586 			ncpts = rc;
587 		}
588 	}
589 
590 	service = kzalloc(offsetof(struct ptlrpc_service, srv_parts[ncpts]),
591 			  GFP_NOFS);
592 	if (!service) {
593 		kfree(cpts);
594 		return ERR_PTR(-ENOMEM);
595 	}
596 
597 	service->srv_cptable = cptable;
598 	service->srv_cpts = cpts;
599 	service->srv_ncpts = ncpts;
600 
601 	service->srv_cpt_bits = 0; /* it's zero already, easy to read... */
602 	while ((1 << service->srv_cpt_bits) < cfs_cpt_number(cptable))
603 		service->srv_cpt_bits++;
604 
605 	/* public members */
606 	spin_lock_init(&service->srv_lock);
607 	service->srv_name = conf->psc_name;
608 	service->srv_watchdog_factor = conf->psc_watchdog_factor;
609 	INIT_LIST_HEAD(&service->srv_list); /* for safety of cleanup */
610 
611 	/* buffer configuration */
612 	service->srv_nbuf_per_group = test_req_buffer_pressure ?
613 					  1 : conf->psc_buf.bc_nbufs;
614 	service->srv_max_req_size = conf->psc_buf.bc_req_max_size +
615 					  SPTLRPC_MAX_PAYLOAD;
616 	service->srv_buf_size = conf->psc_buf.bc_buf_size;
617 	service->srv_rep_portal	= conf->psc_buf.bc_rep_portal;
618 	service->srv_req_portal	= conf->psc_buf.bc_req_portal;
619 
620 	/* Increase max reply size to next power of two */
621 	service->srv_max_reply_size = 1;
622 	while (service->srv_max_reply_size <
623 	       conf->psc_buf.bc_rep_max_size + SPTLRPC_MAX_PAYLOAD)
624 		service->srv_max_reply_size <<= 1;
625 
626 	service->srv_thread_name = conf->psc_thr.tc_thr_name;
627 	service->srv_ctx_tags = conf->psc_thr.tc_ctx_tags;
628 	service->srv_hpreq_ratio = PTLRPC_SVC_HP_RATIO;
629 	service->srv_ops = conf->psc_ops;
630 
631 	for (i = 0; i < ncpts; i++) {
632 		if (!conf->psc_thr.tc_cpu_affinity)
633 			cpt = CFS_CPT_ANY;
634 		else
635 			cpt = cpts != NULL ? cpts[i] : i;
636 
637 		svcpt = kzalloc_node(sizeof(*svcpt), GFP_NOFS,
638 				     cfs_cpt_spread_node(cptable, cpt));
639 		if (svcpt == NULL) {
640 			rc = -ENOMEM;
641 			goto failed;
642 		}
643 
644 		service->srv_parts[i] = svcpt;
645 		rc = ptlrpc_service_part_init(service, svcpt, cpt);
646 		if (rc != 0)
647 			goto failed;
648 	}
649 
650 	ptlrpc_server_nthreads_check(service, conf);
651 
652 	rc = LNetSetLazyPortal(service->srv_req_portal);
653 	LASSERT(rc == 0);
654 
655 	mutex_lock(&ptlrpc_all_services_mutex);
656 	list_add(&service->srv_list, &ptlrpc_all_services);
657 	mutex_unlock(&ptlrpc_all_services_mutex);
658 
659 	if (parent) {
660 		rc = ptlrpc_sysfs_register_service(parent, service);
661 		if (rc)
662 			goto failed;
663 	}
664 
665 	if (!IS_ERR_OR_NULL(debugfs_entry))
666 		ptlrpc_ldebugfs_register_service(debugfs_entry, service);
667 
668 	rc = ptlrpc_service_nrs_setup(service);
669 	if (rc != 0)
670 		goto failed;
671 
672 	CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
673 	       service->srv_name, service->srv_req_portal);
674 
675 	rc = ptlrpc_start_threads(service);
676 	if (rc != 0) {
677 		CERROR("Failed to start threads for service %s: %d\n",
678 		       service->srv_name, rc);
679 		goto failed;
680 	}
681 
682 	return service;
683 failed:
684 	ptlrpc_unregister_service(service);
685 	return ERR_PTR(rc);
686 }
687 EXPORT_SYMBOL(ptlrpc_register_service);
688 
689 /**
690  * to actually free the request, must be called without holding svc_lock.
691  * note it's caller's responsibility to unlink req->rq_list.
692  */
ptlrpc_server_free_request(struct ptlrpc_request * req)693 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
694 {
695 	LASSERT(atomic_read(&req->rq_refcount) == 0);
696 	LASSERT(list_empty(&req->rq_timed_list));
697 
698 	 /* DEBUG_REQ() assumes the reply state of a request with a valid
699 	  * ref will not be destroyed until that reference is dropped. */
700 	ptlrpc_req_drop_rs(req);
701 
702 	sptlrpc_svc_ctx_decref(req);
703 
704 	if (req != &req->rq_rqbd->rqbd_req) {
705 		/* NB request buffers use an embedded
706 		 * req if the incoming req unlinked the
707 		 * MD; this isn't one of them! */
708 		ptlrpc_request_cache_free(req);
709 	}
710 }
711 
712 /**
713  * drop a reference count of the request. if it reaches 0, we either
714  * put it into history list, or free it immediately.
715  */
ptlrpc_server_drop_request(struct ptlrpc_request * req)716 static void ptlrpc_server_drop_request(struct ptlrpc_request *req)
717 {
718 	struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
719 	struct ptlrpc_service_part *svcpt = rqbd->rqbd_svcpt;
720 	struct ptlrpc_service *svc = svcpt->scp_service;
721 	int refcount;
722 	struct list_head *tmp;
723 	struct list_head *nxt;
724 
725 	if (!atomic_dec_and_test(&req->rq_refcount))
726 		return;
727 
728 	if (req->rq_at_linked) {
729 		spin_lock(&svcpt->scp_at_lock);
730 		/* recheck with lock, in case it's unlinked by
731 		 * ptlrpc_at_check_timed() */
732 		if (likely(req->rq_at_linked))
733 			ptlrpc_at_remove_timed(req);
734 		spin_unlock(&svcpt->scp_at_lock);
735 	}
736 
737 	LASSERT(list_empty(&req->rq_timed_list));
738 
739 	/* finalize request */
740 	if (req->rq_export) {
741 		class_export_put(req->rq_export);
742 		req->rq_export = NULL;
743 	}
744 
745 	spin_lock(&svcpt->scp_lock);
746 
747 	list_add(&req->rq_list, &rqbd->rqbd_reqs);
748 
749 	refcount = --(rqbd->rqbd_refcount);
750 	if (refcount == 0) {
751 		/* request buffer is now idle: add to history */
752 		list_del(&rqbd->rqbd_list);
753 
754 		list_add_tail(&rqbd->rqbd_list, &svcpt->scp_hist_rqbds);
755 		svcpt->scp_hist_nrqbds++;
756 
757 		/* cull some history?
758 		 * I expect only about 1 or 2 rqbds need to be recycled here */
759 		while (svcpt->scp_hist_nrqbds > svc->srv_hist_nrqbds_cpt_max) {
760 			rqbd = list_entry(svcpt->scp_hist_rqbds.next,
761 					      struct ptlrpc_request_buffer_desc,
762 					      rqbd_list);
763 
764 			list_del(&rqbd->rqbd_list);
765 			svcpt->scp_hist_nrqbds--;
766 
767 			/* remove rqbd's reqs from svc's req history while
768 			 * I've got the service lock */
769 			list_for_each(tmp, &rqbd->rqbd_reqs) {
770 				req = list_entry(tmp, struct ptlrpc_request,
771 						     rq_list);
772 				/* Track the highest culled req seq */
773 				if (req->rq_history_seq >
774 				    svcpt->scp_hist_seq_culled) {
775 					svcpt->scp_hist_seq_culled =
776 						req->rq_history_seq;
777 				}
778 				list_del(&req->rq_history_list);
779 			}
780 
781 			spin_unlock(&svcpt->scp_lock);
782 
783 			list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
784 				req = list_entry(rqbd->rqbd_reqs.next,
785 						     struct ptlrpc_request,
786 						     rq_list);
787 				list_del(&req->rq_list);
788 				ptlrpc_server_free_request(req);
789 			}
790 
791 			spin_lock(&svcpt->scp_lock);
792 			/*
793 			 * now all reqs including the embedded req has been
794 			 * disposed, schedule request buffer for re-use.
795 			 */
796 			LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) ==
797 				0);
798 			list_add_tail(&rqbd->rqbd_list,
799 					  &svcpt->scp_rqbd_idle);
800 		}
801 
802 		spin_unlock(&svcpt->scp_lock);
803 	} else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
804 		/* If we are low on memory, we are not interested in history */
805 		list_del(&req->rq_list);
806 		list_del_init(&req->rq_history_list);
807 
808 		/* Track the highest culled req seq */
809 		if (req->rq_history_seq > svcpt->scp_hist_seq_culled)
810 			svcpt->scp_hist_seq_culled = req->rq_history_seq;
811 
812 		spin_unlock(&svcpt->scp_lock);
813 
814 		ptlrpc_server_free_request(req);
815 	} else {
816 		spin_unlock(&svcpt->scp_lock);
817 	}
818 }
819 
820 /**
821  * to finish a request: stop sending more early replies, and release
822  * the request.
823  */
ptlrpc_server_finish_request(struct ptlrpc_service_part * svcpt,struct ptlrpc_request * req)824 static void ptlrpc_server_finish_request(struct ptlrpc_service_part *svcpt,
825 					 struct ptlrpc_request *req)
826 {
827 	ptlrpc_server_hpreq_fini(req);
828 
829 	ptlrpc_server_drop_request(req);
830 }
831 
832 /**
833  * to finish a active request: stop sending more early replies, and release
834  * the request. should be called after we finished handling the request.
835  */
ptlrpc_server_finish_active_request(struct ptlrpc_service_part * svcpt,struct ptlrpc_request * req)836 static void ptlrpc_server_finish_active_request(
837 					struct ptlrpc_service_part *svcpt,
838 					struct ptlrpc_request *req)
839 {
840 	spin_lock(&svcpt->scp_req_lock);
841 	ptlrpc_nrs_req_stop_nolock(req);
842 	svcpt->scp_nreqs_active--;
843 	if (req->rq_hp)
844 		svcpt->scp_nhreqs_active--;
845 	spin_unlock(&svcpt->scp_req_lock);
846 
847 	ptlrpc_nrs_req_finalize(req);
848 
849 	if (req->rq_export != NULL)
850 		class_export_rpc_dec(req->rq_export);
851 
852 	ptlrpc_server_finish_request(svcpt, req);
853 }
854 
855 /**
856  * Sanity check request \a req.
857  * Return 0 if all is ok, error code otherwise.
858  */
ptlrpc_check_req(struct ptlrpc_request * req)859 static int ptlrpc_check_req(struct ptlrpc_request *req)
860 {
861 	struct obd_device *obd = req->rq_export->exp_obd;
862 	int rc = 0;
863 
864 	if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
865 		     req->rq_export->exp_conn_cnt)) {
866 		DEBUG_REQ(D_RPCTRACE, req,
867 			  "DROPPING req from old connection %d < %d",
868 			  lustre_msg_get_conn_cnt(req->rq_reqmsg),
869 			  req->rq_export->exp_conn_cnt);
870 		return -EEXIST;
871 	}
872 	if (unlikely(obd == NULL || obd->obd_fail)) {
873 		/*
874 		 * Failing over, don't handle any more reqs, send
875 		 * error response instead.
876 		 */
877 		CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
878 		       req, (obd != NULL) ? obd->obd_name : "unknown");
879 		rc = -ENODEV;
880 	} else if (lustre_msg_get_flags(req->rq_reqmsg) &
881 		   (MSG_REPLAY | MSG_REQ_REPLAY_DONE)) {
882 		DEBUG_REQ(D_ERROR, req, "Invalid replay without recovery");
883 		class_fail_export(req->rq_export);
884 		rc = -ENODEV;
885 	} else if (lustre_msg_get_transno(req->rq_reqmsg) != 0) {
886 		DEBUG_REQ(D_ERROR, req,
887 			  "Invalid req with transno %llu without recovery",
888 			  lustre_msg_get_transno(req->rq_reqmsg));
889 		class_fail_export(req->rq_export);
890 		rc = -ENODEV;
891 	}
892 
893 	if (unlikely(rc < 0)) {
894 		req->rq_status = rc;
895 		ptlrpc_error(req);
896 	}
897 	return rc;
898 }
899 
ptlrpc_at_set_timer(struct ptlrpc_service_part * svcpt)900 static void ptlrpc_at_set_timer(struct ptlrpc_service_part *svcpt)
901 {
902 	struct ptlrpc_at_array *array = &svcpt->scp_at_array;
903 	__s32 next;
904 
905 	if (array->paa_count == 0) {
906 		del_timer(&svcpt->scp_at_timer);
907 		return;
908 	}
909 
910 	/* Set timer for closest deadline */
911 	next = (__s32)(array->paa_deadline - ktime_get_real_seconds() -
912 		       at_early_margin);
913 	if (next <= 0) {
914 		ptlrpc_at_timer((unsigned long)svcpt);
915 	} else {
916 		mod_timer(&svcpt->scp_at_timer, cfs_time_shift(next));
917 		CDEBUG(D_INFO, "armed %s at %+ds\n",
918 		       svcpt->scp_service->srv_name, next);
919 	}
920 }
921 
922 /* Add rpc to early reply check list */
ptlrpc_at_add_timed(struct ptlrpc_request * req)923 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
924 {
925 	struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
926 	struct ptlrpc_at_array *array = &svcpt->scp_at_array;
927 	struct ptlrpc_request *rq = NULL;
928 	__u32 index;
929 
930 	if (AT_OFF)
931 		return 0;
932 
933 	if (req->rq_no_reply)
934 		return 0;
935 
936 	if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
937 		return -ENOSYS;
938 
939 	spin_lock(&svcpt->scp_at_lock);
940 	LASSERT(list_empty(&req->rq_timed_list));
941 
942 	div_u64_rem(req->rq_deadline, array->paa_size, &index);
943 	if (array->paa_reqs_count[index] > 0) {
944 		/* latest rpcs will have the latest deadlines in the list,
945 		 * so search backward. */
946 		list_for_each_entry_reverse(rq,
947 						&array->paa_reqs_array[index],
948 						rq_timed_list) {
949 			if (req->rq_deadline >= rq->rq_deadline) {
950 				list_add(&req->rq_timed_list,
951 					     &rq->rq_timed_list);
952 				break;
953 			}
954 		}
955 	}
956 
957 	/* Add the request at the head of the list */
958 	if (list_empty(&req->rq_timed_list))
959 		list_add(&req->rq_timed_list,
960 			     &array->paa_reqs_array[index]);
961 
962 	spin_lock(&req->rq_lock);
963 	req->rq_at_linked = 1;
964 	spin_unlock(&req->rq_lock);
965 	req->rq_at_index = index;
966 	array->paa_reqs_count[index]++;
967 	array->paa_count++;
968 	if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
969 		array->paa_deadline = req->rq_deadline;
970 		ptlrpc_at_set_timer(svcpt);
971 	}
972 	spin_unlock(&svcpt->scp_at_lock);
973 
974 	return 0;
975 }
976 
977 static void
ptlrpc_at_remove_timed(struct ptlrpc_request * req)978 ptlrpc_at_remove_timed(struct ptlrpc_request *req)
979 {
980 	struct ptlrpc_at_array *array;
981 
982 	array = &req->rq_rqbd->rqbd_svcpt->scp_at_array;
983 
984 	/* NB: must call with hold svcpt::scp_at_lock */
985 	LASSERT(!list_empty(&req->rq_timed_list));
986 	list_del_init(&req->rq_timed_list);
987 
988 	spin_lock(&req->rq_lock);
989 	req->rq_at_linked = 0;
990 	spin_unlock(&req->rq_lock);
991 
992 	array->paa_reqs_count[req->rq_at_index]--;
993 	array->paa_count--;
994 }
995 
ptlrpc_at_send_early_reply(struct ptlrpc_request * req)996 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
997 {
998 	struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
999 	struct ptlrpc_request *reqcopy;
1000 	struct lustre_msg *reqmsg;
1001 	long olddl = req->rq_deadline - ktime_get_real_seconds();
1002 	time64_t newdl;
1003 	int rc;
1004 
1005 	/* deadline is when the client expects us to reply, margin is the
1006 	   difference between clients' and servers' expectations */
1007 	DEBUG_REQ(D_ADAPTTO, req,
1008 		  "%ssending early reply (deadline %+lds, margin %+lds) for %d+%d",
1009 		  AT_OFF ? "AT off - not " : "",
1010 		  olddl, olddl - at_get(&svcpt->scp_at_estimate),
1011 		  at_get(&svcpt->scp_at_estimate), at_extra);
1012 
1013 	if (AT_OFF)
1014 		return 0;
1015 
1016 	if (olddl < 0) {
1017 		DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), not sending early reply. Consider increasing at_early_margin (%d)?",
1018 			  olddl, at_early_margin);
1019 
1020 		/* Return an error so we're not re-added to the timed list. */
1021 		return -ETIMEDOUT;
1022 	}
1023 
1024 	if (!(lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT)) {
1025 		DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, but no AT support");
1026 		return -ENOSYS;
1027 	}
1028 
1029 	/* Fake our processing time into the future to ask the clients
1030 	 * for some extra amount of time */
1031 	at_measured(&svcpt->scp_at_estimate, at_extra +
1032 		    ktime_get_real_seconds() - req->rq_arrival_time.tv_sec);
1033 
1034 	/* Check to see if we've actually increased the deadline -
1035 	 * we may be past adaptive_max */
1036 	if (req->rq_deadline >= req->rq_arrival_time.tv_sec +
1037 	    at_get(&svcpt->scp_at_estimate)) {
1038 		DEBUG_REQ(D_WARNING, req, "Couldn't add any time (%ld/%lld), not sending early reply\n",
1039 			  olddl, req->rq_arrival_time.tv_sec +
1040 			  at_get(&svcpt->scp_at_estimate) -
1041 			  ktime_get_real_seconds());
1042 		return -ETIMEDOUT;
1043 	}
1044 	newdl = ktime_get_real_seconds() + at_get(&svcpt->scp_at_estimate);
1045 
1046 	reqcopy = ptlrpc_request_cache_alloc(GFP_NOFS);
1047 	if (reqcopy == NULL)
1048 		return -ENOMEM;
1049 	reqmsg = libcfs_kvzalloc(req->rq_reqlen, GFP_NOFS);
1050 	if (!reqmsg) {
1051 		rc = -ENOMEM;
1052 		goto out_free;
1053 	}
1054 
1055 	*reqcopy = *req;
1056 	reqcopy->rq_reply_state = NULL;
1057 	reqcopy->rq_rep_swab_mask = 0;
1058 	reqcopy->rq_pack_bulk = 0;
1059 	reqcopy->rq_pack_udesc = 0;
1060 	reqcopy->rq_packed_final = 0;
1061 	sptlrpc_svc_ctx_addref(reqcopy);
1062 	/* We only need the reqmsg for the magic */
1063 	reqcopy->rq_reqmsg = reqmsg;
1064 	memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1065 
1066 	LASSERT(atomic_read(&req->rq_refcount));
1067 	/** if it is last refcount then early reply isn't needed */
1068 	if (atomic_read(&req->rq_refcount) == 1) {
1069 		DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, abort sending early reply\n");
1070 		rc = -EINVAL;
1071 		goto out;
1072 	}
1073 
1074 	/* Connection ref */
1075 	reqcopy->rq_export = class_conn2export(
1076 				     lustre_msg_get_handle(reqcopy->rq_reqmsg));
1077 	if (reqcopy->rq_export == NULL) {
1078 		rc = -ENODEV;
1079 		goto out;
1080 	}
1081 
1082 	/* RPC ref */
1083 	class_export_rpc_inc(reqcopy->rq_export);
1084 	if (reqcopy->rq_export->exp_obd &&
1085 	    reqcopy->rq_export->exp_obd->obd_fail) {
1086 		rc = -ENODEV;
1087 		goto out_put;
1088 	}
1089 
1090 	rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
1091 	if (rc)
1092 		goto out_put;
1093 
1094 	rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
1095 
1096 	if (!rc) {
1097 		/* Adjust our own deadline to what we told the client */
1098 		req->rq_deadline = newdl;
1099 		req->rq_early_count++; /* number sent, server side */
1100 	} else {
1101 		DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
1102 	}
1103 
1104 	/* Free the (early) reply state from lustre_pack_reply.
1105 	   (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
1106 	ptlrpc_req_drop_rs(reqcopy);
1107 
1108 out_put:
1109 	class_export_rpc_dec(reqcopy->rq_export);
1110 	class_export_put(reqcopy->rq_export);
1111 out:
1112 	sptlrpc_svc_ctx_decref(reqcopy);
1113 	kvfree(reqmsg);
1114 out_free:
1115 	ptlrpc_request_cache_free(reqcopy);
1116 	return rc;
1117 }
1118 
1119 /* Send early replies to everybody expiring within at_early_margin
1120    asking for at_extra time */
ptlrpc_at_check_timed(struct ptlrpc_service_part * svcpt)1121 static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
1122 {
1123 	struct ptlrpc_at_array *array = &svcpt->scp_at_array;
1124 	struct ptlrpc_request *rq, *n;
1125 	struct list_head work_list;
1126 	__u32 index, count;
1127 	time64_t deadline;
1128 	time64_t now = ktime_get_real_seconds();
1129 	long delay;
1130 	int first, counter = 0;
1131 
1132 	spin_lock(&svcpt->scp_at_lock);
1133 	if (svcpt->scp_at_check == 0) {
1134 		spin_unlock(&svcpt->scp_at_lock);
1135 		return 0;
1136 	}
1137 	delay = cfs_time_sub(cfs_time_current(), svcpt->scp_at_checktime);
1138 	svcpt->scp_at_check = 0;
1139 
1140 	if (array->paa_count == 0) {
1141 		spin_unlock(&svcpt->scp_at_lock);
1142 		return 0;
1143 	}
1144 
1145 	/* The timer went off, but maybe the nearest rpc already completed. */
1146 	first = array->paa_deadline - now;
1147 	if (first > at_early_margin) {
1148 		/* We've still got plenty of time.  Reset the timer. */
1149 		ptlrpc_at_set_timer(svcpt);
1150 		spin_unlock(&svcpt->scp_at_lock);
1151 		return 0;
1152 	}
1153 
1154 	/* We're close to a timeout, and we don't know how much longer the
1155 	   server will take. Send early replies to everyone expiring soon. */
1156 	INIT_LIST_HEAD(&work_list);
1157 	deadline = -1;
1158 	div_u64_rem(array->paa_deadline, array->paa_size, &index);
1159 	count = array->paa_count;
1160 	while (count > 0) {
1161 		count -= array->paa_reqs_count[index];
1162 		list_for_each_entry_safe(rq, n,
1163 					     &array->paa_reqs_array[index],
1164 					     rq_timed_list) {
1165 			if (rq->rq_deadline > now + at_early_margin) {
1166 				/* update the earliest deadline */
1167 				if (deadline == -1 ||
1168 				    rq->rq_deadline < deadline)
1169 					deadline = rq->rq_deadline;
1170 				break;
1171 			}
1172 
1173 			ptlrpc_at_remove_timed(rq);
1174 			/**
1175 			 * ptlrpc_server_drop_request() may drop
1176 			 * refcount to 0 already. Let's check this and
1177 			 * don't add entry to work_list
1178 			 */
1179 			if (likely(atomic_inc_not_zero(&rq->rq_refcount)))
1180 				list_add(&rq->rq_timed_list, &work_list);
1181 			counter++;
1182 		}
1183 
1184 		if (++index >= array->paa_size)
1185 			index = 0;
1186 	}
1187 	array->paa_deadline = deadline;
1188 	/* we have a new earliest deadline, restart the timer */
1189 	ptlrpc_at_set_timer(svcpt);
1190 
1191 	spin_unlock(&svcpt->scp_at_lock);
1192 
1193 	CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early replies\n",
1194 	       first, at_extra, counter);
1195 	if (first < 0) {
1196 		/* We're already past request deadlines before we even get a
1197 		   chance to send early replies */
1198 		LCONSOLE_WARN("%s: This server is not able to keep up with request traffic (cpu-bound).\n",
1199 			      svcpt->scp_service->srv_name);
1200 		CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, delay=%ld(jiff)\n",
1201 		      counter, svcpt->scp_nreqs_incoming,
1202 		      svcpt->scp_nreqs_active,
1203 		      at_get(&svcpt->scp_at_estimate), delay);
1204 	}
1205 
1206 	/* we took additional refcount so entries can't be deleted from list, no
1207 	 * locking is needed */
1208 	while (!list_empty(&work_list)) {
1209 		rq = list_entry(work_list.next, struct ptlrpc_request,
1210 				    rq_timed_list);
1211 		list_del_init(&rq->rq_timed_list);
1212 
1213 		if (ptlrpc_at_send_early_reply(rq) == 0)
1214 			ptlrpc_at_add_timed(rq);
1215 
1216 		ptlrpc_server_drop_request(rq);
1217 	}
1218 
1219 	return 1; /* return "did_something" for liblustre */
1220 }
1221 
1222 /**
1223  * Put the request to the export list if the request may become
1224  * a high priority one.
1225  */
ptlrpc_server_hpreq_init(struct ptlrpc_service_part * svcpt,struct ptlrpc_request * req)1226 static int ptlrpc_server_hpreq_init(struct ptlrpc_service_part *svcpt,
1227 				    struct ptlrpc_request *req)
1228 {
1229 	int rc = 0;
1230 
1231 	if (svcpt->scp_service->srv_ops.so_hpreq_handler) {
1232 		rc = svcpt->scp_service->srv_ops.so_hpreq_handler(req);
1233 		if (rc < 0)
1234 			return rc;
1235 		LASSERT(rc == 0);
1236 	}
1237 	if (req->rq_export && req->rq_ops) {
1238 		/* Perform request specific check. We should do this check
1239 		 * before the request is added into exp_hp_rpcs list otherwise
1240 		 * it may hit swab race at LU-1044. */
1241 		if (req->rq_ops->hpreq_check) {
1242 			rc = req->rq_ops->hpreq_check(req);
1243 			/**
1244 			 * XXX: Out of all current
1245 			 * ptlrpc_hpreq_ops::hpreq_check(), only
1246 			 * ldlm_cancel_hpreq_check() can return an error code;
1247 			 * other functions assert in similar places, which seems
1248 			 * odd. What also does not seem right is that handlers
1249 			 * for those RPCs do not assert on the same checks, but
1250 			 * rather handle the error cases. e.g. see
1251 			 * ost_rw_hpreq_check(), and ost_brw_read(),
1252 			 * ost_brw_write().
1253 			 */
1254 			if (rc < 0)
1255 				return rc;
1256 			LASSERT(rc == 0 || rc == 1);
1257 		}
1258 
1259 		spin_lock_bh(&req->rq_export->exp_rpc_lock);
1260 		list_add(&req->rq_exp_list,
1261 			     &req->rq_export->exp_hp_rpcs);
1262 		spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1263 	}
1264 
1265 	ptlrpc_nrs_req_initialize(svcpt, req, rc);
1266 
1267 	return rc;
1268 }
1269 
1270 /** Remove the request from the export list. */
ptlrpc_server_hpreq_fini(struct ptlrpc_request * req)1271 static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req)
1272 {
1273 	if (req->rq_export && req->rq_ops) {
1274 		/* refresh lock timeout again so that client has more
1275 		 * room to send lock cancel RPC. */
1276 		if (req->rq_ops->hpreq_fini)
1277 			req->rq_ops->hpreq_fini(req);
1278 
1279 		spin_lock_bh(&req->rq_export->exp_rpc_lock);
1280 		list_del_init(&req->rq_exp_list);
1281 		spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1282 	}
1283 }
1284 
ptlrpc_server_request_add(struct ptlrpc_service_part * svcpt,struct ptlrpc_request * req)1285 static int ptlrpc_server_request_add(struct ptlrpc_service_part *svcpt,
1286 				     struct ptlrpc_request *req)
1287 {
1288 	int	rc;
1289 
1290 	rc = ptlrpc_server_hpreq_init(svcpt, req);
1291 	if (rc < 0)
1292 		return rc;
1293 
1294 	ptlrpc_nrs_req_add(svcpt, req, !!rc);
1295 
1296 	return 0;
1297 }
1298 
1299 /**
1300  * Allow to handle high priority request
1301  * User can call it w/o any lock but need to hold
1302  * ptlrpc_service_part::scp_req_lock to get reliable result
1303  */
ptlrpc_server_allow_high(struct ptlrpc_service_part * svcpt,bool force)1304 static bool ptlrpc_server_allow_high(struct ptlrpc_service_part *svcpt,
1305 				     bool force)
1306 {
1307 	int running = svcpt->scp_nthrs_running;
1308 
1309 	if (!nrs_svcpt_has_hp(svcpt))
1310 		return false;
1311 
1312 	if (force)
1313 		return true;
1314 
1315 	if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1316 		     CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1317 		/* leave just 1 thread for normal RPCs */
1318 		running = PTLRPC_NTHRS_INIT;
1319 		if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1320 			running += 1;
1321 	}
1322 
1323 	if (svcpt->scp_nreqs_active >= running - 1)
1324 		return false;
1325 
1326 	if (svcpt->scp_nhreqs_active == 0)
1327 		return true;
1328 
1329 	return !ptlrpc_nrs_req_pending_nolock(svcpt, false) ||
1330 	       svcpt->scp_hreq_count < svcpt->scp_service->srv_hpreq_ratio;
1331 }
1332 
ptlrpc_server_high_pending(struct ptlrpc_service_part * svcpt,bool force)1333 static bool ptlrpc_server_high_pending(struct ptlrpc_service_part *svcpt,
1334 				       bool force)
1335 {
1336 	return ptlrpc_server_allow_high(svcpt, force) &&
1337 	       ptlrpc_nrs_req_pending_nolock(svcpt, true);
1338 }
1339 
1340 /**
1341  * Only allow normal priority requests on a service that has a high-priority
1342  * queue if forced (i.e. cleanup), if there are other high priority requests
1343  * already being processed (i.e. those threads can service more high-priority
1344  * requests), or if there are enough idle threads that a later thread can do
1345  * a high priority request.
1346  * User can call it w/o any lock but need to hold
1347  * ptlrpc_service_part::scp_req_lock to get reliable result
1348  */
ptlrpc_server_allow_normal(struct ptlrpc_service_part * svcpt,bool force)1349 static bool ptlrpc_server_allow_normal(struct ptlrpc_service_part *svcpt,
1350 				       bool force)
1351 {
1352 	int running = svcpt->scp_nthrs_running;
1353 
1354 	if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1355 		     CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1356 		/* leave just 1 thread for normal RPCs */
1357 		running = PTLRPC_NTHRS_INIT;
1358 		if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1359 			running += 1;
1360 	}
1361 
1362 	if (force ||
1363 	    svcpt->scp_nreqs_active < running - 2)
1364 		return true;
1365 
1366 	if (svcpt->scp_nreqs_active >= running - 1)
1367 		return false;
1368 
1369 	return svcpt->scp_nhreqs_active > 0 || !nrs_svcpt_has_hp(svcpt);
1370 }
1371 
ptlrpc_server_normal_pending(struct ptlrpc_service_part * svcpt,bool force)1372 static bool ptlrpc_server_normal_pending(struct ptlrpc_service_part *svcpt,
1373 					 bool force)
1374 {
1375 	return ptlrpc_server_allow_normal(svcpt, force) &&
1376 	       ptlrpc_nrs_req_pending_nolock(svcpt, false);
1377 }
1378 
1379 /**
1380  * Returns true if there are requests available in incoming
1381  * request queue for processing and it is allowed to fetch them.
1382  * User can call it w/o any lock but need to hold ptlrpc_service::scp_req_lock
1383  * to get reliable result
1384  * \see ptlrpc_server_allow_normal
1385  * \see ptlrpc_server_allow high
1386  */
1387 static inline bool
ptlrpc_server_request_pending(struct ptlrpc_service_part * svcpt,bool force)1388 ptlrpc_server_request_pending(struct ptlrpc_service_part *svcpt, bool force)
1389 {
1390 	return ptlrpc_server_high_pending(svcpt, force) ||
1391 	       ptlrpc_server_normal_pending(svcpt, force);
1392 }
1393 
1394 /**
1395  * Fetch a request for processing from queue of unprocessed requests.
1396  * Favors high-priority requests.
1397  * Returns a pointer to fetched request.
1398  */
1399 static struct ptlrpc_request *
ptlrpc_server_request_get(struct ptlrpc_service_part * svcpt,bool force)1400 ptlrpc_server_request_get(struct ptlrpc_service_part *svcpt, bool force)
1401 {
1402 	struct ptlrpc_request *req = NULL;
1403 
1404 	spin_lock(&svcpt->scp_req_lock);
1405 
1406 	if (ptlrpc_server_high_pending(svcpt, force)) {
1407 		req = ptlrpc_nrs_req_get_nolock(svcpt, true, force);
1408 		if (req != NULL) {
1409 			svcpt->scp_hreq_count++;
1410 			goto got_request;
1411 		}
1412 	}
1413 
1414 	if (ptlrpc_server_normal_pending(svcpt, force)) {
1415 		req = ptlrpc_nrs_req_get_nolock(svcpt, false, force);
1416 		if (req != NULL) {
1417 			svcpt->scp_hreq_count = 0;
1418 			goto got_request;
1419 		}
1420 	}
1421 
1422 	spin_unlock(&svcpt->scp_req_lock);
1423 	return NULL;
1424 
1425 got_request:
1426 	svcpt->scp_nreqs_active++;
1427 	if (req->rq_hp)
1428 		svcpt->scp_nhreqs_active++;
1429 
1430 	spin_unlock(&svcpt->scp_req_lock);
1431 
1432 	if (likely(req->rq_export))
1433 		class_export_rpc_inc(req->rq_export);
1434 
1435 	return req;
1436 }
1437 
1438 /**
1439  * Handle freshly incoming reqs, add to timed early reply list,
1440  * pass on to regular request queue.
1441  * All incoming requests pass through here before getting into
1442  * ptlrpc_server_handle_req later on.
1443  */
1444 static int
ptlrpc_server_handle_req_in(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1445 ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
1446 			    struct ptlrpc_thread *thread)
1447 {
1448 	struct ptlrpc_service *svc = svcpt->scp_service;
1449 	struct ptlrpc_request *req;
1450 	__u32 deadline;
1451 	int rc;
1452 
1453 	spin_lock(&svcpt->scp_lock);
1454 	if (list_empty(&svcpt->scp_req_incoming)) {
1455 		spin_unlock(&svcpt->scp_lock);
1456 		return 0;
1457 	}
1458 
1459 	req = list_entry(svcpt->scp_req_incoming.next,
1460 			     struct ptlrpc_request, rq_list);
1461 	list_del_init(&req->rq_list);
1462 	svcpt->scp_nreqs_incoming--;
1463 	/* Consider this still a "queued" request as far as stats are
1464 	 * concerned */
1465 	spin_unlock(&svcpt->scp_lock);
1466 
1467 	/* go through security check/transform */
1468 	rc = sptlrpc_svc_unwrap_request(req);
1469 	switch (rc) {
1470 	case SECSVC_OK:
1471 		break;
1472 	case SECSVC_COMPLETE:
1473 		target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1474 		goto err_req;
1475 	case SECSVC_DROP:
1476 		goto err_req;
1477 	default:
1478 		LBUG();
1479 	}
1480 
1481 	/*
1482 	 * for null-flavored rpc, msg has been unpacked by sptlrpc, although
1483 	 * redo it wouldn't be harmful.
1484 	 */
1485 	if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
1486 		rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
1487 		if (rc != 0) {
1488 			CERROR("error unpacking request: ptl %d from %s x%llu\n",
1489 			       svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1490 			       req->rq_xid);
1491 			goto err_req;
1492 		}
1493 	}
1494 
1495 	rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1496 	if (rc) {
1497 		CERROR("error unpacking ptlrpc body: ptl %d from %s x%llu\n",
1498 		       svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1499 		       req->rq_xid);
1500 		goto err_req;
1501 	}
1502 
1503 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
1504 	    lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
1505 		CERROR("drop incoming rpc opc %u, x%llu\n",
1506 		       cfs_fail_val, req->rq_xid);
1507 		goto err_req;
1508 	}
1509 
1510 	rc = -EINVAL;
1511 	if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1512 		CERROR("wrong packet type received (type=%u) from %s\n",
1513 		       lustre_msg_get_type(req->rq_reqmsg),
1514 		       libcfs_id2str(req->rq_peer));
1515 		goto err_req;
1516 	}
1517 
1518 	switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1519 	case MDS_WRITEPAGE:
1520 	case OST_WRITE:
1521 		req->rq_bulk_write = 1;
1522 		break;
1523 	case MDS_READPAGE:
1524 	case OST_READ:
1525 	case MGS_CONFIG_READ:
1526 		req->rq_bulk_read = 1;
1527 		break;
1528 	}
1529 
1530 	CDEBUG(D_RPCTRACE, "got req x%llu\n", req->rq_xid);
1531 
1532 	req->rq_export = class_conn2export(
1533 		lustre_msg_get_handle(req->rq_reqmsg));
1534 	if (req->rq_export) {
1535 		rc = ptlrpc_check_req(req);
1536 		if (rc == 0) {
1537 			rc = sptlrpc_target_export_check(req->rq_export, req);
1538 			if (rc)
1539 				DEBUG_REQ(D_ERROR, req, "DROPPING req with illegal security flavor,");
1540 		}
1541 
1542 		if (rc)
1543 			goto err_req;
1544 	}
1545 
1546 	/* req_in handling should/must be fast */
1547 	if (ktime_get_real_seconds() - req->rq_arrival_time.tv_sec > 5)
1548 		DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1549 			  (long)(ktime_get_real_seconds() -
1550 				 req->rq_arrival_time.tv_sec));
1551 
1552 	/* Set rpc server deadline and add it to the timed list */
1553 	deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1554 		    MSGHDR_AT_SUPPORT) ?
1555 		   /* The max time the client expects us to take */
1556 		   lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1557 	req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1558 	if (unlikely(deadline == 0)) {
1559 		DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1560 		goto err_req;
1561 	}
1562 
1563 	req->rq_svc_thread = thread;
1564 
1565 	ptlrpc_at_add_timed(req);
1566 
1567 	/* Move it over to the request processing queue */
1568 	rc = ptlrpc_server_request_add(svcpt, req);
1569 	if (rc)
1570 		goto err_req;
1571 
1572 	wake_up(&svcpt->scp_waitq);
1573 	return 1;
1574 
1575 err_req:
1576 	ptlrpc_server_finish_request(svcpt, req);
1577 
1578 	return 1;
1579 }
1580 
1581 /**
1582  * Main incoming request handling logic.
1583  * Calls handler function from service to do actual processing.
1584  */
1585 static int
ptlrpc_server_handle_request(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1586 ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
1587 			     struct ptlrpc_thread *thread)
1588 {
1589 	struct ptlrpc_service *svc = svcpt->scp_service;
1590 	struct ptlrpc_request *request;
1591 	struct timespec64 work_start;
1592 	struct timespec64 work_end;
1593 	struct timespec64 timediff;
1594 	struct timespec64 arrived;
1595 	unsigned long timediff_usecs;
1596 	unsigned long arrived_usecs;
1597 	int rc;
1598 	int fail_opc = 0;
1599 
1600 	request = ptlrpc_server_request_get(svcpt, false);
1601 	if (request == NULL)
1602 		return 0;
1603 
1604 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1605 		fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1606 	else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1607 		fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1608 
1609 	if (unlikely(fail_opc)) {
1610 		if (request->rq_export && request->rq_ops)
1611 			OBD_FAIL_TIMEOUT(fail_opc, 4);
1612 	}
1613 
1614 	ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1615 
1616 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1617 		libcfs_debug_dumplog();
1618 
1619 	ktime_get_real_ts64(&work_start);
1620 	timediff = timespec64_sub(work_start, request->rq_arrival_time);
1621 	timediff_usecs = timediff.tv_sec * USEC_PER_SEC +
1622 			 timediff.tv_nsec / NSEC_PER_USEC;
1623 	if (likely(svc->srv_stats != NULL)) {
1624 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1625 				    timediff_usecs);
1626 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1627 				    svcpt->scp_nreqs_incoming);
1628 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1629 				    svcpt->scp_nreqs_active);
1630 		lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1631 				    at_get(&svcpt->scp_at_estimate));
1632 	}
1633 
1634 	rc = lu_context_init(&request->rq_session, LCT_SESSION | LCT_NOREF);
1635 	if (rc) {
1636 		CERROR("Failure to initialize session: %d\n", rc);
1637 		goto out_req;
1638 	}
1639 	request->rq_session.lc_thread = thread;
1640 	request->rq_session.lc_cookie = 0x5;
1641 	lu_context_enter(&request->rq_session);
1642 
1643 	CDEBUG(D_NET, "got req %llu\n", request->rq_xid);
1644 
1645 	request->rq_svc_thread = thread;
1646 	if (thread)
1647 		request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1648 
1649 	if (likely(request->rq_export)) {
1650 		if (unlikely(ptlrpc_check_req(request)))
1651 			goto put_conn;
1652 	}
1653 
1654 	/* Discard requests queued for longer than the deadline.
1655 	   The deadline is increased if we send an early reply. */
1656 	if (ktime_get_real_seconds() > request->rq_deadline) {
1657 		DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s: deadline " CFS_DURATION_T ":" CFS_DURATION_T "s ago\n",
1658 			  libcfs_id2str(request->rq_peer),
1659 			  (long)(request->rq_deadline -
1660 				 request->rq_arrival_time.tv_sec),
1661 			  (long)(ktime_get_real_seconds() -
1662 				 request->rq_deadline));
1663 		goto put_conn;
1664 	}
1665 
1666 	CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc %s:%s+%d:%d:x%llu:%s:%d\n",
1667 	       current_comm(),
1668 	       (request->rq_export ?
1669 		(char *)request->rq_export->exp_client_uuid.uuid : "0"),
1670 	       (request->rq_export ?
1671 		atomic_read(&request->rq_export->exp_refcount) : -99),
1672 	       lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1673 	       libcfs_id2str(request->rq_peer),
1674 	       lustre_msg_get_opc(request->rq_reqmsg));
1675 
1676 	if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
1677 		CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
1678 
1679 	rc = svc->srv_ops.so_req_handler(request);
1680 
1681 	ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1682 
1683 put_conn:
1684 	lu_context_exit(&request->rq_session);
1685 	lu_context_fini(&request->rq_session);
1686 
1687 	if (unlikely(ktime_get_real_seconds() > request->rq_deadline)) {
1688 		DEBUG_REQ(D_WARNING, request,
1689 			  "Request took longer than estimated (%lld:%llds); "
1690 			  "client may timeout.",
1691 			  (s64)request->rq_deadline -
1692 			       request->rq_arrival_time.tv_sec,
1693 			  (s64)ktime_get_real_seconds() - request->rq_deadline);
1694 	}
1695 
1696 	ktime_get_real_ts64(&work_end);
1697 	timediff = timespec64_sub(work_end, work_start);
1698 	timediff_usecs = timediff.tv_sec * USEC_PER_SEC +
1699 			 timediff.tv_nsec / NSEC_PER_USEC;
1700 	arrived = timespec64_sub(work_end, request->rq_arrival_time);
1701 	arrived_usecs = arrived.tv_sec * USEC_PER_SEC +
1702 			 arrived.tv_nsec / NSEC_PER_USEC;
1703 	CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc %s:%s+%d:%d:x%llu:%s:%d Request processed in %ldus (%ldus total) trans %llu rc %d/%d\n",
1704 	       current_comm(),
1705 	       (request->rq_export ?
1706 		(char *)request->rq_export->exp_client_uuid.uuid : "0"),
1707 	       (request->rq_export ?
1708 		atomic_read(&request->rq_export->exp_refcount) : -99),
1709 	       lustre_msg_get_status(request->rq_reqmsg),
1710 	       request->rq_xid,
1711 	       libcfs_id2str(request->rq_peer),
1712 	       lustre_msg_get_opc(request->rq_reqmsg),
1713 	       timediff_usecs,
1714 	       arrived_usecs,
1715 	       (request->rq_repmsg ?
1716 		lustre_msg_get_transno(request->rq_repmsg) :
1717 		request->rq_transno),
1718 	       request->rq_status,
1719 	       (request->rq_repmsg ?
1720 		lustre_msg_get_status(request->rq_repmsg) : -999));
1721 	if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1722 		__u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1723 		int opc = opcode_offset(op);
1724 
1725 		if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1726 			LASSERT(opc < LUSTRE_MAX_OPCODES);
1727 			lprocfs_counter_add(svc->srv_stats,
1728 					    opc + EXTRA_MAX_OPCODES,
1729 					    timediff_usecs);
1730 		}
1731 	}
1732 	if (unlikely(request->rq_early_count)) {
1733 		DEBUG_REQ(D_ADAPTTO, request,
1734 			  "sent %d early replies before finishing in %llds",
1735 			  request->rq_early_count,
1736 			  (s64)work_end.tv_sec -
1737 			  request->rq_arrival_time.tv_sec);
1738 	}
1739 
1740 out_req:
1741 	ptlrpc_server_finish_active_request(svcpt, request);
1742 
1743 	return 1;
1744 }
1745 
1746 /**
1747  * An internal function to process a single reply state object.
1748  */
1749 static int
ptlrpc_handle_rs(struct ptlrpc_reply_state * rs)1750 ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
1751 {
1752 	struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
1753 	struct ptlrpc_service *svc = svcpt->scp_service;
1754 	struct obd_export *exp;
1755 	int nlocks;
1756 	int been_handled;
1757 
1758 	exp = rs->rs_export;
1759 
1760 	LASSERT(rs->rs_difficult);
1761 	LASSERT(rs->rs_scheduled);
1762 	LASSERT(list_empty(&rs->rs_list));
1763 
1764 	spin_lock(&exp->exp_lock);
1765 	/* Noop if removed already */
1766 	list_del_init(&rs->rs_exp_list);
1767 	spin_unlock(&exp->exp_lock);
1768 
1769 	/* The disk commit callback holds exp_uncommitted_replies_lock while it
1770 	 * iterates over newly committed replies, removing them from
1771 	 * exp_uncommitted_replies.  It then drops this lock and schedules the
1772 	 * replies it found for handling here.
1773 	 *
1774 	 * We can avoid contention for exp_uncommitted_replies_lock between the
1775 	 * HRT threads and further commit callbacks by checking rs_committed
1776 	 * which is set in the commit callback while it holds both
1777 	 * rs_lock and exp_uncommitted_reples.
1778 	 *
1779 	 * If we see rs_committed clear, the commit callback _may_ not have
1780 	 * handled this reply yet and we race with it to grab
1781 	 * exp_uncommitted_replies_lock before removing the reply from
1782 	 * exp_uncommitted_replies.  Note that if we lose the race and the
1783 	 * reply has already been removed, list_del_init() is a noop.
1784 	 *
1785 	 * If we see rs_committed set, we know the commit callback is handling,
1786 	 * or has handled this reply since store reordering might allow us to
1787 	 * see rs_committed set out of sequence.  But since this is done
1788 	 * holding rs_lock, we can be sure it has all completed once we hold
1789 	 * rs_lock, which we do right next.
1790 	 */
1791 	if (!rs->rs_committed) {
1792 		spin_lock(&exp->exp_uncommitted_replies_lock);
1793 		list_del_init(&rs->rs_obd_list);
1794 		spin_unlock(&exp->exp_uncommitted_replies_lock);
1795 	}
1796 
1797 	spin_lock(&rs->rs_lock);
1798 
1799 	been_handled = rs->rs_handled;
1800 	rs->rs_handled = 1;
1801 
1802 	nlocks = rs->rs_nlocks;		 /* atomic "steal", but */
1803 	rs->rs_nlocks = 0;		      /* locks still on rs_locks! */
1804 
1805 	if (nlocks == 0 && !been_handled) {
1806 		/* If we see this, we should already have seen the warning
1807 		 * in mds_steal_ack_locks()  */
1808 		CDEBUG(D_HA, "All locks stolen from rs %p x%lld.t%lld o%d NID %s\n",
1809 		       rs,
1810 		       rs->rs_xid, rs->rs_transno, rs->rs_opc,
1811 		       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1812 	}
1813 
1814 	if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1815 		spin_unlock(&rs->rs_lock);
1816 
1817 		if (!been_handled && rs->rs_on_net) {
1818 			LNetMDUnlink(rs->rs_md_h);
1819 			/* Ignore return code; we're racing with completion */
1820 		}
1821 
1822 		while (nlocks-- > 0)
1823 			ldlm_lock_decref(&rs->rs_locks[nlocks],
1824 					 rs->rs_modes[nlocks]);
1825 
1826 		spin_lock(&rs->rs_lock);
1827 	}
1828 
1829 	rs->rs_scheduled = 0;
1830 
1831 	if (!rs->rs_on_net) {
1832 		/* Off the net */
1833 		spin_unlock(&rs->rs_lock);
1834 
1835 		class_export_put(exp);
1836 		rs->rs_export = NULL;
1837 		ptlrpc_rs_decref(rs);
1838 		if (atomic_dec_and_test(&svcpt->scp_nreps_difficult) &&
1839 		    svc->srv_is_stopping)
1840 			wake_up_all(&svcpt->scp_waitq);
1841 		return 1;
1842 	}
1843 
1844 	/* still on the net; callback will schedule */
1845 	spin_unlock(&rs->rs_lock);
1846 	return 1;
1847 }
1848 
1849 static void
ptlrpc_check_rqbd_pool(struct ptlrpc_service_part * svcpt)1850 ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
1851 {
1852 	int avail = svcpt->scp_nrqbds_posted;
1853 	int low_water = test_req_buffer_pressure ? 0 :
1854 			svcpt->scp_service->srv_nbuf_per_group / 2;
1855 
1856 	/* NB I'm not locking; just looking. */
1857 
1858 	/* CAVEAT EMPTOR: We might be allocating buffers here because we've
1859 	 * allowed the request history to grow out of control.  We could put a
1860 	 * sanity check on that here and cull some history if we need the
1861 	 * space. */
1862 
1863 	if (avail <= low_water)
1864 		ptlrpc_grow_req_bufs(svcpt, 1);
1865 
1866 	if (svcpt->scp_service->srv_stats) {
1867 		lprocfs_counter_add(svcpt->scp_service->srv_stats,
1868 				    PTLRPC_REQBUF_AVAIL_CNTR, avail);
1869 	}
1870 }
1871 
1872 static int
ptlrpc_retry_rqbds(void * arg)1873 ptlrpc_retry_rqbds(void *arg)
1874 {
1875 	struct ptlrpc_service_part *svcpt = arg;
1876 
1877 	svcpt->scp_rqbd_timeout = 0;
1878 	return -ETIMEDOUT;
1879 }
1880 
1881 static inline int
ptlrpc_threads_enough(struct ptlrpc_service_part * svcpt)1882 ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
1883 {
1884 	return svcpt->scp_nreqs_active <
1885 	       svcpt->scp_nthrs_running - 1 -
1886 	       (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL);
1887 }
1888 
1889 /**
1890  * allowed to create more threads
1891  * user can call it w/o any lock but need to hold
1892  * ptlrpc_service_part::scp_lock to get reliable result
1893  */
1894 static inline int
ptlrpc_threads_increasable(struct ptlrpc_service_part * svcpt)1895 ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
1896 {
1897 	return svcpt->scp_nthrs_running +
1898 	       svcpt->scp_nthrs_starting <
1899 	       svcpt->scp_service->srv_nthrs_cpt_limit;
1900 }
1901 
1902 /**
1903  * too many requests and allowed to create more threads
1904  */
1905 static inline int
ptlrpc_threads_need_create(struct ptlrpc_service_part * svcpt)1906 ptlrpc_threads_need_create(struct ptlrpc_service_part *svcpt)
1907 {
1908 	return !ptlrpc_threads_enough(svcpt) &&
1909 		ptlrpc_threads_increasable(svcpt);
1910 }
1911 
1912 static inline int
ptlrpc_thread_stopping(struct ptlrpc_thread * thread)1913 ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
1914 {
1915 	return thread_is_stopping(thread) ||
1916 	       thread->t_svcpt->scp_service->srv_is_stopping;
1917 }
1918 
1919 static inline int
ptlrpc_rqbd_pending(struct ptlrpc_service_part * svcpt)1920 ptlrpc_rqbd_pending(struct ptlrpc_service_part *svcpt)
1921 {
1922 	return !list_empty(&svcpt->scp_rqbd_idle) &&
1923 	       svcpt->scp_rqbd_timeout == 0;
1924 }
1925 
1926 static inline int
ptlrpc_at_check(struct ptlrpc_service_part * svcpt)1927 ptlrpc_at_check(struct ptlrpc_service_part *svcpt)
1928 {
1929 	return svcpt->scp_at_check;
1930 }
1931 
1932 /**
1933  * requests wait on preprocessing
1934  * user can call it w/o any lock but need to hold
1935  * ptlrpc_service_part::scp_lock to get reliable result
1936  */
1937 static inline int
ptlrpc_server_request_incoming(struct ptlrpc_service_part * svcpt)1938 ptlrpc_server_request_incoming(struct ptlrpc_service_part *svcpt)
1939 {
1940 	return !list_empty(&svcpt->scp_req_incoming);
1941 }
1942 
1943 static __attribute__((__noinline__)) int
ptlrpc_wait_event(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1944 ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
1945 		  struct ptlrpc_thread *thread)
1946 {
1947 	/* Don't exit while there are replies to be handled */
1948 	struct l_wait_info lwi = LWI_TIMEOUT(svcpt->scp_rqbd_timeout,
1949 					     ptlrpc_retry_rqbds, svcpt);
1950 
1951 	/* XXX: Add this back when libcfs watchdog is merged upstream
1952 	lc_watchdog_disable(thread->t_watchdog);
1953 	 */
1954 
1955 	cond_resched();
1956 
1957 	l_wait_event_exclusive_head(svcpt->scp_waitq,
1958 				ptlrpc_thread_stopping(thread) ||
1959 				ptlrpc_server_request_incoming(svcpt) ||
1960 				ptlrpc_server_request_pending(svcpt, false) ||
1961 				ptlrpc_rqbd_pending(svcpt) ||
1962 				ptlrpc_at_check(svcpt), &lwi);
1963 
1964 	if (ptlrpc_thread_stopping(thread))
1965 		return -EINTR;
1966 
1967 	/*
1968 	lc_watchdog_touch(thread->t_watchdog,
1969 			  ptlrpc_server_get_timeout(svcpt));
1970 	 */
1971 	return 0;
1972 }
1973 
1974 /**
1975  * Main thread body for service threads.
1976  * Waits in a loop waiting for new requests to process to appear.
1977  * Every time an incoming requests is added to its queue, a waitq
1978  * is woken up and one of the threads will handle it.
1979  */
ptlrpc_main(void * arg)1980 static int ptlrpc_main(void *arg)
1981 {
1982 	struct ptlrpc_thread *thread = arg;
1983 	struct ptlrpc_service_part *svcpt = thread->t_svcpt;
1984 	struct ptlrpc_service *svc = svcpt->scp_service;
1985 	struct ptlrpc_reply_state *rs;
1986 	struct group_info *ginfo = NULL;
1987 	struct lu_env *env;
1988 	int counter = 0, rc = 0;
1989 
1990 	thread->t_pid = current_pid();
1991 	unshare_fs_struct();
1992 
1993 	/* NB: we will call cfs_cpt_bind() for all threads, because we
1994 	 * might want to run lustre server only on a subset of system CPUs,
1995 	 * in that case ->scp_cpt is CFS_CPT_ANY */
1996 	rc = cfs_cpt_bind(svc->srv_cptable, svcpt->scp_cpt);
1997 	if (rc != 0) {
1998 		CWARN("%s: failed to bind %s on CPT %d\n",
1999 		      svc->srv_name, thread->t_name, svcpt->scp_cpt);
2000 	}
2001 
2002 	ginfo = groups_alloc(0);
2003 	if (!ginfo) {
2004 		rc = -ENOMEM;
2005 		goto out;
2006 	}
2007 
2008 	set_current_groups(ginfo);
2009 	put_group_info(ginfo);
2010 
2011 	if (svc->srv_ops.so_thr_init != NULL) {
2012 		rc = svc->srv_ops.so_thr_init(thread);
2013 		if (rc)
2014 			goto out;
2015 	}
2016 
2017 	env = kzalloc(sizeof(*env), GFP_NOFS);
2018 	if (!env) {
2019 		rc = -ENOMEM;
2020 		goto out_srv_fini;
2021 	}
2022 
2023 	rc = lu_context_init(&env->le_ctx,
2024 			     svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
2025 	if (rc)
2026 		goto out_srv_fini;
2027 
2028 	thread->t_env = env;
2029 	env->le_ctx.lc_thread = thread;
2030 	env->le_ctx.lc_cookie = 0x6;
2031 
2032 	while (!list_empty(&svcpt->scp_rqbd_idle)) {
2033 		rc = ptlrpc_server_post_idle_rqbds(svcpt);
2034 		if (rc >= 0)
2035 			continue;
2036 
2037 		CERROR("Failed to post rqbd for %s on CPT %d: %d\n",
2038 			svc->srv_name, svcpt->scp_cpt, rc);
2039 		goto out_srv_fini;
2040 	}
2041 
2042 	/* Alloc reply state structure for this one */
2043 	rs = libcfs_kvzalloc(svc->srv_max_reply_size, GFP_NOFS);
2044 	if (!rs) {
2045 		rc = -ENOMEM;
2046 		goto out_srv_fini;
2047 	}
2048 
2049 	spin_lock(&svcpt->scp_lock);
2050 
2051 	LASSERT(thread_is_starting(thread));
2052 	thread_clear_flags(thread, SVC_STARTING);
2053 
2054 	LASSERT(svcpt->scp_nthrs_starting == 1);
2055 	svcpt->scp_nthrs_starting--;
2056 
2057 	/* SVC_STOPPING may already be set here if someone else is trying
2058 	 * to stop the service while this new thread has been dynamically
2059 	 * forked. We still set SVC_RUNNING to let our creator know that
2060 	 * we are now running, however we will exit as soon as possible */
2061 	thread_add_flags(thread, SVC_RUNNING);
2062 	svcpt->scp_nthrs_running++;
2063 	spin_unlock(&svcpt->scp_lock);
2064 
2065 	/* wake up our creator in case he's still waiting. */
2066 	wake_up(&thread->t_ctl_waitq);
2067 
2068 	/*
2069 	thread->t_watchdog = lc_watchdog_add(ptlrpc_server_get_timeout(svcpt),
2070 					     NULL, NULL);
2071 	 */
2072 
2073 	spin_lock(&svcpt->scp_rep_lock);
2074 	list_add(&rs->rs_list, &svcpt->scp_rep_idle);
2075 	wake_up(&svcpt->scp_rep_waitq);
2076 	spin_unlock(&svcpt->scp_rep_lock);
2077 
2078 	CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
2079 	       svcpt->scp_nthrs_running);
2080 
2081 	/* XXX maintain a list of all managed devices: insert here */
2082 	while (!ptlrpc_thread_stopping(thread)) {
2083 		if (ptlrpc_wait_event(svcpt, thread))
2084 			break;
2085 
2086 		ptlrpc_check_rqbd_pool(svcpt);
2087 
2088 		if (ptlrpc_threads_need_create(svcpt)) {
2089 			/* Ignore return code - we tried... */
2090 			ptlrpc_start_thread(svcpt, 0);
2091 		}
2092 
2093 		/* Process all incoming reqs before handling any */
2094 		if (ptlrpc_server_request_incoming(svcpt)) {
2095 			lu_context_enter(&env->le_ctx);
2096 			env->le_ses = NULL;
2097 			ptlrpc_server_handle_req_in(svcpt, thread);
2098 			lu_context_exit(&env->le_ctx);
2099 
2100 			/* but limit ourselves in case of flood */
2101 			if (counter++ < 100)
2102 				continue;
2103 			counter = 0;
2104 		}
2105 
2106 		if (ptlrpc_at_check(svcpt))
2107 			ptlrpc_at_check_timed(svcpt);
2108 
2109 		if (ptlrpc_server_request_pending(svcpt, false)) {
2110 			lu_context_enter(&env->le_ctx);
2111 			ptlrpc_server_handle_request(svcpt, thread);
2112 			lu_context_exit(&env->le_ctx);
2113 		}
2114 
2115 		if (ptlrpc_rqbd_pending(svcpt) &&
2116 		    ptlrpc_server_post_idle_rqbds(svcpt) < 0) {
2117 			/* I just failed to repost request buffers.
2118 			 * Wait for a timeout (unless something else
2119 			 * happens) before I try again */
2120 			svcpt->scp_rqbd_timeout = cfs_time_seconds(1) / 10;
2121 			CDEBUG(D_RPCTRACE, "Posted buffers: %d\n",
2122 			       svcpt->scp_nrqbds_posted);
2123 		}
2124 	}
2125 
2126 	/*
2127 	lc_watchdog_delete(thread->t_watchdog);
2128 	thread->t_watchdog = NULL;
2129 	*/
2130 
2131 out_srv_fini:
2132 	/*
2133 	 * deconstruct service specific state created by ptlrpc_start_thread()
2134 	 */
2135 	if (svc->srv_ops.so_thr_done != NULL)
2136 		svc->srv_ops.so_thr_done(thread);
2137 
2138 	if (env != NULL) {
2139 		lu_context_fini(&env->le_ctx);
2140 		kfree(env);
2141 	}
2142 out:
2143 	CDEBUG(D_RPCTRACE, "service thread [ %p : %u ] %d exiting: rc %d\n",
2144 	       thread, thread->t_pid, thread->t_id, rc);
2145 
2146 	spin_lock(&svcpt->scp_lock);
2147 	if (thread_test_and_clear_flags(thread, SVC_STARTING))
2148 		svcpt->scp_nthrs_starting--;
2149 
2150 	if (thread_test_and_clear_flags(thread, SVC_RUNNING)) {
2151 		/* must know immediately */
2152 		svcpt->scp_nthrs_running--;
2153 	}
2154 
2155 	thread->t_id = rc;
2156 	thread_add_flags(thread, SVC_STOPPED);
2157 
2158 	wake_up(&thread->t_ctl_waitq);
2159 	spin_unlock(&svcpt->scp_lock);
2160 
2161 	return rc;
2162 }
2163 
hrt_dont_sleep(struct ptlrpc_hr_thread * hrt,struct list_head * replies)2164 static int hrt_dont_sleep(struct ptlrpc_hr_thread *hrt,
2165 			  struct list_head *replies)
2166 {
2167 	int result;
2168 
2169 	spin_lock(&hrt->hrt_lock);
2170 
2171 	list_splice_init(&hrt->hrt_queue, replies);
2172 	result = ptlrpc_hr.hr_stopping || !list_empty(replies);
2173 
2174 	spin_unlock(&hrt->hrt_lock);
2175 	return result;
2176 }
2177 
2178 /**
2179  * Main body of "handle reply" function.
2180  * It processes acked reply states
2181  */
ptlrpc_hr_main(void * arg)2182 static int ptlrpc_hr_main(void *arg)
2183 {
2184 	struct ptlrpc_hr_thread	*hrt = arg;
2185 	struct ptlrpc_hr_partition *hrp = hrt->hrt_partition;
2186 	LIST_HEAD	(replies);
2187 	char threadname[20];
2188 	int rc;
2189 
2190 	snprintf(threadname, sizeof(threadname), "ptlrpc_hr%02d_%03d",
2191 		 hrp->hrp_cpt, hrt->hrt_id);
2192 	unshare_fs_struct();
2193 
2194 	rc = cfs_cpt_bind(ptlrpc_hr.hr_cpt_table, hrp->hrp_cpt);
2195 	if (rc != 0) {
2196 		CWARN("Failed to bind %s on CPT %d of CPT table %p: rc = %d\n",
2197 		      threadname, hrp->hrp_cpt, ptlrpc_hr.hr_cpt_table, rc);
2198 	}
2199 
2200 	atomic_inc(&hrp->hrp_nstarted);
2201 	wake_up(&ptlrpc_hr.hr_waitq);
2202 
2203 	while (!ptlrpc_hr.hr_stopping) {
2204 		l_wait_condition(hrt->hrt_waitq, hrt_dont_sleep(hrt, &replies));
2205 
2206 		while (!list_empty(&replies)) {
2207 			struct ptlrpc_reply_state *rs;
2208 
2209 			rs = list_entry(replies.prev,
2210 					    struct ptlrpc_reply_state,
2211 					    rs_list);
2212 			list_del_init(&rs->rs_list);
2213 			ptlrpc_handle_rs(rs);
2214 		}
2215 	}
2216 
2217 	atomic_inc(&hrp->hrp_nstopped);
2218 	wake_up(&ptlrpc_hr.hr_waitq);
2219 
2220 	return 0;
2221 }
2222 
ptlrpc_stop_hr_threads(void)2223 static void ptlrpc_stop_hr_threads(void)
2224 {
2225 	struct ptlrpc_hr_partition *hrp;
2226 	int i;
2227 	int j;
2228 
2229 	ptlrpc_hr.hr_stopping = 1;
2230 
2231 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2232 		if (hrp->hrp_thrs == NULL)
2233 			continue; /* uninitialized */
2234 		for (j = 0; j < hrp->hrp_nthrs; j++)
2235 			wake_up_all(&hrp->hrp_thrs[j].hrt_waitq);
2236 	}
2237 
2238 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2239 		if (hrp->hrp_thrs == NULL)
2240 			continue; /* uninitialized */
2241 		wait_event(ptlrpc_hr.hr_waitq,
2242 			       atomic_read(&hrp->hrp_nstopped) ==
2243 			       atomic_read(&hrp->hrp_nstarted));
2244 	}
2245 }
2246 
ptlrpc_start_hr_threads(void)2247 static int ptlrpc_start_hr_threads(void)
2248 {
2249 	struct ptlrpc_hr_partition *hrp;
2250 	int i;
2251 	int j;
2252 
2253 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2254 		int rc = 0;
2255 
2256 		for (j = 0; j < hrp->hrp_nthrs; j++) {
2257 			struct	ptlrpc_hr_thread *hrt = &hrp->hrp_thrs[j];
2258 
2259 			rc = PTR_ERR(kthread_run(ptlrpc_hr_main,
2260 						 &hrp->hrp_thrs[j],
2261 						 "ptlrpc_hr%02d_%03d",
2262 						 hrp->hrp_cpt,
2263 						 hrt->hrt_id));
2264 			if (IS_ERR_VALUE(rc))
2265 				break;
2266 		}
2267 		wait_event(ptlrpc_hr.hr_waitq,
2268 			       atomic_read(&hrp->hrp_nstarted) == j);
2269 		if (!IS_ERR_VALUE(rc))
2270 			continue;
2271 
2272 		CERROR("Reply handling thread %d:%d Failed on starting: rc = %d\n",
2273 		       i, j, rc);
2274 		ptlrpc_stop_hr_threads();
2275 		return rc;
2276 	}
2277 	return 0;
2278 }
2279 
ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part * svcpt)2280 static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
2281 {
2282 	struct l_wait_info lwi = { 0 };
2283 	struct ptlrpc_thread *thread;
2284 	LIST_HEAD	(zombie);
2285 
2286 	CDEBUG(D_INFO, "Stopping threads for service %s\n",
2287 	       svcpt->scp_service->srv_name);
2288 
2289 	spin_lock(&svcpt->scp_lock);
2290 	/* let the thread know that we would like it to stop asap */
2291 	list_for_each_entry(thread, &svcpt->scp_threads, t_link) {
2292 		CDEBUG(D_INFO, "Stopping thread %s #%u\n",
2293 		       svcpt->scp_service->srv_thread_name, thread->t_id);
2294 		thread_add_flags(thread, SVC_STOPPING);
2295 	}
2296 
2297 	wake_up_all(&svcpt->scp_waitq);
2298 
2299 	while (!list_empty(&svcpt->scp_threads)) {
2300 		thread = list_entry(svcpt->scp_threads.next,
2301 					struct ptlrpc_thread, t_link);
2302 		if (thread_is_stopped(thread)) {
2303 			list_del(&thread->t_link);
2304 			list_add(&thread->t_link, &zombie);
2305 			continue;
2306 		}
2307 		spin_unlock(&svcpt->scp_lock);
2308 
2309 		CDEBUG(D_INFO, "waiting for stopping-thread %s #%u\n",
2310 		       svcpt->scp_service->srv_thread_name, thread->t_id);
2311 		l_wait_event(thread->t_ctl_waitq,
2312 			     thread_is_stopped(thread), &lwi);
2313 
2314 		spin_lock(&svcpt->scp_lock);
2315 	}
2316 
2317 	spin_unlock(&svcpt->scp_lock);
2318 
2319 	while (!list_empty(&zombie)) {
2320 		thread = list_entry(zombie.next,
2321 					struct ptlrpc_thread, t_link);
2322 		list_del(&thread->t_link);
2323 		kfree(thread);
2324 	}
2325 }
2326 
2327 /**
2328  * Stops all threads of a particular service \a svc
2329  */
ptlrpc_stop_all_threads(struct ptlrpc_service * svc)2330 static void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
2331 {
2332 	struct ptlrpc_service_part *svcpt;
2333 	int i;
2334 
2335 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2336 		if (svcpt->scp_service != NULL)
2337 			ptlrpc_svcpt_stop_threads(svcpt);
2338 	}
2339 }
2340 
ptlrpc_start_threads(struct ptlrpc_service * svc)2341 int ptlrpc_start_threads(struct ptlrpc_service *svc)
2342 {
2343 	int rc = 0;
2344 	int i;
2345 	int j;
2346 
2347 	/* We require 2 threads min, see note in ptlrpc_server_handle_request */
2348 	LASSERT(svc->srv_nthrs_cpt_init >= PTLRPC_NTHRS_INIT);
2349 
2350 	for (i = 0; i < svc->srv_ncpts; i++) {
2351 		for (j = 0; j < svc->srv_nthrs_cpt_init; j++) {
2352 			rc = ptlrpc_start_thread(svc->srv_parts[i], 1);
2353 			if (rc == 0)
2354 				continue;
2355 
2356 			if (rc != -EMFILE)
2357 				goto failed;
2358 			/* We have enough threads, don't start more. b=15759 */
2359 			break;
2360 		}
2361 	}
2362 
2363 	return 0;
2364  failed:
2365 	CERROR("cannot start %s thread #%d_%d: rc %d\n",
2366 	       svc->srv_thread_name, i, j, rc);
2367 	ptlrpc_stop_all_threads(svc);
2368 	return rc;
2369 }
2370 EXPORT_SYMBOL(ptlrpc_start_threads);
2371 
ptlrpc_start_thread(struct ptlrpc_service_part * svcpt,int wait)2372 int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
2373 {
2374 	struct l_wait_info lwi = { 0 };
2375 	struct ptlrpc_thread *thread;
2376 	struct ptlrpc_service *svc;
2377 	int rc;
2378 
2379 	LASSERT(svcpt != NULL);
2380 
2381 	svc = svcpt->scp_service;
2382 
2383 	CDEBUG(D_RPCTRACE, "%s[%d] started %d min %d max %d\n",
2384 	       svc->srv_name, svcpt->scp_cpt, svcpt->scp_nthrs_running,
2385 	       svc->srv_nthrs_cpt_init, svc->srv_nthrs_cpt_limit);
2386 
2387  again:
2388 	if (unlikely(svc->srv_is_stopping))
2389 		return -ESRCH;
2390 
2391 	if (!ptlrpc_threads_increasable(svcpt) ||
2392 	    (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
2393 	     svcpt->scp_nthrs_running == svc->srv_nthrs_cpt_init - 1))
2394 		return -EMFILE;
2395 
2396 	thread = kzalloc_node(sizeof(*thread), GFP_NOFS,
2397 			      cfs_cpt_spread_node(svc->srv_cptable,
2398 						  svcpt->scp_cpt));
2399 	if (thread == NULL)
2400 		return -ENOMEM;
2401 	init_waitqueue_head(&thread->t_ctl_waitq);
2402 
2403 	spin_lock(&svcpt->scp_lock);
2404 	if (!ptlrpc_threads_increasable(svcpt)) {
2405 		spin_unlock(&svcpt->scp_lock);
2406 		kfree(thread);
2407 		return -EMFILE;
2408 	}
2409 
2410 	if (svcpt->scp_nthrs_starting != 0) {
2411 		/* serialize starting because some modules (obdfilter)
2412 		 * might require unique and contiguous t_id */
2413 		LASSERT(svcpt->scp_nthrs_starting == 1);
2414 		spin_unlock(&svcpt->scp_lock);
2415 		kfree(thread);
2416 		if (wait) {
2417 			CDEBUG(D_INFO, "Waiting for creating thread %s #%d\n",
2418 			       svc->srv_thread_name, svcpt->scp_thr_nextid);
2419 			schedule();
2420 			goto again;
2421 		}
2422 
2423 		CDEBUG(D_INFO, "Creating thread %s #%d race, retry later\n",
2424 		       svc->srv_thread_name, svcpt->scp_thr_nextid);
2425 		return -EAGAIN;
2426 	}
2427 
2428 	svcpt->scp_nthrs_starting++;
2429 	thread->t_id = svcpt->scp_thr_nextid++;
2430 	thread_add_flags(thread, SVC_STARTING);
2431 	thread->t_svcpt = svcpt;
2432 
2433 	list_add(&thread->t_link, &svcpt->scp_threads);
2434 	spin_unlock(&svcpt->scp_lock);
2435 
2436 	if (svcpt->scp_cpt >= 0) {
2437 		snprintf(thread->t_name, sizeof(thread->t_name), "%s%02d_%03d",
2438 			 svc->srv_thread_name, svcpt->scp_cpt, thread->t_id);
2439 	} else {
2440 		snprintf(thread->t_name, sizeof(thread->t_name), "%s_%04d",
2441 			 svc->srv_thread_name, thread->t_id);
2442 	}
2443 
2444 	CDEBUG(D_RPCTRACE, "starting thread '%s'\n", thread->t_name);
2445 	rc = PTR_ERR(kthread_run(ptlrpc_main, thread, "%s", thread->t_name));
2446 	if (IS_ERR_VALUE(rc)) {
2447 		CERROR("cannot start thread '%s': rc %d\n",
2448 		       thread->t_name, rc);
2449 		spin_lock(&svcpt->scp_lock);
2450 		--svcpt->scp_nthrs_starting;
2451 		if (thread_is_stopping(thread)) {
2452 			/* this ptlrpc_thread is being handled
2453 			 * by ptlrpc_svcpt_stop_threads now
2454 			 */
2455 			thread_add_flags(thread, SVC_STOPPED);
2456 			wake_up(&thread->t_ctl_waitq);
2457 			spin_unlock(&svcpt->scp_lock);
2458 		} else {
2459 			list_del(&thread->t_link);
2460 			spin_unlock(&svcpt->scp_lock);
2461 			kfree(thread);
2462 		}
2463 		return rc;
2464 	}
2465 
2466 	if (!wait)
2467 		return 0;
2468 
2469 	l_wait_event(thread->t_ctl_waitq,
2470 		     thread_is_running(thread) || thread_is_stopped(thread),
2471 		     &lwi);
2472 
2473 	rc = thread_is_stopped(thread) ? thread->t_id : 0;
2474 	return rc;
2475 }
2476 
ptlrpc_hr_init(void)2477 int ptlrpc_hr_init(void)
2478 {
2479 	struct ptlrpc_hr_partition *hrp;
2480 	struct ptlrpc_hr_thread	*hrt;
2481 	int rc;
2482 	int i;
2483 	int j;
2484 	int weight;
2485 
2486 	memset(&ptlrpc_hr, 0, sizeof(ptlrpc_hr));
2487 	ptlrpc_hr.hr_cpt_table = cfs_cpt_table;
2488 
2489 	ptlrpc_hr.hr_partitions = cfs_percpt_alloc(ptlrpc_hr.hr_cpt_table,
2490 						   sizeof(*hrp));
2491 	if (ptlrpc_hr.hr_partitions == NULL)
2492 		return -ENOMEM;
2493 
2494 	init_waitqueue_head(&ptlrpc_hr.hr_waitq);
2495 
2496 	weight = cpumask_weight(topology_sibling_cpumask(0));
2497 
2498 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2499 		hrp->hrp_cpt = i;
2500 
2501 		atomic_set(&hrp->hrp_nstarted, 0);
2502 		atomic_set(&hrp->hrp_nstopped, 0);
2503 
2504 		hrp->hrp_nthrs = cfs_cpt_weight(ptlrpc_hr.hr_cpt_table, i);
2505 		hrp->hrp_nthrs /= weight;
2506 
2507 		LASSERT(hrp->hrp_nthrs > 0);
2508 		hrp->hrp_thrs =
2509 			kzalloc_node(hrp->hrp_nthrs * sizeof(*hrt), GFP_NOFS,
2510 				cfs_cpt_spread_node(ptlrpc_hr.hr_cpt_table,
2511 						    i));
2512 		if (hrp->hrp_thrs == NULL) {
2513 			rc = -ENOMEM;
2514 			goto out;
2515 		}
2516 
2517 		for (j = 0; j < hrp->hrp_nthrs; j++) {
2518 			hrt = &hrp->hrp_thrs[j];
2519 
2520 			hrt->hrt_id = j;
2521 			hrt->hrt_partition = hrp;
2522 			init_waitqueue_head(&hrt->hrt_waitq);
2523 			spin_lock_init(&hrt->hrt_lock);
2524 			INIT_LIST_HEAD(&hrt->hrt_queue);
2525 		}
2526 	}
2527 
2528 	rc = ptlrpc_start_hr_threads();
2529 out:
2530 	if (rc != 0)
2531 		ptlrpc_hr_fini();
2532 	return rc;
2533 }
2534 
ptlrpc_hr_fini(void)2535 void ptlrpc_hr_fini(void)
2536 {
2537 	struct ptlrpc_hr_partition *hrp;
2538 	int i;
2539 
2540 	if (ptlrpc_hr.hr_partitions == NULL)
2541 		return;
2542 
2543 	ptlrpc_stop_hr_threads();
2544 
2545 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2546 		kfree(hrp->hrp_thrs);
2547 	}
2548 
2549 	cfs_percpt_free(ptlrpc_hr.hr_partitions);
2550 	ptlrpc_hr.hr_partitions = NULL;
2551 }
2552 
2553 /**
2554  * Wait until all already scheduled replies are processed.
2555  */
ptlrpc_wait_replies(struct ptlrpc_service_part * svcpt)2556 static void ptlrpc_wait_replies(struct ptlrpc_service_part *svcpt)
2557 {
2558 	while (1) {
2559 		int rc;
2560 		struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
2561 						     NULL, NULL);
2562 
2563 		rc = l_wait_event(svcpt->scp_waitq,
2564 		     atomic_read(&svcpt->scp_nreps_difficult) == 0, &lwi);
2565 		if (rc == 0)
2566 			break;
2567 		CWARN("Unexpectedly long timeout %s %p\n",
2568 		      svcpt->scp_service->srv_name, svcpt->scp_service);
2569 	}
2570 }
2571 
2572 static void
ptlrpc_service_del_atimer(struct ptlrpc_service * svc)2573 ptlrpc_service_del_atimer(struct ptlrpc_service *svc)
2574 {
2575 	struct ptlrpc_service_part *svcpt;
2576 	int i;
2577 
2578 	/* early disarm AT timer... */
2579 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2580 		if (svcpt->scp_service != NULL)
2581 			del_timer(&svcpt->scp_at_timer);
2582 	}
2583 }
2584 
2585 static void
ptlrpc_service_unlink_rqbd(struct ptlrpc_service * svc)2586 ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
2587 {
2588 	struct ptlrpc_service_part *svcpt;
2589 	struct ptlrpc_request_buffer_desc *rqbd;
2590 	struct l_wait_info lwi;
2591 	int rc;
2592 	int i;
2593 
2594 	/* All history will be culled when the next request buffer is
2595 	 * freed in ptlrpc_service_purge_all() */
2596 	svc->srv_hist_nrqbds_cpt_max = 0;
2597 
2598 	rc = LNetClearLazyPortal(svc->srv_req_portal);
2599 	LASSERT(rc == 0);
2600 
2601 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2602 		if (svcpt->scp_service == NULL)
2603 			break;
2604 
2605 		/* Unlink all the request buffers.  This forces a 'final'
2606 		 * event with its 'unlink' flag set for each posted rqbd */
2607 		list_for_each_entry(rqbd, &svcpt->scp_rqbd_posted,
2608 					rqbd_list) {
2609 			rc = LNetMDUnlink(rqbd->rqbd_md_h);
2610 			LASSERT(rc == 0 || rc == -ENOENT);
2611 		}
2612 	}
2613 
2614 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2615 		if (svcpt->scp_service == NULL)
2616 			break;
2617 
2618 		/* Wait for the network to release any buffers
2619 		 * it's currently filling */
2620 		spin_lock(&svcpt->scp_lock);
2621 		while (svcpt->scp_nrqbds_posted != 0) {
2622 			spin_unlock(&svcpt->scp_lock);
2623 			/* Network access will complete in finite time but
2624 			 * the HUGE timeout lets us CWARN for visibility
2625 			 * of sluggish NALs */
2626 			lwi = LWI_TIMEOUT_INTERVAL(
2627 					cfs_time_seconds(LONG_UNLINK),
2628 					cfs_time_seconds(1), NULL, NULL);
2629 			rc = l_wait_event(svcpt->scp_waitq,
2630 					  svcpt->scp_nrqbds_posted == 0, &lwi);
2631 			if (rc == -ETIMEDOUT) {
2632 				CWARN("Service %s waiting for request buffers\n",
2633 				      svcpt->scp_service->srv_name);
2634 			}
2635 			spin_lock(&svcpt->scp_lock);
2636 		}
2637 		spin_unlock(&svcpt->scp_lock);
2638 	}
2639 }
2640 
2641 static void
ptlrpc_service_purge_all(struct ptlrpc_service * svc)2642 ptlrpc_service_purge_all(struct ptlrpc_service *svc)
2643 {
2644 	struct ptlrpc_service_part *svcpt;
2645 	struct ptlrpc_request_buffer_desc *rqbd;
2646 	struct ptlrpc_request *req;
2647 	struct ptlrpc_reply_state *rs;
2648 	int i;
2649 
2650 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2651 		if (svcpt->scp_service == NULL)
2652 			break;
2653 
2654 		spin_lock(&svcpt->scp_rep_lock);
2655 		while (!list_empty(&svcpt->scp_rep_active)) {
2656 			rs = list_entry(svcpt->scp_rep_active.next,
2657 					    struct ptlrpc_reply_state, rs_list);
2658 			spin_lock(&rs->rs_lock);
2659 			ptlrpc_schedule_difficult_reply(rs);
2660 			spin_unlock(&rs->rs_lock);
2661 		}
2662 		spin_unlock(&svcpt->scp_rep_lock);
2663 
2664 		/* purge the request queue.  NB No new replies (rqbds
2665 		 * all unlinked) and no service threads, so I'm the only
2666 		 * thread noodling the request queue now */
2667 		while (!list_empty(&svcpt->scp_req_incoming)) {
2668 			req = list_entry(svcpt->scp_req_incoming.next,
2669 					     struct ptlrpc_request, rq_list);
2670 
2671 			list_del(&req->rq_list);
2672 			svcpt->scp_nreqs_incoming--;
2673 			ptlrpc_server_finish_request(svcpt, req);
2674 		}
2675 
2676 		while (ptlrpc_server_request_pending(svcpt, true)) {
2677 			req = ptlrpc_server_request_get(svcpt, true);
2678 			ptlrpc_server_finish_active_request(svcpt, req);
2679 		}
2680 
2681 		LASSERT(list_empty(&svcpt->scp_rqbd_posted));
2682 		LASSERT(svcpt->scp_nreqs_incoming == 0);
2683 		LASSERT(svcpt->scp_nreqs_active == 0);
2684 		/* history should have been culled by
2685 		 * ptlrpc_server_finish_request */
2686 		LASSERT(svcpt->scp_hist_nrqbds == 0);
2687 
2688 		/* Now free all the request buffers since nothing
2689 		 * references them any more... */
2690 
2691 		while (!list_empty(&svcpt->scp_rqbd_idle)) {
2692 			rqbd = list_entry(svcpt->scp_rqbd_idle.next,
2693 					      struct ptlrpc_request_buffer_desc,
2694 					      rqbd_list);
2695 			ptlrpc_free_rqbd(rqbd);
2696 		}
2697 		ptlrpc_wait_replies(svcpt);
2698 
2699 		while (!list_empty(&svcpt->scp_rep_idle)) {
2700 			rs = list_entry(svcpt->scp_rep_idle.next,
2701 					    struct ptlrpc_reply_state,
2702 					    rs_list);
2703 			list_del(&rs->rs_list);
2704 			kvfree(rs);
2705 		}
2706 	}
2707 }
2708 
2709 static void
ptlrpc_service_free(struct ptlrpc_service * svc)2710 ptlrpc_service_free(struct ptlrpc_service *svc)
2711 {
2712 	struct ptlrpc_service_part *svcpt;
2713 	struct ptlrpc_at_array *array;
2714 	int i;
2715 
2716 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2717 		if (svcpt->scp_service == NULL)
2718 			break;
2719 
2720 		/* In case somebody rearmed this in the meantime */
2721 		del_timer(&svcpt->scp_at_timer);
2722 		array = &svcpt->scp_at_array;
2723 
2724 		kfree(array->paa_reqs_array);
2725 		array->paa_reqs_array = NULL;
2726 		kfree(array->paa_reqs_count);
2727 		array->paa_reqs_count = NULL;
2728 	}
2729 
2730 	ptlrpc_service_for_each_part(svcpt, i, svc)
2731 		kfree(svcpt);
2732 
2733 	if (svc->srv_cpts != NULL)
2734 		cfs_expr_list_values_free(svc->srv_cpts, svc->srv_ncpts);
2735 
2736 	kfree(svc);
2737 }
2738 
ptlrpc_unregister_service(struct ptlrpc_service * service)2739 int ptlrpc_unregister_service(struct ptlrpc_service *service)
2740 {
2741 	CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
2742 
2743 	service->srv_is_stopping = 1;
2744 
2745 	mutex_lock(&ptlrpc_all_services_mutex);
2746 	list_del_init(&service->srv_list);
2747 	mutex_unlock(&ptlrpc_all_services_mutex);
2748 
2749 	ptlrpc_service_del_atimer(service);
2750 	ptlrpc_stop_all_threads(service);
2751 
2752 	ptlrpc_service_unlink_rqbd(service);
2753 	ptlrpc_service_purge_all(service);
2754 	ptlrpc_service_nrs_cleanup(service);
2755 
2756 	ptlrpc_lprocfs_unregister_service(service);
2757 	ptlrpc_sysfs_unregister_service(service);
2758 
2759 	ptlrpc_service_free(service);
2760 
2761 	return 0;
2762 }
2763 EXPORT_SYMBOL(ptlrpc_unregister_service);
2764