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