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