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