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