Whamcloud - gitweb
LU-4423 ptlrpc: Fix using smp_processor_id() in preemptible context
[fs/lustre-release.git] / 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, 2017, 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
35 #include <linux/kthread.h>
36 #include <linux/ratelimit.h>
37
38 #include <obd_support.h>
39 #include <obd_class.h>
40 #include <lustre_net.h>
41 #include <lu_object.h>
42 #include <uapi/linux/lnet/lnet-types.h>
43 #include "ptlrpc_internal.h"
44
45 /* The following are visible and mutable through /sys/module/ptlrpc */
46 int test_req_buffer_pressure = 0;
47 module_param(test_req_buffer_pressure, int, 0444);
48 MODULE_PARM_DESC(test_req_buffer_pressure, "set non-zero to put pressure on request buffer pools");
49 module_param(at_min, int, 0644);
50 MODULE_PARM_DESC(at_min, "Adaptive timeout minimum (sec)");
51 module_param(at_max, int, 0644);
52 MODULE_PARM_DESC(at_max, "Adaptive timeout maximum (sec)");
53 module_param(at_history, int, 0644);
54 MODULE_PARM_DESC(at_history,
55                  "Adaptive timeouts remember the slowest event that took place within this period (sec)");
56 module_param(at_early_margin, int, 0644);
57 MODULE_PARM_DESC(at_early_margin, "How soon before an RPC deadline to send an early reply");
58 module_param(at_extra, int, 0644);
59 MODULE_PARM_DESC(at_extra, "How much extra time to give with each early reply");
60
61 /* forward ref */
62 static int ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt);
63 static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req);
64 static void ptlrpc_at_remove_timed(struct ptlrpc_request *req);
65
66 /** Holds a list of all PTLRPC services */
67 struct list_head ptlrpc_all_services;
68 /** Used to protect the \e ptlrpc_all_services list */
69 struct mutex ptlrpc_all_services_mutex;
70
71 static struct ptlrpc_request_buffer_desc *
72 ptlrpc_alloc_rqbd(struct ptlrpc_service_part *svcpt)
73 {
74         struct ptlrpc_service             *svc = svcpt->scp_service;
75         struct ptlrpc_request_buffer_desc *rqbd;
76
77         OBD_CPT_ALLOC_PTR(rqbd, svc->srv_cptable, svcpt->scp_cpt);
78         if (rqbd == NULL)
79                 return NULL;
80
81         rqbd->rqbd_svcpt = svcpt;
82         rqbd->rqbd_refcount = 0;
83         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
84         rqbd->rqbd_cbid.cbid_arg = rqbd;
85         INIT_LIST_HEAD(&rqbd->rqbd_reqs);
86         OBD_CPT_ALLOC_LARGE(rqbd->rqbd_buffer, svc->srv_cptable,
87                             svcpt->scp_cpt, svc->srv_buf_size);
88         if (rqbd->rqbd_buffer == NULL) {
89                 OBD_FREE_PTR(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 ptlrpc_free_rqbd(struct ptlrpc_request_buffer_desc *rqbd)
102 {
103         struct ptlrpc_service_part *svcpt = rqbd->rqbd_svcpt;
104
105         LASSERT(rqbd->rqbd_refcount == 0);
106         LASSERT(list_empty(&rqbd->rqbd_reqs));
107
108         spin_lock(&svcpt->scp_lock);
109         list_del(&rqbd->rqbd_list);
110         svcpt->scp_nrqbds_total--;
111         spin_unlock(&svcpt->scp_lock);
112
113         OBD_FREE_LARGE(rqbd->rqbd_buffer, svcpt->scp_service->srv_buf_size);
114         OBD_FREE_PTR(rqbd);
115 }
116
117 static int ptlrpc_grow_req_bufs(struct ptlrpc_service_part *svcpt, int post)
118 {
119         struct ptlrpc_service *svc = svcpt->scp_service;
120         struct ptlrpc_request_buffer_desc *rqbd;
121         int rc = 0;
122         int i;
123
124         if (svcpt->scp_rqbd_allocating)
125                 goto try_post;
126
127         spin_lock(&svcpt->scp_lock);
128         /* check again with lock */
129         if (svcpt->scp_rqbd_allocating) {
130                 /* NB: we might allow more than one thread in the future */
131                 LASSERT(svcpt->scp_rqbd_allocating == 1);
132                 spin_unlock(&svcpt->scp_lock);
133                 goto try_post;
134         }
135
136         svcpt->scp_rqbd_allocating++;
137         spin_unlock(&svcpt->scp_lock);
138
139
140         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
141                 /*
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                     (svc->srv_nrqbds_max != 0 &&
147                      svcpt->scp_nrqbds_total > svc->srv_nrqbds_max))
148                         break;
149
150                 rqbd = ptlrpc_alloc_rqbd(svcpt);
151
152                 if (rqbd == NULL) {
153                         CERROR("%s: Can't allocate request buffer\n",
154                                svc->srv_name);
155                         rc = -ENOMEM;
156                         break;
157                 }
158         }
159
160         spin_lock(&svcpt->scp_lock);
161
162         LASSERT(svcpt->scp_rqbd_allocating == 1);
163         svcpt->scp_rqbd_allocating--;
164
165         spin_unlock(&svcpt->scp_lock);
166
167         CDEBUG(D_RPCTRACE,
168                "%s: allocate %d new %d-byte reqbufs (%d/%d left), rc = %d\n",
169                svc->srv_name, i, svc->srv_buf_size, svcpt->scp_nrqbds_posted,
170                svcpt->scp_nrqbds_total, rc);
171
172  try_post:
173         if (post && rc == 0)
174                 rc = ptlrpc_server_post_idle_rqbds(svcpt);
175
176         return rc;
177 }
178
179 /**
180  * Part of Rep-Ack logic.
181  * Puts a lock and its mode into reply state assotiated to request reply.
182  */
183 void ptlrpc_save_lock(struct ptlrpc_request *req, struct lustre_handle *lock,
184                       int mode, bool no_ack, bool convert_lock)
185 {
186         struct ptlrpc_reply_state *rs = req->rq_reply_state;
187         int idx;
188
189         LASSERT(rs != NULL);
190         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
191
192         idx = rs->rs_nlocks++;
193         rs->rs_locks[idx] = *lock;
194         rs->rs_modes[idx] = mode;
195         rs->rs_difficult = 1;
196         rs->rs_no_ack = no_ack;
197         rs->rs_convert_lock = convert_lock;
198 }
199 EXPORT_SYMBOL(ptlrpc_save_lock);
200
201
202 struct ptlrpc_hr_partition;
203
204 struct ptlrpc_hr_thread {
205         int                             hrt_id;         /* thread ID */
206         spinlock_t                      hrt_lock;
207         wait_queue_head_t               hrt_waitq;
208         struct list_head                hrt_queue;
209         struct ptlrpc_hr_partition      *hrt_partition;
210 };
211
212 struct ptlrpc_hr_partition {
213         /* # of started threads */
214         atomic_t                        hrp_nstarted;
215         /* # of stopped threads */
216         atomic_t                        hrp_nstopped;
217         /* cpu partition id */
218         int                             hrp_cpt;
219         /* round-robin rotor for choosing thread */
220         int                             hrp_rotor;
221         /* total number of threads on this partition */
222         int                             hrp_nthrs;
223         /* threads table */
224         struct ptlrpc_hr_thread         *hrp_thrs;
225 };
226
227 #define HRT_RUNNING 0
228 #define HRT_STOPPING 1
229
230 struct ptlrpc_hr_service {
231         /* CPU partition table, it's just cfs_cpt_table for now */
232         struct cfs_cpt_table            *hr_cpt_table;
233         /** controller sleep waitq */
234         wait_queue_head_t               hr_waitq;
235         unsigned int                    hr_stopping;
236         /** roundrobin rotor for non-affinity service */
237         unsigned int                    hr_rotor;
238         /* partition data */
239         struct ptlrpc_hr_partition      **hr_partitions;
240 };
241
242 struct rs_batch {
243         struct list_head                        rsb_replies;
244         unsigned int                    rsb_n_replies;
245         struct ptlrpc_service_part      *rsb_svcpt;
246 };
247
248 /** reply handling service. */
249 static struct ptlrpc_hr_service         ptlrpc_hr;
250
251 /**
252  * maximum mumber of replies scheduled in one batch
253  */
254 #define MAX_SCHEDULED 256
255
256 /**
257  * Initialize a reply batch.
258  *
259  * \param b batch
260  */
261 static void rs_batch_init(struct rs_batch *b)
262 {
263         memset(b, 0, sizeof(*b));
264         INIT_LIST_HEAD(&b->rsb_replies);
265 }
266
267 /**
268  * Choose an hr thread to dispatch requests to.
269  */
270 static
271 struct ptlrpc_hr_thread *ptlrpc_hr_select(struct ptlrpc_service_part *svcpt)
272 {
273         struct ptlrpc_hr_partition      *hrp;
274         unsigned int                    rotor;
275
276         if (svcpt->scp_cpt >= 0 &&
277             svcpt->scp_service->srv_cptable == ptlrpc_hr.hr_cpt_table) {
278                 /* directly match partition */
279                 hrp = ptlrpc_hr.hr_partitions[svcpt->scp_cpt];
280
281         } else {
282                 rotor = ptlrpc_hr.hr_rotor++;
283                 rotor %= cfs_cpt_number(ptlrpc_hr.hr_cpt_table);
284
285                 hrp = ptlrpc_hr.hr_partitions[rotor];
286         }
287
288         rotor = hrp->hrp_rotor++;
289         return &hrp->hrp_thrs[rotor % hrp->hrp_nthrs];
290 }
291
292 /**
293  * Dispatch all replies accumulated in the batch to one from
294  * dedicated reply handling threads.
295  *
296  * \param b batch
297  */
298 static void rs_batch_dispatch(struct rs_batch *b)
299 {
300         if (b->rsb_n_replies != 0) {
301                 struct ptlrpc_hr_thread *hrt;
302
303                 hrt = ptlrpc_hr_select(b->rsb_svcpt);
304
305                 spin_lock(&hrt->hrt_lock);
306                 list_splice_init(&b->rsb_replies, &hrt->hrt_queue);
307                 spin_unlock(&hrt->hrt_lock);
308
309                 wake_up(&hrt->hrt_waitq);
310                 b->rsb_n_replies = 0;
311         }
312 }
313
314 /**
315  * Add a reply to a batch.
316  * Add one reply object to a batch, schedule batched replies if overload.
317  *
318  * \param b batch
319  * \param rs reply
320  */
321 static void rs_batch_add(struct rs_batch *b, struct ptlrpc_reply_state *rs)
322 {
323         struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
324
325         if (svcpt != b->rsb_svcpt || b->rsb_n_replies >= MAX_SCHEDULED) {
326                 if (b->rsb_svcpt != NULL) {
327                         rs_batch_dispatch(b);
328                         spin_unlock(&b->rsb_svcpt->scp_rep_lock);
329                 }
330                 spin_lock(&svcpt->scp_rep_lock);
331                 b->rsb_svcpt = svcpt;
332         }
333         spin_lock(&rs->rs_lock);
334         rs->rs_scheduled_ever = 1;
335         if (rs->rs_scheduled == 0) {
336                 list_move(&rs->rs_list, &b->rsb_replies);
337                 rs->rs_scheduled = 1;
338                 b->rsb_n_replies++;
339         }
340         rs->rs_committed = 1;
341         spin_unlock(&rs->rs_lock);
342 }
343
344 /**
345  * Reply batch finalization.
346  * Dispatch remaining replies from the batch
347  * and release remaining spinlock.
348  *
349  * \param b batch
350  */
351 static void rs_batch_fini(struct rs_batch *b)
352 {
353         if (b->rsb_svcpt != NULL) {
354                 rs_batch_dispatch(b);
355                 spin_unlock(&b->rsb_svcpt->scp_rep_lock);
356         }
357 }
358
359 #define DECLARE_RS_BATCH(b)     struct rs_batch b
360
361
362 /**
363  * Put reply state into a queue for processing because we received
364  * ACK from the client
365  */
366 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
367 {
368         struct ptlrpc_hr_thread *hrt;
369
370         ENTRY;
371
372         LASSERT(list_empty(&rs->rs_list));
373
374         hrt = ptlrpc_hr_select(rs->rs_svcpt);
375
376         spin_lock(&hrt->hrt_lock);
377         list_add_tail(&rs->rs_list, &hrt->hrt_queue);
378         spin_unlock(&hrt->hrt_lock);
379
380         wake_up(&hrt->hrt_waitq);
381         EXIT;
382 }
383
384 void ptlrpc_schedule_difficult_reply(struct ptlrpc_reply_state *rs)
385 {
386         ENTRY;
387
388         assert_spin_locked(&rs->rs_svcpt->scp_rep_lock);
389         assert_spin_locked(&rs->rs_lock);
390         LASSERT(rs->rs_difficult);
391         rs->rs_scheduled_ever = 1;  /* flag any notification attempt */
392
393         if (rs->rs_scheduled) {     /* being set up or already notified */
394                 EXIT;
395                 return;
396         }
397
398         rs->rs_scheduled = 1;
399         list_del_init(&rs->rs_list);
400         ptlrpc_dispatch_difficult_reply(rs);
401         EXIT;
402 }
403 EXPORT_SYMBOL(ptlrpc_schedule_difficult_reply);
404
405 void ptlrpc_commit_replies(struct obd_export *exp)
406 {
407         struct ptlrpc_reply_state *rs, *nxt;
408         DECLARE_RS_BATCH(batch);
409
410         ENTRY;
411
412         rs_batch_init(&batch);
413         /*
414          * Find any replies that have been committed and get their service
415          * to attend to complete them.
416          */
417
418         /* CAVEAT EMPTOR: spinlock ordering!!! */
419         spin_lock(&exp->exp_uncommitted_replies_lock);
420         list_for_each_entry_safe(rs, nxt, &exp->exp_uncommitted_replies,
421                                  rs_obd_list) {
422                 LASSERT(rs->rs_difficult);
423                 /* VBR: per-export last_committed */
424                 LASSERT(rs->rs_export);
425                 if (rs->rs_transno <= exp->exp_last_committed) {
426                         list_del_init(&rs->rs_obd_list);
427                         rs_batch_add(&batch, rs);
428                 }
429         }
430         spin_unlock(&exp->exp_uncommitted_replies_lock);
431         rs_batch_fini(&batch);
432         EXIT;
433 }
434
435 static int ptlrpc_server_post_idle_rqbds(struct ptlrpc_service_part *svcpt)
436 {
437         struct ptlrpc_request_buffer_desc *rqbd;
438         int rc;
439         int posted = 0;
440
441         for (;;) {
442                 spin_lock(&svcpt->scp_lock);
443
444                 if (list_empty(&svcpt->scp_rqbd_idle)) {
445                         spin_unlock(&svcpt->scp_lock);
446                         return posted;
447                 }
448
449                 rqbd = list_entry(svcpt->scp_rqbd_idle.next,
450                                       struct ptlrpc_request_buffer_desc,
451                                       rqbd_list);
452                 list_del(&rqbd->rqbd_list);
453
454                 /* assume we will post successfully */
455                 svcpt->scp_nrqbds_posted++;
456                 list_add(&rqbd->rqbd_list, &svcpt->scp_rqbd_posted);
457
458                 spin_unlock(&svcpt->scp_lock);
459
460                 rc = ptlrpc_register_rqbd(rqbd);
461                 if (rc != 0)
462                         break;
463
464                 posted = 1;
465         }
466
467         spin_lock(&svcpt->scp_lock);
468
469         svcpt->scp_nrqbds_posted--;
470         list_del(&rqbd->rqbd_list);
471         list_add_tail(&rqbd->rqbd_list, &svcpt->scp_rqbd_idle);
472
473         /*
474          * Don't complain if no request buffers are posted right now; LNET
475          * won't drop requests because we set the portal lazy!
476          */
477
478         spin_unlock(&svcpt->scp_lock);
479
480         return -1;
481 }
482
483 static void ptlrpc_at_timer(cfs_timer_cb_arg_t data)
484 {
485         struct ptlrpc_service_part *svcpt;
486
487         svcpt = cfs_from_timer(svcpt, data, scp_at_timer);
488
489         svcpt->scp_at_check = 1;
490         svcpt->scp_at_checktime = ktime_get();
491         wake_up(&svcpt->scp_waitq);
492 }
493
494 static void ptlrpc_server_nthreads_check(struct ptlrpc_service *svc,
495                                          struct ptlrpc_service_conf *conf)
496 {
497         struct ptlrpc_service_thr_conf *tc = &conf->psc_thr;
498         unsigned int init;
499         unsigned int total;
500         unsigned int nthrs;
501         int weight;
502
503         /*
504          * Common code for estimating & validating threads number.
505          * CPT affinity service could have percpt thread-pool instead
506          * of a global thread-pool, which means user might not always
507          * get the threads number they give it in conf::tc_nthrs_user
508          * even they did set. It's because we need to validate threads
509          * number for each CPT to guarantee each pool will have enough
510          * threads to keep the service healthy.
511          */
512         init = PTLRPC_NTHRS_INIT + (svc->srv_ops.so_hpreq_handler != NULL);
513         init = max_t(int, init, tc->tc_nthrs_init);
514
515         /*
516          * NB: please see comments in lustre_lnet.h for definition
517          * details of these members
518          */
519         LASSERT(tc->tc_nthrs_max != 0);
520
521         if (tc->tc_nthrs_user != 0) {
522                 /*
523                  * In case there is a reason to test a service with many
524                  * threads, we give a less strict check here, it can
525                  * be up to 8 * nthrs_max
526                  */
527                 total = min(tc->tc_nthrs_max * 8, tc->tc_nthrs_user);
528                 nthrs = total / svc->srv_ncpts;
529                 init  = max(init, nthrs);
530                 goto out;
531         }
532
533         total = tc->tc_nthrs_max;
534         if (tc->tc_nthrs_base == 0) {
535                 /*
536                  * don't care about base threads number per partition,
537                  * this is most for non-affinity service
538                  */
539                 nthrs = total / svc->srv_ncpts;
540                 goto out;
541         }
542
543         nthrs = tc->tc_nthrs_base;
544         if (svc->srv_ncpts == 1) {
545                 int     i;
546
547                 /*
548                  * NB: Increase the base number if it's single partition
549                  * and total number of cores/HTs is larger or equal to 4.
550                  * result will always < 2 * nthrs_base
551                  */
552                 weight = cfs_cpt_weight(svc->srv_cptable, CFS_CPT_ANY);
553                 for (i = 1; (weight >> (i + 1)) != 0 && /* >= 4 cores/HTs */
554                             (tc->tc_nthrs_base >> i) != 0; i++)
555                         nthrs += tc->tc_nthrs_base >> i;
556         }
557
558         if (tc->tc_thr_factor != 0) {
559                 int       factor = tc->tc_thr_factor;
560                 const int fade = 4;
561
562                 /*
563                  * User wants to increase number of threads with for
564                  * each CPU core/HT, most likely the factor is larger than
565                  * one thread/core because service threads are supposed to
566                  * be blocked by lock or wait for IO.
567                  */
568                 /*
569                  * Amdahl's law says that adding processors wouldn't give
570                  * a linear increasing of parallelism, so it's nonsense to
571                  * have too many threads no matter how many cores/HTs
572                  * there are.
573                  */
574                 preempt_disable();
575                 if (cpumask_weight
576                     (topology_sibling_cpumask(smp_processor_id())) > 1) {
577                         /* weight is # of HTs */
578                         /* depress thread factor for hyper-thread */
579                         factor = factor - (factor >> 1) + (factor >> 3);
580                 }
581                 preempt_enable();
582
583                 weight = cfs_cpt_weight(svc->srv_cptable, 0);
584
585                 for (; factor > 0 && weight > 0; factor--, weight -= fade)
586                         nthrs += min(weight, fade) * factor;
587         }
588
589         if (nthrs * svc->srv_ncpts > tc->tc_nthrs_max) {
590                 nthrs = max(tc->tc_nthrs_base,
591                             tc->tc_nthrs_max / svc->srv_ncpts);
592         }
593  out:
594         nthrs = max(nthrs, tc->tc_nthrs_init);
595         svc->srv_nthrs_cpt_limit = nthrs;
596         svc->srv_nthrs_cpt_init = init;
597
598         if (nthrs * svc->srv_ncpts > tc->tc_nthrs_max) {
599                 CDEBUG(D_OTHER,
600                        "%s: This service may have more threads (%d) than the given soft limit (%d)\n",
601                        svc->srv_name, nthrs * svc->srv_ncpts,
602                        tc->tc_nthrs_max);
603         }
604 }
605
606 /**
607  * Initialize percpt data for a service
608  */
609 static int ptlrpc_service_part_init(struct ptlrpc_service *svc,
610                                     struct ptlrpc_service_part *svcpt, int cpt)
611 {
612         struct ptlrpc_at_array *array;
613         int size;
614         int index;
615         int rc;
616
617         svcpt->scp_cpt = cpt;
618         INIT_LIST_HEAD(&svcpt->scp_threads);
619
620         /* rqbd and incoming request queue */
621         spin_lock_init(&svcpt->scp_lock);
622         mutex_init(&svcpt->scp_mutex);
623         INIT_LIST_HEAD(&svcpt->scp_rqbd_idle);
624         INIT_LIST_HEAD(&svcpt->scp_rqbd_posted);
625         INIT_LIST_HEAD(&svcpt->scp_req_incoming);
626         init_waitqueue_head(&svcpt->scp_waitq);
627         /* history request & rqbd list */
628         INIT_LIST_HEAD(&svcpt->scp_hist_reqs);
629         INIT_LIST_HEAD(&svcpt->scp_hist_rqbds);
630
631         /* acitve requests and hp requests */
632         spin_lock_init(&svcpt->scp_req_lock);
633
634         /* reply states */
635         spin_lock_init(&svcpt->scp_rep_lock);
636         INIT_LIST_HEAD(&svcpt->scp_rep_active);
637         INIT_LIST_HEAD(&svcpt->scp_rep_idle);
638         init_waitqueue_head(&svcpt->scp_rep_waitq);
639         atomic_set(&svcpt->scp_nreps_difficult, 0);
640
641         /* adaptive timeout */
642         spin_lock_init(&svcpt->scp_at_lock);
643         array = &svcpt->scp_at_array;
644
645         size = at_est2timeout(at_max);
646         array->paa_size     = size;
647         array->paa_count    = 0;
648         array->paa_deadline = -1;
649
650         /* allocate memory for scp_at_array (ptlrpc_at_array) */
651         OBD_CPT_ALLOC(array->paa_reqs_array,
652                       svc->srv_cptable, cpt, sizeof(struct list_head) * size);
653         if (array->paa_reqs_array == NULL)
654                 return -ENOMEM;
655
656         for (index = 0; index < size; index++)
657                 INIT_LIST_HEAD(&array->paa_reqs_array[index]);
658
659         OBD_CPT_ALLOC(array->paa_reqs_count,
660                       svc->srv_cptable, cpt, sizeof(__u32) * size);
661         if (array->paa_reqs_count == NULL)
662                 goto failed;
663
664         cfs_timer_setup(&svcpt->scp_at_timer, ptlrpc_at_timer,
665                         (unsigned long)svcpt, 0);
666
667         /*
668          * At SOW, service time should be quick; 10s seems generous. If client
669          * timeout is less than this, we'll be sending an early reply.
670          */
671         at_init(&svcpt->scp_at_estimate, 10, 0);
672
673         /* assign this before call ptlrpc_grow_req_bufs */
674         svcpt->scp_service = svc;
675         /* Now allocate the request buffers, but don't post them now */
676         rc = ptlrpc_grow_req_bufs(svcpt, 0);
677         /*
678          * We shouldn't be under memory pressure at startup, so
679          * fail if we can't allocate all our buffers at this time.
680          */
681         if (rc != 0)
682                 goto failed;
683
684         return 0;
685
686  failed:
687         if (array->paa_reqs_count != NULL) {
688                 OBD_FREE(array->paa_reqs_count, sizeof(__u32) * size);
689                 array->paa_reqs_count = NULL;
690         }
691
692         if (array->paa_reqs_array != NULL) {
693                 OBD_FREE(array->paa_reqs_array,
694                          sizeof(struct list_head) * array->paa_size);
695                 array->paa_reqs_array = NULL;
696         }
697
698         return -ENOMEM;
699 }
700
701 /**
702  * Initialize service on a given portal.
703  * This includes starting serving threads , allocating and posting rqbds and
704  * so on.
705  */
706 struct ptlrpc_service *ptlrpc_register_service(struct ptlrpc_service_conf *conf,
707                                                struct kset *parent,
708                                                struct dentry *debugfs_entry)
709 {
710         struct ptlrpc_service_cpt_conf *cconf = &conf->psc_cpt;
711         struct ptlrpc_service *service;
712         struct ptlrpc_service_part *svcpt;
713         struct cfs_cpt_table *cptable;
714         __u32 *cpts = NULL;
715         int ncpts;
716         int cpt;
717         int rc;
718         int i;
719
720         ENTRY;
721
722         LASSERT(conf->psc_buf.bc_nbufs > 0);
723         LASSERT(conf->psc_buf.bc_buf_size >=
724                 conf->psc_buf.bc_req_max_size + SPTLRPC_MAX_PAYLOAD);
725         LASSERT(conf->psc_thr.tc_ctx_tags != 0);
726
727         cptable = cconf->cc_cptable;
728         if (cptable == NULL)
729                 cptable = cfs_cpt_table;
730
731         if (conf->psc_thr.tc_cpu_bind > 1) {
732                 CERROR("%s: Invalid cpu bind value %d, only 1 or 0 allowed\n",
733                        conf->psc_name, conf->psc_thr.tc_cpu_bind);
734                 RETURN(ERR_PTR(-EINVAL));
735         }
736
737         if (!cconf->cc_affinity) {
738                 ncpts = 1;
739         } else {
740                 ncpts = cfs_cpt_number(cptable);
741                 if (cconf->cc_pattern != NULL) {
742                         struct cfs_expr_list    *el;
743
744                         rc = cfs_expr_list_parse(cconf->cc_pattern,
745                                                  strlen(cconf->cc_pattern),
746                                                  0, ncpts - 1, &el);
747                         if (rc != 0) {
748                                 CERROR("%s: invalid CPT pattern string: %s",
749                                        conf->psc_name, cconf->cc_pattern);
750                                 RETURN(ERR_PTR(-EINVAL));
751                         }
752
753                         rc = cfs_expr_list_values(el, ncpts, &cpts);
754                         cfs_expr_list_free(el);
755                         if (rc <= 0) {
756                                 CERROR("%s: failed to parse CPT array %s: %d\n",
757                                        conf->psc_name, cconf->cc_pattern, rc);
758                                 if (cpts != NULL)
759                                         OBD_FREE(cpts, sizeof(*cpts) * ncpts);
760                                 RETURN(ERR_PTR(rc < 0 ? rc : -EINVAL));
761                         }
762                         ncpts = rc;
763                 }
764         }
765
766         OBD_ALLOC(service, offsetof(struct ptlrpc_service, srv_parts[ncpts]));
767         if (service == NULL) {
768                 if (cpts != NULL)
769                         OBD_FREE(cpts, sizeof(*cpts) * ncpts);
770                 RETURN(ERR_PTR(-ENOMEM));
771         }
772
773         service->srv_cptable            = cptable;
774         service->srv_cpts               = cpts;
775         service->srv_ncpts              = ncpts;
776         service->srv_cpt_bind           = conf->psc_thr.tc_cpu_bind;
777
778         service->srv_cpt_bits = 0; /* it's zero already, easy to read... */
779         while ((1 << service->srv_cpt_bits) < cfs_cpt_number(cptable))
780                 service->srv_cpt_bits++;
781
782         /* public members */
783         spin_lock_init(&service->srv_lock);
784         service->srv_name               = conf->psc_name;
785         service->srv_watchdog_factor    = conf->psc_watchdog_factor;
786         INIT_LIST_HEAD(&service->srv_list); /* for safty of cleanup */
787
788         /* buffer configuration */
789         service->srv_nbuf_per_group     = test_req_buffer_pressure ?
790                                           1 : conf->psc_buf.bc_nbufs;
791         /* do not limit max number of rqbds by default */
792         service->srv_nrqbds_max         = 0;
793
794         service->srv_max_req_size       = conf->psc_buf.bc_req_max_size +
795                                           SPTLRPC_MAX_PAYLOAD;
796         service->srv_buf_size           = conf->psc_buf.bc_buf_size;
797         service->srv_rep_portal         = conf->psc_buf.bc_rep_portal;
798         service->srv_req_portal         = conf->psc_buf.bc_req_portal;
799
800         /* With slab/alloc_pages buffer size will be rounded up to 2^n */
801         if (service->srv_buf_size & (service->srv_buf_size - 1)) {
802                 int round = size_roundup_power2(service->srv_buf_size);
803
804                 service->srv_buf_size = round;
805         }
806
807         /* Increase max reply size to next power of two */
808         service->srv_max_reply_size = 1;
809         while (service->srv_max_reply_size <
810                conf->psc_buf.bc_rep_max_size + SPTLRPC_MAX_PAYLOAD)
811                 service->srv_max_reply_size <<= 1;
812
813         service->srv_thread_name        = conf->psc_thr.tc_thr_name;
814         service->srv_ctx_tags           = conf->psc_thr.tc_ctx_tags;
815         service->srv_hpreq_ratio        = PTLRPC_SVC_HP_RATIO;
816         service->srv_ops                = conf->psc_ops;
817
818         for (i = 0; i < ncpts; i++) {
819                 if (!cconf->cc_affinity)
820                         cpt = CFS_CPT_ANY;
821                 else
822                         cpt = cpts != NULL ? cpts[i] : i;
823
824                 OBD_CPT_ALLOC(svcpt, cptable, cpt, sizeof(*svcpt));
825                 if (svcpt == NULL)
826                         GOTO(failed, rc = -ENOMEM);
827
828                 service->srv_parts[i] = svcpt;
829                 rc = ptlrpc_service_part_init(service, svcpt, cpt);
830                 if (rc != 0)
831                         GOTO(failed, rc);
832         }
833
834         ptlrpc_server_nthreads_check(service, conf);
835
836         rc = LNetSetLazyPortal(service->srv_req_portal);
837         LASSERT(rc == 0);
838
839         mutex_lock(&ptlrpc_all_services_mutex);
840         list_add(&service->srv_list, &ptlrpc_all_services);
841         mutex_unlock(&ptlrpc_all_services_mutex);
842
843         if (parent) {
844                 rc = ptlrpc_sysfs_register_service(parent, service);
845                 if (rc)
846                         GOTO(failed, rc);
847         }
848
849         if (debugfs_entry != NULL)
850                 ptlrpc_ldebugfs_register_service(debugfs_entry, service);
851
852         rc = ptlrpc_service_nrs_setup(service);
853         if (rc != 0)
854                 GOTO(failed, rc);
855
856         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
857                service->srv_name, service->srv_req_portal);
858
859         rc = ptlrpc_start_threads(service);
860         if (rc != 0) {
861                 CERROR("Failed to start threads for service %s: %d\n",
862                        service->srv_name, rc);
863                 GOTO(failed, rc);
864         }
865
866         RETURN(service);
867 failed:
868         ptlrpc_unregister_service(service);
869         RETURN(ERR_PTR(rc));
870 }
871 EXPORT_SYMBOL(ptlrpc_register_service);
872
873 /**
874  * to actually free the request, must be called without holding svc_lock.
875  * note it's caller's responsibility to unlink req->rq_list.
876  */
877 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
878 {
879         LASSERT(atomic_read(&req->rq_refcount) == 0);
880         LASSERT(list_empty(&req->rq_timed_list));
881
882         /*
883          * DEBUG_REQ() assumes the reply state of a request with a valid
884          * ref will not be destroyed until that reference is dropped.
885          */
886         ptlrpc_req_drop_rs(req);
887
888         sptlrpc_svc_ctx_decref(req);
889
890         if (req != &req->rq_rqbd->rqbd_req) {
891                 /*
892                  * NB request buffers use an embedded
893                  * req if the incoming req unlinked the
894                  * MD; this isn't one of them!
895                  */
896                 ptlrpc_request_cache_free(req);
897         }
898 }
899
900 /**
901  * drop a reference count of the request. if it reaches 0, we either
902  * put it into history list, or free it immediately.
903  */
904 void ptlrpc_server_drop_request(struct ptlrpc_request *req)
905 {
906         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
907         struct ptlrpc_service_part        *svcpt = rqbd->rqbd_svcpt;
908         struct ptlrpc_service             *svc = svcpt->scp_service;
909         int                                refcount;
910         struct list_head                          *tmp;
911         struct list_head                          *nxt;
912
913         if (!atomic_dec_and_test(&req->rq_refcount))
914                 return;
915
916         if (req->rq_session.lc_state == LCS_ENTERED) {
917                 lu_context_exit(&req->rq_session);
918                 lu_context_fini(&req->rq_session);
919         }
920
921         if (req->rq_at_linked) {
922                 spin_lock(&svcpt->scp_at_lock);
923                 /*
924                  * recheck with lock, in case it's unlinked by
925                  * ptlrpc_at_check_timed()
926                  */
927                 if (likely(req->rq_at_linked))
928                         ptlrpc_at_remove_timed(req);
929                 spin_unlock(&svcpt->scp_at_lock);
930         }
931
932         LASSERT(list_empty(&req->rq_timed_list));
933
934         /* finalize request */
935         if (req->rq_export) {
936                 class_export_put(req->rq_export);
937                 req->rq_export = NULL;
938         }
939
940         spin_lock(&svcpt->scp_lock);
941
942         list_add(&req->rq_list, &rqbd->rqbd_reqs);
943
944         refcount = --(rqbd->rqbd_refcount);
945         if (refcount == 0) {
946                 /* request buffer is now idle: add to history */
947                 list_del(&rqbd->rqbd_list);
948
949                 list_add_tail(&rqbd->rqbd_list, &svcpt->scp_hist_rqbds);
950                 svcpt->scp_hist_nrqbds++;
951
952                 /*
953                  * cull some history?
954                  * I expect only about 1 or 2 rqbds need to be recycled here
955                  */
956                 while (svcpt->scp_hist_nrqbds > svc->srv_hist_nrqbds_cpt_max) {
957                         rqbd = list_entry(svcpt->scp_hist_rqbds.next,
958                                           struct ptlrpc_request_buffer_desc,
959                                           rqbd_list);
960
961                         list_del(&rqbd->rqbd_list);
962                         svcpt->scp_hist_nrqbds--;
963
964                         /*
965                          * remove rqbd's reqs from svc's req history while
966                          * I've got the service lock
967                          */
968                         list_for_each(tmp, &rqbd->rqbd_reqs) {
969                                 req = list_entry(tmp, struct ptlrpc_request,
970                                                  rq_list);
971                                 /* Track the highest culled req seq */
972                                 if (req->rq_history_seq >
973                                     svcpt->scp_hist_seq_culled) {
974                                         svcpt->scp_hist_seq_culled =
975                                                 req->rq_history_seq;
976                                 }
977                                 list_del(&req->rq_history_list);
978                         }
979
980                         spin_unlock(&svcpt->scp_lock);
981
982                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
983                                 req = list_entry(rqbd->rqbd_reqs.next,
984                                                  struct ptlrpc_request,
985                                                  rq_list);
986                                 list_del(&req->rq_list);
987                                 ptlrpc_server_free_request(req);
988                         }
989
990                         spin_lock(&svcpt->scp_lock);
991                         /*
992                          * now all reqs including the embedded req has been
993                          * disposed, schedule request buffer for re-use
994                          * or free it to drain some in excess.
995                          */
996                         LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) == 0);
997                         if (svcpt->scp_nrqbds_posted >=
998                             svc->srv_nbuf_per_group ||
999                             (svc->srv_nrqbds_max != 0 &&
1000                              svcpt->scp_nrqbds_total > svc->srv_nrqbds_max) ||
1001                             test_req_buffer_pressure) {
1002                                 /* like in ptlrpc_free_rqbd() */
1003                                 svcpt->scp_nrqbds_total--;
1004                                 OBD_FREE_LARGE(rqbd->rqbd_buffer,
1005                                                svc->srv_buf_size);
1006                                 OBD_FREE_PTR(rqbd);
1007                         } else {
1008                                 list_add_tail(&rqbd->rqbd_list,
1009                                               &svcpt->scp_rqbd_idle);
1010                         }
1011                 }
1012
1013                 spin_unlock(&svcpt->scp_lock);
1014         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
1015                 /* If we are low on memory, we are not interested in history */
1016                 list_del(&req->rq_list);
1017                 list_del_init(&req->rq_history_list);
1018
1019                 /* Track the highest culled req seq */
1020                 if (req->rq_history_seq > svcpt->scp_hist_seq_culled)
1021                         svcpt->scp_hist_seq_culled = req->rq_history_seq;
1022
1023                 spin_unlock(&svcpt->scp_lock);
1024
1025                 ptlrpc_server_free_request(req);
1026         } else {
1027                 spin_unlock(&svcpt->scp_lock);
1028         }
1029 }
1030
1031 /** Change request export and move hp request from old export to new */
1032 void ptlrpc_request_change_export(struct ptlrpc_request *req,
1033                                   struct obd_export *export)
1034 {
1035         if (req->rq_export != NULL) {
1036                 LASSERT(!list_empty(&req->rq_exp_list));
1037                 /* remove rq_exp_list from last export */
1038                 spin_lock(&req->rq_export->exp_rpc_lock);
1039                 list_del_init(&req->rq_exp_list);
1040                 spin_unlock(&req->rq_export->exp_rpc_lock);
1041                 /*
1042                  * export has one reference already, so it`s safe to
1043                  * add req to export queue here and get another
1044                  * reference for request later
1045                  */
1046                 spin_lock(&export->exp_rpc_lock);
1047                 if (req->rq_ops != NULL) /* hp request */
1048                         list_add(&req->rq_exp_list, &export->exp_hp_rpcs);
1049                 else
1050                         list_add(&req->rq_exp_list, &export->exp_reg_rpcs);
1051                 spin_unlock(&export->exp_rpc_lock);
1052
1053                 class_export_rpc_dec(req->rq_export);
1054                 class_export_put(req->rq_export);
1055         }
1056
1057         /* request takes one export refcount */
1058         req->rq_export = class_export_get(export);
1059         class_export_rpc_inc(export);
1060
1061         return;
1062 }
1063
1064 /**
1065  * to finish a request: stop sending more early replies, and release
1066  * the request.
1067  */
1068 static void ptlrpc_server_finish_request(struct ptlrpc_service_part *svcpt,
1069                                          struct ptlrpc_request *req)
1070 {
1071         ptlrpc_server_hpreq_fini(req);
1072
1073         ptlrpc_server_drop_request(req);
1074 }
1075
1076 /**
1077  * to finish an active request: stop sending more early replies, and release
1078  * the request. should be called after we finished handling the request.
1079  */
1080 static void ptlrpc_server_finish_active_request(
1081                                         struct ptlrpc_service_part *svcpt,
1082                                         struct ptlrpc_request *req)
1083 {
1084         spin_lock(&svcpt->scp_req_lock);
1085         ptlrpc_nrs_req_stop_nolock(req);
1086         svcpt->scp_nreqs_active--;
1087         if (req->rq_hp)
1088                 svcpt->scp_nhreqs_active--;
1089         spin_unlock(&svcpt->scp_req_lock);
1090
1091         ptlrpc_nrs_req_finalize(req);
1092
1093         if (req->rq_export != NULL)
1094                 class_export_rpc_dec(req->rq_export);
1095
1096         ptlrpc_server_finish_request(svcpt, req);
1097 }
1098
1099 /**
1100  * This function makes sure dead exports are evicted in a timely manner.
1101  * This function is only called when some export receives a message (i.e.,
1102  * the network is up.)
1103  */
1104 void ptlrpc_update_export_timer(struct obd_export *exp, time64_t extra_delay)
1105 {
1106         struct obd_export *oldest_exp;
1107         time64_t oldest_time, new_time;
1108
1109         ENTRY;
1110
1111         LASSERT(exp);
1112
1113         /*
1114          * Compensate for slow machines, etc, by faking our request time
1115          * into the future.  Although this can break the strict time-ordering
1116          * of the list, we can be really lazy here - we don't have to evict
1117          * at the exact right moment.  Eventually, all silent exports
1118          * will make it to the top of the list.
1119          */
1120
1121         /* Do not pay attention on 1sec or smaller renewals. */
1122         new_time = ktime_get_real_seconds() + extra_delay;
1123         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
1124                 RETURN_EXIT;
1125
1126         exp->exp_last_request_time = new_time;
1127
1128         /*
1129          * exports may get disconnected from the chain even though the
1130          * export has references, so we must keep the spin lock while
1131          * manipulating the lists
1132          */
1133         spin_lock(&exp->exp_obd->obd_dev_lock);
1134
1135         if (list_empty(&exp->exp_obd_chain_timed)) {
1136                 /* this one is not timed */
1137                 spin_unlock(&exp->exp_obd->obd_dev_lock);
1138                 RETURN_EXIT;
1139         }
1140
1141         list_move_tail(&exp->exp_obd_chain_timed,
1142                        &exp->exp_obd->obd_exports_timed);
1143
1144         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
1145                                 struct obd_export, exp_obd_chain_timed);
1146         oldest_time = oldest_exp->exp_last_request_time;
1147         spin_unlock(&exp->exp_obd->obd_dev_lock);
1148
1149         if (exp->exp_obd->obd_recovering) {
1150                 /* be nice to everyone during recovery */
1151                 EXIT;
1152                 return;
1153         }
1154
1155         /* Note - racing to start/reset the obd_eviction timer is safe */
1156         if (exp->exp_obd->obd_eviction_timer == 0) {
1157                 /* Check if the oldest entry is expired. */
1158                 if (ktime_get_real_seconds() >
1159                     oldest_time + PING_EVICT_TIMEOUT + extra_delay) {
1160                         /*
1161                          * We need a second timer, in case the net was down and
1162                          * it just came back. Since the pinger may skip every
1163                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
1164                          * we better wait for 3.
1165                          */
1166                         exp->exp_obd->obd_eviction_timer =
1167                                 ktime_get_real_seconds() + 3 * PING_INTERVAL;
1168                         CDEBUG(D_HA, "%s: Think about evicting %s from %lld\n",
1169                                exp->exp_obd->obd_name,
1170                                obd_export_nid2str(oldest_exp), oldest_time);
1171                 }
1172         } else {
1173                 if (ktime_get_real_seconds() >
1174                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
1175                         /*
1176                          * The evictor won't evict anyone who we've heard from
1177                          * recently, so we don't have to check before we start
1178                          * it.
1179                          */
1180                         if (!ping_evictor_wake(exp))
1181                                 exp->exp_obd->obd_eviction_timer = 0;
1182                 }
1183         }
1184
1185         EXIT;
1186 }
1187
1188 /**
1189  * Sanity check request \a req.
1190  * Return 0 if all is ok, error code otherwise.
1191  */
1192 static int ptlrpc_check_req(struct ptlrpc_request *req)
1193 {
1194         struct obd_device *obd = req->rq_export->exp_obd;
1195         int rc = 0;
1196
1197         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
1198                      req->rq_export->exp_conn_cnt)) {
1199                 DEBUG_REQ(D_RPCTRACE, req,
1200                           "DROPPING req from old connection %d < %d",
1201                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
1202                           req->rq_export->exp_conn_cnt);
1203                 return -EEXIST;
1204         }
1205         if (unlikely(obd == NULL || obd->obd_fail)) {
1206                 /*
1207                  * Failing over, don't handle any more reqs,
1208                  * send error response instead.
1209                  */
1210                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
1211                         req, (obd != NULL) ? obd->obd_name : "unknown");
1212                 rc = -ENODEV;
1213         } else if (lustre_msg_get_flags(req->rq_reqmsg) &
1214                    (MSG_REPLAY | MSG_REQ_REPLAY_DONE) &&
1215                    !obd->obd_recovering) {
1216                 DEBUG_REQ(D_ERROR, req,
1217                           "Invalid replay without recovery");
1218                 class_fail_export(req->rq_export);
1219                 rc = -ENODEV;
1220         } else if (lustre_msg_get_transno(req->rq_reqmsg) != 0 &&
1221                    !obd->obd_recovering) {
1222                 DEBUG_REQ(D_ERROR, req,
1223                           "Invalid req with transno %llu without recovery",
1224                           lustre_msg_get_transno(req->rq_reqmsg));
1225                 class_fail_export(req->rq_export);
1226                 rc = -ENODEV;
1227         }
1228
1229         if (unlikely(rc < 0)) {
1230                 req->rq_status = rc;
1231                 ptlrpc_error(req);
1232         }
1233         return rc;
1234 }
1235
1236 static void ptlrpc_at_set_timer(struct ptlrpc_service_part *svcpt)
1237 {
1238         struct ptlrpc_at_array *array = &svcpt->scp_at_array;
1239         time64_t next;
1240
1241         if (array->paa_count == 0) {
1242                 del_timer(&svcpt->scp_at_timer);
1243                 return;
1244         }
1245
1246         /* Set timer for closest deadline */
1247         next = array->paa_deadline - ktime_get_real_seconds() -
1248                at_early_margin;
1249         if (next <= 0) {
1250                 ptlrpc_at_timer(cfs_timer_cb_arg(svcpt, scp_at_timer));
1251         } else {
1252                 mod_timer(&svcpt->scp_at_timer,
1253                           jiffies + nsecs_to_jiffies(next * NSEC_PER_SEC));
1254                 CDEBUG(D_INFO, "armed %s at %+llds\n",
1255                        svcpt->scp_service->srv_name, next);
1256         }
1257 }
1258
1259 /* Add rpc to early reply check list */
1260 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
1261 {
1262         struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
1263         struct ptlrpc_at_array *array = &svcpt->scp_at_array;
1264         struct ptlrpc_request *rq = NULL;
1265         __u32 index;
1266
1267         if (AT_OFF)
1268                 return(0);
1269
1270         if (req->rq_no_reply)
1271                 return 0;
1272
1273         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
1274                 return(-ENOSYS);
1275
1276         spin_lock(&svcpt->scp_at_lock);
1277         LASSERT(list_empty(&req->rq_timed_list));
1278
1279         div_u64_rem(req->rq_deadline, array->paa_size, &index);
1280         if (array->paa_reqs_count[index] > 0) {
1281                 /*
1282                  * latest rpcs will have the latest deadlines in the list,
1283                  * so search backward.
1284                  */
1285                 list_for_each_entry_reverse(rq, &array->paa_reqs_array[index],
1286                                             rq_timed_list) {
1287                         if (req->rq_deadline >= rq->rq_deadline) {
1288                                 list_add(&req->rq_timed_list,
1289                                          &rq->rq_timed_list);
1290                                 break;
1291                         }
1292                 }
1293         }
1294
1295         /* Add the request at the head of the list */
1296         if (list_empty(&req->rq_timed_list))
1297                 list_add(&req->rq_timed_list, &array->paa_reqs_array[index]);
1298
1299         spin_lock(&req->rq_lock);
1300         req->rq_at_linked = 1;
1301         spin_unlock(&req->rq_lock);
1302         req->rq_at_index = index;
1303         array->paa_reqs_count[index]++;
1304         array->paa_count++;
1305         if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
1306                 array->paa_deadline = req->rq_deadline;
1307                 ptlrpc_at_set_timer(svcpt);
1308         }
1309         spin_unlock(&svcpt->scp_at_lock);
1310
1311         return 0;
1312 }
1313
1314 static void ptlrpc_at_remove_timed(struct ptlrpc_request *req)
1315 {
1316         struct ptlrpc_at_array *array;
1317
1318         array = &req->rq_rqbd->rqbd_svcpt->scp_at_array;
1319
1320         /* NB: must call with hold svcpt::scp_at_lock */
1321         LASSERT(!list_empty(&req->rq_timed_list));
1322         list_del_init(&req->rq_timed_list);
1323
1324         spin_lock(&req->rq_lock);
1325         req->rq_at_linked = 0;
1326         spin_unlock(&req->rq_lock);
1327
1328         array->paa_reqs_count[req->rq_at_index]--;
1329         array->paa_count--;
1330 }
1331
1332 /*
1333  * Attempt to extend the request deadline by sending an early reply to the
1334  * client.
1335  */
1336 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req)
1337 {
1338         struct ptlrpc_service_part *svcpt = req->rq_rqbd->rqbd_svcpt;
1339         struct ptlrpc_request *reqcopy;
1340         struct lustre_msg *reqmsg;
1341         time64_t olddl = req->rq_deadline - ktime_get_real_seconds();
1342         time64_t newdl;
1343         int rc;
1344
1345         ENTRY;
1346
1347         if (CFS_FAIL_CHECK(OBD_FAIL_TGT_REPLAY_RECONNECT)) {
1348                 /* don't send early reply */
1349                 RETURN(1);
1350         }
1351
1352         /*
1353          * deadline is when the client expects us to reply, margin is the
1354          * difference between clients' and servers' expectations
1355          */
1356         DEBUG_REQ(D_ADAPTTO, req,
1357                   "%ssending early reply (deadline %+llds, margin %+llds) for %d+%d",
1358                   AT_OFF ? "AT off - not " : "",
1359                   (s64)olddl, (s64)(olddl - at_get(&svcpt->scp_at_estimate)),
1360                   at_get(&svcpt->scp_at_estimate), at_extra);
1361
1362         if (AT_OFF)
1363                 RETURN(0);
1364
1365         if (olddl < 0) {
1366                 DEBUG_REQ(D_WARNING, req,
1367                           "Already past deadline (%+llds), not sending early reply. Consider increasing at_early_margin (%d)?",
1368                           (s64)olddl, at_early_margin);
1369
1370                 /* Return an error so we're not re-added to the timed list. */
1371                 RETURN(-ETIMEDOUT);
1372         }
1373
1374         if ((lustre_msghdr_get_flags(req->rq_reqmsg) &
1375              MSGHDR_AT_SUPPORT) == 0) {
1376                 DEBUG_REQ(D_INFO, req,
1377                           "Wanted to ask client for more time, but no AT support");
1378                 RETURN(-ENOSYS);
1379         }
1380
1381         if (req->rq_export &&
1382             lustre_msg_get_flags(req->rq_reqmsg) &
1383             (MSG_REPLAY | MSG_REQ_REPLAY_DONE | MSG_LOCK_REPLAY_DONE)) {
1384                 struct obd_device *obd_exp = req->rq_export->exp_obd;
1385
1386                 /*
1387                  * During recovery, we don't want to send too many early
1388                  * replies, but on the other hand we want to make sure the
1389                  * client has enough time to resend if the rpc is lost. So
1390                  * during the recovery period send at least 4 early replies,
1391                  * spacing them every at_extra if we can. at_estimate should
1392                  * always equal this fixed value during recovery.
1393                  */
1394
1395                 /*
1396                  * Don't account request processing time into AT history
1397                  * during recovery, it is not service time we need but
1398                  * includes also waiting time for recovering clients
1399                  */
1400                 newdl = min_t(time64_t, at_extra,
1401                               obd_exp->obd_recovery_timeout / 4) +
1402                         ktime_get_real_seconds();
1403         } else {
1404                 /*
1405                  * We want to extend the request deadline by at_extra seconds,
1406                  * so we set our service estimate to reflect how much time has
1407                  * passed since this request arrived plus an additional
1408                  * at_extra seconds. The client will calculate the new deadline
1409                  * based on this service estimate (plus some additional time to
1410                  * account for network latency). See ptlrpc_at_recv_early_reply
1411                  */
1412                 at_measured(&svcpt->scp_at_estimate, at_extra +
1413                             ktime_get_real_seconds() -
1414                             req->rq_arrival_time.tv_sec);
1415                 newdl = req->rq_arrival_time.tv_sec +
1416                         at_get(&svcpt->scp_at_estimate);
1417         }
1418
1419         /*
1420          * Check to see if we've actually increased the deadline -
1421          * we may be past adaptive_max
1422          */
1423         if (req->rq_deadline >= newdl) {
1424                 DEBUG_REQ(D_WARNING, req, "Couldn't add any time (%lld/%lld), not sending early reply\n",
1425                           (s64)olddl, (s64)(newdl - ktime_get_real_seconds()));
1426                 RETURN(-ETIMEDOUT);
1427         }
1428
1429         reqcopy = ptlrpc_request_cache_alloc(GFP_NOFS);
1430         if (reqcopy == NULL)
1431                 RETURN(-ENOMEM);
1432         OBD_ALLOC_LARGE(reqmsg, req->rq_reqlen);
1433         if (!reqmsg)
1434                 GOTO(out_free, rc = -ENOMEM);
1435
1436         *reqcopy = *req;
1437         reqcopy->rq_reply_state = NULL;
1438         reqcopy->rq_rep_swab_mask = 0;
1439         reqcopy->rq_pack_bulk = 0;
1440         reqcopy->rq_pack_udesc = 0;
1441         reqcopy->rq_packed_final = 0;
1442         sptlrpc_svc_ctx_addref(reqcopy);
1443         /* We only need the reqmsg for the magic */
1444         reqcopy->rq_reqmsg = reqmsg;
1445         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
1446
1447         /*
1448          * tgt_brw_read() and tgt_brw_write() may have decided not to reply.
1449          * Without this check, we would fail the rq_no_reply assertion in
1450          * ptlrpc_send_reply().
1451          */
1452         if (reqcopy->rq_no_reply)
1453                 GOTO(out, rc = -ETIMEDOUT);
1454
1455         LASSERT(atomic_read(&req->rq_refcount));
1456         /** if it is last refcount then early reply isn't needed */
1457         if (atomic_read(&req->rq_refcount) == 1) {
1458                 DEBUG_REQ(D_ADAPTTO, reqcopy,
1459                           "Normal reply already sent out, abort sending early reply\n");
1460                 GOTO(out, rc = -EINVAL);
1461         }
1462
1463         /* Connection ref */
1464         reqcopy->rq_export = class_conn2export(
1465                         lustre_msg_get_handle(reqcopy->rq_reqmsg));
1466         if (reqcopy->rq_export == NULL)
1467                 GOTO(out, rc = -ENODEV);
1468
1469         /* RPC ref */
1470         class_export_rpc_inc(reqcopy->rq_export);
1471         if (reqcopy->rq_export->exp_obd &&
1472             reqcopy->rq_export->exp_obd->obd_fail)
1473                 GOTO(out_put, rc = -ENODEV);
1474
1475         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
1476         if (rc)
1477                 GOTO(out_put, rc);
1478
1479         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
1480
1481         if (!rc) {
1482                 /* Adjust our own deadline to what we told the client */
1483                 req->rq_deadline = newdl;
1484                 req->rq_early_count++; /* number sent, server side */
1485         } else {
1486                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
1487         }
1488
1489         /*
1490          * Free the (early) reply state from lustre_pack_reply.
1491          * (ptlrpc_send_reply takes it's own rs ref, so this is safe here)
1492          */
1493         ptlrpc_req_drop_rs(reqcopy);
1494
1495 out_put:
1496         class_export_rpc_dec(reqcopy->rq_export);
1497         class_export_put(reqcopy->rq_export);
1498 out:
1499         sptlrpc_svc_ctx_decref(reqcopy);
1500         OBD_FREE_LARGE(reqmsg, req->rq_reqlen);
1501 out_free:
1502         ptlrpc_request_cache_free(reqcopy);
1503         RETURN(rc);
1504 }
1505
1506 /*
1507  * Send early replies to everybody expiring within at_early_margin
1508  * asking for at_extra time
1509  */
1510 static int ptlrpc_at_check_timed(struct ptlrpc_service_part *svcpt)
1511 {
1512         struct ptlrpc_at_array *array = &svcpt->scp_at_array;
1513         struct ptlrpc_request *rq, *n;
1514         struct list_head work_list;
1515         __u32 index, count;
1516         time64_t deadline;
1517         time64_t now = ktime_get_real_seconds();
1518         s64 delay;
1519         int first, counter = 0;
1520
1521         ENTRY;
1522         spin_lock(&svcpt->scp_at_lock);
1523         if (svcpt->scp_at_check == 0) {
1524                 spin_unlock(&svcpt->scp_at_lock);
1525                 RETURN(0);
1526         }
1527         delay = ktime_ms_delta(ktime_get(), svcpt->scp_at_checktime);
1528         svcpt->scp_at_check = 0;
1529
1530         if (array->paa_count == 0) {
1531                 spin_unlock(&svcpt->scp_at_lock);
1532                 RETURN(0);
1533         }
1534
1535         /* The timer went off, but maybe the nearest rpc already completed. */
1536         first = array->paa_deadline - now;
1537         if (first > at_early_margin) {
1538                 /* We've still got plenty of time.  Reset the timer. */
1539                 ptlrpc_at_set_timer(svcpt);
1540                 spin_unlock(&svcpt->scp_at_lock);
1541                 RETURN(0);
1542         }
1543
1544         /*
1545          * We're close to a timeout, and we don't know how much longer the
1546          * server will take. Send early replies to everyone expiring soon.
1547          */
1548         INIT_LIST_HEAD(&work_list);
1549         deadline = -1;
1550         div_u64_rem(array->paa_deadline, array->paa_size, &index);
1551         count = array->paa_count;
1552         while (count > 0) {
1553                 count -= array->paa_reqs_count[index];
1554                 list_for_each_entry_safe(rq, n,
1555                                          &array->paa_reqs_array[index],
1556                                          rq_timed_list) {
1557                         if (rq->rq_deadline > now + at_early_margin) {
1558                                 /* update the earliest deadline */
1559                                 if (deadline == -1 ||
1560                                     rq->rq_deadline < deadline)
1561                                         deadline = rq->rq_deadline;
1562                                 break;
1563                         }
1564
1565                         /**
1566                          * ptlrpc_server_drop_request() may drop
1567                          * refcount to 0 already. Let's check this and
1568                          * don't add entry to work_list
1569                          */
1570                         if (likely(atomic_inc_not_zero(&rq->rq_refcount))) {
1571                                 ptlrpc_at_remove_timed(rq);
1572                                 list_add(&rq->rq_timed_list, &work_list);
1573                         } else {
1574                                 ptlrpc_at_remove_timed(rq);
1575                         }
1576
1577                         counter++;
1578                 }
1579
1580                 if (++index >= array->paa_size)
1581                         index = 0;
1582         }
1583         array->paa_deadline = deadline;
1584         /* we have a new earliest deadline, restart the timer */
1585         ptlrpc_at_set_timer(svcpt);
1586
1587         spin_unlock(&svcpt->scp_at_lock);
1588
1589         CDEBUG(D_ADAPTTO,
1590                "timeout in %+ds, asking for %d secs on %d early replies\n",
1591                first, at_extra, counter);
1592         if (first < 0) {
1593                 /*
1594                  * We're already past request deadlines before we even get a
1595                  * chance to send early replies
1596                  */
1597                 LCONSOLE_WARN("%s: This server is not able to keep up with request traffic (cpu-bound).\n",
1598                               svcpt->scp_service->srv_name);
1599                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, delay=%lld\n",
1600                       counter, svcpt->scp_nreqs_incoming,
1601                       svcpt->scp_nreqs_active,
1602                       at_get(&svcpt->scp_at_estimate), delay);
1603         }
1604
1605         /*
1606          * we took additional refcount so entries can't be deleted from list, no
1607          * locking is needed
1608          */
1609         while (!list_empty(&work_list)) {
1610                 rq = list_entry(work_list.next, struct ptlrpc_request,
1611                                 rq_timed_list);
1612                 list_del_init(&rq->rq_timed_list);
1613
1614                 if (ptlrpc_at_send_early_reply(rq) == 0)
1615                         ptlrpc_at_add_timed(rq);
1616
1617                 ptlrpc_server_drop_request(rq);
1618         }
1619
1620         RETURN(1); /* return "did_something" for liblustre */
1621 }
1622
1623 /*
1624  * Check if we are already handling earlier incarnation of this request.
1625  * Called under &req->rq_export->exp_rpc_lock locked
1626  */
1627 static struct ptlrpc_request*
1628 ptlrpc_server_check_resend_in_progress(struct ptlrpc_request *req)
1629 {
1630         struct ptlrpc_request *tmp = NULL;
1631
1632         if (!(lustre_msg_get_flags(req->rq_reqmsg) & MSG_RESENT) ||
1633             (atomic_read(&req->rq_export->exp_rpc_count) == 0))
1634                 return NULL;
1635
1636         /*
1637          * bulk request are aborted upon reconnect, don't try to
1638          * find a match
1639          */
1640         if (req->rq_bulk_write || req->rq_bulk_read)
1641                 return NULL;
1642
1643         /*
1644          * This list should not be longer than max_requests in
1645          * flights on the client, so it is not all that long.
1646          * Also we only hit this codepath in case of a resent
1647          * request which makes it even more rarely hit
1648          */
1649         list_for_each_entry(tmp, &req->rq_export->exp_reg_rpcs,
1650                                 rq_exp_list) {
1651                 /* Found duplicate one */
1652                 if (tmp->rq_xid == req->rq_xid)
1653                         goto found;
1654         }
1655         list_for_each_entry(tmp, &req->rq_export->exp_hp_rpcs,
1656                                 rq_exp_list) {
1657                 /* Found duplicate one */
1658                 if (tmp->rq_xid == req->rq_xid)
1659                         goto found;
1660         }
1661         return NULL;
1662
1663 found:
1664         DEBUG_REQ(D_HA, req, "Found duplicate req in processing");
1665         DEBUG_REQ(D_HA, tmp, "Request being processed");
1666         return tmp;
1667 }
1668
1669 /**
1670  * Check if a request should be assigned with a high priority.
1671  *
1672  * \retval      < 0: error occurred
1673  *                0: normal RPC request
1674  *               +1: high priority request
1675  */
1676 static int ptlrpc_server_hpreq_init(struct ptlrpc_service_part *svcpt,
1677                                     struct ptlrpc_request *req)
1678 {
1679         int rc = 0;
1680
1681         ENTRY;
1682         if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL) {
1683                 rc = svcpt->scp_service->srv_ops.so_hpreq_handler(req);
1684                 if (rc < 0)
1685                         RETURN(rc);
1686
1687                 LASSERT(rc == 0);
1688         }
1689
1690         if (req->rq_export != NULL && req->rq_ops != NULL) {
1691                 /*
1692                  * Perform request specific check. We should do this
1693                  * check before the request is added into exp_hp_rpcs
1694                  * list otherwise it may hit swab race at LU-1044.
1695                  */
1696                 if (req->rq_ops->hpreq_check != NULL) {
1697                         rc = req->rq_ops->hpreq_check(req);
1698                         if (rc == -ESTALE) {
1699                                 req->rq_status = rc;
1700                                 ptlrpc_error(req);
1701                         }
1702                         /*
1703                          * can only return error,
1704                          * 0 for normal request,
1705                          * or 1 for high priority request
1706                          */
1707                         LASSERT(rc <= 1);
1708                 }
1709         }
1710
1711         RETURN(rc);
1712 }
1713
1714 /** Remove the request from the export list. */
1715 static void ptlrpc_server_hpreq_fini(struct ptlrpc_request *req)
1716 {
1717         ENTRY;
1718         if (req->rq_export) {
1719                 /*
1720                  * refresh lock timeout again so that client has more
1721                  * room to send lock cancel RPC.
1722                  */
1723                 if (req->rq_ops && req->rq_ops->hpreq_fini)
1724                         req->rq_ops->hpreq_fini(req);
1725
1726                 spin_lock(&req->rq_export->exp_rpc_lock);
1727                 list_del_init(&req->rq_exp_list);
1728                 spin_unlock(&req->rq_export->exp_rpc_lock);
1729         }
1730         EXIT;
1731 }
1732
1733 static int ptlrpc_hpreq_check(struct ptlrpc_request *req)
1734 {
1735         return 1;
1736 }
1737
1738 static struct ptlrpc_hpreq_ops ptlrpc_hpreq_common = {
1739         .hpreq_check       = ptlrpc_hpreq_check,
1740 };
1741
1742 /* Hi-Priority RPC check by RPC operation code. */
1743 int ptlrpc_hpreq_handler(struct ptlrpc_request *req)
1744 {
1745         int opc = lustre_msg_get_opc(req->rq_reqmsg);
1746
1747         /*
1748          * Check for export to let only reconnects for not yet evicted
1749          * export to become a HP rpc.
1750          */
1751         if ((req->rq_export != NULL) &&
1752             (opc == OBD_PING || opc == MDS_CONNECT || opc == OST_CONNECT))
1753                 req->rq_ops = &ptlrpc_hpreq_common;
1754
1755         return 0;
1756 }
1757 EXPORT_SYMBOL(ptlrpc_hpreq_handler);
1758
1759 static int ptlrpc_server_request_add(struct ptlrpc_service_part *svcpt,
1760                                      struct ptlrpc_request *req)
1761 {
1762         int rc;
1763         bool hp;
1764         struct ptlrpc_request *orig;
1765
1766         ENTRY;
1767
1768         rc = ptlrpc_server_hpreq_init(svcpt, req);
1769         if (rc < 0)
1770                 RETURN(rc);
1771
1772         hp = rc > 0;
1773         ptlrpc_nrs_req_initialize(svcpt, req, hp);
1774
1775         if (req->rq_export != NULL) {
1776                 struct obd_export *exp = req->rq_export;
1777
1778                 /*
1779                  * do search for duplicated xid and the adding to the list
1780                  * atomically
1781                  */
1782                 spin_lock_bh(&exp->exp_rpc_lock);
1783                 orig = ptlrpc_server_check_resend_in_progress(req);
1784                 if (orig && likely(atomic_inc_not_zero(&orig->rq_refcount))) {
1785                         bool linked;
1786
1787                         spin_unlock_bh(&exp->exp_rpc_lock);
1788
1789                         /*
1790                          * When the client resend request and the server has
1791                          * the previous copy of it, we need to update deadlines,
1792                          * to be sure that the client and the server have equal
1793                          *  request deadlines.
1794                          */
1795
1796                         spin_lock(&orig->rq_rqbd->rqbd_svcpt->scp_at_lock);
1797                         linked = orig->rq_at_linked;
1798                         if (likely(linked))
1799                                 ptlrpc_at_remove_timed(orig);
1800                         spin_unlock(&orig->rq_rqbd->rqbd_svcpt->scp_at_lock);
1801                         orig->rq_deadline = req->rq_deadline;
1802                         if (likely(linked))
1803                                 ptlrpc_at_add_timed(orig);
1804                         ptlrpc_server_drop_request(orig);
1805                         ptlrpc_nrs_req_finalize(req);
1806                         RETURN(-EBUSY);
1807                 }
1808
1809                 if (hp || req->rq_ops != NULL)
1810                         list_add(&req->rq_exp_list, &exp->exp_hp_rpcs);
1811                 else
1812                         list_add(&req->rq_exp_list, &exp->exp_reg_rpcs);
1813                 spin_unlock_bh(&exp->exp_rpc_lock);
1814         }
1815
1816         /*
1817          * the current thread is not the processing thread for this request
1818          * since that, but request is in exp_hp_list and can be find there.
1819          * Remove all relations between request and old thread.
1820          */
1821         req->rq_svc_thread->t_env->le_ses = NULL;
1822         req->rq_svc_thread = NULL;
1823         req->rq_session.lc_thread = NULL;
1824
1825         ptlrpc_nrs_req_add(svcpt, req, hp);
1826
1827         RETURN(0);
1828 }
1829
1830 /**
1831  * Allow to handle high priority request
1832  * User can call it w/o any lock but need to hold
1833  * ptlrpc_service_part::scp_req_lock to get reliable result
1834  */
1835 static bool ptlrpc_server_allow_high(struct ptlrpc_service_part *svcpt,
1836                                      bool force)
1837 {
1838         int running = svcpt->scp_nthrs_running;
1839
1840         if (!nrs_svcpt_has_hp(svcpt))
1841                 return false;
1842
1843         if (force)
1844                 return true;
1845
1846         if (ptlrpc_nrs_req_throttling_nolock(svcpt, true))
1847                 return false;
1848
1849         if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1850                      CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1851                 /* leave just 1 thread for normal RPCs */
1852                 running = PTLRPC_NTHRS_INIT;
1853                 if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1854                         running += 1;
1855         }
1856
1857         if (svcpt->scp_nreqs_active >= running - 1)
1858                 return false;
1859
1860         if (svcpt->scp_nhreqs_active == 0)
1861                 return true;
1862
1863         return !ptlrpc_nrs_req_pending_nolock(svcpt, false) ||
1864                svcpt->scp_hreq_count < svcpt->scp_service->srv_hpreq_ratio;
1865 }
1866
1867 static bool ptlrpc_server_high_pending(struct ptlrpc_service_part *svcpt,
1868                                        bool force)
1869 {
1870         return ptlrpc_server_allow_high(svcpt, force) &&
1871                ptlrpc_nrs_req_pending_nolock(svcpt, true);
1872 }
1873
1874 /**
1875  * Only allow normal priority requests on a service that has a high-priority
1876  * queue if forced (i.e. cleanup), if there are other high priority requests
1877  * already being processed (i.e. those threads can service more high-priority
1878  * requests), or if there are enough idle threads that a later thread can do
1879  * a high priority request.
1880  * User can call it w/o any lock but need to hold
1881  * ptlrpc_service_part::scp_req_lock to get reliable result
1882  */
1883 static bool ptlrpc_server_allow_normal(struct ptlrpc_service_part *svcpt,
1884                                        bool force)
1885 {
1886         int running = svcpt->scp_nthrs_running;
1887
1888         if (unlikely(svcpt->scp_service->srv_req_portal == MDS_REQUEST_PORTAL &&
1889                      CFS_FAIL_PRECHECK(OBD_FAIL_PTLRPC_CANCEL_RESEND))) {
1890                 /* leave just 1 thread for normal RPCs */
1891                 running = PTLRPC_NTHRS_INIT;
1892                 if (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL)
1893                         running += 1;
1894         }
1895
1896         if (force)
1897                 return true;
1898
1899         if (ptlrpc_nrs_req_throttling_nolock(svcpt, false))
1900                 return false;
1901
1902         if (svcpt->scp_nreqs_active < running - 2)
1903                 return true;
1904
1905         if (svcpt->scp_nreqs_active >= running - 1)
1906                 return false;
1907
1908         return svcpt->scp_nhreqs_active > 0 || !nrs_svcpt_has_hp(svcpt);
1909 }
1910
1911 static bool ptlrpc_server_normal_pending(struct ptlrpc_service_part *svcpt,
1912                                          bool force)
1913 {
1914         return ptlrpc_server_allow_normal(svcpt, force) &&
1915                ptlrpc_nrs_req_pending_nolock(svcpt, false);
1916 }
1917
1918 /**
1919  * Returns true if there are requests available in incoming
1920  * request queue for processing and it is allowed to fetch them.
1921  * User can call it w/o any lock but need to hold ptlrpc_service::scp_req_lock
1922  * to get reliable result
1923  * \see ptlrpc_server_allow_normal
1924  * \see ptlrpc_server_allow high
1925  */
1926 static inline
1927 bool ptlrpc_server_request_pending(struct ptlrpc_service_part *svcpt,
1928                                    bool force)
1929 {
1930         return ptlrpc_server_high_pending(svcpt, force) ||
1931                ptlrpc_server_normal_pending(svcpt, force);
1932 }
1933
1934 /**
1935  * Fetch a request for processing from queue of unprocessed requests.
1936  * Favors high-priority requests.
1937  * Returns a pointer to fetched request.
1938  */
1939 static struct ptlrpc_request *
1940 ptlrpc_server_request_get(struct ptlrpc_service_part *svcpt, bool force)
1941 {
1942         struct ptlrpc_request *req = NULL;
1943
1944         ENTRY;
1945
1946         spin_lock(&svcpt->scp_req_lock);
1947
1948         if (ptlrpc_server_high_pending(svcpt, force)) {
1949                 req = ptlrpc_nrs_req_get_nolock(svcpt, true, force);
1950                 if (req != NULL) {
1951                         svcpt->scp_hreq_count++;
1952                         goto got_request;
1953                 }
1954         }
1955
1956         if (ptlrpc_server_normal_pending(svcpt, force)) {
1957                 req = ptlrpc_nrs_req_get_nolock(svcpt, false, force);
1958                 if (req != NULL) {
1959                         svcpt->scp_hreq_count = 0;
1960                         goto got_request;
1961                 }
1962         }
1963
1964         spin_unlock(&svcpt->scp_req_lock);
1965         RETURN(NULL);
1966
1967 got_request:
1968         svcpt->scp_nreqs_active++;
1969         if (req->rq_hp)
1970                 svcpt->scp_nhreqs_active++;
1971
1972         spin_unlock(&svcpt->scp_req_lock);
1973
1974         if (likely(req->rq_export))
1975                 class_export_rpc_inc(req->rq_export);
1976
1977         RETURN(req);
1978 }
1979
1980 /**
1981  * Handle freshly incoming reqs, add to timed early reply list,
1982  * pass on to regular request queue.
1983  * All incoming requests pass through here before getting into
1984  * ptlrpc_server_handle_req later on.
1985  */
1986 static int ptlrpc_server_handle_req_in(struct ptlrpc_service_part *svcpt,
1987                                        struct ptlrpc_thread *thread)
1988 {
1989         struct ptlrpc_service *svc = svcpt->scp_service;
1990         struct ptlrpc_request *req;
1991         __u32 deadline;
1992         int rc;
1993
1994         ENTRY;
1995
1996         spin_lock(&svcpt->scp_lock);
1997         if (list_empty(&svcpt->scp_req_incoming)) {
1998                 spin_unlock(&svcpt->scp_lock);
1999                 RETURN(0);
2000         }
2001
2002         req = list_entry(svcpt->scp_req_incoming.next,
2003                              struct ptlrpc_request, rq_list);
2004         list_del_init(&req->rq_list);
2005         svcpt->scp_nreqs_incoming--;
2006         /*
2007          * Consider this still a "queued" request as far as stats are
2008          * concerned
2009          */
2010         spin_unlock(&svcpt->scp_lock);
2011
2012         /* go through security check/transform */
2013         rc = sptlrpc_svc_unwrap_request(req);
2014         switch (rc) {
2015         case SECSVC_OK:
2016                 break;
2017         case SECSVC_COMPLETE:
2018                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
2019                 goto err_req;
2020         case SECSVC_DROP:
2021                 goto err_req;
2022         default:
2023                 LBUG();
2024         }
2025
2026         /*
2027          * for null-flavored rpc, msg has been unpacked by sptlrpc, although
2028          * redo it wouldn't be harmful.
2029          */
2030         if (SPTLRPC_FLVR_POLICY(req->rq_flvr.sf_rpc) != SPTLRPC_POLICY_NULL) {
2031                 rc = ptlrpc_unpack_req_msg(req, req->rq_reqlen);
2032                 if (rc != 0) {
2033                         CERROR("error unpacking request: ptl %d from %s x%llu\n",
2034                                svc->srv_req_portal, libcfs_id2str(req->rq_peer),
2035                                req->rq_xid);
2036                         goto err_req;
2037                 }
2038         }
2039
2040         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
2041         if (rc) {
2042                 CERROR("error unpacking ptlrpc body: ptl %d from %s x %llu\n",
2043                        svc->srv_req_portal, libcfs_id2str(req->rq_peer),
2044                        req->rq_xid);
2045                 goto err_req;
2046         }
2047
2048         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DROP_REQ_OPC) &&
2049             lustre_msg_get_opc(req->rq_reqmsg) == cfs_fail_val) {
2050                 CERROR("drop incoming rpc opc %u, x%llu\n",
2051                        cfs_fail_val, req->rq_xid);
2052                 goto err_req;
2053         }
2054
2055         rc = -EINVAL;
2056         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
2057                 CERROR("wrong packet type received (type=%u) from %s\n",
2058                        lustre_msg_get_type(req->rq_reqmsg),
2059                        libcfs_id2str(req->rq_peer));
2060                 goto err_req;
2061         }
2062
2063         switch (lustre_msg_get_opc(req->rq_reqmsg)) {
2064         case MDS_WRITEPAGE:
2065         case OST_WRITE:
2066         case OUT_UPDATE:
2067                 req->rq_bulk_write = 1;
2068                 break;
2069         case MDS_READPAGE:
2070         case OST_READ:
2071         case MGS_CONFIG_READ:
2072                 req->rq_bulk_read = 1;
2073                 break;
2074         }
2075
2076         CDEBUG(D_RPCTRACE, "got req x%llu\n", req->rq_xid);
2077
2078         req->rq_export = class_conn2export(
2079                 lustre_msg_get_handle(req->rq_reqmsg));
2080         if (req->rq_export) {
2081                 rc = ptlrpc_check_req(req);
2082                 if (rc == 0) {
2083                         rc = sptlrpc_target_export_check(req->rq_export, req);
2084                         if (rc)
2085                                 DEBUG_REQ(D_ERROR, req,
2086                                           "DROPPING req with illegal security flavor,");
2087                 }
2088
2089                 if (rc)
2090                         goto err_req;
2091                 ptlrpc_update_export_timer(req->rq_export, 0);
2092         }
2093
2094         /* req_in handling should/must be fast */
2095         if (ktime_get_real_seconds() - req->rq_arrival_time.tv_sec > 5)
2096                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling %llds",
2097                           (s64)(ktime_get_real_seconds() -
2098                                 req->rq_arrival_time.tv_sec));
2099
2100         /* Set rpc server deadline and add it to the timed list */
2101         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
2102                     MSGHDR_AT_SUPPORT) ?
2103                     /* The max time the client expects us to take */
2104                     lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
2105
2106         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
2107         if (unlikely(deadline == 0)) {
2108                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
2109                 goto err_req;
2110         }
2111
2112         /* Skip early reply */
2113         if (OBD_FAIL_PRECHECK(OBD_FAIL_MDS_RESEND))
2114                 req->rq_deadline += obd_timeout;
2115
2116         req->rq_svc_thread = thread;
2117         if (thread != NULL) {
2118                 /*
2119                  * initialize request session, it is needed for request
2120                  * processing by target
2121                  */
2122                 rc = lu_context_init(&req->rq_session, LCT_SERVER_SESSION |
2123                                                        LCT_NOREF);
2124                 if (rc) {
2125                         CERROR("%s: failure to initialize session: rc = %d\n",
2126                                thread->t_name, rc);
2127                         goto err_req;
2128                 }
2129                 req->rq_session.lc_thread = thread;
2130                 lu_context_enter(&req->rq_session);
2131                 thread->t_env->le_ses = &req->rq_session;
2132         }
2133
2134         ptlrpc_at_add_timed(req);
2135
2136         /* Move it over to the request processing queue */
2137         rc = ptlrpc_server_request_add(svcpt, req);
2138         if (rc)
2139                 GOTO(err_req, rc);
2140
2141         wake_up(&svcpt->scp_waitq);
2142         RETURN(1);
2143
2144 err_req:
2145         ptlrpc_server_finish_request(svcpt, req);
2146
2147         RETURN(1);
2148 }
2149
2150 /**
2151  * Main incoming request handling logic.
2152  * Calls handler function from service to do actual processing.
2153  */
2154 static int ptlrpc_server_handle_request(struct ptlrpc_service_part *svcpt,
2155                                         struct ptlrpc_thread *thread)
2156 {
2157         struct ptlrpc_service *svc = svcpt->scp_service;
2158         struct ptlrpc_request *request;
2159         ktime_t work_start;
2160         ktime_t work_end;
2161         ktime_t arrived;
2162         s64 timediff_usecs;
2163         s64 arrived_usecs;
2164         int fail_opc = 0;
2165
2166         ENTRY;
2167
2168         request = ptlrpc_server_request_get(svcpt, false);
2169         if (request == NULL)
2170                 RETURN(0);
2171
2172         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
2173                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
2174         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
2175                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
2176
2177         if (unlikely(fail_opc)) {
2178                 if (request->rq_export && request->rq_ops)
2179                         OBD_FAIL_TIMEOUT(fail_opc, 4);
2180         }
2181
2182         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
2183
2184         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
2185                 libcfs_debug_dumplog();
2186
2187         work_start = ktime_get_real();
2188         arrived = timespec64_to_ktime(request->rq_arrival_time);
2189         timediff_usecs = ktime_us_delta(work_start, arrived);
2190         if (likely(svc->srv_stats != NULL)) {
2191                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
2192                                     timediff_usecs);
2193                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
2194                                     svcpt->scp_nreqs_incoming);
2195                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
2196                                     svcpt->scp_nreqs_active);
2197                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
2198                                     at_get(&svcpt->scp_at_estimate));
2199         }
2200
2201         if (likely(request->rq_export)) {
2202                 if (unlikely(ptlrpc_check_req(request)))
2203                         goto put_conn;
2204                 ptlrpc_update_export_timer(request->rq_export,
2205                                            div_u64(timediff_usecs,
2206                                                    USEC_PER_SEC / 2));
2207         }
2208
2209         /*
2210          * Discard requests queued for longer than the deadline.
2211          * The deadline is increased if we send an early reply.
2212          */
2213         if (ktime_get_real_seconds() > request->rq_deadline) {
2214                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s: deadline %lld:%llds ago\n",
2215                           libcfs_id2str(request->rq_peer),
2216                           request->rq_deadline -
2217                           request->rq_arrival_time.tv_sec,
2218                           ktime_get_real_seconds() - request->rq_deadline);
2219                 goto put_conn;
2220         }
2221
2222         CDEBUG(D_RPCTRACE,
2223                "Handling RPC req@%p pname:cluuid+ref:pid:xid:nid:opc:job %s:%s+%d:%d:x%llu:%s:%d:%s\n",
2224                request, current_comm(),
2225                (request->rq_export ?
2226                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
2227                (request->rq_export ?
2228                 atomic_read(&request->rq_export->exp_refcount) : -99),
2229                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
2230                libcfs_id2str(request->rq_peer),
2231                lustre_msg_get_opc(request->rq_reqmsg),
2232                lustre_msg_get_jobid(request->rq_reqmsg));
2233
2234         if (lustre_msg_get_opc(request->rq_reqmsg) != OBD_PING)
2235                 CFS_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, cfs_fail_val);
2236
2237         CDEBUG(D_NET, "got req %llu\n", request->rq_xid);
2238
2239         /* re-assign request and sesson thread to the current one */
2240         request->rq_svc_thread = thread;
2241         if (thread != NULL) {
2242                 LASSERT(request->rq_session.lc_thread == NULL);
2243                 request->rq_session.lc_thread = thread;
2244                 thread->t_env->le_ses = &request->rq_session;
2245         }
2246         svc->srv_ops.so_req_handler(request);
2247
2248         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
2249
2250 put_conn:
2251         if (unlikely(ktime_get_real_seconds() > request->rq_deadline)) {
2252                 DEBUG_REQ(D_WARNING, request,
2253                           "Request took longer than estimated (%lld:%llds); "
2254                           "client may timeout.",
2255                           request->rq_deadline -
2256                           request->rq_arrival_time.tv_sec,
2257                           ktime_get_real_seconds() - request->rq_deadline);
2258         }
2259
2260         work_end = ktime_get_real();
2261         timediff_usecs = ktime_us_delta(work_end, work_start);
2262         arrived_usecs = ktime_us_delta(work_end, arrived);
2263         CDEBUG(D_RPCTRACE,
2264                "Handled RPC req@%p pname:cluuid+ref:pid:xid:nid:opc:job %s:%s+%d:%d:x%llu:%s:%d:%s Request processed in %lldus (%lldus total) trans %llu rc %d/%d\n",
2265                request, current_comm(),
2266                (request->rq_export ?
2267                (char *)request->rq_export->exp_client_uuid.uuid : "0"),
2268                (request->rq_export ?
2269                atomic_read(&request->rq_export->exp_refcount) : -99),
2270                lustre_msg_get_status(request->rq_reqmsg),
2271                request->rq_xid,
2272                libcfs_id2str(request->rq_peer),
2273                lustre_msg_get_opc(request->rq_reqmsg),
2274                lustre_msg_get_jobid(request->rq_reqmsg),
2275                timediff_usecs,
2276                arrived_usecs,
2277                (request->rq_repmsg ?
2278                lustre_msg_get_transno(request->rq_repmsg) :
2279                request->rq_transno),
2280                request->rq_status,
2281                (request->rq_repmsg ?
2282                lustre_msg_get_status(request->rq_repmsg) : -999));
2283         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
2284                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
2285                 int opc = opcode_offset(op);
2286
2287                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
2288                         LASSERT(opc < LUSTRE_MAX_OPCODES);
2289                         lprocfs_counter_add(svc->srv_stats,
2290                                             opc + EXTRA_MAX_OPCODES,
2291                                             timediff_usecs);
2292                 }
2293         }
2294         if (unlikely(request->rq_early_count)) {
2295                 DEBUG_REQ(D_ADAPTTO, request,
2296                           "sent %d early replies before finishing in %llds",
2297                           request->rq_early_count,
2298                           div_u64(arrived_usecs, USEC_PER_SEC));
2299         }
2300
2301         ptlrpc_server_finish_active_request(svcpt, request);
2302
2303         RETURN(1);
2304 }
2305
2306 /**
2307  * An internal function to process a single reply state object.
2308  */
2309 static int ptlrpc_handle_rs(struct ptlrpc_reply_state *rs)
2310 {
2311         struct ptlrpc_service_part *svcpt = rs->rs_svcpt;
2312         struct ptlrpc_service *svc = svcpt->scp_service;
2313         struct obd_export *exp;
2314         int nlocks;
2315         int been_handled;
2316
2317         ENTRY;
2318
2319         exp = rs->rs_export;
2320
2321         LASSERT(rs->rs_difficult);
2322         LASSERT(rs->rs_scheduled);
2323         LASSERT(list_empty(&rs->rs_list));
2324
2325         /*
2326          * The disk commit callback holds exp_uncommitted_replies_lock while it
2327          * iterates over newly committed replies, removing them from
2328          * exp_uncommitted_replies.  It then drops this lock and schedules the
2329          * replies it found for handling here.
2330          *
2331          * We can avoid contention for exp_uncommitted_replies_lock between the
2332          * HRT threads and further commit callbacks by checking rs_committed
2333          * which is set in the commit callback while it holds both
2334          * rs_lock and exp_uncommitted_reples.
2335          *
2336          * If we see rs_committed clear, the commit callback _may_ not have
2337          * handled this reply yet and we race with it to grab
2338          * exp_uncommitted_replies_lock before removing the reply from
2339          * exp_uncommitted_replies.  Note that if we lose the race and the
2340          * reply has already been removed, list_del_init() is a noop.
2341          *
2342          * If we see rs_committed set, we know the commit callback is handling,
2343          * or has handled this reply since store reordering might allow us to
2344          * see rs_committed set out of sequence.  But since this is done
2345          * holding rs_lock, we can be sure it has all completed once we hold
2346          * rs_lock, which we do right next.
2347          */
2348         if (!rs->rs_committed) {
2349                 /*
2350                  * if rs was commited, no need to convert locks, don't check
2351                  * rs_committed here because rs may never be added into
2352                  * exp_uncommitted_replies and this flag never be set, see
2353                  * target_send_reply()
2354                  */
2355                 if (rs->rs_convert_lock &&
2356                     rs->rs_transno > exp->exp_last_committed) {
2357                         struct ldlm_lock *lock;
2358                         struct ldlm_lock *ack_locks[RS_MAX_LOCKS] = { NULL };
2359
2360                         spin_lock(&rs->rs_lock);
2361                         if (rs->rs_convert_lock &&
2362                             rs->rs_transno > exp->exp_last_committed) {
2363                                 nlocks = rs->rs_nlocks;
2364                                 while (nlocks-- > 0) {
2365                                         /*
2366                                          * NB don't assume rs is always handled
2367                                          * by the same service thread (see
2368                                          * ptlrpc_hr_select, so REP-ACK hr may
2369                                          * race with trans commit, while the
2370                                          * latter will release locks, get locks
2371                                          * here early to convert to COS mode
2372                                          * safely.
2373                                          */
2374                                         lock = ldlm_handle2lock(
2375                                                         &rs->rs_locks[nlocks]);
2376                                         LASSERT(lock);
2377                                         ack_locks[nlocks] = lock;
2378                                         rs->rs_modes[nlocks] = LCK_COS;
2379                                 }
2380                                 nlocks = rs->rs_nlocks;
2381                                 rs->rs_convert_lock = 0;
2382                                 /*
2383                                  * clear rs_scheduled so that commit callback
2384                                  * can schedule again
2385                                  */
2386                                 rs->rs_scheduled = 0;
2387                                 spin_unlock(&rs->rs_lock);
2388
2389                                 while (nlocks-- > 0) {
2390                                         lock = ack_locks[nlocks];
2391                                         ldlm_lock_mode_downgrade(lock, LCK_COS);
2392                                         LDLM_LOCK_PUT(lock);
2393                                 }
2394                                 RETURN(0);
2395                         }
2396                         spin_unlock(&rs->rs_lock);
2397                 }
2398
2399                 spin_lock(&exp->exp_uncommitted_replies_lock);
2400                 list_del_init(&rs->rs_obd_list);
2401                 spin_unlock(&exp->exp_uncommitted_replies_lock);
2402         }
2403
2404         spin_lock(&exp->exp_lock);
2405         /* Noop if removed already */
2406         list_del_init(&rs->rs_exp_list);
2407         spin_unlock(&exp->exp_lock);
2408
2409         spin_lock(&rs->rs_lock);
2410
2411         been_handled = rs->rs_handled;
2412         rs->rs_handled = 1;
2413
2414         nlocks = rs->rs_nlocks; /* atomic "steal", but */
2415         rs->rs_nlocks = 0; /* locks still on rs_locks! */
2416
2417         if (nlocks == 0 && !been_handled) {
2418                 /*
2419                  * If we see this, we should already have seen the warning
2420                  * in mds_steal_ack_locks()
2421                  */
2422                 CDEBUG(D_HA,
2423                        "All locks stolen from rs %p x%lld.t%lld o%d NID %s\n",
2424                        rs, rs->rs_xid, rs->rs_transno, rs->rs_opc,
2425                        libcfs_nid2str(exp->exp_connection->c_peer.nid));
2426         }
2427
2428         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
2429                 spin_unlock(&rs->rs_lock);
2430
2431                 if (!been_handled && rs->rs_on_net) {
2432                         LNetMDUnlink(rs->rs_md_h);
2433                         /* Ignore return code; we're racing with completion */
2434                 }
2435
2436                 while (nlocks-- > 0)
2437                         ldlm_lock_decref(&rs->rs_locks[nlocks],
2438                                          rs->rs_modes[nlocks]);
2439
2440                 spin_lock(&rs->rs_lock);
2441         }
2442
2443         rs->rs_scheduled = 0;
2444         rs->rs_convert_lock = 0;
2445
2446         if (!rs->rs_on_net) {
2447                 /* Off the net */
2448                 spin_unlock(&rs->rs_lock);
2449
2450                 class_export_put(exp);
2451                 rs->rs_export = NULL;
2452                 ptlrpc_rs_decref(rs);
2453                 if (atomic_dec_and_test(&svcpt->scp_nreps_difficult) &&
2454                     svc->srv_is_stopping)
2455                         wake_up_all(&svcpt->scp_waitq);
2456                 RETURN(1);
2457         }
2458
2459         /* still on the net; callback will schedule */
2460         spin_unlock(&rs->rs_lock);
2461         RETURN(1);
2462 }
2463
2464
2465 static void ptlrpc_check_rqbd_pool(struct ptlrpc_service_part *svcpt)
2466 {
2467         int avail = svcpt->scp_nrqbds_posted;
2468         int low_water = test_req_buffer_pressure ? 0 :
2469                         svcpt->scp_service->srv_nbuf_per_group / 2;
2470
2471         /* NB I'm not locking; just looking. */
2472
2473         /*
2474          * CAVEAT EMPTOR: We might be allocating buffers here because we've
2475          * allowed the request history to grow out of control.  We could put a
2476          * sanity check on that here and cull some history if we need the
2477          * space.
2478          */
2479
2480         if (avail <= low_water)
2481                 ptlrpc_grow_req_bufs(svcpt, 1);
2482
2483         if (svcpt->scp_service->srv_stats) {
2484                 lprocfs_counter_add(svcpt->scp_service->srv_stats,
2485                                     PTLRPC_REQBUF_AVAIL_CNTR, avail);
2486         }
2487 }
2488
2489 static int ptlrpc_retry_rqbds(void *arg)
2490 {
2491         struct ptlrpc_service_part *svcpt = (struct ptlrpc_service_part *)arg;
2492
2493         svcpt->scp_rqbd_timeout = 0;
2494         return -ETIMEDOUT;
2495 }
2496
2497 static inline int ptlrpc_threads_enough(struct ptlrpc_service_part *svcpt)
2498 {
2499         return svcpt->scp_nreqs_active <
2500                svcpt->scp_nthrs_running - 1 -
2501                (svcpt->scp_service->srv_ops.so_hpreq_handler != NULL);
2502 }
2503
2504 /**
2505  * allowed to create more threads
2506  * user can call it w/o any lock but need to hold
2507  * ptlrpc_service_part::scp_lock to get reliable result
2508  */
2509 static inline int ptlrpc_threads_increasable(struct ptlrpc_service_part *svcpt)
2510 {
2511         return svcpt->scp_nthrs_running +
2512                svcpt->scp_nthrs_starting <
2513                svcpt->scp_service->srv_nthrs_cpt_limit;
2514 }
2515
2516 /**
2517  * too many requests and allowed to create more threads
2518  */
2519 static inline int ptlrpc_threads_need_create(struct ptlrpc_service_part *svcpt)
2520 {
2521         return !ptlrpc_threads_enough(svcpt) &&
2522                 ptlrpc_threads_increasable(svcpt);
2523 }
2524
2525 static inline int ptlrpc_thread_stopping(struct ptlrpc_thread *thread)
2526 {
2527         return thread_is_stopping(thread) ||
2528                thread->t_svcpt->scp_service->srv_is_stopping;
2529 }
2530
2531 /* stop the highest numbered thread if there are too many threads running */
2532 static inline bool ptlrpc_thread_should_stop(struct ptlrpc_thread *thread)
2533 {
2534         struct ptlrpc_service_part *svcpt = thread->t_svcpt;
2535
2536         return thread->t_id >= svcpt->scp_service->srv_nthrs_cpt_limit &&
2537                 thread->t_id == svcpt->scp_thr_nextid - 1;
2538 }
2539
2540 static void ptlrpc_stop_thread(struct ptlrpc_thread *thread)
2541 {
2542         CDEBUG(D_INFO, "Stopping thread %s #%u\n",
2543                thread->t_svcpt->scp_service->srv_thread_name, thread->t_id);
2544         thread_add_flags(thread, SVC_STOPPING);
2545 }
2546
2547 static inline void ptlrpc_thread_stop(struct ptlrpc_thread *thread)
2548 {
2549         struct ptlrpc_service_part *svcpt = thread->t_svcpt;
2550
2551         spin_lock(&svcpt->scp_lock);
2552         if (ptlrpc_thread_should_stop(thread)) {
2553                 ptlrpc_stop_thread(thread);
2554                 svcpt->scp_thr_nextid--;
2555         }
2556         spin_unlock(&svcpt->scp_lock);
2557 }
2558
2559 static inline int ptlrpc_rqbd_pending(struct ptlrpc_service_part *svcpt)
2560 {
2561         return !list_empty(&svcpt->scp_rqbd_idle) &&
2562                svcpt->scp_rqbd_timeout == 0;
2563 }
2564
2565 static inline int
2566 ptlrpc_at_check(struct ptlrpc_service_part *svcpt)
2567 {
2568         return svcpt->scp_at_check;
2569 }
2570
2571 /*
2572  * If a thread runs too long or spends to much time on a single request,
2573  * we want to know about it, so we set up a delayed work item as a watchdog.
2574  * If it fires, we display a stack trace of the delayed thread,
2575  * providing we aren't rate-limited
2576  *
2577  * Watchdog stack traces are limited to 3 per 'libcfs_watchdog_ratelimit'
2578  * seconds
2579  */
2580 static struct ratelimit_state watchdog_limit;
2581
2582 static void ptlrpc_watchdog_fire(struct work_struct *w)
2583 {
2584         struct ptlrpc_thread *thread = container_of(w, struct ptlrpc_thread,
2585                                                     t_watchdog.work);
2586         u64 ms_lapse = ktime_ms_delta(ktime_get(), thread->t_touched);
2587         u32 ms_frac = do_div(ms_lapse, MSEC_PER_SEC);
2588
2589         if (!__ratelimit(&watchdog_limit)) {
2590                 LCONSOLE_WARN("%s: service thread pid %u was inactive for %llu.%03u seconds. The thread might be hung, or it might only be slow and will resume later. Dumping the stack trace for debugging purposes:\n",
2591                               thread->t_task->comm, thread->t_task->pid,
2592                               ms_lapse, ms_frac);
2593
2594                 libcfs_debug_dumpstack(thread->t_task);
2595         } else {
2596                 LCONSOLE_WARN("%s: service thread pid %u was inactive for %llu.%03u seconds. Watchdog stack traces are limited to 3 per %u seconds, skipping this one.\n",
2597                               thread->t_task->comm, thread->t_task->pid,
2598                               ms_lapse, ms_frac, libcfs_watchdog_ratelimit);
2599         }
2600 }
2601
2602 static void ptlrpc_watchdog_init(struct delayed_work *work, time_t time)
2603 {
2604         INIT_DELAYED_WORK(work, ptlrpc_watchdog_fire);
2605         schedule_delayed_work(work, cfs_time_seconds(time));
2606 }
2607
2608 static void ptlrpc_watchdog_disable(struct delayed_work *work)
2609 {
2610         cancel_delayed_work_sync(work);
2611 }
2612
2613 static void ptlrpc_watchdog_touch(struct delayed_work *work, time_t time)
2614 {
2615         struct ptlrpc_thread *thread = container_of(&work->work,
2616                                                     struct ptlrpc_thread,
2617                                                     t_watchdog.work);
2618         thread->t_touched = ktime_get();
2619         mod_delayed_work(system_wq, work, cfs_time_seconds(time));
2620 }
2621
2622 /**
2623  * requests wait on preprocessing
2624  * user can call it w/o any lock but need to hold
2625  * ptlrpc_service_part::scp_lock to get reliable result
2626  */
2627 static inline int
2628 ptlrpc_server_request_incoming(struct ptlrpc_service_part *svcpt)
2629 {
2630         return !list_empty(&svcpt->scp_req_incoming);
2631 }
2632
2633 static __attribute__((__noinline__)) int
2634 ptlrpc_wait_event(struct ptlrpc_service_part *svcpt,
2635                   struct ptlrpc_thread *thread)
2636 {
2637         /* Don't exit while there are replies to be handled */
2638         struct l_wait_info lwi = LWI_TIMEOUT(svcpt->scp_rqbd_timeout,
2639                                              ptlrpc_retry_rqbds, svcpt);
2640
2641         ptlrpc_watchdog_disable(&thread->t_watchdog);
2642
2643         cond_resched();
2644
2645         l_wait_event_exclusive_head(svcpt->scp_waitq,
2646                                 ptlrpc_thread_stopping(thread) ||
2647                                 ptlrpc_server_request_incoming(svcpt) ||
2648                                 ptlrpc_server_request_pending(svcpt, false) ||
2649                                 ptlrpc_rqbd_pending(svcpt) ||
2650                                 ptlrpc_at_check(svcpt), &lwi);
2651
2652         if (ptlrpc_thread_stopping(thread))
2653                 return -EINTR;
2654
2655         ptlrpc_watchdog_touch(&thread->t_watchdog,
2656                               ptlrpc_server_get_timeout(svcpt));
2657         return 0;
2658 }
2659
2660 /**
2661  * Main thread body for service threads.
2662  * Waits in a loop waiting for new requests to process to appear.
2663  * Every time an incoming requests is added to its queue, a waitq
2664  * is woken up and one of the threads will handle it.
2665  */
2666 static int ptlrpc_main(void *arg)
2667 {
2668         struct ptlrpc_thread *thread = (struct ptlrpc_thread *)arg;
2669         struct ptlrpc_service_part *svcpt = thread->t_svcpt;
2670         struct ptlrpc_service *svc = svcpt->scp_service;
2671         struct ptlrpc_reply_state *rs;
2672         struct group_info *ginfo = NULL;
2673         struct lu_env *env;
2674         int counter = 0, rc = 0;
2675
2676         ENTRY;
2677
2678         thread->t_task = current;
2679         thread->t_pid = current_pid();
2680         unshare_fs_struct();
2681
2682         if (svc->srv_cpt_bind) {
2683                 rc = cfs_cpt_bind(svc->srv_cptable, svcpt->scp_cpt);
2684                 if (rc != 0) {
2685                         CWARN("%s: failed to bind %s on CPT %d\n",
2686                               svc->srv_name, thread->t_name, svcpt->scp_cpt);
2687                 }
2688         }
2689
2690         ginfo = groups_alloc(0);
2691         if (!ginfo)
2692                 GOTO(out, rc = -ENOMEM);
2693
2694         set_current_groups(ginfo);
2695         put_group_info(ginfo);
2696
2697         if (svc->srv_ops.so_thr_init != NULL) {
2698                 rc = svc->srv_ops.so_thr_init(thread);
2699                 if (rc)
2700                         GOTO(out, rc);
2701         }
2702
2703         OBD_ALLOC_PTR(env);
2704         if (env == NULL)
2705                 GOTO(out_srv_fini, rc = -ENOMEM);
2706         rc = lu_env_add(env);
2707         if (rc)
2708                 GOTO(out_env, rc);
2709
2710         rc = lu_context_init(&env->le_ctx,
2711                              svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
2712         if (rc)
2713                 GOTO(out_env_remove, rc);
2714
2715         thread->t_env = env;
2716         env->le_ctx.lc_thread = thread;
2717         env->le_ctx.lc_cookie = 0x6;
2718
2719         while (!list_empty(&svcpt->scp_rqbd_idle)) {
2720                 rc = ptlrpc_server_post_idle_rqbds(svcpt);
2721                 if (rc >= 0)
2722                         continue;
2723
2724                 CERROR("Failed to post rqbd for %s on CPT %d: %d\n",
2725                         svc->srv_name, svcpt->scp_cpt, rc);
2726                 GOTO(out_ctx_fini, rc);
2727         }
2728
2729         /* Alloc reply state structure for this one */
2730         OBD_ALLOC_LARGE(rs, svc->srv_max_reply_size);
2731         if (!rs)
2732                 GOTO(out_ctx_fini, rc = -ENOMEM);
2733
2734         spin_lock(&svcpt->scp_lock);
2735
2736         LASSERT(thread_is_starting(thread));
2737         thread_clear_flags(thread, SVC_STARTING);
2738
2739         LASSERT(svcpt->scp_nthrs_starting == 1);
2740         svcpt->scp_nthrs_starting--;
2741
2742         /*
2743          * SVC_STOPPING may already be set here if someone else is trying
2744          * to stop the service while this new thread has been dynamically
2745          * forked. We still set SVC_RUNNING to let our creator know that
2746          * we are now running, however we will exit as soon as possible
2747          */
2748         thread_add_flags(thread, SVC_RUNNING);
2749         svcpt->scp_nthrs_running++;
2750         spin_unlock(&svcpt->scp_lock);
2751
2752         /* wake up our creator in case he's still waiting. */
2753         wake_up(&thread->t_ctl_waitq);
2754
2755         thread->t_touched = ktime_get();
2756         ptlrpc_watchdog_init(&thread->t_watchdog,
2757                          ptlrpc_server_get_timeout(svcpt));
2758
2759         spin_lock(&svcpt->scp_rep_lock);
2760         list_add(&rs->rs_list, &svcpt->scp_rep_idle);
2761         wake_up(&svcpt->scp_rep_waitq);
2762         spin_unlock(&svcpt->scp_rep_lock);
2763
2764         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
2765                svcpt->scp_nthrs_running);
2766
2767         /* XXX maintain a list of all managed devices: insert here */
2768         while (!ptlrpc_thread_stopping(thread)) {
2769                 if (ptlrpc_wait_event(svcpt, thread))
2770                         break;
2771
2772                 ptlrpc_check_rqbd_pool(svcpt);
2773
2774                 if (ptlrpc_threads_need_create(svcpt)) {
2775                         /* Ignore return code - we tried... */
2776                         ptlrpc_start_thread(svcpt, 0);
2777                 }
2778
2779                 /* reset le_ses to initial state */
2780                 env->le_ses = NULL;
2781                 /* Process all incoming reqs before handling any */
2782                 if (ptlrpc_server_request_incoming(svcpt)) {
2783                         lu_context_enter(&env->le_ctx);
2784                         ptlrpc_server_handle_req_in(svcpt, thread);
2785                         lu_context_exit(&env->le_ctx);
2786
2787                         /* but limit ourselves in case of flood */
2788                         if (counter++ < 100)
2789                                 continue;
2790                         counter = 0;
2791                 }
2792
2793                 if (ptlrpc_at_check(svcpt))
2794                         ptlrpc_at_check_timed(svcpt);
2795
2796                 if (ptlrpc_server_request_pending(svcpt, false)) {
2797                         lu_context_enter(&env->le_ctx);
2798                         ptlrpc_server_handle_request(svcpt, thread);
2799                         lu_context_exit(&env->le_ctx);
2800                 }
2801
2802                 if (ptlrpc_rqbd_pending(svcpt) &&
2803                     ptlrpc_server_post_idle_rqbds(svcpt) < 0) {
2804                         /*
2805                          * I just failed to repost request buffers.
2806                          * Wait for a timeout (unless something else
2807                          * happens) before I try again
2808                          */
2809                         svcpt->scp_rqbd_timeout = cfs_time_seconds(1) / 10;
2810                         CDEBUG(D_RPCTRACE, "Posted buffers: %d\n",
2811                                svcpt->scp_nrqbds_posted);
2812                 }
2813                 /*
2814                  * If the number of threads has been tuned downward and this
2815                  * thread should be stopped, then stop in reverse order so the
2816                  * the threads always have contiguous thread index values.
2817                  */
2818                 if (unlikely(ptlrpc_thread_should_stop(thread)))
2819                         ptlrpc_thread_stop(thread);
2820         }
2821
2822         ptlrpc_watchdog_disable(&thread->t_watchdog);
2823
2824 out_ctx_fini:
2825         lu_context_fini(&env->le_ctx);
2826 out_env_remove:
2827         lu_env_remove(env);
2828 out_env:
2829         OBD_FREE_PTR(env);
2830 out_srv_fini:
2831         /* deconstruct service thread state created by ptlrpc_start_thread() */
2832         if (svc->srv_ops.so_thr_done != NULL)
2833                 svc->srv_ops.so_thr_done(thread);
2834 out:
2835         CDEBUG(D_RPCTRACE, "%s: service thread [%p:%u] %d exiting: rc = %d\n",
2836                thread->t_name, thread, thread->t_pid, thread->t_id, rc);
2837         spin_lock(&svcpt->scp_lock);
2838         if (thread_test_and_clear_flags(thread, SVC_STARTING))
2839                 svcpt->scp_nthrs_starting--;
2840
2841         if (thread_test_and_clear_flags(thread, SVC_RUNNING)) {
2842                 /* must know immediately */
2843                 svcpt->scp_nthrs_running--;
2844         }
2845
2846         thread->t_id = rc;
2847         thread_add_flags(thread, SVC_STOPPED);
2848
2849         wake_up(&thread->t_ctl_waitq);
2850         spin_unlock(&svcpt->scp_lock);
2851
2852         return rc;
2853 }
2854
2855 static int hrt_dont_sleep(struct ptlrpc_hr_thread *hrt,
2856                           struct list_head *replies)
2857 {
2858         int result;
2859
2860         spin_lock(&hrt->hrt_lock);
2861
2862         list_splice_init(&hrt->hrt_queue, replies);
2863         result = ptlrpc_hr.hr_stopping || !list_empty(replies);
2864
2865         spin_unlock(&hrt->hrt_lock);
2866         return result;
2867 }
2868
2869 /**
2870  * Main body of "handle reply" function.
2871  * It processes acked reply states
2872  */
2873 static int ptlrpc_hr_main(void *arg)
2874 {
2875         struct ptlrpc_hr_thread *hrt = (struct ptlrpc_hr_thread *)arg;
2876         struct ptlrpc_hr_partition *hrp = hrt->hrt_partition;
2877         struct list_head replies;
2878         struct lu_env *env;
2879         int rc;
2880
2881         OBD_ALLOC_PTR(env);
2882         if (env == NULL)
2883                 RETURN(-ENOMEM);
2884
2885         INIT_LIST_HEAD(&replies);
2886         unshare_fs_struct();
2887
2888         rc = cfs_cpt_bind(ptlrpc_hr.hr_cpt_table, hrp->hrp_cpt);
2889         if (rc != 0) {
2890                 char threadname[20];
2891
2892                 snprintf(threadname, sizeof(threadname), "ptlrpc_hr%02d_%03d",
2893                          hrp->hrp_cpt, hrt->hrt_id);
2894                 CWARN("Failed to bind %s on CPT %d of CPT table %p: rc = %d\n",
2895                       threadname, hrp->hrp_cpt, ptlrpc_hr.hr_cpt_table, rc);
2896         }
2897
2898         rc = lu_context_init(&env->le_ctx, LCT_MD_THREAD | LCT_DT_THREAD |
2899                              LCT_REMEMBER | LCT_NOREF);
2900         if (rc)
2901                 GOTO(out_env, rc);
2902
2903         rc = lu_env_add(env);
2904         if (rc)
2905                 GOTO(out_ctx_fini, rc);
2906
2907         atomic_inc(&hrp->hrp_nstarted);
2908         wake_up(&ptlrpc_hr.hr_waitq);
2909
2910         while (!ptlrpc_hr.hr_stopping) {
2911                 l_wait_condition(hrt->hrt_waitq, hrt_dont_sleep(hrt, &replies));
2912
2913                 while (!list_empty(&replies)) {
2914                         struct ptlrpc_reply_state *rs;
2915
2916                         rs = list_entry(replies.prev,
2917                                         struct ptlrpc_reply_state,
2918                                         rs_list);
2919                         list_del_init(&rs->rs_list);
2920                         /* refill keys if needed */
2921                         lu_env_refill(env);
2922                         lu_context_enter(&env->le_ctx);
2923                         ptlrpc_handle_rs(rs);
2924                         lu_context_exit(&env->le_ctx);
2925                 }
2926         }
2927
2928         atomic_inc(&hrp->hrp_nstopped);
2929         wake_up(&ptlrpc_hr.hr_waitq);
2930
2931         lu_env_remove(env);
2932 out_ctx_fini:
2933         lu_context_fini(&env->le_ctx);
2934 out_env:
2935         OBD_FREE_PTR(env);
2936         return 0;
2937 }
2938
2939 static void ptlrpc_stop_hr_threads(void)
2940 {
2941         struct ptlrpc_hr_partition *hrp;
2942         int i;
2943         int j;
2944
2945         ptlrpc_hr.hr_stopping = 1;
2946
2947         cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2948                 if (hrp->hrp_thrs == NULL)
2949                         continue; /* uninitialized */
2950                 for (j = 0; j < hrp->hrp_nthrs; j++)
2951                         wake_up_all(&hrp->hrp_thrs[j].hrt_waitq);
2952         }
2953
2954         cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2955                 if (hrp->hrp_thrs == NULL)
2956                         continue; /* uninitialized */
2957                 wait_event(ptlrpc_hr.hr_waitq,
2958                                atomic_read(&hrp->hrp_nstopped) ==
2959                                atomic_read(&hrp->hrp_nstarted));
2960         }
2961 }
2962
2963 static int ptlrpc_start_hr_threads(void)
2964 {
2965         struct ptlrpc_hr_partition *hrp;
2966         int i;
2967         int j;
2968
2969         ENTRY;
2970
2971         cfs_percpt_for_each(hrp, i, ptlrpc_hr.hr_partitions) {
2972                 int     rc = 0;
2973
2974                 for (j = 0; j < hrp->hrp_nthrs; j++) {
2975                         struct ptlrpc_hr_thread *hrt = &hrp->hrp_thrs[j];
2976                         struct task_struct *task;
2977
2978                         task = kthread_run(ptlrpc_hr_main,
2979                                            &hrp->hrp_thrs[j],
2980                                            "ptlrpc_hr%02d_%03d",
2981                                            hrp->hrp_cpt,
2982                                            hrt->hrt_id);
2983                         if (IS_ERR(task)) {
2984                                 rc = PTR_ERR(task);
2985                                 break;
2986                         }
2987                 }
2988
2989                 wait_event(ptlrpc_hr.hr_waitq,
2990                            atomic_read(&hrp->hrp_nstarted) == j);
2991
2992                 if (rc < 0) {
2993                         CERROR("cannot start reply handler thread %d:%d: rc = %d\n",
2994                                i, j, rc);
2995                         ptlrpc_stop_hr_threads();
2996                         RETURN(rc);
2997                 }
2998         }
2999
3000         RETURN(0);
3001 }
3002
3003 static void ptlrpc_svcpt_stop_threads(struct ptlrpc_service_part *svcpt)
3004 {
3005         struct l_wait_info lwi = { 0 };
3006         struct ptlrpc_thread *thread;
3007         struct list_head zombie;
3008
3009         ENTRY;
3010
3011         CDEBUG(D_INFO, "Stopping threads for service %s\n",
3012                svcpt->scp_service->srv_name);
3013
3014         INIT_LIST_HEAD(&zombie);
3015         spin_lock(&svcpt->scp_lock);
3016         /* let the thread know that we would like it to stop asap */
3017         list_for_each_entry(thread, &svcpt->scp_threads, t_link)
3018                 ptlrpc_stop_thread(thread);
3019
3020         wake_up_all(&svcpt->scp_waitq);
3021
3022         while (!list_empty(&svcpt->scp_threads)) {
3023                 thread = list_entry(svcpt->scp_threads.next,
3024                                         struct ptlrpc_thread, t_link);
3025                 if (thread_is_stopped(thread)) {
3026                         list_del(&thread->t_link);
3027                         list_add(&thread->t_link, &zombie);
3028                         continue;
3029                 }
3030                 spin_unlock(&svcpt->scp_lock);
3031
3032                 CDEBUG(D_INFO, "waiting for stopping-thread %s #%u\n",
3033                        svcpt->scp_service->srv_thread_name, thread->t_id);
3034                 l_wait_event(thread->t_ctl_waitq,
3035                              thread_is_stopped(thread), &lwi);
3036
3037                 spin_lock(&svcpt->scp_lock);
3038         }
3039
3040         spin_unlock(&svcpt->scp_lock);
3041
3042         while (!list_empty(&zombie)) {
3043                 thread = list_entry(zombie.next,
3044                                         struct ptlrpc_thread, t_link);
3045                 list_del(&thread->t_link);
3046                 OBD_FREE_PTR(thread);
3047         }
3048         EXIT;
3049 }
3050
3051 /**
3052  * Stops all threads of a particular service \a svc
3053  */
3054 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
3055 {
3056         struct ptlrpc_service_part *svcpt;
3057         int i;
3058
3059         ENTRY;
3060
3061         ptlrpc_service_for_each_part(svcpt, i, svc) {
3062                 if (svcpt->scp_service != NULL)
3063                         ptlrpc_svcpt_stop_threads(svcpt);
3064         }
3065
3066         EXIT;
3067 }
3068
3069 int ptlrpc_start_threads(struct ptlrpc_service *svc)
3070 {
3071         int rc = 0;
3072         int i;
3073         int j;
3074
3075         ENTRY;
3076
3077         /* We require 2 threads min, see note in ptlrpc_server_handle_request */
3078         LASSERT(svc->srv_nthrs_cpt_init >= PTLRPC_NTHRS_INIT);
3079
3080         for (i = 0; i < svc->srv_ncpts; i++) {
3081                 for (j = 0; j < svc->srv_nthrs_cpt_init; j++) {
3082                         rc = ptlrpc_start_thread(svc->srv_parts[i], 1);
3083                         if (rc == 0)
3084                                 continue;
3085
3086                         if (rc != -EMFILE)
3087                                 goto failed;
3088                         /* We have enough threads, don't start more. b=15759 */
3089                         break;
3090                 }
3091         }
3092
3093         RETURN(0);
3094  failed:
3095         CERROR("cannot start %s thread #%d_%d: rc %d\n",
3096                svc->srv_thread_name, i, j, rc);
3097         ptlrpc_stop_all_threads(svc);
3098         RETURN(rc);
3099 }
3100
3101 int ptlrpc_start_thread(struct ptlrpc_service_part *svcpt, int wait)
3102 {
3103         struct l_wait_info lwi = { 0 };
3104         struct ptlrpc_thread *thread;
3105         struct ptlrpc_service *svc;
3106         struct task_struct *task;
3107         int rc;
3108
3109         ENTRY;
3110
3111         LASSERT(svcpt != NULL);
3112
3113         svc = svcpt->scp_service;
3114
3115         CDEBUG(D_RPCTRACE, "%s[%d] started %d min %d max %d\n",
3116                svc->srv_name, svcpt->scp_cpt, svcpt->scp_nthrs_running,
3117                svc->srv_nthrs_cpt_init, svc->srv_nthrs_cpt_limit);
3118
3119  again:
3120         if (unlikely(svc->srv_is_stopping))
3121                 RETURN(-ESRCH);
3122
3123         if (!ptlrpc_threads_increasable(svcpt) ||
3124             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
3125              svcpt->scp_nthrs_running == svc->srv_nthrs_cpt_init - 1))
3126                 RETURN(-EMFILE);
3127
3128         OBD_CPT_ALLOC_PTR(thread, svc->srv_cptable, svcpt->scp_cpt);
3129         if (thread == NULL)
3130                 RETURN(-ENOMEM);
3131         init_waitqueue_head(&thread->t_ctl_waitq);
3132
3133         spin_lock(&svcpt->scp_lock);
3134         if (!ptlrpc_threads_increasable(svcpt)) {
3135                 spin_unlock(&svcpt->scp_lock);
3136                 OBD_FREE_PTR(thread);
3137                 RETURN(-EMFILE);
3138         }
3139
3140         if (svcpt->scp_nthrs_starting != 0) {
3141                 /*
3142                  * serialize starting because some modules (obdfilter)
3143                  * might require unique and contiguous t_id
3144                  */
3145                 LASSERT(svcpt->scp_nthrs_starting == 1);
3146                 spin_unlock(&svcpt->scp_lock);
3147                 OBD_FREE_PTR(thread);
3148                 if (wait) {
3149                         CDEBUG(D_INFO, "Waiting for creating thread %s #%d\n",
3150                                svc->srv_thread_name, svcpt->scp_thr_nextid);
3151                         schedule();
3152                         goto again;
3153                 }
3154
3155                 CDEBUG(D_INFO, "Creating thread %s #%d race, retry later\n",
3156                        svc->srv_thread_name, svcpt->scp_thr_nextid);
3157                 RETURN(-EAGAIN);
3158         }
3159
3160         svcpt->scp_nthrs_starting++;
3161         thread->t_id = svcpt->scp_thr_nextid++;
3162         thread_add_flags(thread, SVC_STARTING);
3163         thread->t_svcpt = svcpt;
3164
3165         list_add(&thread->t_link, &svcpt->scp_threads);
3166         spin_unlock(&svcpt->scp_lock);
3167
3168         if (svcpt->scp_cpt >= 0) {
3169                 snprintf(thread->t_name, PTLRPC_THR_NAME_LEN, "%s%02d_%03d",
3170                          svc->srv_thread_name, svcpt->scp_cpt, thread->t_id);
3171         } else {
3172                 snprintf(thread->t_name, PTLRPC_THR_NAME_LEN, "%s_%04d",
3173                          svc->srv_thread_name, thread->t_id);
3174         }
3175
3176         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", thread->t_name);
3177         task = kthread_run(ptlrpc_main, thread, "%s", thread->t_name);
3178         if (IS_ERR(task)) {
3179                 rc = PTR_ERR(task);
3180                 CERROR("cannot start thread '%s': rc = %d\n",
3181                        thread->t_name, rc);
3182                 spin_lock(&svcpt->scp_lock);
3183                 --svcpt->scp_nthrs_starting;
3184                 if (thread_is_stopping(thread)) {
3185                         /*
3186                          * this ptlrpc_thread is being hanled
3187                          * by ptlrpc_svcpt_stop_threads now
3188                          */
3189                         thread_add_flags(thread, SVC_STOPPED);
3190                         wake_up(&thread->t_ctl_waitq);
3191                         spin_unlock(&svcpt->scp_lock);
3192                 } else {
3193                         list_del(&thread->t_link);
3194                         spin_unlock(&svcpt->scp_lock);
3195                         OBD_FREE_PTR(thread);
3196                 }
3197                 RETURN(rc);
3198         }
3199
3200         if (!wait)
3201                 RETURN(0);
3202
3203         l_wait_event(thread->t_ctl_waitq,
3204                      thread_is_running(thread) || thread_is_stopped(thread),
3205                      &lwi);
3206
3207         rc = thread_is_stopped(thread) ? thread->t_id : 0;
3208         RETURN(rc);
3209 }
3210
3211 int ptlrpc_hr_init(void)
3212 {
3213         struct ptlrpc_hr_partition *hrp;
3214         struct ptlrpc_hr_thread *hrt;
3215         int rc;
3216         int cpt;
3217         int i;
3218         int weight;
3219
3220         ENTRY;
3221
3222         memset(&ptlrpc_hr, 0, sizeof(ptlrpc_hr));
3223         ptlrpc_hr.hr_cpt_table = cfs_cpt_table;
3224
3225         ptlrpc_hr.hr_partitions = cfs_percpt_alloc(ptlrpc_hr.hr_cpt_table,
3226                                                    sizeof(*hrp));
3227         if (ptlrpc_hr.hr_partitions == NULL)
3228                 RETURN(-ENOMEM);
3229
3230         ratelimit_state_init(&watchdog_limit,
3231                              cfs_time_seconds(libcfs_watchdog_ratelimit), 3);
3232
3233         init_waitqueue_head(&ptlrpc_hr.hr_waitq);
3234
3235         preempt_disable();
3236         weight = cpumask_weight(topology_sibling_cpumask(smp_processor_id()));
3237         preempt_enable();
3238
3239         cfs_percpt_for_each(hrp, cpt, ptlrpc_hr.hr_partitions) {
3240                 hrp->hrp_cpt = cpt;
3241
3242                 atomic_set(&hrp->hrp_nstarted, 0);
3243                 atomic_set(&hrp->hrp_nstopped, 0);
3244
3245                 hrp->hrp_nthrs = cfs_cpt_weight(ptlrpc_hr.hr_cpt_table, cpt);
3246                 hrp->hrp_nthrs /= weight;
3247                 if (hrp->hrp_nthrs == 0)
3248                         hrp->hrp_nthrs = 1;
3249
3250                 OBD_CPT_ALLOC(hrp->hrp_thrs, ptlrpc_hr.hr_cpt_table, cpt,
3251                               hrp->hrp_nthrs * sizeof(*hrt));
3252                 if (hrp->hrp_thrs == NULL)
3253                         GOTO(out, rc = -ENOMEM);
3254
3255                 for (i = 0; i < hrp->hrp_nthrs; i++) {
3256                         hrt = &hrp->hrp_thrs[i];
3257
3258                         hrt->hrt_id = i;
3259                         hrt->hrt_partition = hrp;
3260                         init_waitqueue_head(&hrt->hrt_waitq);
3261                         spin_lock_init(&hrt->hrt_lock);
3262                         INIT_LIST_HEAD(&hrt->hrt_queue);
3263                 }
3264         }
3265
3266         rc = ptlrpc_start_hr_threads();
3267 out:
3268         if (rc != 0)
3269                 ptlrpc_hr_fini();
3270         RETURN(rc);
3271 }
3272
3273 void ptlrpc_hr_fini(void)
3274 {
3275         struct ptlrpc_hr_partition *hrp;
3276         int cpt;
3277
3278         if (ptlrpc_hr.hr_partitions == NULL)
3279                 return;
3280
3281         ptlrpc_stop_hr_threads();
3282
3283         cfs_percpt_for_each(hrp, cpt, ptlrpc_hr.hr_partitions) {
3284                 if (hrp->hrp_thrs != NULL) {
3285                         OBD_FREE(hrp->hrp_thrs,
3286                                  hrp->hrp_nthrs * sizeof(hrp->hrp_thrs[0]));
3287                 }
3288         }
3289
3290         cfs_percpt_free(ptlrpc_hr.hr_partitions);
3291         ptlrpc_hr.hr_partitions = NULL;
3292 }
3293
3294
3295 /**
3296  * Wait until all already scheduled replies are processed.
3297  */
3298 static void ptlrpc_wait_replies(struct ptlrpc_service_part *svcpt)
3299 {
3300         while (1) {
3301                 int rc;
3302                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
3303                                                      NULL, NULL);
3304
3305                 rc = l_wait_event(svcpt->scp_waitq,
3306                      atomic_read(&svcpt->scp_nreps_difficult) == 0, &lwi);
3307                 if (rc == 0)
3308                         break;
3309                 CWARN("Unexpectedly long timeout %s %p\n",
3310                       svcpt->scp_service->srv_name, svcpt->scp_service);
3311         }
3312 }
3313
3314 static void
3315 ptlrpc_service_del_atimer(struct ptlrpc_service *svc)
3316 {
3317         struct ptlrpc_service_part *svcpt;
3318         int i;
3319
3320         /* early disarm AT timer... */
3321         ptlrpc_service_for_each_part(svcpt, i, svc) {
3322                 if (svcpt->scp_service != NULL)
3323                         del_timer(&svcpt->scp_at_timer);
3324         }
3325 }
3326
3327 static void
3328 ptlrpc_service_unlink_rqbd(struct ptlrpc_service *svc)
3329 {
3330         struct ptlrpc_service_part *svcpt;
3331         struct ptlrpc_request_buffer_desc *rqbd;
3332         struct l_wait_info lwi;
3333         int rc;
3334         int i;
3335
3336         /*
3337          * All history will be culled when the next request buffer is
3338          * freed in ptlrpc_service_purge_all()
3339          */
3340         svc->srv_hist_nrqbds_cpt_max = 0;
3341
3342         rc = LNetClearLazyPortal(svc->srv_req_portal);
3343         LASSERT(rc == 0);
3344
3345         ptlrpc_service_for_each_part(svcpt, i, svc) {
3346                 if (svcpt->scp_service == NULL)
3347                         break;
3348
3349                 /*
3350                  * Unlink all the request buffers.  This forces a 'final'
3351                  * event with its 'unlink' flag set for each posted rqbd
3352                  */
3353                 list_for_each_entry(rqbd, &svcpt->scp_rqbd_posted,
3354                                         rqbd_list) {
3355                         rc = LNetMDUnlink(rqbd->rqbd_md_h);
3356                         LASSERT(rc == 0 || rc == -ENOENT);
3357                 }
3358         }
3359
3360         ptlrpc_service_for_each_part(svcpt, i, svc) {
3361                 if (svcpt->scp_service == NULL)
3362                         break;
3363
3364                 /*
3365                  * Wait for the network to release any buffers
3366                  * it's currently filling
3367                  */
3368                 spin_lock(&svcpt->scp_lock);
3369                 while (svcpt->scp_nrqbds_posted != 0) {
3370                         spin_unlock(&svcpt->scp_lock);
3371                         /*
3372                          * Network access will complete in finite time but
3373                          * the HUGE timeout lets us CWARN for visibility
3374                          * of sluggish NALs
3375                          */
3376                         lwi = LWI_TIMEOUT_INTERVAL(
3377                                         cfs_time_seconds(LONG_UNLINK),
3378                                         cfs_time_seconds(1), NULL, NULL);
3379                         rc = l_wait_event(svcpt->scp_waitq,
3380                                           svcpt->scp_nrqbds_posted == 0, &lwi);
3381                         if (rc == -ETIMEDOUT) {
3382                                 CWARN("Service %s waiting for request buffers\n",
3383                                       svcpt->scp_service->srv_name);
3384                         }
3385                         spin_lock(&svcpt->scp_lock);
3386                 }
3387                 spin_unlock(&svcpt->scp_lock);
3388         }
3389 }
3390
3391 static void
3392 ptlrpc_service_purge_all(struct ptlrpc_service *svc)
3393 {
3394         struct ptlrpc_service_part *svcpt;
3395         struct ptlrpc_request_buffer_desc *rqbd;
3396         struct ptlrpc_request *req;
3397         struct ptlrpc_reply_state *rs;
3398         int i;
3399
3400         ptlrpc_service_for_each_part(svcpt, i, svc) {
3401                 if (svcpt->scp_service == NULL)
3402                         break;
3403
3404                 spin_lock(&svcpt->scp_rep_lock);
3405                 while (!list_empty(&svcpt->scp_rep_active)) {
3406                         rs = list_entry(svcpt->scp_rep_active.next,
3407                                             struct ptlrpc_reply_state, rs_list);
3408                         spin_lock(&rs->rs_lock);
3409                         ptlrpc_schedule_difficult_reply(rs);
3410                         spin_unlock(&rs->rs_lock);
3411                 }
3412                 spin_unlock(&svcpt->scp_rep_lock);
3413
3414                 /*
3415                  * purge the request queue.  NB No new replies (rqbds
3416                  * all unlinked) and no service threads, so I'm the only
3417                  * thread noodling the request queue now
3418                  */
3419                 while (!list_empty(&svcpt->scp_req_incoming)) {
3420                         req = list_entry(svcpt->scp_req_incoming.next,
3421                                              struct ptlrpc_request, rq_list);
3422
3423                         list_del(&req->rq_list);
3424                         svcpt->scp_nreqs_incoming--;
3425                         ptlrpc_server_finish_request(svcpt, req);
3426                 }
3427
3428                 while (ptlrpc_server_request_pending(svcpt, true)) {
3429                         req = ptlrpc_server_request_get(svcpt, true);
3430                         ptlrpc_server_finish_active_request(svcpt, req);
3431                 }
3432
3433                 LASSERT(list_empty(&svcpt->scp_rqbd_posted));
3434                 LASSERT(svcpt->scp_nreqs_incoming == 0);
3435                 LASSERT(svcpt->scp_nreqs_active == 0);
3436                 /*
3437                  * history should have been culled by
3438                  * ptlrpc_server_finish_request
3439                  */
3440                 LASSERT(svcpt->scp_hist_nrqbds == 0);
3441
3442                 /*
3443                  * Now free all the request buffers since nothing
3444                  * references them any more...
3445                  */
3446
3447                 while (!list_empty(&svcpt->scp_rqbd_idle)) {
3448                         rqbd = list_entry(svcpt->scp_rqbd_idle.next,
3449                                               struct ptlrpc_request_buffer_desc,
3450                                               rqbd_list);
3451                         ptlrpc_free_rqbd(rqbd);
3452                 }
3453                 ptlrpc_wait_replies(svcpt);
3454
3455                 while (!list_empty(&svcpt->scp_rep_idle)) {
3456                         rs = list_entry(svcpt->scp_rep_idle.next,
3457                                             struct ptlrpc_reply_state,
3458                                             rs_list);
3459                         list_del(&rs->rs_list);
3460                         OBD_FREE_LARGE(rs, svc->srv_max_reply_size);
3461                 }
3462         }
3463 }
3464
3465 static void
3466 ptlrpc_service_free(struct ptlrpc_service *svc)
3467 {
3468         struct ptlrpc_service_part      *svcpt;
3469         struct ptlrpc_at_array          *array;
3470         int                             i;
3471
3472         ptlrpc_service_for_each_part(svcpt, i, svc) {
3473                 if (svcpt->scp_service == NULL)
3474                         break;
3475
3476                 /* In case somebody rearmed this in the meantime */
3477                 del_timer(&svcpt->scp_at_timer);
3478                 array = &svcpt->scp_at_array;
3479
3480                 if (array->paa_reqs_array != NULL) {
3481                         OBD_FREE(array->paa_reqs_array,
3482                                  sizeof(struct list_head) * array->paa_size);
3483                         array->paa_reqs_array = NULL;
3484                 }
3485
3486                 if (array->paa_reqs_count != NULL) {
3487                         OBD_FREE(array->paa_reqs_count,
3488                                  sizeof(__u32) * array->paa_size);
3489                         array->paa_reqs_count = NULL;
3490                 }
3491         }
3492
3493         ptlrpc_service_for_each_part(svcpt, i, svc)
3494                 OBD_FREE_PTR(svcpt);
3495
3496         if (svc->srv_cpts != NULL)
3497                 cfs_expr_list_values_free(svc->srv_cpts, svc->srv_ncpts);
3498
3499         OBD_FREE(svc, offsetof(struct ptlrpc_service,
3500                                srv_parts[svc->srv_ncpts]));
3501 }
3502
3503 int ptlrpc_unregister_service(struct ptlrpc_service *service)
3504 {
3505         ENTRY;
3506
3507         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
3508
3509         service->srv_is_stopping = 1;
3510
3511         mutex_lock(&ptlrpc_all_services_mutex);
3512         list_del_init(&service->srv_list);
3513         mutex_unlock(&ptlrpc_all_services_mutex);
3514
3515         ptlrpc_service_del_atimer(service);
3516         ptlrpc_stop_all_threads(service);
3517
3518         ptlrpc_service_unlink_rqbd(service);
3519         ptlrpc_service_purge_all(service);
3520         ptlrpc_service_nrs_cleanup(service);
3521
3522         ptlrpc_lprocfs_unregister_service(service);
3523         ptlrpc_sysfs_unregister_service(service);
3524
3525         ptlrpc_service_free(service);
3526
3527         RETURN(0);
3528 }
3529 EXPORT_SYMBOL(ptlrpc_unregister_service);
3530
3531 /**
3532  * Returns 0 if the service is healthy.
3533  *
3534  * Right now, it just checks to make sure that requests aren't languishing
3535  * in the queue.  We'll use this health check to govern whether a node needs
3536  * to be shot, so it's intentionally non-aggressive.
3537  */
3538 static int ptlrpc_svcpt_health_check(struct ptlrpc_service_part *svcpt)
3539 {
3540         struct ptlrpc_request *request = NULL;
3541         struct timespec64 right_now;
3542         struct timespec64 timediff;
3543
3544         ktime_get_real_ts64(&right_now);
3545
3546         spin_lock(&svcpt->scp_req_lock);
3547         /* How long has the next entry been waiting? */
3548         if (ptlrpc_server_high_pending(svcpt, true))
3549                 request = ptlrpc_nrs_req_peek_nolock(svcpt, true);
3550         else if (ptlrpc_server_normal_pending(svcpt, true))
3551                 request = ptlrpc_nrs_req_peek_nolock(svcpt, false);
3552
3553         if (request == NULL) {
3554                 spin_unlock(&svcpt->scp_req_lock);
3555                 return 0;
3556         }
3557
3558         timediff = timespec64_sub(right_now, request->rq_arrival_time);
3559         spin_unlock(&svcpt->scp_req_lock);
3560
3561         if ((timediff.tv_sec) >
3562             (AT_OFF ? obd_timeout * 3 / 2 : at_max)) {
3563                 CERROR("%s: unhealthy - request has been waiting %llds\n",
3564                        svcpt->scp_service->srv_name, (s64)timediff.tv_sec);
3565                 return -1;
3566         }
3567
3568         return 0;
3569 }
3570
3571 int
3572 ptlrpc_service_health_check(struct ptlrpc_service *svc)
3573 {
3574         struct ptlrpc_service_part      *svcpt;
3575         int                             i;
3576
3577         if (svc == NULL)
3578                 return 0;
3579
3580         ptlrpc_service_for_each_part(svcpt, i, svc) {
3581                 int rc = ptlrpc_svcpt_health_check(svcpt);
3582
3583                 if (rc != 0)
3584                         return rc;
3585         }
3586         return 0;
3587 }
3588 EXPORT_SYMBOL(ptlrpc_service_health_check);