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