Whamcloud - gitweb
acl includes and time_t formats cleanup.
[fs/lustre-release.git] / lustre / ptlrpc / service.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
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 unsigned int at_min = 0;
53 CFS_MODULE_PARM(at_min, "i", int, 0644,
54                 "Adaptive timeout minimum (sec)");
55 unsigned int at_max = 600;
56 EXPORT_SYMBOL(at_max);
57 CFS_MODULE_PARM(at_max, "i", int, 0644,
58                 "Adaptive timeout maximum (sec)");
59 unsigned int at_history = 600;
60 CFS_MODULE_PARM(at_history, "i", int, 0644,
61                 "Adaptive timeouts remember the slowest event that took place "
62                 "within this period (sec)");
63 static int at_early_margin = 5;
64 CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
65                 "How soon before an RPC deadline to send an early reply");
66 static int at_extra = 30;
67 CFS_MODULE_PARM(at_extra, "i", int, 0644,
68                 "How much extra time to give with each early reply");
69
70
71 /* forward ref */
72 static int ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc);
73
74 static CFS_LIST_HEAD(ptlrpc_all_services);
75 spinlock_t ptlrpc_all_services_lock;
76
77 static char *
78 ptlrpc_alloc_request_buffer (int size)
79 {
80         char *ptr;
81
82         if (size > SVC_BUF_VMALLOC_THRESHOLD)
83                 OBD_VMALLOC(ptr, size);
84         else
85                 OBD_ALLOC(ptr, size);
86
87         return (ptr);
88 }
89
90 static void
91 ptlrpc_free_request_buffer (char *ptr, int size)
92 {
93         if (size > SVC_BUF_VMALLOC_THRESHOLD)
94                 OBD_VFREE(ptr, size);
95         else
96                 OBD_FREE(ptr, size);
97 }
98
99 struct ptlrpc_request_buffer_desc *
100 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
101 {
102         struct ptlrpc_request_buffer_desc *rqbd;
103
104         OBD_ALLOC_PTR(rqbd);
105         if (rqbd == NULL)
106                 return (NULL);
107
108         rqbd->rqbd_service = svc;
109         rqbd->rqbd_refcount = 0;
110         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
111         rqbd->rqbd_cbid.cbid_arg = rqbd;
112         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
113         rqbd->rqbd_buffer = ptlrpc_alloc_request_buffer(svc->srv_buf_size);
114
115         if (rqbd->rqbd_buffer == NULL) {
116                 OBD_FREE_PTR(rqbd);
117                 return (NULL);
118         }
119
120         spin_lock(&svc->srv_lock);
121         list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
122         svc->srv_nbufs++;
123         spin_unlock(&svc->srv_lock);
124
125         return (rqbd);
126 }
127
128 void
129 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
130 {
131         struct ptlrpc_service *svc = rqbd->rqbd_service;
132
133         LASSERT (rqbd->rqbd_refcount == 0);
134         LASSERT (list_empty(&rqbd->rqbd_reqs));
135
136         spin_lock(&svc->srv_lock);
137         list_del(&rqbd->rqbd_list);
138         svc->srv_nbufs--;
139         spin_unlock(&svc->srv_lock);
140
141         ptlrpc_free_request_buffer (rqbd->rqbd_buffer, svc->srv_buf_size);
142         OBD_FREE_PTR(rqbd);
143 }
144
145 int
146 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
147 {
148         struct ptlrpc_request_buffer_desc *rqbd;
149         int                                i;
150
151         CDEBUG(D_RPCTRACE, "%s: allocate %d new %d-byte reqbufs (%d/%d left)\n",
152                svc->srv_name, svc->srv_nbuf_per_group, svc->srv_buf_size,
153                svc->srv_nrqbd_receiving, svc->srv_nbufs);
154         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
155                 rqbd = ptlrpc_alloc_rqbd(svc);
156
157                 if (rqbd == NULL) {
158                         CERROR ("%s: Can't allocate request buffer\n",
159                                 svc->srv_name);
160                         return (-ENOMEM);
161                 }
162
163                 if (ptlrpc_server_post_idle_rqbds(svc) < 0)
164                         return (-EAGAIN);
165         }
166
167         return (0);
168 }
169
170 void
171 ptlrpc_save_lock (struct ptlrpc_request *req,
172                   struct lustre_handle *lock, int mode)
173 {
174         struct ptlrpc_reply_state *rs = req->rq_reply_state;
175         int                        idx;
176
177         LASSERT(rs != NULL);
178         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
179
180         idx = rs->rs_nlocks++;
181         rs->rs_locks[idx] = *lock;
182         rs->rs_modes[idx] = mode;
183         rs->rs_difficult = 1;
184 }
185
186 void
187 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
188 {
189         struct ptlrpc_service *svc = rs->rs_service;
190
191 #ifdef CONFIG_SMP
192         LASSERT (spin_is_locked (&svc->srv_lock));
193 #endif
194         LASSERT (rs->rs_difficult);
195         rs->rs_scheduled_ever = 1;              /* flag any notification attempt */
196
197         if (rs->rs_scheduled)                   /* being set up or already notified */
198                 return;
199
200         rs->rs_scheduled = 1;
201         list_del (&rs->rs_list);
202         list_add (&rs->rs_list, &svc->srv_reply_queue);
203         cfs_waitq_signal (&svc->srv_waitq);
204 }
205
206 void
207 ptlrpc_commit_replies (struct obd_device *obd)
208 {
209         struct list_head   *tmp;
210         struct list_head   *nxt;
211
212         /* Find any replies that have been committed and get their service
213          * to attend to complete them. */
214
215         /* CAVEAT EMPTOR: spinlock ordering!!! */
216         spin_lock(&obd->obd_uncommitted_replies_lock);
217
218         list_for_each_safe (tmp, nxt, &obd->obd_uncommitted_replies) {
219                 struct ptlrpc_reply_state *rs =
220                         list_entry(tmp, struct ptlrpc_reply_state, rs_obd_list);
221
222                 LASSERT (rs->rs_difficult);
223
224                 if (rs->rs_transno <= obd->obd_last_committed) {
225                         struct ptlrpc_service *svc = rs->rs_service;
226
227                         spin_lock (&svc->srv_lock);
228                         list_del_init (&rs->rs_obd_list);
229                         ptlrpc_schedule_difficult_reply (rs);
230                         spin_unlock (&svc->srv_lock);
231                 }
232         }
233
234         spin_unlock(&obd->obd_uncommitted_replies_lock);
235 }
236
237 static int
238 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
239 {
240         struct ptlrpc_request_buffer_desc *rqbd;
241         int                                rc;
242         int                                posted = 0;
243
244         for (;;) {
245                 spin_lock(&svc->srv_lock);
246
247                 if (list_empty (&svc->srv_idle_rqbds)) {
248                         spin_unlock(&svc->srv_lock);
249                         return (posted);
250                 }
251
252                 rqbd = list_entry(svc->srv_idle_rqbds.next,
253                                   struct ptlrpc_request_buffer_desc,
254                                   rqbd_list);
255                 list_del (&rqbd->rqbd_list);
256
257                 /* assume we will post successfully */
258                 svc->srv_nrqbd_receiving++;
259                 list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
260
261                 spin_unlock(&svc->srv_lock);
262
263                 rc = ptlrpc_register_rqbd(rqbd);
264                 if (rc != 0)
265                         break;
266
267                 posted = 1;
268         }
269
270         spin_lock(&svc->srv_lock);
271
272         svc->srv_nrqbd_receiving--;
273         list_del(&rqbd->rqbd_list);
274         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
275
276         /* Don't complain if no request buffers are posted right now; LNET
277          * won't drop requests because we set the portal lazy! */
278
279         spin_unlock(&svc->srv_lock);
280
281         return (-1);
282 }
283
284 struct ptlrpc_service *ptlrpc_init_svc_conf(struct ptlrpc_service_conf *c,
285                                             svc_handler_t h, char *name,
286                                             struct proc_dir_entry *proc_entry,
287                                             svcreq_printfn_t prntfn,
288                                             char *threadname)
289 {
290         return ptlrpc_init_svc(c->psc_nbufs, c->psc_bufsize,
291                                c->psc_max_req_size, c->psc_max_reply_size,
292                                c->psc_req_portal, c->psc_rep_portal,
293                                c->psc_watchdog_factor,
294                                h, name, proc_entry,
295                                prntfn, c->psc_min_threads, c->psc_max_threads,
296                                threadname, c->psc_ctx_tags);
297 }
298 EXPORT_SYMBOL(ptlrpc_init_svc_conf);
299
300 static void ptlrpc_at_timer(unsigned long castmeharder)
301 {
302         struct ptlrpc_service *svc = (struct ptlrpc_service *)castmeharder;
303         svc->srv_at_check = 1;
304         svc->srv_at_checktime = cfs_time_current();
305         cfs_waitq_signal(&svc->srv_waitq);
306 }
307
308 /* @threadname should be 11 characters or less - 3 will be added on */
309 struct ptlrpc_service *
310 ptlrpc_init_svc(int nbufs, int bufsize, int max_req_size, int max_reply_size,
311                 int req_portal, int rep_portal, int watchdog_factor,
312                 svc_handler_t handler, char *name,
313                 cfs_proc_dir_entry_t *proc_entry,
314                 svcreq_printfn_t svcreq_printfn,
315                 int min_threads, int max_threads,
316                 char *threadname, __u32 ctx_tags)
317 {
318         int                    rc;
319         struct ptlrpc_service *service;
320         ENTRY;
321
322         LASSERT (nbufs > 0);
323         LASSERT (bufsize >= max_req_size + SPTLRPC_MAX_PAYLOAD);
324         LASSERT (ctx_tags != 0);
325
326         OBD_ALLOC_PTR(service);
327         if (service == NULL)
328                 RETURN(NULL);
329
330         /* First initialise enough for early teardown */
331
332         service->srv_name = name;
333         spin_lock_init(&service->srv_lock);
334         CFS_INIT_LIST_HEAD(&service->srv_threads);
335         cfs_waitq_init(&service->srv_waitq);
336
337         service->srv_nbuf_per_group = test_req_buffer_pressure ? 1 : nbufs;
338         service->srv_max_req_size = max_req_size + SPTLRPC_MAX_PAYLOAD;
339         service->srv_buf_size = bufsize;
340         service->srv_rep_portal = rep_portal;
341         service->srv_req_portal = req_portal;
342         service->srv_watchdog_factor = watchdog_factor;
343         service->srv_handler = handler;
344         service->srv_request_history_print_fn = svcreq_printfn;
345         service->srv_request_seq = 1;           /* valid seq #s start at 1 */
346         service->srv_request_max_cull_seq = 0;
347         service->srv_threads_min = min_threads;
348         service->srv_threads_max = max_threads;
349         service->srv_thread_name = threadname;
350         service->srv_ctx_tags = ctx_tags;
351
352         rc = LNetSetLazyPortal(service->srv_req_portal);
353         LASSERT (rc == 0);
354
355         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
356         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
357         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
358         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
359         CFS_INIT_LIST_HEAD(&service->srv_request_history);
360         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
361         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
362         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
363         cfs_waitq_init(&service->srv_free_rs_waitq);
364
365         spin_lock_init(&service->srv_at_lock);
366         CFS_INIT_LIST_HEAD(&service->srv_req_in_queue);
367         CFS_INIT_LIST_HEAD(&service->srv_at_list);
368         cfs_timer_init(&service->srv_at_timer, ptlrpc_at_timer, service);
369         /* At SOW, service time should be quick; 10s seems generous. If client
370            timeout is less than this, we'll be sending an early reply. */
371         at_init(&service->srv_at_estimate, 10, 0);
372
373         spin_lock (&ptlrpc_all_services_lock);
374         list_add (&service->srv_list, &ptlrpc_all_services);
375         spin_unlock (&ptlrpc_all_services_lock);
376
377         /* Now allocate the request buffers */
378         rc = ptlrpc_grow_req_bufs(service);
379         /* We shouldn't be under memory pressure at startup, so
380          * fail if we can't post all our buffers at this time. */
381         if (rc != 0)
382                 GOTO(failed, NULL);
383
384         /* Now allocate pool of reply buffers */
385         /* Increase max reply size to next power of two */
386         service->srv_max_reply_size = 1;
387         while (service->srv_max_reply_size <
388                max_reply_size + SPTLRPC_MAX_PAYLOAD)
389                 service->srv_max_reply_size <<= 1;
390
391         if (proc_entry != NULL)
392                 ptlrpc_lprocfs_register_service(proc_entry, service);
393
394         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
395                service->srv_name, service->srv_req_portal);
396
397         RETURN(service);
398 failed:
399         ptlrpc_unregister_service(service);
400         return NULL;
401 }
402
403 static void ptlrpc_server_req_decref(struct ptlrpc_request *req)
404 {
405         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
406
407         if (!atomic_dec_and_test(&req->rq_refcount))
408                 return;
409
410         sptlrpc_svc_ctx_decref(req);
411
412         LASSERT(list_empty(&req->rq_timed_list));
413         if (req != &rqbd->rqbd_req) {
414                 /* NB request buffers use an embedded
415                  * req if the incoming req unlinked the
416                  * MD; this isn't one of them! */
417                 OBD_FREE(req, sizeof(*req));
418         } else {
419                 struct ptlrpc_service *svc = rqbd->rqbd_service;
420                 /* schedule request buffer for re-use.
421                  * NB I can only do this after I've disposed of their
422                  * reqs; particularly the embedded req */
423                 spin_lock(&svc->srv_lock);
424                 list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
425                 spin_unlock(&svc->srv_lock);
426         }
427 }
428
429 static void __ptlrpc_server_free_request(struct ptlrpc_request *req)
430 {
431         list_del(&req->rq_list);
432         ptlrpc_req_drop_rs(req);
433         ptlrpc_server_req_decref(req);
434 }
435
436 static void
437 ptlrpc_server_free_request(struct ptlrpc_request *req)
438 {
439         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
440         struct ptlrpc_service             *svc = rqbd->rqbd_service;
441         int                                refcount;
442         struct list_head                  *tmp;
443         struct list_head                  *nxt;
444
445         if (req->rq_phase != RQ_PHASE_NEW) /* incorrect message magic */
446                 DEBUG_REQ(D_INFO, req, "free req");
447         spin_lock(&svc->srv_at_lock);
448         req->rq_sent_final = 1;
449         list_del_init(&req->rq_timed_list);
450         spin_unlock(&svc->srv_at_lock);
451
452         spin_lock(&svc->srv_lock);
453
454         svc->srv_n_active_reqs--;
455         list_add(&req->rq_list, &rqbd->rqbd_reqs);
456
457         refcount = --(rqbd->rqbd_refcount);
458         if (refcount == 0) {
459                 /* request buffer is now idle: add to history */
460                 list_del(&rqbd->rqbd_list);
461                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
462                 svc->srv_n_history_rqbds++;
463
464                 /* cull some history?
465                  * I expect only about 1 or 2 rqbds need to be recycled here */
466                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
467                         rqbd = list_entry(svc->srv_history_rqbds.next,
468                                           struct ptlrpc_request_buffer_desc,
469                                           rqbd_list);
470
471                         list_del(&rqbd->rqbd_list);
472                         svc->srv_n_history_rqbds--;
473
474                         /* remove rqbd's reqs from svc's req history while
475                          * I've got the service lock */
476                         list_for_each(tmp, &rqbd->rqbd_reqs) {
477                                 req = list_entry(tmp, struct ptlrpc_request,
478                                                  rq_list);
479                                 /* Track the highest culled req seq */
480                                 if (req->rq_history_seq >
481                                     svc->srv_request_max_cull_seq)
482                                         svc->srv_request_max_cull_seq =
483                                                 req->rq_history_seq;
484                                 list_del(&req->rq_history_list);
485                         }
486
487                         spin_unlock(&svc->srv_lock);
488
489                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
490                                 req = list_entry(rqbd->rqbd_reqs.next,
491                                                  struct ptlrpc_request,
492                                                  rq_list);
493                                 __ptlrpc_server_free_request(req);
494                         }
495
496                         spin_lock(&svc->srv_lock);
497                 }
498         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
499                  /* If we are low on memory, we are not interested in
500                     history */
501                 list_del(&req->rq_history_list);
502                 __ptlrpc_server_free_request(req);
503         }
504
505         spin_unlock(&svc->srv_lock);
506
507 }
508
509 /* This function makes sure dead exports are evicted in a timely manner.
510    This function is only called when some export receives a message (i.e.,
511    the network is up.) */
512 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
513 {
514         struct obd_export *oldest_exp;
515         time_t oldest_time;
516
517         ENTRY;
518
519         LASSERT(exp);
520
521         /* Compensate for slow machines, etc, by faking our request time
522            into the future.  Although this can break the strict time-ordering
523            of the list, we can be really lazy here - we don't have to evict
524            at the exact right moment.  Eventually, all silent exports
525            will make it to the top of the list. */
526         exp->exp_last_request_time = max(exp->exp_last_request_time,
527                                          cfs_time_current_sec() + extra_delay);
528
529         CDEBUG(D_HA, "updating export %s at "CFS_TIME_T" exp %p\n",
530                exp->exp_client_uuid.uuid,
531                exp->exp_last_request_time, exp);
532
533         /* exports may get disconnected from the chain even though the
534            export has references, so we must keep the spin lock while
535            manipulating the lists */
536         spin_lock(&exp->exp_obd->obd_dev_lock);
537
538         if (list_empty(&exp->exp_obd_chain_timed)) {
539                 /* this one is not timed */
540                 spin_unlock(&exp->exp_obd->obd_dev_lock);
541                 EXIT;
542                 return;
543         }
544
545         list_move_tail(&exp->exp_obd_chain_timed,
546                        &exp->exp_obd->obd_exports_timed);
547
548         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
549                                 struct obd_export, exp_obd_chain_timed);
550         oldest_time = oldest_exp->exp_last_request_time;
551         spin_unlock(&exp->exp_obd->obd_dev_lock);
552
553         if (exp->exp_obd->obd_recovering) {
554                 /* be nice to everyone during recovery */
555                 EXIT;
556                 return;
557         }
558
559         /* Note - racing to start/reset the obd_eviction timer is safe */
560         if (exp->exp_obd->obd_eviction_timer == 0) {
561                 /* Check if the oldest entry is expired. */
562                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
563                                               extra_delay)) {
564                         /* We need a second timer, in case the net was down and
565                          * it just came back. Since the pinger may skip every
566                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
567                          * we better wait for 3. */
568                         exp->exp_obd->obd_eviction_timer =
569                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
570                         CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
571                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
572                                oldest_time);
573                 }
574         } else {
575                 if (cfs_time_current_sec() >
576                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
577                         /* The evictor won't evict anyone who we've heard from
578                          * recently, so we don't have to check before we start
579                          * it. */
580                         if (!ping_evictor_wake(exp))
581                                 exp->exp_obd->obd_eviction_timer = 0;
582                 }
583         }
584
585         EXIT;
586 }
587
588 #ifndef __KERNEL__
589 int lu_context_init(struct lu_context *ctx, __u32 tags)
590 {
591         return 0;
592 }
593
594 void lu_context_fini(struct lu_context *ctx)
595 {
596 }
597
598 void lu_context_enter(struct lu_context *ctx)
599 {
600 }
601
602 void lu_context_exit(struct lu_context *ctx)
603 {
604 }
605
606 #endif
607
608 static int ptlrpc_check_req(struct ptlrpc_request *req)
609 {
610         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
611                      req->rq_export->exp_conn_cnt)) {
612                 DEBUG_REQ(D_ERROR, req,
613                           "DROPPING req from old connection %d < %d",
614                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
615                           req->rq_export->exp_conn_cnt);
616                 return -EEXIST;
617         }
618         if (unlikely(req->rq_export->exp_obd &&
619                      req->rq_export->exp_obd->obd_fail)) {
620              /* Failing over, don't handle any more reqs, send
621                 error response instead. */
622                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
623                        req, req->rq_export->exp_obd->obd_name);
624                 req->rq_status = -ENODEV;
625                 ptlrpc_error(req);
626                 return -ENODEV;
627         }
628
629         return 0;
630 }
631
632 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
633 {
634         struct ptlrpc_request *rq;
635         __s32 next;
636
637         spin_lock(&svc->srv_at_lock);
638         if (list_empty(&svc->srv_at_list)) {
639                 cfs_timer_disarm(&svc->srv_at_timer);
640                 spin_unlock(&svc->srv_at_lock);
641                 return;
642         }
643
644         /* Set timer for closest deadline */
645         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request,
646                         rq_timed_list);
647         next = (__s32)(rq->rq_deadline - cfs_time_current_sec() - 
648                        at_early_margin);
649         if (next <= 0)
650                 ptlrpc_at_timer((unsigned long)svc);
651         else
652                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
653         spin_unlock(&svc->srv_at_lock);
654         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
655 }
656
657 /* Add rpc to early reply check list */
658 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
659 {
660         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
661         struct ptlrpc_request *rq;
662         int found = 0;
663
664         if (AT_OFF)
665                 return(0);
666
667         if (req->rq_no_reply)
668                 return 0;
669
670         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
671                 return(-ENOSYS);
672
673         DEBUG_REQ(D_ADAPTTO, req, "add timed "CFS_DURATION_T"s",
674                   cfs_time_sub(req->rq_deadline, cfs_time_current_sec()));
675
676         spin_lock(&svc->srv_at_lock);
677
678         if (unlikely(req->rq_sent_final)) {
679                 spin_unlock(&svc->srv_at_lock);
680                 return 0;
681         }
682
683         LASSERT(list_empty(&req->rq_timed_list));
684         /* Add to sorted list.  Presumably latest rpcs will have the latest
685            deadlines, so search backward. */
686         list_for_each_entry_reverse(rq, &svc->srv_at_list, rq_timed_list) {
687                 if (req->rq_deadline > rq->rq_deadline) {
688                         list_add(&req->rq_timed_list, &rq->rq_timed_list);
689                         found++;
690                         break;
691                 }
692         }
693         if (!found)
694                 /* Add to front if shortest deadline or list empty */
695                 list_add(&req->rq_timed_list, &svc->srv_at_list);
696
697         /* Check if we're the head of the list */
698         found = (svc->srv_at_list.next == &req->rq_timed_list);
699
700         spin_unlock(&svc->srv_at_lock);
701
702         if (found)
703                 ptlrpc_at_set_timer(svc);
704
705         return 0;
706 }
707
708 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req,
709                                       int extra_time)
710 {
711         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
712         struct ptlrpc_request *reqcopy;
713         struct lustre_msg *reqmsg;
714         cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
715         time_t newdl;
716         int rc;
717         ENTRY;
718
719         /* deadline is when the client expects us to reply, margin is the
720            difference between clients' and servers' expectations */
721         DEBUG_REQ(D_ADAPTTO, req,
722                   "%ssending early reply (deadline %+lds, margin %+lds) for "
723                   "%d+%d", AT_OFF ? "AT off - not " : "",
724                   olddl, olddl - at_get(&svc->srv_at_estimate),
725                   at_get(&svc->srv_at_estimate), extra_time);
726
727         if (AT_OFF)
728                 RETURN(0);
729
730         if (olddl < 0) {
731                 CDEBUG(D_WARNING, "x"LPU64": Already past deadline (%+lds), not"
732                        " sending early reply. Increase at_early_margin (%d)?\n",
733                        req->rq_xid, olddl, at_early_margin);
734                 /* Return an error so we're not re-added to the timed list. */
735                 RETURN(-ETIMEDOUT);
736         }
737
738         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
739                 CDEBUG(D_INFO, "Wanted to ask client for more time, but no AT "
740                       "support\n");
741                 RETURN(-ENOSYS);
742         }
743
744         if (extra_time) {
745                 /* Fake our processing time into the future to ask the
746                    clients for some extra amount of time */
747                 extra_time += cfs_time_current_sec() -
748                         req->rq_arrival_time.tv_sec;
749                 at_add(&svc->srv_at_estimate, extra_time);
750         }
751
752         newdl = req->rq_arrival_time.tv_sec + at_get(&svc->srv_at_estimate);
753         if (req->rq_deadline >= newdl) {
754                 /* We're not adding any time, no need to send an early reply
755                    (e.g. maybe at adaptive_max) */
756                 CDEBUG(D_ADAPTTO, "x"LPU64": Couldn't add any time ("
757                        CFS_DURATION_T"/"CFS_DURATION_T"), "
758                        "not sending early reply\n", req->rq_xid, olddl,
759                        cfs_time_sub(newdl, cfs_time_current_sec()));
760                 RETURN(-ETIMEDOUT);
761         }
762
763         OBD_ALLOC(reqcopy, sizeof *reqcopy);
764         if (reqcopy == NULL)
765                 RETURN(-ENOMEM);
766         OBD_ALLOC(reqmsg, req->rq_reqlen);
767         if (!reqmsg) {
768                 OBD_FREE(reqcopy, sizeof *reqcopy);
769                 RETURN(-ENOMEM);
770         }
771
772         *reqcopy = *req;
773         reqcopy->rq_reply_state = NULL;
774         reqcopy->rq_rep_swab_mask = 0;
775         reqcopy->rq_pack_bulk = 0;
776         reqcopy->rq_pack_udesc = 0;
777         reqcopy->rq_packed_final = 0;
778         sptlrpc_svc_ctx_addref(reqcopy);
779         /* We only need the reqmsg for the magic */
780         reqcopy->rq_reqmsg = reqmsg;
781         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
782
783         if (req->rq_sent_final) {
784                 CDEBUG(D_ADAPTTO, "x"LPU64": normal reply already sent out, "
785                        "abort sending early reply\n", req->rq_xid);
786                 GOTO(out, rc = 0);
787         }
788
789         /* Connection ref */
790         reqcopy->rq_export = class_conn2export(
791                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
792         if (reqcopy->rq_export == NULL)
793                 GOTO(out, rc = -ENODEV);
794
795         /* RPC ref */
796         class_export_rpc_get(reqcopy->rq_export);
797         if (reqcopy->rq_export->exp_obd &&
798             reqcopy->rq_export->exp_obd->obd_fail)
799                 GOTO(out_put, rc = -ENODEV);
800
801         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
802         if (rc)
803                 GOTO(out_put, rc);
804
805         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
806
807         if (!rc) {
808                 /* Adjust our own deadline to what we told the client */
809                 req->rq_deadline = newdl;
810                 req->rq_early_count++; /* number sent, server side */
811         } else {
812                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
813         }
814
815         /* Free the (early) reply state from lustre_pack_reply.
816            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
817         ptlrpc_req_drop_rs(reqcopy);
818
819 out_put:
820         class_export_rpc_put(reqcopy->rq_export);
821         class_export_put(reqcopy->rq_export);
822 out:
823         sptlrpc_svc_ctx_decref(reqcopy);
824         OBD_FREE(reqmsg, req->rq_reqlen);
825         OBD_FREE(reqcopy, sizeof *reqcopy);
826         RETURN(rc);
827 }
828
829 /* Send early replies to everybody expiring within at_early_margin
830    asking for at_extra time */
831 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
832 {
833         struct ptlrpc_request *rq, *n;
834         struct list_head work_list;
835         time_t now = cfs_time_current_sec();
836         cfs_duration_t delay;
837         int first, counter = 0;
838         ENTRY;
839
840         spin_lock(&svc->srv_at_lock);
841         if (svc->srv_at_check == 0) {
842                 spin_unlock(&svc->srv_at_lock);
843                 RETURN(0);
844         }
845         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
846         svc->srv_at_check = 0;
847
848         if (list_empty(&svc->srv_at_list)) {
849                 spin_unlock(&svc->srv_at_lock);
850                 RETURN(0);
851         }
852
853         /* The timer went off, but maybe the nearest rpc already completed. */
854         rq = list_entry(svc->srv_at_list.next, struct ptlrpc_request,
855                         rq_timed_list);
856         first = (int)(rq->rq_deadline - now);
857         if (first > at_early_margin) {
858                 /* We've still got plenty of time.  Reset the timer. */
859                 spin_unlock(&svc->srv_at_lock);
860                 ptlrpc_at_set_timer(svc);
861                 RETURN(0);
862         }
863
864         /* We're close to a timeout, and we don't know how much longer the
865            server will take. Send early replies to everyone expiring soon. */
866         CFS_INIT_LIST_HEAD(&work_list);
867         list_for_each_entry_safe(rq, n, &svc->srv_at_list, rq_timed_list) {
868                 if (rq->rq_deadline <= now + at_early_margin) {
869                         list_move_tail(&rq->rq_timed_list, &work_list);
870                         counter++;
871                 } else {
872                         break;
873                 }
874         }
875
876         spin_unlock(&svc->srv_at_lock);
877
878         /* we have a new earliest deadline, restart the timer */
879         ptlrpc_at_set_timer(svc);
880
881         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
882                "replies\n", first, at_extra, counter);
883         if (first < 0) {
884                 /* We're already past request deadlines before we even get a
885                    chance to send early replies */
886                 LCONSOLE_WARN("%s: This server is not able to keep up with "
887                               "request traffic (cpu-bound).\n", svc->srv_name);
888                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
889                       "delay="CFS_DURATION_T"(jiff)\n",
890                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
891                       at_get(&svc->srv_at_estimate), delay);
892         }
893
894         /* ptlrpc_server_free_request may delete an entry out of the work
895            list */
896         spin_lock(&svc->srv_at_lock);
897         while (!list_empty(&work_list)) {
898                 rq = list_entry(work_list.next, struct ptlrpc_request,
899                                 rq_timed_list);
900                 list_del_init(&rq->rq_timed_list);
901                 /* if the entry is still in the worklist, it hasn't been
902                    deleted, and is safe to take a ref to keep the req around */
903                 atomic_inc(&rq->rq_refcount);
904                 spin_unlock(&svc->srv_at_lock);
905
906                 if (ptlrpc_at_send_early_reply(rq, at_extra) == 0)
907                         ptlrpc_at_add_timed(rq);
908
909                 ptlrpc_server_req_decref(rq);
910                 spin_lock(&svc->srv_at_lock);
911         }
912         spin_unlock(&svc->srv_at_lock);
913
914         RETURN(0);
915 }
916
917 /* Handle freshly incoming reqs, add to timed early reply list,
918    pass on to regular request queue */
919 static int
920 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
921 {
922         struct ptlrpc_request *req;
923         __u32                  deadline;
924         int                    rc;
925         ENTRY;
926
927         LASSERT(svc);
928
929         spin_lock(&svc->srv_lock);
930         if (list_empty(&svc->srv_req_in_queue)) {
931                 spin_unlock(&svc->srv_lock);
932                 RETURN(0);
933         }
934
935         req = list_entry(svc->srv_req_in_queue.next,
936                          struct ptlrpc_request, rq_list);
937         list_del_init (&req->rq_list);
938         /* Consider this still a "queued" request as far as stats are
939            concerned */
940         spin_unlock(&svc->srv_lock);
941
942         /* go through security check/transform */
943         rc = sptlrpc_svc_unwrap_request(req);
944         switch (rc) {
945         case SECSVC_OK:
946                 break;
947         case SECSVC_COMPLETE:
948                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
949                 goto err_req;
950         case SECSVC_DROP:
951                 goto err_req;
952         default:
953                 LBUG();
954         }
955
956         /* Clear request swab mask; this is a new request */
957         req->rq_req_swab_mask = 0;
958
959         rc = lustre_unpack_msg(req->rq_reqmsg, req->rq_reqlen);
960         if (rc != 0) {
961                 CERROR("error unpacking request: ptl %d from %s x"LPU64"\n",
962                        svc->srv_req_portal, libcfs_id2str(req->rq_peer),
963                        req->rq_xid);
964                 goto err_req;
965         }
966
967         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
968         if (rc) {
969                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
970                         LPU64"\n", svc->srv_req_portal,
971                         libcfs_id2str(req->rq_peer), req->rq_xid);
972                 goto err_req;
973         }
974
975         rc = -EINVAL;
976         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
977                 CERROR("wrong packet type received (type=%u) from %s\n",
978                        lustre_msg_get_type(req->rq_reqmsg),
979                        libcfs_id2str(req->rq_peer));
980                 goto err_req;
981         }
982
983         CDEBUG(D_NET, "got req "LPD64"\n", req->rq_xid);
984
985         req->rq_export = class_conn2export(
986                 lustre_msg_get_handle(req->rq_reqmsg));
987         if (req->rq_export) {
988                 rc = ptlrpc_check_req(req);
989                 if (rc == 0) {
990                         rc = sptlrpc_target_export_check(req->rq_export, req);
991                         if (rc)
992                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
993                                           "illegal security flavor,");
994                 }
995
996                 class_export_put(req->rq_export);
997                 req->rq_export = NULL;
998                 if (rc)
999                         goto err_req;
1000         }
1001
1002         /* req_in handling should/must be fast */
1003         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1004                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1005                           cfs_time_sub(cfs_time_current_sec(),
1006                                        req->rq_arrival_time.tv_sec));
1007
1008         /* Set rpc server deadline and add it to the timed list */
1009         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1010                     MSGHDR_AT_SUPPORT) ?
1011                    /* The max time the client expects us to take */
1012                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1013         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1014         if (unlikely(deadline == 0)) {
1015                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1016                 goto err_req;
1017         }
1018
1019         ptlrpc_at_add_timed(req);
1020
1021         /* Move it over to the request processing queue */
1022         spin_lock(&svc->srv_lock);
1023         list_add_tail(&req->rq_list, &svc->srv_request_queue);
1024         cfs_waitq_signal(&svc->srv_waitq);
1025         spin_unlock(&svc->srv_lock);
1026         RETURN(1);
1027
1028 err_req:
1029         spin_lock(&svc->srv_lock);
1030         svc->srv_n_queued_reqs--;
1031         svc->srv_n_active_reqs++;
1032         spin_unlock(&svc->srv_lock);
1033         ptlrpc_server_free_request(req);
1034
1035         RETURN(1);
1036 }
1037
1038 static int
1039 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1040                              struct ptlrpc_thread *thread)
1041 {
1042         struct obd_export     *export = NULL;
1043         struct ptlrpc_request *request;
1044         struct timeval         work_start;
1045         struct timeval         work_end;
1046         long                   timediff;
1047         int                    rc;
1048         ENTRY;
1049
1050         LASSERT(svc);
1051
1052         spin_lock(&svc->srv_lock);
1053         if (unlikely(list_empty (&svc->srv_request_queue) ||
1054             (
1055 #ifndef __KERNEL__
1056              /* !@%$# liblustre only has 1 thread */
1057              svc->srv_n_difficult_replies != 0 &&
1058 #endif
1059              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
1060                  /* Don't handle regular requests in the last thread, in order               * re
1061                   * to handle difficult replies (which might block other threads)
1062                   * as well as handle any incoming reqs, early replies, etc.
1063                   * That means we always need at least 2 service threads. */
1064                 spin_unlock(&svc->srv_lock);
1065                 RETURN(0);
1066         }
1067
1068         request = list_entry (svc->srv_request_queue.next,
1069                               struct ptlrpc_request, rq_list);
1070         list_del_init (&request->rq_list);
1071         svc->srv_n_queued_reqs--;
1072         svc->srv_n_active_reqs++;
1073
1074         spin_unlock(&svc->srv_lock);
1075
1076         do_gettimeofday(&work_start);
1077         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1078         if (likely(svc->srv_stats != NULL)) {
1079                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1080                                     timediff);
1081                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1082                                     svc->srv_n_queued_reqs);
1083                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1084                                     svc->srv_n_active_reqs);
1085                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1086                                     at_get(&svc->srv_at_estimate));
1087         }
1088
1089         rc = lu_context_init(&request->rq_session, LCT_SESSION);
1090         if (rc) {
1091                 CERROR("Failure to initialize session: %d\n", rc);
1092                 goto out_req;
1093         }
1094         request->rq_session.lc_thread = thread;
1095         lu_context_enter(&request->rq_session);
1096
1097         CDEBUG(D_NET, "got req "LPD64"\n", request->rq_xid);
1098
1099         request->rq_svc_thread = thread;
1100         if (thread)
1101                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1102
1103         request->rq_export = class_conn2export(
1104                                      lustre_msg_get_handle(request->rq_reqmsg));
1105
1106         if (likely(request->rq_export)) {
1107                 if (unlikely(ptlrpc_check_req(request)))
1108                         goto put_conn;
1109                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1110                 export = class_export_rpc_get(request->rq_export);
1111         }
1112
1113         /* Discard requests queued for longer than the deadline.
1114            The deadline is increased if we send an early reply. */
1115         if (cfs_time_current_sec() > request->rq_deadline) {
1116                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1117                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1118                           libcfs_id2str(request->rq_peer),
1119                           cfs_time_sub(request->rq_deadline,
1120                           request->rq_arrival_time.tv_sec),
1121                           cfs_time_sub(cfs_time_current_sec(),
1122                           request->rq_deadline));
1123                 goto put_rpc_export;
1124         }
1125
1126         request->rq_phase = RQ_PHASE_INTERPRET;
1127
1128         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1129                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1130                (request->rq_export ?
1131                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1132                (request->rq_export ?
1133                 atomic_read(&request->rq_export->exp_refcount) : -99),
1134                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1135                libcfs_id2str(request->rq_peer),
1136                lustre_msg_get_opc(request->rq_reqmsg));
1137
1138         OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1139
1140         rc = svc->srv_handler(request);
1141
1142         request->rq_phase = RQ_PHASE_COMPLETE;
1143
1144         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1145                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1146                (request->rq_export ?
1147                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1148                (request->rq_export ?
1149                 atomic_read(&request->rq_export->exp_refcount) : -99),
1150                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1151                libcfs_id2str(request->rq_peer),
1152                lustre_msg_get_opc(request->rq_reqmsg));
1153
1154 put_rpc_export:
1155         if (export != NULL)
1156                 class_export_rpc_put(export);
1157 put_conn:
1158         if (likely(request->rq_export != NULL))
1159                 class_export_put(request->rq_export);
1160
1161         lu_context_exit(&request->rq_session);
1162         lu_context_fini(&request->rq_session);
1163
1164         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1165                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1166                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1167                           " client may timeout.",
1168                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1169                           request->rq_arrival_time.tv_sec),
1170                           cfs_time_sub(cfs_time_current_sec(),
1171                           request->rq_deadline));
1172         }
1173
1174         do_gettimeofday(&work_end);
1175         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1176         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1177                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1178                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1179                libcfs_id2str(request->rq_peer), timediff,
1180                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1181                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1182                request->rq_transno, request->rq_status,
1183                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg):
1184                -999);
1185         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1186                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1187                 int opc = opcode_offset(op);
1188                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1189                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1190                         lprocfs_counter_add(svc->srv_stats,
1191                                             opc + EXTRA_MAX_OPCODES,
1192                                             timediff);
1193                 }
1194         }
1195         if (unlikely(request->rq_early_count)) {
1196                 DEBUG_REQ(D_ADAPTTO, request,
1197                           "sent %d early replies before finishing in "
1198                           CFS_DURATION_T"s",
1199                           request->rq_early_count,
1200                           cfs_time_sub(work_end.tv_sec,
1201                           request->rq_arrival_time.tv_sec));
1202         }
1203
1204 out_req:
1205         ptlrpc_server_free_request(request);
1206
1207         RETURN(1);
1208 }
1209
1210 static int
1211 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
1212 {
1213         struct ptlrpc_reply_state *rs;
1214         struct obd_export         *exp;
1215         struct obd_device         *obd;
1216         int                        nlocks;
1217         int                        been_handled;
1218         ENTRY;
1219
1220         spin_lock(&svc->srv_lock);
1221         if (list_empty (&svc->srv_reply_queue)) {
1222                 spin_unlock(&svc->srv_lock);
1223                 RETURN(0);
1224         }
1225
1226         rs = list_entry (svc->srv_reply_queue.next,
1227                          struct ptlrpc_reply_state, rs_list);
1228
1229         exp = rs->rs_export;
1230         obd = exp->exp_obd;
1231
1232         LASSERT (rs->rs_difficult);
1233         LASSERT (rs->rs_scheduled);
1234
1235         list_del_init (&rs->rs_list);
1236
1237         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
1238         spin_unlock(&svc->srv_lock);
1239
1240         spin_lock (&obd->obd_uncommitted_replies_lock);
1241         /* Noop if removed already */
1242         list_del_init (&rs->rs_obd_list);
1243         spin_unlock (&obd->obd_uncommitted_replies_lock);
1244
1245         spin_lock (&exp->exp_lock);
1246         /* Noop if removed already */
1247         list_del_init (&rs->rs_exp_list);
1248         spin_unlock (&exp->exp_lock);
1249
1250         spin_lock(&svc->srv_lock);
1251
1252         been_handled = rs->rs_handled;
1253         rs->rs_handled = 1;
1254
1255         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1256         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1257
1258         if (nlocks == 0 && !been_handled) {
1259                 /* If we see this, we should already have seen the warning
1260                  * in mds_steal_ack_locks()  */
1261                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1262                       " o%d NID %s\n",
1263                       rs,
1264                       rs->rs_xid, rs->rs_transno,
1265                       lustre_msg_get_opc(rs->rs_msg),
1266                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1267         }
1268
1269         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1270                 spin_unlock(&svc->srv_lock);
1271
1272                 if (!been_handled && rs->rs_on_net) {
1273                         LNetMDUnlink(rs->rs_md_h);
1274                         /* Ignore return code; we're racing with
1275                          * completion... */
1276                 }
1277
1278                 while (nlocks-- > 0)
1279                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1280                                          rs->rs_modes[nlocks]);
1281
1282                 spin_lock(&svc->srv_lock);
1283         }
1284
1285         rs->rs_scheduled = 0;
1286
1287         if (!rs->rs_on_net) {
1288                 /* Off the net */
1289                 svc->srv_n_difficult_replies--;
1290                 spin_unlock(&svc->srv_lock);
1291
1292                 class_export_put (exp);
1293                 rs->rs_export = NULL;
1294                 ptlrpc_rs_decref (rs);
1295                 atomic_dec (&svc->srv_outstanding_replies);
1296                 RETURN(1);
1297         }
1298
1299         /* still on the net; callback will schedule */
1300         spin_unlock(&svc->srv_lock);
1301         RETURN(1);
1302 }
1303
1304 #ifndef __KERNEL__
1305 /* FIXME make use of timeout later */
1306 int
1307 liblustre_check_services (void *arg)
1308 {
1309         int  did_something = 0;
1310         int  rc;
1311         struct list_head *tmp, *nxt;
1312         ENTRY;
1313
1314         /* I'm relying on being single threaded, not to have to lock
1315          * ptlrpc_all_services etc */
1316         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1317                 struct ptlrpc_service *svc =
1318                         list_entry (tmp, struct ptlrpc_service, srv_list);
1319
1320                 if (svc->srv_threads_running != 0)     /* I've recursed */
1321                         continue;
1322
1323                 /* service threads can block for bulk, so this limits us
1324                  * (arbitrarily) to recursing 1 stack frame per service.
1325                  * Note that the problem with recursion is that we have to
1326                  * unwind completely before our caller can resume. */
1327
1328                 svc->srv_threads_running++;
1329
1330                 do {
1331                         rc = ptlrpc_server_handle_req_in(svc);
1332                         rc |= ptlrpc_server_handle_reply(svc);
1333                         rc |= ptlrpc_at_check_timed(svc);
1334                         rc |= ptlrpc_server_handle_request(svc, NULL);
1335                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1336                         did_something |= rc;
1337                 } while (rc);
1338
1339                 svc->srv_threads_running--;
1340         }
1341
1342         RETURN(did_something);
1343 }
1344 #define ptlrpc_stop_all_threads(s) do {} while (0)
1345
1346 #else /* __KERNEL__ */
1347
1348 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
1349 void ptlrpc_daemonize(char *name)
1350 {
1351         struct fs_struct *fs = current->fs;
1352
1353         atomic_inc(&fs->count);
1354         cfs_daemonize(name);
1355         exit_fs(cfs_current());
1356         current->fs = fs;
1357         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
1358 }
1359
1360 static void
1361 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1362 {
1363         int avail = svc->srv_nrqbd_receiving;
1364         int low_water = test_req_buffer_pressure ? 0 :
1365                         svc->srv_nbuf_per_group/2;
1366
1367         /* NB I'm not locking; just looking. */
1368
1369         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1370          * allowed the request history to grow out of control.  We could put a
1371          * sanity check on that here and cull some history if we need the
1372          * space. */
1373
1374         if (avail <= low_water)
1375                 ptlrpc_grow_req_bufs(svc);
1376
1377         if (svc->srv_stats)
1378                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1379                                     avail);
1380 }
1381
1382 static int
1383 ptlrpc_retry_rqbds(void *arg)
1384 {
1385         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1386
1387         svc->srv_rqbd_timeout = 0;
1388         return (-ETIMEDOUT);
1389 }
1390
1391 static int ptlrpc_main(void *arg)
1392 {
1393         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1394         struct ptlrpc_service  *svc = data->svc;
1395         struct ptlrpc_thread   *thread = data->thread;
1396         struct obd_device      *dev = data->dev;
1397         struct ptlrpc_reply_state *rs;
1398         struct lc_watchdog     *watchdog;
1399 #ifdef WITH_GROUP_INFO
1400         struct group_info *ginfo = NULL;
1401 #endif
1402         struct lu_env env;
1403         int counter = 0, rc = 0;
1404         ENTRY;
1405
1406         ptlrpc_daemonize(data->name);
1407
1408 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1409         /* we need to do this before any per-thread allocation is done so that
1410          * we get the per-thread allocations on local node.  bug 7342 */
1411         if (svc->srv_cpu_affinity) {
1412                 int cpu, num_cpu;
1413
1414                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1415                         if (!cpu_online(cpu))
1416                                 continue;
1417                         if (num_cpu == thread->t_id % num_online_cpus())
1418                                 break;
1419                         num_cpu++;
1420                 }
1421                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1422         }
1423 #endif
1424
1425 #ifdef WITH_GROUP_INFO
1426         ginfo = groups_alloc(0);
1427         if (!ginfo) {
1428                 rc = -ENOMEM;
1429                 goto out;
1430         }
1431
1432         set_current_groups(ginfo);
1433         put_group_info(ginfo);
1434 #endif
1435
1436         if (svc->srv_init != NULL) {
1437                 rc = svc->srv_init(thread);
1438                 if (rc)
1439                         goto out;
1440         }
1441
1442         rc = lu_context_init(&env.le_ctx, svc->srv_ctx_tags);
1443         if (rc)
1444                 goto out_srv_fini;
1445
1446         thread->t_env = &env;
1447         env.le_ctx.lc_thread = thread;
1448
1449         /* Alloc reply state structure for this one */
1450         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1451         if (!rs) {
1452                 rc = -ENOMEM;
1453                 goto out_srv_fini;
1454         }
1455
1456         /* Record that the thread is running */
1457         thread->t_flags = SVC_RUNNING;
1458         /*
1459          * wake up our creator. Note: @data is invalid after this point,
1460          * because it's allocated on ptlrpc_start_thread() stack.
1461          */
1462         cfs_waitq_signal(&thread->t_ctl_waitq);
1463
1464         watchdog = lc_watchdog_add(max_t(int, obd_timeout, AT_OFF ? 0 :
1465                                    at_get(&svc->srv_at_estimate)) *
1466                                    svc->srv_watchdog_factor, NULL, NULL);
1467
1468         spin_lock(&svc->srv_lock);
1469         svc->srv_threads_running++;
1470         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1471         spin_unlock(&svc->srv_lock);
1472         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1473
1474         CDEBUG(D_NET, "service thread %d (#%d)started\n", thread->t_id,
1475               svc->srv_threads_running);
1476
1477         /* XXX maintain a list of all managed devices: insert here */
1478
1479         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1480                svc->srv_n_difficult_replies != 0) {
1481                 /* Don't exit while there are replies to be handled */
1482                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1483                                                      ptlrpc_retry_rqbds, svc);
1484
1485                 lc_watchdog_disable(watchdog);
1486
1487                 cond_resched();
1488
1489                 l_wait_event_exclusive (svc->srv_waitq,
1490                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1491                                svc->srv_n_difficult_replies == 0) ||
1492                               (!list_empty(&svc->srv_idle_rqbds) &&
1493                                svc->srv_rqbd_timeout == 0) ||
1494                               !list_empty(&svc->srv_req_in_queue) ||
1495                               !list_empty(&svc->srv_reply_queue) ||
1496                               (!list_empty(&svc->srv_request_queue) &&
1497                                (svc->srv_n_active_reqs <
1498                                 (svc->srv_threads_running - 1))) ||
1499                               svc->srv_at_check,
1500                               &lwi);
1501
1502                 lc_watchdog_touch_ms(watchdog, max_t(int, obd_timeout,
1503                                      AT_OFF ? 0 :
1504                                      at_get(&svc->srv_at_estimate)) *
1505                                      svc->srv_watchdog_factor);
1506
1507                 ptlrpc_check_rqbd_pool(svc);
1508
1509                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1510                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1511                         /* Ignore return code - we tried... */
1512                         ptlrpc_start_thread(dev, svc);
1513                 }
1514
1515                 if (!list_empty(&svc->srv_reply_queue))
1516                         ptlrpc_server_handle_reply(svc);
1517
1518                 if (!list_empty(&svc->srv_req_in_queue)) {
1519                         /* Process all incoming reqs before handling any */
1520                         ptlrpc_server_handle_req_in(svc);
1521                         /* but limit ourselves in case of flood */
1522                         if (counter++ < 1000)
1523                                 continue;
1524                         counter = 0;
1525                 }
1526
1527                 if (svc->srv_at_check)
1528                         ptlrpc_at_check_timed(svc);
1529
1530                 /* don't handle requests in the last thread */
1531                 if (!list_empty (&svc->srv_request_queue) &&
1532                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
1533                         lu_context_enter(&env.le_ctx);
1534                         ptlrpc_server_handle_request(svc, thread);
1535                         lu_context_exit(&env.le_ctx);
1536                 }
1537
1538                 if (!list_empty(&svc->srv_idle_rqbds) &&
1539                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1540                         /* I just failed to repost request buffers.  Wait
1541                          * for a timeout (unless something else happens)
1542                          * before I try again */
1543                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1544                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1545                                svc->srv_nrqbd_receiving);
1546                 }
1547         }
1548
1549         lc_watchdog_delete(watchdog);
1550
1551 out_srv_fini:
1552         /*
1553          * deconstruct service specific state created by ptlrpc_start_thread()
1554          */
1555         if (svc->srv_done != NULL)
1556                 svc->srv_done(thread);
1557
1558         lu_context_fini(&env.le_ctx);
1559 out:
1560         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1561
1562         spin_lock(&svc->srv_lock);
1563         svc->srv_threads_running--; /* must know immediately */
1564         thread->t_id = rc;
1565         thread->t_flags = SVC_STOPPED;
1566
1567         cfs_waitq_signal(&thread->t_ctl_waitq);
1568         spin_unlock(&svc->srv_lock);
1569
1570         return rc;
1571 }
1572
1573 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1574                                struct ptlrpc_thread *thread)
1575 {
1576         struct l_wait_info lwi = { 0 };
1577
1578         spin_lock(&svc->srv_lock);
1579         thread->t_flags = SVC_STOPPING;
1580         spin_unlock(&svc->srv_lock);
1581
1582         cfs_waitq_broadcast(&svc->srv_waitq);
1583         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1584                      &lwi);
1585
1586         spin_lock(&svc->srv_lock);
1587         list_del(&thread->t_link);
1588         spin_unlock(&svc->srv_lock);
1589
1590         OBD_FREE_PTR(thread);
1591 }
1592
1593 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1594 {
1595         struct ptlrpc_thread *thread;
1596
1597         spin_lock(&svc->srv_lock);
1598         while (!list_empty(&svc->srv_threads)) {
1599                 thread = list_entry(svc->srv_threads.next,
1600                                     struct ptlrpc_thread, t_link);
1601
1602                 spin_unlock(&svc->srv_lock);
1603                 ptlrpc_stop_thread(svc, thread);
1604                 spin_lock(&svc->srv_lock);
1605         }
1606
1607         spin_unlock(&svc->srv_lock);
1608 }
1609
1610 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1611 {
1612         int i, rc = 0;
1613         ENTRY;
1614
1615         /* We require 2 threads min - see note in
1616            ptlrpc_server_handle_request */
1617         LASSERT(svc->srv_threads_min >= 2);
1618         for (i = 0; i < svc->srv_threads_min; i++) {
1619                 rc = ptlrpc_start_thread(dev, svc);
1620                 /* We have enough threads, don't start more.  b=15759 */
1621                 if (rc == -EMFILE)
1622                         break;
1623                 if (rc) {
1624                         CERROR("cannot start %s thread #%d: rc %d\n", 
1625                                svc->srv_thread_name, i, rc);
1626                         ptlrpc_stop_all_threads(svc);
1627                 }
1628         }
1629         RETURN(rc);
1630 }
1631
1632 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1633 {
1634         struct l_wait_info lwi = { 0 };
1635         struct ptlrpc_svc_data d;
1636         struct ptlrpc_thread *thread;
1637         char name[32];
1638         int id, rc;
1639         ENTRY;
1640
1641         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1642                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1643                svc->srv_threads_max, svc->srv_threads_running);
1644         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
1645             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
1646              svc->srv_threads_started == svc->srv_threads_min - 1))
1647                 RETURN(-EMFILE);
1648
1649         OBD_ALLOC_PTR(thread);
1650         if (thread == NULL)
1651                 RETURN(-ENOMEM);
1652         cfs_waitq_init(&thread->t_ctl_waitq);
1653
1654         spin_lock(&svc->srv_lock);
1655         if (svc->srv_threads_started >= svc->srv_threads_max) {
1656                 spin_unlock(&svc->srv_lock);
1657                 OBD_FREE_PTR(thread);
1658                 RETURN(-EMFILE);
1659         }
1660         list_add(&thread->t_link, &svc->srv_threads);
1661         id = svc->srv_threads_started++;
1662         spin_unlock(&svc->srv_lock);
1663
1664         thread->t_id = id;
1665         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1666         d.dev = dev;
1667         d.svc = svc;
1668         d.name = name;
1669         d.thread = thread;
1670
1671         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1672         
1673           /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1674          * just drop the VM and FILES in ptlrpc_daemonize() right away.
1675          */
1676         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1677         if (rc < 0) {
1678                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1679
1680                 spin_lock(&svc->srv_lock);
1681                 list_del(&thread->t_link);
1682                 --svc->srv_threads_started;
1683                 spin_unlock(&svc->srv_lock);
1684
1685                 OBD_FREE(thread, sizeof(*thread));
1686                 RETURN(rc);
1687         }
1688         l_wait_event(thread->t_ctl_waitq,
1689                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1690
1691         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1692         RETURN(rc);
1693 }
1694 #endif
1695
1696 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1697 {
1698         int                   rc;
1699         struct l_wait_info    lwi;
1700         struct list_head     *tmp;
1701         struct ptlrpc_reply_state *rs, *t;
1702
1703         cfs_timer_disarm(&service->srv_at_timer);
1704
1705         ptlrpc_stop_all_threads(service);
1706         LASSERT(list_empty(&service->srv_threads));
1707
1708         spin_lock (&ptlrpc_all_services_lock);
1709         list_del_init (&service->srv_list);
1710         spin_unlock (&ptlrpc_all_services_lock);
1711
1712         ptlrpc_lprocfs_unregister_service(service);
1713
1714         /* All history will be culled when the next request buffer is
1715          * freed */
1716         service->srv_max_history_rqbds = 0;
1717
1718         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1719
1720         rc = LNetClearLazyPortal(service->srv_req_portal);
1721         LASSERT (rc == 0);
1722
1723         /* Unlink all the request buffers.  This forces a 'final' event with
1724          * its 'unlink' flag set for each posted rqbd */
1725         list_for_each(tmp, &service->srv_active_rqbds) {
1726                 struct ptlrpc_request_buffer_desc *rqbd =
1727                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
1728                                    rqbd_list);
1729
1730                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1731                 LASSERT (rc == 0 || rc == -ENOENT);
1732         }
1733
1734         /* Wait for the network to release any buffers it's currently
1735          * filling */
1736         for (;;) {
1737                 spin_lock(&service->srv_lock);
1738                 rc = service->srv_nrqbd_receiving;
1739                 spin_unlock(&service->srv_lock);
1740
1741                 if (rc == 0)
1742                         break;
1743
1744                 /* Network access will complete in finite time but the HUGE
1745                  * timeout lets us CWARN for visibility of sluggish NALs */
1746                 lwi = LWI_TIMEOUT(cfs_time_seconds(LONG_UNLINK), NULL, NULL);
1747                 rc = l_wait_event(service->srv_waitq,
1748                                   service->srv_nrqbd_receiving == 0,
1749                                   &lwi);
1750                 if (rc == -ETIMEDOUT)
1751                         CWARN("Service %s waiting for request buffers\n",
1752                               service->srv_name);
1753         }
1754
1755         /* schedule all outstanding replies to terminate them */
1756         spin_lock(&service->srv_lock);
1757         while (!list_empty(&service->srv_active_replies)) {
1758                 struct ptlrpc_reply_state *rs =
1759                         list_entry(service->srv_active_replies.next,
1760                                    struct ptlrpc_reply_state, rs_list);
1761                 ptlrpc_schedule_difficult_reply(rs);
1762         }
1763         spin_unlock(&service->srv_lock);
1764
1765         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1766          * and no service threads, so I'm the only thread noodling the
1767          * request queue now */
1768         while (!list_empty(&service->srv_req_in_queue)) {
1769                 struct ptlrpc_request *req =
1770                         list_entry(service->srv_req_in_queue.next,
1771                                    struct ptlrpc_request,
1772                                    rq_list);
1773
1774                 list_del(&req->rq_list);
1775                 service->srv_n_queued_reqs--;
1776                 service->srv_n_active_reqs++;
1777                 ptlrpc_server_free_request(req);
1778         }
1779         while (!list_empty(&service->srv_request_queue)) {
1780                 struct ptlrpc_request *req =
1781                         list_entry(service->srv_request_queue.next,
1782                                    struct ptlrpc_request,
1783                                    rq_list);
1784
1785                 list_del(&req->rq_list);
1786                 service->srv_n_queued_reqs--;
1787                 service->srv_n_active_reqs++;
1788
1789                 ptlrpc_server_free_request(req);
1790         }
1791         LASSERT(service->srv_n_queued_reqs == 0);
1792         LASSERT(service->srv_n_active_reqs == 0);
1793         LASSERT(service->srv_n_history_rqbds == 0);
1794         LASSERT(list_empty(&service->srv_active_rqbds));
1795
1796         /* Now free all the request buffers since nothing references them
1797          * any more... */
1798         while (!list_empty(&service->srv_idle_rqbds)) {
1799                 struct ptlrpc_request_buffer_desc *rqbd =
1800                         list_entry(service->srv_idle_rqbds.next,
1801                                    struct ptlrpc_request_buffer_desc,
1802                                    rqbd_list);
1803
1804                 ptlrpc_free_rqbd(rqbd);
1805         }
1806
1807         /* wait for all outstanding replies to complete (they were
1808          * scheduled having been flagged to abort above) */
1809         while (atomic_read(&service->srv_outstanding_replies) != 0) {
1810                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
1811
1812                 rc = l_wait_event(service->srv_waitq,
1813                                   !list_empty(&service->srv_reply_queue), &lwi);
1814                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1815
1816                 if (rc == 0) {
1817                         ptlrpc_server_handle_reply(service);
1818                         continue;
1819                 }
1820                 CWARN("Unexpectedly long timeout %p\n", service);
1821         }
1822
1823         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
1824                 list_del(&rs->rs_list);
1825                 OBD_FREE(rs, service->srv_max_reply_size);
1826         }
1827
1828         /* In case somebody rearmed this in the meantime */
1829         cfs_timer_disarm(&service->srv_at_timer);
1830
1831         OBD_FREE_PTR(service);
1832         return 0;
1833 }
1834
1835 /* Returns 0 if the service is healthy.
1836  *
1837  * Right now, it just checks to make sure that requests aren't languishing
1838  * in the queue.  We'll use this health check to govern whether a node needs
1839  * to be shot, so it's intentionally non-aggressive. */
1840 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
1841 {
1842         struct ptlrpc_request *request;
1843         struct timeval         right_now;
1844         long                   timediff;
1845
1846         if (svc == NULL)
1847                 return 0;
1848
1849         do_gettimeofday(&right_now);
1850
1851         spin_lock(&svc->srv_lock);
1852         if (list_empty(&svc->srv_request_queue)) {
1853                 spin_unlock(&svc->srv_lock);
1854                 return 0;
1855         }
1856
1857         /* How long has the next entry been waiting? */
1858         request = list_entry(svc->srv_request_queue.next,
1859                              struct ptlrpc_request, rq_list);
1860         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
1861         spin_unlock(&svc->srv_lock);
1862
1863         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
1864                                         at_max)) {
1865                 CERROR("%s: unhealthy - request has been waiting %lds\n",
1866                        svc->srv_name, timediff / ONE_MILLION);
1867                 return (-1);
1868         }
1869
1870         return 0;
1871 }