• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 			if (rc == -ESTALE) {
1244 				req->rq_status = rc;
1245 				ptlrpc_error(req);
1246 			}
1247 			/** can only return error,
1248 			 * 0 for normal request,
1249 			 *  or 1 for high priority request
1250 			 */
1251 			LASSERT(rc <= 1);
1252 		}
1253 
1254 		spin_lock_bh(&req->rq_export->exp_rpc_lock);
1255 		list_add(&req->rq_exp_list,
1256 			     &req->rq_export->exp_hp_rpcs);
1257 		spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1258 	}
1259 
1260 	ptlrpc_nrs_req_initialize(svcpt, req, rc);
1261 
1262 	return rc;
1263 }
1264 
1265 /** Remove the request from the export list. */
ptlrpc_server_hpreq_fini(struct ptlrpc_request * req)1266 static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req)
1267 {
1268 	if (req->rq_export && req->rq_ops) {
1269 		/* refresh lock timeout again so that client has more
1270 		 * room to send lock cancel RPC. */
1271 		if (req->rq_ops->hpreq_fini)
1272 			req->rq_ops->hpreq_fini(req);
1273 
1274 		spin_lock_bh(&req->rq_export->exp_rpc_lock);
1275 		list_del_init(&req->rq_exp_list);
1276 		spin_unlock_bh(&req->rq_export->exp_rpc_lock);
1277 	}
1278 }
1279 
ptlrpc_server_request_add(struct ptlrpc_service_part * svcpt,struct ptlrpc_request * req)1280 static int ptlrpc_server_request_add(struct ptlrpc_service_part *svcpt,
1281 				     struct ptlrpc_request *req)
1282 {
1283 	int	rc;
1284 
1285 	rc = ptlrpc_server_hpreq_init(svcpt, req);
1286 	if (rc < 0)
1287 		return rc;
1288 
1289 	ptlrpc_nrs_req_add(svcpt, req, !!rc);
1290 
1291 	return 0;
1292 }
1293 
1294 /**
1295  * Allow to handle high priority request
1296  * User can call it w/o any lock but need to hold
1297  * ptlrpc_service_part::scp_req_lock to get reliable result
1298  */
ptlrpc_server_allow_high(struct ptlrpc_service_part * svcpt,bool force)1299 static bool ptlrpc_server_allow_high(struct ptlrpc_service_part *svcpt,
1300 				     bool force)
1301 {
1302 	int running = svcpt->scp_nthrs_running;
1303 
1304 	if (!nrs_svcpt_has_hp(svcpt))
1305 		return false;
1306 
1307 	if (force)
1308 		return true;
1309 
1310 	if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1311 		     CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1312 		/* leave just 1 thread for normal RPCs */
1313 		running = PTLRPC_NTHRS_INIT;
1314 		if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1315 			running += 1;
1316 	}
1317 
1318 	if (svcpt->scp_nreqs_active >= running - 1)
1319 		return false;
1320 
1321 	if (svcpt->scp_nhreqs_active == 0)
1322 		return true;
1323 
1324 	return !ptlrpc_nrs_req_pending_nolock(svcpt, false) ||
1325 	       svcpt->scp_hreq_count < svcpt->scp_service->srv_hpreq_ratio;
1326 }
1327 
ptlrpc_server_high_pending(struct ptlrpc_service_part * svcpt,bool force)1328 static bool ptlrpc_server_high_pending(struct ptlrpc_service_part *svcpt,
1329 				       bool force)
1330 {
1331 	return ptlrpc_server_allow_high(svcpt, force) &&
1332 	       ptlrpc_nrs_req_pending_nolock(svcpt, true);
1333 }
1334 
1335 /**
1336  * Only allow normal priority requests on a service that has a high-priority
1337  * queue if forced (i.e. cleanup), if there are other high priority requests
1338  * already being processed (i.e. those threads can service more high-priority
1339  * requests), or if there are enough idle threads that a later thread can do
1340  * a high priority request.
1341  * User can call it w/o any lock but need to hold
1342  * ptlrpc_service_part::scp_req_lock to get reliable result
1343  */
ptlrpc_server_allow_normal(struct ptlrpc_service_part * svcpt,bool force)1344 static bool ptlrpc_server_allow_normal(struct ptlrpc_service_part *svcpt,
1345 				       bool force)
1346 {
1347 	int running = svcpt->scp_nthrs_running;
1348 
1349 	if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1350 		     CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1351 		/* leave just 1 thread for normal RPCs */
1352 		running = PTLRPC_NTHRS_INIT;
1353 		if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1354 			running += 1;
1355 	}
1356 
1357 	if (force ||
1358 	    svcpt->scp_nreqs_active < running - 2)
1359 		return true;
1360 
1361 	if (svcpt->scp_nreqs_active >= running - 1)
1362 		return false;
1363 
1364 	return svcpt->scp_nhreqs_active > 0 || !nrs_svcpt_has_hp(svcpt);
1365 }
1366 
ptlrpc_server_normal_pending(struct ptlrpc_service_part * svcpt,bool force)1367 static bool ptlrpc_server_normal_pending(struct ptlrpc_service_part *svcpt,
1368 					 bool force)
1369 {
1370 	return ptlrpc_server_allow_normal(svcpt, force) &&
1371 	       ptlrpc_nrs_req_pending_nolock(svcpt, false);
1372 }
1373 
1374 /**
1375  * Returns true if there are requests available in incoming
1376  * request queue for processing and it is allowed to fetch them.
1377  * User can call it w/o any lock but need to hold ptlrpc_service::scp_req_lock
1378  * to get reliable result
1379  * \see ptlrpc_server_allow_normal
1380  * \see ptlrpc_server_allow high
1381  */
1382 static inline bool
ptlrpc_server_request_pending(struct ptlrpc_service_part * svcpt,bool force)1383 ptlrpc_server_request_pending(struct ptlrpc_service_part *svcpt, bool force)
1384 {
1385 	return ptlrpc_server_high_pending(svcpt, force) ||
1386 	       ptlrpc_server_normal_pending(svcpt, force);
1387 }
1388 
1389 /**
1390  * Fetch a request for processing from queue of unprocessed requests.
1391  * Favors high-priority requests.
1392  * Returns a pointer to fetched request.
1393  */
1394 static struct ptlrpc_request *
ptlrpc_server_request_get(struct ptlrpc_service_part * svcpt,bool force)1395 ptlrpc_server_request_get(struct ptlrpc_service_part *svcpt, bool force)
1396 {
1397 	struct ptlrpc_request *req = NULL;
1398 
1399 	spin_lock(&svcpt->scp_req_lock);
1400 
1401 	if (ptlrpc_server_high_pending(svcpt, force)) {
1402 		req = ptlrpc_nrs_req_get_nolock(svcpt, true, force);
1403 		if (req != NULL) {
1404 			svcpt->scp_hreq_count++;
1405 			goto got_request;
1406 		}
1407 	}
1408 
1409 	if (ptlrpc_server_normal_pending(svcpt, force)) {
1410 		req = ptlrpc_nrs_req_get_nolock(svcpt, false, force);
1411 		if (req != NULL) {
1412 			svcpt->scp_hreq_count = 0;
1413 			goto got_request;
1414 		}
1415 	}
1416 
1417 	spin_unlock(&svcpt->scp_req_lock);
1418 	return NULL;
1419 
1420 got_request:
1421 	svcpt->scp_nreqs_active++;
1422 	if (req->rq_hp)
1423 		svcpt->scp_nhreqs_active++;
1424 
1425 	spin_unlock(&svcpt->scp_req_lock);
1426 
1427 	if (likely(req->rq_export))
1428 		class_export_rpc_inc(req->rq_export);
1429 
1430 	return req;
1431 }
1432 
1433 /**
1434  * Handle freshly incoming reqs, add to timed early reply list,
1435  * pass on to regular request queue.
1436  * All incoming requests pass through here before getting into
1437  * ptlrpc_server_handle_req later on.
1438  */
1439 static int
ptlrpc_server_handle_req_in(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1440 ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
1441 			    struct ptlrpc_thread *thread)
1442 {
1443 	struct ptlrpc_service *svc = svcpt->scp_service;
1444 	struct ptlrpc_request *req;
1445 	__u32 deadline;
1446 	int rc;
1447 
1448 	spin_lock(&svcpt->scp_lock);
1449 	if (list_empty(&svcpt->scp_req_incoming)) {
1450 		spin_unlock(&svcpt->scp_lock);
1451 		return 0;
1452 	}
1453 
1454 	req = list_entry(svcpt->scp_req_incoming.next,
1455 			     struct ptlrpc_request, rq_list);
1456 	list_del_init(&req->rq_list);
1457 	svcpt->scp_nreqs_incoming--;
1458 	/* Consider this still a "queued" request as far as stats are
1459 	 * concerned */
1460 	spin_unlock(&svcpt->scp_lock);
1461 
1462 	/* go through security check/transform */
1463 	rc = sptlrpc_svc_unwrap_request(req);
1464 	switch (rc) {
1465 	case SECSVC_OK:
1466 		break;
1467 	case SECSVC_COMPLETE:
1468 		target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1469 		goto err_req;
1470 	case SECSVC_DROP:
1471 		goto err_req;
1472 	default:
1473 		LBUG();
1474 	}
1475 
1476 	/*
1477 	 * for null-flavored rpc, msg has been unpacked by sptlrpc, although
1478 	 * redo it wouldn't be harmful.
1479 	 */
1480 	if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
1481 		rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
1482 		if (rc != 0) {
1483 			CERROR("error unpacking request: ptl %d from %s x%llu\n",
1484 			       svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1485 			       req->rq_xid);
1486 			goto err_req;
1487 		}
1488 	}
1489 
1490 	rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1491 	if (rc) {
1492 		CERROR("error unpacking ptlrpc body: ptl %d from %s x%llu\n",
1493 		       svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1494 		       req->rq_xid);
1495 		goto err_req;
1496 	}
1497 
1498 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
1499 	    lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
1500 		CERROR("drop incoming rpc opc %u, x%llu\n",
1501 		       cfs_fail_val, req->rq_xid);
1502 		goto err_req;
1503 	}
1504 
1505 	rc = -EINVAL;
1506 	if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1507 		CERROR("wrong packet type received (type=%u) from %s\n",
1508 		       lustre_msg_get_type(req->rq_reqmsg),
1509 		       libcfs_id2str(req->rq_peer));
1510 		goto err_req;
1511 	}
1512 
1513 	switch (lustre_msg_get_opc(req->rq_reqmsg)) {
1514 	case MDS_WRITEPAGE:
1515 	case OST_WRITE:
1516 		req->rq_bulk_write = 1;
1517 		break;
1518 	case MDS_READPAGE:
1519 	case OST_READ:
1520 	case MGS_CONFIG_READ:
1521 		req->rq_bulk_read = 1;
1522 		break;
1523 	}
1524 
1525 	CDEBUG(D_RPCTRACE, "got req x%llu\n", req->rq_xid);
1526 
1527 	req->rq_export = class_conn2export(
1528 		lustre_msg_get_handle(req->rq_reqmsg));
1529 	if (req->rq_export) {
1530 		rc = ptlrpc_check_req(req);
1531 		if (rc == 0) {
1532 			rc = sptlrpc_target_export_check(req->rq_export, req);
1533 			if (rc)
1534 				DEBUG_REQ(D_ERROR, req, "DROPPING req with illegal security flavor,");
1535 		}
1536 
1537 		if (rc)
1538 			goto err_req;
1539 	}
1540 
1541 	/* req_in handling should/must be fast */
1542 	if (ktime_get_real_seconds() - req->rq_arrival_time.tv_sec > 5)
1543 		DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1544 			  (long)(ktime_get_real_seconds() -
1545 				 req->rq_arrival_time.tv_sec));
1546 
1547 	/* Set rpc server deadline and add it to the timed list */
1548 	deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1549 		    MSGHDR_AT_SUPPORT) ?
1550 		   /* The max time the client expects us to take */
1551 		   lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1552 	req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1553 	if (unlikely(deadline == 0)) {
1554 		DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1555 		goto err_req;
1556 	}
1557 
1558 	req->rq_svc_thread = thread;
1559 
1560 	ptlrpc_at_add_timed(req);
1561 
1562 	/* Move it over to the request processing queue */
1563 	rc = ptlrpc_server_request_add(svcpt, req);
1564 	if (rc)
1565 		goto err_req;
1566 
1567 	wake_up(&svcpt->scp_waitq);
1568 	return 1;
1569 
1570 err_req:
1571 	ptlrpc_server_finish_request(svcpt, req);
1572 
1573 	return 1;
1574 }
1575 
1576 /**
1577  * Main incoming request handling logic.
1578  * Calls handler function from service to do actual processing.
1579  */
1580 static int
ptlrpc_server_handle_request(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1581 ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
1582 			     struct ptlrpc_thread *thread)
1583 {
1584 	struct ptlrpc_service *svc = svcpt->scp_service;
1585 	struct ptlrpc_request *request;
1586 	struct timespec64 work_start;
1587 	struct timespec64 work_end;
1588 	struct timespec64 timediff;
1589 	struct timespec64 arrived;
1590 	unsigned long timediff_usecs;
1591 	unsigned long arrived_usecs;
1592 	int rc;
1593 	int fail_opc = 0;
1594 
1595 	request = ptlrpc_server_request_get(svcpt, false);
1596 	if (request == NULL)
1597 		return 0;
1598 
1599 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1600 		fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1601 	else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1602 		fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1603 
1604 	if (unlikely(fail_opc)) {
1605 		if (request->rq_export && request->rq_ops)
1606 			OBD_FAIL_TIMEOUT(fail_opc, 4);
1607 	}
1608 
1609 	ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1610 
1611 	if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1612 		libcfs_debug_dumplog();
1613 
1614 	ktime_get_real_ts64(&work_start);
1615 	timediff = timespec64_sub(work_start, request->rq_arrival_time);
1616 	timediff_usecs = timediff.tv_sec * USEC_PER_SEC +
1617 			 timediff.tv_nsec / NSEC_PER_USEC;
1618 	if (likely(svc->srv_stats != NULL)) {
1619 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1620 				    timediff_usecs);
1621 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1622 				    svcpt->scp_nreqs_incoming);
1623 		lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1624 				    svcpt->scp_nreqs_active);
1625 		lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1626 				    at_get(&svcpt->scp_at_estimate));
1627 	}
1628 
1629 	rc = lu_context_init(&request->rq_session, LCT_SESSION | LCT_NOREF);
1630 	if (rc) {
1631 		CERROR("Failure to initialize session: %d\n", rc);
1632 		goto out_req;
1633 	}
1634 	request->rq_session.lc_thread = thread;
1635 	request->rq_session.lc_cookie = 0x5;
1636 	lu_context_enter(&request->rq_session);
1637 
1638 	CDEBUG(D_NET, "got req %llu\n", request->rq_xid);
1639 
1640 	request->rq_svc_thread = thread;
1641 	if (thread)
1642 		request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1643 
1644 	if (likely(request->rq_export)) {
1645 		if (unlikely(ptlrpc_check_req(request)))
1646 			goto put_conn;
1647 	}
1648 
1649 	/* Discard requests queued for longer than the deadline.
1650 	   The deadline is increased if we send an early reply. */
1651 	if (ktime_get_real_seconds() > request->rq_deadline) {
1652 		DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s: deadline " CFS_DURATION_T ":" CFS_DURATION_T "s ago\n",
1653 			  libcfs_id2str(request->rq_peer),
1654 			  (long)(request->rq_deadline -
1655 				 request->rq_arrival_time.tv_sec),
1656 			  (long)(ktime_get_real_seconds() -
1657 				 request->rq_deadline));
1658 		goto put_conn;
1659 	}
1660 
1661 	CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc %s:%s+%d:%d:x%llu:%s:%d\n",
1662 	       current_comm(),
1663 	       (request->rq_export ?
1664 		(char *)request->rq_export->exp_client_uuid.uuid : "0"),
1665 	       (request->rq_export ?
1666 		atomic_read(&request->rq_export->exp_refcount) : -99),
1667 	       lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1668 	       libcfs_id2str(request->rq_peer),
1669 	       lustre_msg_get_opc(request->rq_reqmsg));
1670 
1671 	if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
1672 		CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
1673 
1674 	rc = svc->srv_ops.so_req_handler(request);
1675 
1676 	ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1677 
1678 put_conn:
1679 	lu_context_exit(&request->rq_session);
1680 	lu_context_fini(&request->rq_session);
1681 
1682 	if (unlikely(ktime_get_real_seconds() > request->rq_deadline)) {
1683 		DEBUG_REQ(D_WARNING, request,
1684 			  "Request took longer than estimated (%lld:%llds); "
1685 			  "client may timeout.",
1686 			  (s64)request->rq_deadline -
1687 			       request->rq_arrival_time.tv_sec,
1688 			  (s64)ktime_get_real_seconds() - request->rq_deadline);
1689 	}
1690 
1691 	ktime_get_real_ts64(&work_end);
1692 	timediff = timespec64_sub(work_end, work_start);
1693 	timediff_usecs = timediff.tv_sec * USEC_PER_SEC +
1694 			 timediff.tv_nsec / NSEC_PER_USEC;
1695 	arrived = timespec64_sub(work_end, request->rq_arrival_time);
1696 	arrived_usecs = arrived.tv_sec * USEC_PER_SEC +
1697 			 arrived.tv_nsec / NSEC_PER_USEC;
1698 	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",
1699 	       current_comm(),
1700 	       (request->rq_export ?
1701 		(char *)request->rq_export->exp_client_uuid.uuid : "0"),
1702 	       (request->rq_export ?
1703 		atomic_read(&request->rq_export->exp_refcount) : -99),
1704 	       lustre_msg_get_status(request->rq_reqmsg),
1705 	       request->rq_xid,
1706 	       libcfs_id2str(request->rq_peer),
1707 	       lustre_msg_get_opc(request->rq_reqmsg),
1708 	       timediff_usecs,
1709 	       arrived_usecs,
1710 	       (request->rq_repmsg ?
1711 		lustre_msg_get_transno(request->rq_repmsg) :
1712 		request->rq_transno),
1713 	       request->rq_status,
1714 	       (request->rq_repmsg ?
1715 		lustre_msg_get_status(request->rq_repmsg) : -999));
1716 	if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1717 		__u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1718 		int opc = opcode_offset(op);
1719 
1720 		if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1721 			LASSERT(opc < LUSTRE_MAX_OPCODES);
1722 			lprocfs_counter_add(svc->srv_stats,
1723 					    opc + EXTRA_MAX_OPCODES,
1724 					    timediff_usecs);
1725 		}
1726 	}
1727 	if (unlikely(request->rq_early_count)) {
1728 		DEBUG_REQ(D_ADAPTTO, request,
1729 			  "sent %d early replies before finishing in %llds",
1730 			  request->rq_early_count,
1731 			  (s64)work_end.tv_sec -
1732 			  request->rq_arrival_time.tv_sec);
1733 	}
1734 
1735 out_req:
1736 	ptlrpc_server_finish_active_request(svcpt, request);
1737 
1738 	return 1;
1739 }
1740 
1741 /**
1742  * An internal function to process a single reply state object.
1743  */
1744 static int
ptlrpc_handle_rs(struct ptlrpc_reply_state * rs)1745 ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
1746 {
1747 	struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
1748 	struct ptlrpc_service *svc = svcpt->scp_service;
1749 	struct obd_export *exp;
1750 	int nlocks;
1751 	int been_handled;
1752 
1753 	exp = rs->rs_export;
1754 
1755 	LASSERT(rs->rs_difficult);
1756 	LASSERT(rs->rs_scheduled);
1757 	LASSERT(list_empty(&rs->rs_list));
1758 
1759 	spin_lock(&exp->exp_lock);
1760 	/* Noop if removed already */
1761 	list_del_init(&rs->rs_exp_list);
1762 	spin_unlock(&exp->exp_lock);
1763 
1764 	/* The disk commit callback holds exp_uncommitted_replies_lock while it
1765 	 * iterates over newly committed replies, removing them from
1766 	 * exp_uncommitted_replies.  It then drops this lock and schedules the
1767 	 * replies it found for handling here.
1768 	 *
1769 	 * We can avoid contention for exp_uncommitted_replies_lock between the
1770 	 * HRT threads and further commit callbacks by checking rs_committed
1771 	 * which is set in the commit callback while it holds both
1772 	 * rs_lock and exp_uncommitted_reples.
1773 	 *
1774 	 * If we see rs_committed clear, the commit callback _may_ not have
1775 	 * handled this reply yet and we race with it to grab
1776 	 * exp_uncommitted_replies_lock before removing the reply from
1777 	 * exp_uncommitted_replies.  Note that if we lose the race and the
1778 	 * reply has already been removed, list_del_init() is a noop.
1779 	 *
1780 	 * If we see rs_committed set, we know the commit callback is handling,
1781 	 * or has handled this reply since store reordering might allow us to
1782 	 * see rs_committed set out of sequence.  But since this is done
1783 	 * holding rs_lock, we can be sure it has all completed once we hold
1784 	 * rs_lock, which we do right next.
1785 	 */
1786 	if (!rs->rs_committed) {
1787 		spin_lock(&exp->exp_uncommitted_replies_lock);
1788 		list_del_init(&rs->rs_obd_list);
1789 		spin_unlock(&exp->exp_uncommitted_replies_lock);
1790 	}
1791 
1792 	spin_lock(&rs->rs_lock);
1793 
1794 	been_handled = rs->rs_handled;
1795 	rs->rs_handled = 1;
1796 
1797 	nlocks = rs->rs_nlocks;		 /* atomic "steal", but */
1798 	rs->rs_nlocks = 0;		      /* locks still on rs_locks! */
1799 
1800 	if (nlocks == 0 && !been_handled) {
1801 		/* If we see this, we should already have seen the warning
1802 		 * in mds_steal_ack_locks()  */
1803 		CDEBUG(D_HA, "All locks stolen from rs %p x%lld.t%lld o%d NID %s\n",
1804 		       rs,
1805 		       rs->rs_xid, rs->rs_transno, rs->rs_opc,
1806 		       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1807 	}
1808 
1809 	if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1810 		spin_unlock(&rs->rs_lock);
1811 
1812 		if (!been_handled && rs->rs_on_net) {
1813 			LNetMDUnlink(rs->rs_md_h);
1814 			/* Ignore return code; we're racing with completion */
1815 		}
1816 
1817 		while (nlocks-- > 0)
1818 			ldlm_lock_decref(&rs->rs_locks[nlocks],
1819 					 rs->rs_modes[nlocks]);
1820 
1821 		spin_lock(&rs->rs_lock);
1822 	}
1823 
1824 	rs->rs_scheduled = 0;
1825 
1826 	if (!rs->rs_on_net) {
1827 		/* Off the net */
1828 		spin_unlock(&rs->rs_lock);
1829 
1830 		class_export_put(exp);
1831 		rs->rs_export = NULL;
1832 		ptlrpc_rs_decref(rs);
1833 		if (atomic_dec_and_test(&svcpt->scp_nreps_difficult) &&
1834 		    svc->srv_is_stopping)
1835 			wake_up_all(&svcpt->scp_waitq);
1836 		return 1;
1837 	}
1838 
1839 	/* still on the net; callback will schedule */
1840 	spin_unlock(&rs->rs_lock);
1841 	return 1;
1842 }
1843 
1844 static void
ptlrpc_check_rqbd_pool(struct ptlrpc_service_part * svcpt)1845 ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
1846 {
1847 	int avail = svcpt->scp_nrqbds_posted;
1848 	int low_water = test_req_buffer_pressure ? 0 :
1849 			svcpt->scp_service->srv_nbuf_per_group / 2;
1850 
1851 	/* NB I'm not locking; just looking. */
1852 
1853 	/* CAVEAT EMPTOR: We might be allocating buffers here because we've
1854 	 * allowed the request history to grow out of control.  We could put a
1855 	 * sanity check on that here and cull some history if we need the
1856 	 * space. */
1857 
1858 	if (avail <= low_water)
1859 		ptlrpc_grow_req_bufs(svcpt, 1);
1860 
1861 	if (svcpt->scp_service->srv_stats) {
1862 		lprocfs_counter_add(svcpt->scp_service->srv_stats,
1863 				    PTLRPC_REQBUF_AVAIL_CNTR, avail);
1864 	}
1865 }
1866 
1867 static int
ptlrpc_retry_rqbds(void * arg)1868 ptlrpc_retry_rqbds(void *arg)
1869 {
1870 	struct ptlrpc_service_part *svcpt = arg;
1871 
1872 	svcpt->scp_rqbd_timeout = 0;
1873 	return -ETIMEDOUT;
1874 }
1875 
1876 static inline int
ptlrpc_threads_enough(struct ptlrpc_service_part * svcpt)1877 ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
1878 {
1879 	return svcpt->scp_nreqs_active <
1880 	       svcpt->scp_nthrs_running - 1 -
1881 	       (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL);
1882 }
1883 
1884 /**
1885  * allowed to create more threads
1886  * user can call it w/o any lock but need to hold
1887  * ptlrpc_service_part::scp_lock to get reliable result
1888  */
1889 static inline int
ptlrpc_threads_increasable(struct ptlrpc_service_part * svcpt)1890 ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
1891 {
1892 	return svcpt->scp_nthrs_running +
1893 	       svcpt->scp_nthrs_starting <
1894 	       svcpt->scp_service->srv_nthrs_cpt_limit;
1895 }
1896 
1897 /**
1898  * too many requests and allowed to create more threads
1899  */
1900 static inline int
ptlrpc_threads_need_create(struct ptlrpc_service_part * svcpt)1901 ptlrpc_threads_need_create(struct ptlrpc_service_part *svcpt)
1902 {
1903 	return !ptlrpc_threads_enough(svcpt) &&
1904 		ptlrpc_threads_increasable(svcpt);
1905 }
1906 
1907 static inline int
ptlrpc_thread_stopping(struct ptlrpc_thread * thread)1908 ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
1909 {
1910 	return thread_is_stopping(thread) ||
1911 	       thread->t_svcpt->scp_service->srv_is_stopping;
1912 }
1913 
1914 static inline int
ptlrpc_rqbd_pending(struct ptlrpc_service_part * svcpt)1915 ptlrpc_rqbd_pending(struct ptlrpc_service_part *svcpt)
1916 {
1917 	return !list_empty(&svcpt->scp_rqbd_idle) &&
1918 	       svcpt->scp_rqbd_timeout == 0;
1919 }
1920 
1921 static inline int
ptlrpc_at_check(struct ptlrpc_service_part * svcpt)1922 ptlrpc_at_check(struct ptlrpc_service_part *svcpt)
1923 {
1924 	return svcpt->scp_at_check;
1925 }
1926 
1927 /**
1928  * requests wait on preprocessing
1929  * user can call it w/o any lock but need to hold
1930  * ptlrpc_service_part::scp_lock to get reliable result
1931  */
1932 static inline int
ptlrpc_server_request_incoming(struct ptlrpc_service_part * svcpt)1933 ptlrpc_server_request_incoming(struct ptlrpc_service_part *svcpt)
1934 {
1935 	return !list_empty(&svcpt->scp_req_incoming);
1936 }
1937 
1938 static __attribute__((__noinline__)) int
ptlrpc_wait_event(struct ptlrpc_service_part * svcpt,struct ptlrpc_thread * thread)1939 ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
1940 		  struct ptlrpc_thread *thread)
1941 {
1942 	/* Don't exit while there are replies to be handled */
1943 	struct l_wait_info lwi = LWI_TIMEOUT(svcpt->scp_rqbd_timeout,
1944 					     ptlrpc_retry_rqbds, svcpt);
1945 
1946 	/* XXX: Add this back when libcfs watchdog is merged upstream
1947 	lc_watchdog_disable(thread->t_watchdog);
1948 	 */
1949 
1950 	cond_resched();
1951 
1952 	l_wait_event_exclusive_head(svcpt->scp_waitq,
1953 				ptlrpc_thread_stopping(thread) ||
1954 				ptlrpc_server_request_incoming(svcpt) ||
1955 				ptlrpc_server_request_pending(svcpt, false) ||
1956 				ptlrpc_rqbd_pending(svcpt) ||
1957 				ptlrpc_at_check(svcpt), &lwi);
1958 
1959 	if (ptlrpc_thread_stopping(thread))
1960 		return -EINTR;
1961 
1962 	/*
1963 	lc_watchdog_touch(thread->t_watchdog,
1964 			  ptlrpc_server_get_timeout(svcpt));
1965 	 */
1966 	return 0;
1967 }
1968 
1969 /**
1970  * Main thread body for service threads.
1971  * Waits in a loop waiting for new requests to process to appear.
1972  * Every time an incoming requests is added to its queue, a waitq
1973  * is woken up and one of the threads will handle it.
1974  */
ptlrpc_main(void * arg)1975 static int ptlrpc_main(void *arg)
1976 {
1977 	struct ptlrpc_thread *thread = arg;
1978 	struct ptlrpc_service_part *svcpt = thread->t_svcpt;
1979 	struct ptlrpc_service *svc = svcpt->scp_service;
1980 	struct ptlrpc_reply_state *rs;
1981 	struct group_info *ginfo = NULL;
1982 	struct lu_env *env;
1983 	int counter = 0, rc = 0;
1984 
1985 	thread->t_pid = current_pid();
1986 	unshare_fs_struct();
1987 
1988 	/* NB: we will call cfs_cpt_bind() for all threads, because we
1989 	 * might want to run lustre server only on a subset of system CPUs,
1990 	 * in that case ->scp_cpt is CFS_CPT_ANY */
1991 	rc = cfs_cpt_bind(svc->srv_cptable, svcpt->scp_cpt);
1992 	if (rc != 0) {
1993 		CWARN("%s: failed to bind %s on CPT %d\n",
1994 		      svc->srv_name, thread->t_name, svcpt->scp_cpt);
1995 	}
1996 
1997 	ginfo = groups_alloc(0);
1998 	if (!ginfo) {
1999 		rc = -ENOMEM;
2000 		goto out;
2001 	}
2002 
2003 	set_current_groups(ginfo);
2004 	put_group_info(ginfo);
2005 
2006 	if (svc->srv_ops.so_thr_init != NULL) {
2007 		rc = svc->srv_ops.so_thr_init(thread);
2008 		if (rc)
2009 			goto out;
2010 	}
2011 
2012 	env = kzalloc(sizeof(*env), GFP_NOFS);
2013 	if (!env) {
2014 		rc = -ENOMEM;
2015 		goto out_srv_fini;
2016 	}
2017 
2018 	rc = lu_context_init(&env->le_ctx,
2019 			     svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
2020 	if (rc)
2021 		goto out_srv_fini;
2022 
2023 	thread->t_env = env;
2024 	env->le_ctx.lc_thread = thread;
2025 	env->le_ctx.lc_cookie = 0x6;
2026 
2027 	while (!list_empty(&svcpt->scp_rqbd_idle)) {
2028 		rc = ptlrpc_server_post_idle_rqbds(svcpt);
2029 		if (rc >= 0)
2030 			continue;
2031 
2032 		CERROR("Failed to post rqbd for %s on CPT %d: %d\n",
2033 			svc->srv_name, svcpt->scp_cpt, rc);
2034 		goto out_srv_fini;
2035 	}
2036 
2037 	/* Alloc reply state structure for this one */
2038 	rs = libcfs_kvzalloc(svc->srv_max_reply_size, GFP_NOFS);
2039 	if (!rs) {
2040 		rc = -ENOMEM;
2041 		goto out_srv_fini;
2042 	}
2043 
2044 	spin_lock(&svcpt->scp_lock);
2045 
2046 	LASSERT(thread_is_starting(thread));
2047 	thread_clear_flags(thread, SVC_STARTING);
2048 
2049 	LASSERT(svcpt->scp_nthrs_starting == 1);
2050 	svcpt->scp_nthrs_starting--;
2051 
2052 	/* SVC_STOPPING may already be set here if someone else is trying
2053 	 * to stop the service while this new thread has been dynamically
2054 	 * forked. We still set SVC_RUNNING to let our creator know that
2055 	 * we are now running, however we will exit as soon as possible */
2056 	thread_add_flags(thread, SVC_RUNNING);
2057 	svcpt->scp_nthrs_running++;
2058 	spin_unlock(&svcpt->scp_lock);
2059 
2060 	/* wake up our creator in case he's still waiting. */
2061 	wake_up(&thread->t_ctl_waitq);
2062 
2063 	/*
2064 	thread->t_watchdog = lc_watchdog_add(ptlrpc_server_get_timeout(svcpt),
2065 					     NULL, NULL);
2066 	 */
2067 
2068 	spin_lock(&svcpt->scp_rep_lock);
2069 	list_add(&rs->rs_list, &svcpt->scp_rep_idle);
2070 	wake_up(&svcpt->scp_rep_waitq);
2071 	spin_unlock(&svcpt->scp_rep_lock);
2072 
2073 	CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
2074 	       svcpt->scp_nthrs_running);
2075 
2076 	/* XXX maintain a list of all managed devices: insert here */
2077 	while (!ptlrpc_thread_stopping(thread)) {
2078 		if (ptlrpc_wait_event(svcpt, thread))
2079 			break;
2080 
2081 		ptlrpc_check_rqbd_pool(svcpt);
2082 
2083 		if (ptlrpc_threads_need_create(svcpt)) {
2084 			/* Ignore return code - we tried... */
2085 			ptlrpc_start_thread(svcpt, 0);
2086 		}
2087 
2088 		/* Process all incoming reqs before handling any */
2089 		if (ptlrpc_server_request_incoming(svcpt)) {
2090 			lu_context_enter(&env->le_ctx);
2091 			env->le_ses = NULL;
2092 			ptlrpc_server_handle_req_in(svcpt, thread);
2093 			lu_context_exit(&env->le_ctx);
2094 
2095 			/* but limit ourselves in case of flood */
2096 			if (counter++ < 100)
2097 				continue;
2098 			counter = 0;
2099 		}
2100 
2101 		if (ptlrpc_at_check(svcpt))
2102 			ptlrpc_at_check_timed(svcpt);
2103 
2104 		if (ptlrpc_server_request_pending(svcpt, false)) {
2105 			lu_context_enter(&env->le_ctx);
2106 			ptlrpc_server_handle_request(svcpt, thread);
2107 			lu_context_exit(&env->le_ctx);
2108 		}
2109 
2110 		if (ptlrpc_rqbd_pending(svcpt) &&
2111 		    ptlrpc_server_post_idle_rqbds(svcpt) < 0) {
2112 			/* I just failed to repost request buffers.
2113 			 * Wait for a timeout (unless something else
2114 			 * happens) before I try again */
2115 			svcpt->scp_rqbd_timeout = cfs_time_seconds(1) / 10;
2116 			CDEBUG(D_RPCTRACE, "Posted buffers: %d\n",
2117 			       svcpt->scp_nrqbds_posted);
2118 		}
2119 	}
2120 
2121 	/*
2122 	lc_watchdog_delete(thread->t_watchdog);
2123 	thread->t_watchdog = NULL;
2124 	*/
2125 
2126 out_srv_fini:
2127 	/*
2128 	 * deconstruct service specific state created by ptlrpc_start_thread()
2129 	 */
2130 	if (svc->srv_ops.so_thr_done != NULL)
2131 		svc->srv_ops.so_thr_done(thread);
2132 
2133 	if (env != NULL) {
2134 		lu_context_fini(&env->le_ctx);
2135 		kfree(env);
2136 	}
2137 out:
2138 	CDEBUG(D_RPCTRACE, "service thread [ %p : %u ] %d exiting: rc %d\n",
2139 	       thread, thread->t_pid, thread->t_id, rc);
2140 
2141 	spin_lock(&svcpt->scp_lock);
2142 	if (thread_test_and_clear_flags(thread, SVC_STARTING))
2143 		svcpt->scp_nthrs_starting--;
2144 
2145 	if (thread_test_and_clear_flags(thread, SVC_RUNNING)) {
2146 		/* must know immediately */
2147 		svcpt->scp_nthrs_running--;
2148 	}
2149 
2150 	thread->t_id = rc;
2151 	thread_add_flags(thread, SVC_STOPPED);
2152 
2153 	wake_up(&thread->t_ctl_waitq);
2154 	spin_unlock(&svcpt->scp_lock);
2155 
2156 	return rc;
2157 }
2158 
hrt_dont_sleep(struct ptlrpc_hr_thread * hrt,struct list_head * replies)2159 static int hrt_dont_sleep(struct ptlrpc_hr_thread *hrt,
2160 			  struct list_head *replies)
2161 {
2162 	int result;
2163 
2164 	spin_lock(&hrt->hrt_lock);
2165 
2166 	list_splice_init(&hrt->hrt_queue, replies);
2167 	result = ptlrpc_hr.hr_stopping || !list_empty(replies);
2168 
2169 	spin_unlock(&hrt->hrt_lock);
2170 	return result;
2171 }
2172 
2173 /**
2174  * Main body of "handle reply" function.
2175  * It processes acked reply states
2176  */
ptlrpc_hr_main(void * arg)2177 static int ptlrpc_hr_main(void *arg)
2178 {
2179 	struct ptlrpc_hr_thread	*hrt = arg;
2180 	struct ptlrpc_hr_partition *hrp = hrt->hrt_partition;
2181 	LIST_HEAD	(replies);
2182 	char threadname[20];
2183 	int rc;
2184 
2185 	snprintf(threadname, sizeof(threadname), "ptlrpc_hr%02d_%03d",
2186 		 hrp->hrp_cpt, hrt->hrt_id);
2187 	unshare_fs_struct();
2188 
2189 	rc = cfs_cpt_bind(ptlrpc_hr.hr_cpt_table, hrp->hrp_cpt);
2190 	if (rc != 0) {
2191 		CWARN("Failed to bind %s on CPT %d of CPT table %p: rc = %d\n",
2192 		      threadname, hrp->hrp_cpt, ptlrpc_hr.hr_cpt_table, rc);
2193 	}
2194 
2195 	atomic_inc(&hrp->hrp_nstarted);
2196 	wake_up(&ptlrpc_hr.hr_waitq);
2197 
2198 	while (!ptlrpc_hr.hr_stopping) {
2199 		l_wait_condition(hrt->hrt_waitq, hrt_dont_sleep(hrt, &replies));
2200 
2201 		while (!list_empty(&replies)) {
2202 			struct ptlrpc_reply_state *rs;
2203 
2204 			rs = list_entry(replies.prev,
2205 					    struct ptlrpc_reply_state,
2206 					    rs_list);
2207 			list_del_init(&rs->rs_list);
2208 			ptlrpc_handle_rs(rs);
2209 		}
2210 	}
2211 
2212 	atomic_inc(&hrp->hrp_nstopped);
2213 	wake_up(&ptlrpc_hr.hr_waitq);
2214 
2215 	return 0;
2216 }
2217 
ptlrpc_stop_hr_threads(void)2218 static void ptlrpc_stop_hr_threads(void)
2219 {
2220 	struct ptlrpc_hr_partition *hrp;
2221 	int i;
2222 	int j;
2223 
2224 	ptlrpc_hr.hr_stopping = 1;
2225 
2226 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2227 		if (hrp->hrp_thrs == NULL)
2228 			continue; /* uninitialized */
2229 		for (j = 0; j < hrp->hrp_nthrs; j++)
2230 			wake_up_all(&hrp->hrp_thrs[j].hrt_waitq);
2231 	}
2232 
2233 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2234 		if (hrp->hrp_thrs == NULL)
2235 			continue; /* uninitialized */
2236 		wait_event(ptlrpc_hr.hr_waitq,
2237 			       atomic_read(&hrp->hrp_nstopped) ==
2238 			       atomic_read(&hrp->hrp_nstarted));
2239 	}
2240 }
2241 
ptlrpc_start_hr_threads(void)2242 static int ptlrpc_start_hr_threads(void)
2243 {
2244 	struct ptlrpc_hr_partition *hrp;
2245 	int i;
2246 	int j;
2247 
2248 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2249 		int rc = 0;
2250 
2251 		for (j = 0; j < hrp->hrp_nthrs; j++) {
2252 			struct	ptlrpc_hr_thread *hrt = &hrp->hrp_thrs[j];
2253 
2254 			rc = PTR_ERR(kthread_run(ptlrpc_hr_main,
2255 						 &hrp->hrp_thrs[j],
2256 						 "ptlrpc_hr%02d_%03d",
2257 						 hrp->hrp_cpt,
2258 						 hrt->hrt_id));
2259 			if (IS_ERR_VALUE(rc))
2260 				break;
2261 		}
2262 		wait_event(ptlrpc_hr.hr_waitq,
2263 			       atomic_read(&hrp->hrp_nstarted) == j);
2264 		if (!IS_ERR_VALUE(rc))
2265 			continue;
2266 
2267 		CERROR("Reply handling thread %d:%d Failed on starting: rc = %d\n",
2268 		       i, j, rc);
2269 		ptlrpc_stop_hr_threads();
2270 		return rc;
2271 	}
2272 	return 0;
2273 }
2274 
ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part * svcpt)2275 static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
2276 {
2277 	struct l_wait_info lwi = { 0 };
2278 	struct ptlrpc_thread *thread;
2279 	LIST_HEAD	(zombie);
2280 
2281 	CDEBUG(D_INFO, "Stopping threads for service %s\n",
2282 	       svcpt->scp_service->srv_name);
2283 
2284 	spin_lock(&svcpt->scp_lock);
2285 	/* let the thread know that we would like it to stop asap */
2286 	list_for_each_entry(thread, &svcpt->scp_threads, t_link) {
2287 		CDEBUG(D_INFO, "Stopping thread %s #%u\n",
2288 		       svcpt->scp_service->srv_thread_name, thread->t_id);
2289 		thread_add_flags(thread, SVC_STOPPING);
2290 	}
2291 
2292 	wake_up_all(&svcpt->scp_waitq);
2293 
2294 	while (!list_empty(&svcpt->scp_threads)) {
2295 		thread = list_entry(svcpt->scp_threads.next,
2296 					struct ptlrpc_thread, t_link);
2297 		if (thread_is_stopped(thread)) {
2298 			list_del(&thread->t_link);
2299 			list_add(&thread->t_link, &zombie);
2300 			continue;
2301 		}
2302 		spin_unlock(&svcpt->scp_lock);
2303 
2304 		CDEBUG(D_INFO, "waiting for stopping-thread %s #%u\n",
2305 		       svcpt->scp_service->srv_thread_name, thread->t_id);
2306 		l_wait_event(thread->t_ctl_waitq,
2307 			     thread_is_stopped(thread), &lwi);
2308 
2309 		spin_lock(&svcpt->scp_lock);
2310 	}
2311 
2312 	spin_unlock(&svcpt->scp_lock);
2313 
2314 	while (!list_empty(&zombie)) {
2315 		thread = list_entry(zombie.next,
2316 					struct ptlrpc_thread, t_link);
2317 		list_del(&thread->t_link);
2318 		kfree(thread);
2319 	}
2320 }
2321 
2322 /**
2323  * Stops all threads of a particular service \a svc
2324  */
ptlrpc_stop_all_threads(struct ptlrpc_service * svc)2325 static void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
2326 {
2327 	struct ptlrpc_service_part *svcpt;
2328 	int i;
2329 
2330 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2331 		if (svcpt->scp_service != NULL)
2332 			ptlrpc_svcpt_stop_threads(svcpt);
2333 	}
2334 }
2335 
ptlrpc_start_threads(struct ptlrpc_service * svc)2336 int ptlrpc_start_threads(struct ptlrpc_service *svc)
2337 {
2338 	int rc = 0;
2339 	int i;
2340 	int j;
2341 
2342 	/* We require 2 threads min, see note in ptlrpc_server_handle_request */
2343 	LASSERT(svc->srv_nthrs_cpt_init >= PTLRPC_NTHRS_INIT);
2344 
2345 	for (i = 0; i < svc->srv_ncpts; i++) {
2346 		for (j = 0; j < svc->srv_nthrs_cpt_init; j++) {
2347 			rc = ptlrpc_start_thread(svc->srv_parts[i], 1);
2348 			if (rc == 0)
2349 				continue;
2350 
2351 			if (rc != -EMFILE)
2352 				goto failed;
2353 			/* We have enough threads, don't start more. b=15759 */
2354 			break;
2355 		}
2356 	}
2357 
2358 	return 0;
2359  failed:
2360 	CERROR("cannot start %s thread #%d_%d: rc %d\n",
2361 	       svc->srv_thread_name, i, j, rc);
2362 	ptlrpc_stop_all_threads(svc);
2363 	return rc;
2364 }
2365 EXPORT_SYMBOL(ptlrpc_start_threads);
2366 
ptlrpc_start_thread(struct ptlrpc_service_part * svcpt,int wait)2367 int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
2368 {
2369 	struct l_wait_info lwi = { 0 };
2370 	struct ptlrpc_thread *thread;
2371 	struct ptlrpc_service *svc;
2372 	int rc;
2373 
2374 	LASSERT(svcpt != NULL);
2375 
2376 	svc = svcpt->scp_service;
2377 
2378 	CDEBUG(D_RPCTRACE, "%s[%d] started %d min %d max %d\n",
2379 	       svc->srv_name, svcpt->scp_cpt, svcpt->scp_nthrs_running,
2380 	       svc->srv_nthrs_cpt_init, svc->srv_nthrs_cpt_limit);
2381 
2382  again:
2383 	if (unlikely(svc->srv_is_stopping))
2384 		return -ESRCH;
2385 
2386 	if (!ptlrpc_threads_increasable(svcpt) ||
2387 	    (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
2388 	     svcpt->scp_nthrs_running == svc->srv_nthrs_cpt_init - 1))
2389 		return -EMFILE;
2390 
2391 	thread = kzalloc_node(sizeof(*thread), GFP_NOFS,
2392 			      cfs_cpt_spread_node(svc->srv_cptable,
2393 						  svcpt->scp_cpt));
2394 	if (thread == NULL)
2395 		return -ENOMEM;
2396 	init_waitqueue_head(&thread->t_ctl_waitq);
2397 
2398 	spin_lock(&svcpt->scp_lock);
2399 	if (!ptlrpc_threads_increasable(svcpt)) {
2400 		spin_unlock(&svcpt->scp_lock);
2401 		kfree(thread);
2402 		return -EMFILE;
2403 	}
2404 
2405 	if (svcpt->scp_nthrs_starting != 0) {
2406 		/* serialize starting because some modules (obdfilter)
2407 		 * might require unique and contiguous t_id */
2408 		LASSERT(svcpt->scp_nthrs_starting == 1);
2409 		spin_unlock(&svcpt->scp_lock);
2410 		kfree(thread);
2411 		if (wait) {
2412 			CDEBUG(D_INFO, "Waiting for creating thread %s #%d\n",
2413 			       svc->srv_thread_name, svcpt->scp_thr_nextid);
2414 			schedule();
2415 			goto again;
2416 		}
2417 
2418 		CDEBUG(D_INFO, "Creating thread %s #%d race, retry later\n",
2419 		       svc->srv_thread_name, svcpt->scp_thr_nextid);
2420 		return -EAGAIN;
2421 	}
2422 
2423 	svcpt->scp_nthrs_starting++;
2424 	thread->t_id = svcpt->scp_thr_nextid++;
2425 	thread_add_flags(thread, SVC_STARTING);
2426 	thread->t_svcpt = svcpt;
2427 
2428 	list_add(&thread->t_link, &svcpt->scp_threads);
2429 	spin_unlock(&svcpt->scp_lock);
2430 
2431 	if (svcpt->scp_cpt >= 0) {
2432 		snprintf(thread->t_name, sizeof(thread->t_name), "%s%02d_%03d",
2433 			 svc->srv_thread_name, svcpt->scp_cpt, thread->t_id);
2434 	} else {
2435 		snprintf(thread->t_name, sizeof(thread->t_name), "%s_%04d",
2436 			 svc->srv_thread_name, thread->t_id);
2437 	}
2438 
2439 	CDEBUG(D_RPCTRACE, "starting thread '%s'\n", thread->t_name);
2440 	rc = PTR_ERR(kthread_run(ptlrpc_main, thread, "%s", thread->t_name));
2441 	if (IS_ERR_VALUE(rc)) {
2442 		CERROR("cannot start thread '%s': rc %d\n",
2443 		       thread->t_name, rc);
2444 		spin_lock(&svcpt->scp_lock);
2445 		--svcpt->scp_nthrs_starting;
2446 		if (thread_is_stopping(thread)) {
2447 			/* this ptlrpc_thread is being handled
2448 			 * by ptlrpc_svcpt_stop_threads now
2449 			 */
2450 			thread_add_flags(thread, SVC_STOPPED);
2451 			wake_up(&thread->t_ctl_waitq);
2452 			spin_unlock(&svcpt->scp_lock);
2453 		} else {
2454 			list_del(&thread->t_link);
2455 			spin_unlock(&svcpt->scp_lock);
2456 			kfree(thread);
2457 		}
2458 		return rc;
2459 	}
2460 
2461 	if (!wait)
2462 		return 0;
2463 
2464 	l_wait_event(thread->t_ctl_waitq,
2465 		     thread_is_running(thread) || thread_is_stopped(thread),
2466 		     &lwi);
2467 
2468 	rc = thread_is_stopped(thread) ? thread->t_id : 0;
2469 	return rc;
2470 }
2471 
ptlrpc_hr_init(void)2472 int ptlrpc_hr_init(void)
2473 {
2474 	struct ptlrpc_hr_partition *hrp;
2475 	struct ptlrpc_hr_thread	*hrt;
2476 	int rc;
2477 	int i;
2478 	int j;
2479 	int weight;
2480 
2481 	memset(&ptlrpc_hr, 0, sizeof(ptlrpc_hr));
2482 	ptlrpc_hr.hr_cpt_table = cfs_cpt_table;
2483 
2484 	ptlrpc_hr.hr_partitions = cfs_percpt_alloc(ptlrpc_hr.hr_cpt_table,
2485 						   sizeof(*hrp));
2486 	if (ptlrpc_hr.hr_partitions == NULL)
2487 		return -ENOMEM;
2488 
2489 	init_waitqueue_head(&ptlrpc_hr.hr_waitq);
2490 
2491 	weight = cpumask_weight(topology_sibling_cpumask(0));
2492 
2493 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2494 		hrp->hrp_cpt = i;
2495 
2496 		atomic_set(&hrp->hrp_nstarted, 0);
2497 		atomic_set(&hrp->hrp_nstopped, 0);
2498 
2499 		hrp->hrp_nthrs = cfs_cpt_weight(ptlrpc_hr.hr_cpt_table, i);
2500 		hrp->hrp_nthrs /= weight;
2501 
2502 		LASSERT(hrp->hrp_nthrs > 0);
2503 		hrp->hrp_thrs =
2504 			kzalloc_node(hrp->hrp_nthrs * sizeof(*hrt), GFP_NOFS,
2505 				cfs_cpt_spread_node(ptlrpc_hr.hr_cpt_table,
2506 						    i));
2507 		if (hrp->hrp_thrs == NULL) {
2508 			rc = -ENOMEM;
2509 			goto out;
2510 		}
2511 
2512 		for (j = 0; j < hrp->hrp_nthrs; j++) {
2513 			hrt = &hrp->hrp_thrs[j];
2514 
2515 			hrt->hrt_id = j;
2516 			hrt->hrt_partition = hrp;
2517 			init_waitqueue_head(&hrt->hrt_waitq);
2518 			spin_lock_init(&hrt->hrt_lock);
2519 			INIT_LIST_HEAD(&hrt->hrt_queue);
2520 		}
2521 	}
2522 
2523 	rc = ptlrpc_start_hr_threads();
2524 out:
2525 	if (rc != 0)
2526 		ptlrpc_hr_fini();
2527 	return rc;
2528 }
2529 
ptlrpc_hr_fini(void)2530 void ptlrpc_hr_fini(void)
2531 {
2532 	struct ptlrpc_hr_partition *hrp;
2533 	int i;
2534 
2535 	if (ptlrpc_hr.hr_partitions == NULL)
2536 		return;
2537 
2538 	ptlrpc_stop_hr_threads();
2539 
2540 	cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2541 		kfree(hrp->hrp_thrs);
2542 	}
2543 
2544 	cfs_percpt_free(ptlrpc_hr.hr_partitions);
2545 	ptlrpc_hr.hr_partitions = NULL;
2546 }
2547 
2548 /**
2549  * Wait until all already scheduled replies are processed.
2550  */
ptlrpc_wait_replies(struct ptlrpc_service_part * svcpt)2551 static void ptlrpc_wait_replies(struct ptlrpc_service_part *svcpt)
2552 {
2553 	while (1) {
2554 		int rc;
2555 		struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
2556 						     NULL, NULL);
2557 
2558 		rc = l_wait_event(svcpt->scp_waitq,
2559 		     atomic_read(&svcpt->scp_nreps_difficult) == 0, &lwi);
2560 		if (rc == 0)
2561 			break;
2562 		CWARN("Unexpectedly long timeout %s %p\n",
2563 		      svcpt->scp_service->srv_name, svcpt->scp_service);
2564 	}
2565 }
2566 
2567 static void
ptlrpc_service_del_atimer(struct ptlrpc_service * svc)2568 ptlrpc_service_del_atimer(struct ptlrpc_service *svc)
2569 {
2570 	struct ptlrpc_service_part *svcpt;
2571 	int i;
2572 
2573 	/* early disarm AT timer... */
2574 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2575 		if (svcpt->scp_service != NULL)
2576 			del_timer(&svcpt->scp_at_timer);
2577 	}
2578 }
2579 
2580 static void
ptlrpc_service_unlink_rqbd(struct ptlrpc_service * svc)2581 ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
2582 {
2583 	struct ptlrpc_service_part *svcpt;
2584 	struct ptlrpc_request_buffer_desc *rqbd;
2585 	struct l_wait_info lwi;
2586 	int rc;
2587 	int i;
2588 
2589 	/* All history will be culled when the next request buffer is
2590 	 * freed in ptlrpc_service_purge_all() */
2591 	svc->srv_hist_nrqbds_cpt_max = 0;
2592 
2593 	rc = LNetClearLazyPortal(svc->srv_req_portal);
2594 	LASSERT(rc == 0);
2595 
2596 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2597 		if (svcpt->scp_service == NULL)
2598 			break;
2599 
2600 		/* Unlink all the request buffers.  This forces a 'final'
2601 		 * event with its 'unlink' flag set for each posted rqbd */
2602 		list_for_each_entry(rqbd, &svcpt->scp_rqbd_posted,
2603 					rqbd_list) {
2604 			rc = LNetMDUnlink(rqbd->rqbd_md_h);
2605 			LASSERT(rc == 0 || rc == -ENOENT);
2606 		}
2607 	}
2608 
2609 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2610 		if (svcpt->scp_service == NULL)
2611 			break;
2612 
2613 		/* Wait for the network to release any buffers
2614 		 * it's currently filling */
2615 		spin_lock(&svcpt->scp_lock);
2616 		while (svcpt->scp_nrqbds_posted != 0) {
2617 			spin_unlock(&svcpt->scp_lock);
2618 			/* Network access will complete in finite time but
2619 			 * the HUGE timeout lets us CWARN for visibility
2620 			 * of sluggish NALs */
2621 			lwi = LWI_TIMEOUT_INTERVAL(
2622 					cfs_time_seconds(LONG_UNLINK),
2623 					cfs_time_seconds(1), NULL, NULL);
2624 			rc = l_wait_event(svcpt->scp_waitq,
2625 					  svcpt->scp_nrqbds_posted == 0, &lwi);
2626 			if (rc == -ETIMEDOUT) {
2627 				CWARN("Service %s waiting for request buffers\n",
2628 				      svcpt->scp_service->srv_name);
2629 			}
2630 			spin_lock(&svcpt->scp_lock);
2631 		}
2632 		spin_unlock(&svcpt->scp_lock);
2633 	}
2634 }
2635 
2636 static void
ptlrpc_service_purge_all(struct ptlrpc_service * svc)2637 ptlrpc_service_purge_all(struct ptlrpc_service *svc)
2638 {
2639 	struct ptlrpc_service_part *svcpt;
2640 	struct ptlrpc_request_buffer_desc *rqbd;
2641 	struct ptlrpc_request *req;
2642 	struct ptlrpc_reply_state *rs;
2643 	int i;
2644 
2645 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2646 		if (svcpt->scp_service == NULL)
2647 			break;
2648 
2649 		spin_lock(&svcpt->scp_rep_lock);
2650 		while (!list_empty(&svcpt->scp_rep_active)) {
2651 			rs = list_entry(svcpt->scp_rep_active.next,
2652 					    struct ptlrpc_reply_state, rs_list);
2653 			spin_lock(&rs->rs_lock);
2654 			ptlrpc_schedule_difficult_reply(rs);
2655 			spin_unlock(&rs->rs_lock);
2656 		}
2657 		spin_unlock(&svcpt->scp_rep_lock);
2658 
2659 		/* purge the request queue.  NB No new replies (rqbds
2660 		 * all unlinked) and no service threads, so I'm the only
2661 		 * thread noodling the request queue now */
2662 		while (!list_empty(&svcpt->scp_req_incoming)) {
2663 			req = list_entry(svcpt->scp_req_incoming.next,
2664 					     struct ptlrpc_request, rq_list);
2665 
2666 			list_del(&req->rq_list);
2667 			svcpt->scp_nreqs_incoming--;
2668 			ptlrpc_server_finish_request(svcpt, req);
2669 		}
2670 
2671 		while (ptlrpc_server_request_pending(svcpt, true)) {
2672 			req = ptlrpc_server_request_get(svcpt, true);
2673 			ptlrpc_server_finish_active_request(svcpt, req);
2674 		}
2675 
2676 		LASSERT(list_empty(&svcpt->scp_rqbd_posted));
2677 		LASSERT(svcpt->scp_nreqs_incoming == 0);
2678 		LASSERT(svcpt->scp_nreqs_active == 0);
2679 		/* history should have been culled by
2680 		 * ptlrpc_server_finish_request */
2681 		LASSERT(svcpt->scp_hist_nrqbds == 0);
2682 
2683 		/* Now free all the request buffers since nothing
2684 		 * references them any more... */
2685 
2686 		while (!list_empty(&svcpt->scp_rqbd_idle)) {
2687 			rqbd = list_entry(svcpt->scp_rqbd_idle.next,
2688 					      struct ptlrpc_request_buffer_desc,
2689 					      rqbd_list);
2690 			ptlrpc_free_rqbd(rqbd);
2691 		}
2692 		ptlrpc_wait_replies(svcpt);
2693 
2694 		while (!list_empty(&svcpt->scp_rep_idle)) {
2695 			rs = list_entry(svcpt->scp_rep_idle.next,
2696 					    struct ptlrpc_reply_state,
2697 					    rs_list);
2698 			list_del(&rs->rs_list);
2699 			kvfree(rs);
2700 		}
2701 	}
2702 }
2703 
2704 static void
ptlrpc_service_free(struct ptlrpc_service * svc)2705 ptlrpc_service_free(struct ptlrpc_service *svc)
2706 {
2707 	struct ptlrpc_service_part *svcpt;
2708 	struct ptlrpc_at_array *array;
2709 	int i;
2710 
2711 	ptlrpc_service_for_each_part(svcpt, i, svc) {
2712 		if (svcpt->scp_service == NULL)
2713 			break;
2714 
2715 		/* In case somebody rearmed this in the meantime */
2716 		del_timer(&svcpt->scp_at_timer);
2717 		array = &svcpt->scp_at_array;
2718 
2719 		kfree(array->paa_reqs_array);
2720 		array->paa_reqs_array = NULL;
2721 		kfree(array->paa_reqs_count);
2722 		array->paa_reqs_count = NULL;
2723 	}
2724 
2725 	ptlrpc_service_for_each_part(svcpt, i, svc)
2726 		kfree(svcpt);
2727 
2728 	if (svc->srv_cpts != NULL)
2729 		cfs_expr_list_values_free(svc->srv_cpts, svc->srv_ncpts);
2730 
2731 	kfree(svc);
2732 }
2733 
ptlrpc_unregister_service(struct ptlrpc_service * service)2734 int ptlrpc_unregister_service(struct ptlrpc_service *service)
2735 {
2736 	CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
2737 
2738 	service->srv_is_stopping = 1;
2739 
2740 	mutex_lock(&ptlrpc_all_services_mutex);
2741 	list_del_init(&service->srv_list);
2742 	mutex_unlock(&ptlrpc_all_services_mutex);
2743 
2744 	ptlrpc_service_del_atimer(service);
2745 	ptlrpc_stop_all_threads(service);
2746 
2747 	ptlrpc_service_unlink_rqbd(service);
2748 	ptlrpc_service_purge_all(service);
2749 	ptlrpc_service_nrs_cleanup(service);
2750 
2751 	ptlrpc_lprocfs_unregister_service(service);
2752 	ptlrpc_sysfs_unregister_service(service);
2753 
2754 	ptlrpc_service_free(service);
2755 
2756 	return 0;
2757 }
2758 EXPORT_SYMBOL(ptlrpc_unregister_service);
2759