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