Whamcloud - gitweb
ee8913c1e41589f246867cc34e076643853322ed
[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         if (rc > 0)
978                 lustre_set_req_swabbed(req, MSG_PTLRPC_HEADER_OFF);
979
980         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
981         if (rc) {
982                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
983                         LPU64"\n", svc->srv_req_portal,
984                         libcfs_id2str(req->rq_peer), req->rq_xid);
985                 goto err_req;
986         }
987
988         rc = -EINVAL;
989         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
990                 CERROR("wrong packet type received (type=%u) from %s\n",
991                        lustre_msg_get_type(req->rq_reqmsg),
992                        libcfs_id2str(req->rq_peer));
993                 goto err_req;
994         }
995
996         CDEBUG(D_NET, "got req "LPD64"\n", req->rq_xid);
997
998         req->rq_export = class_conn2export(
999                 lustre_msg_get_handle(req->rq_reqmsg));
1000         if (req->rq_export) {
1001                 rc = ptlrpc_check_req(req);
1002                 if (rc == 0) {
1003                         rc = sptlrpc_target_export_check(req->rq_export, req);
1004                         if (rc)
1005                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
1006                                           "illegal security flavor,");
1007                 }
1008
1009                 class_export_put(req->rq_export);
1010                 req->rq_export = NULL;
1011                 if (rc)
1012                         goto err_req;
1013         }
1014
1015         /* req_in handling should/must be fast */
1016         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1017                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1018                           cfs_time_sub(cfs_time_current_sec(),
1019                                        req->rq_arrival_time.tv_sec));
1020
1021         /* Set rpc server deadline and add it to the timed list */
1022         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1023                     MSGHDR_AT_SUPPORT) ?
1024                    /* The max time the client expects us to take */
1025                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1026         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1027         if (unlikely(deadline == 0)) {
1028                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1029                 goto err_req;
1030         }
1031
1032         ptlrpc_at_add_timed(req);
1033
1034         /* Move it over to the request processing queue */
1035         spin_lock(&svc->srv_lock);
1036         list_add_tail(&req->rq_list, &svc->srv_request_queue);
1037         cfs_waitq_signal(&svc->srv_waitq);
1038         spin_unlock(&svc->srv_lock);
1039         RETURN(1);
1040
1041 err_req:
1042         spin_lock(&svc->srv_lock);
1043         svc->srv_n_queued_reqs--;
1044         svc->srv_n_active_reqs++;
1045         spin_unlock(&svc->srv_lock);
1046         ptlrpc_server_finish_request(req);
1047
1048         RETURN(1);
1049 }
1050
1051 static int
1052 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1053                              struct ptlrpc_thread *thread)
1054 {
1055         struct obd_export     *export = NULL;
1056         struct ptlrpc_request *request;
1057         struct timeval         work_start;
1058         struct timeval         work_end;
1059         long                   timediff;
1060         int                    rc;
1061         ENTRY;
1062
1063         LASSERT(svc);
1064
1065         spin_lock(&svc->srv_lock);
1066         if (unlikely(list_empty (&svc->srv_request_queue) ||
1067             (
1068 #ifndef __KERNEL__
1069              /* !@%$# liblustre only has 1 thread */
1070              svc->srv_n_difficult_replies != 0 &&
1071 #endif
1072              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
1073                  /* Don't handle regular requests in the last thread, in order               * re
1074                   * to handle difficult replies (which might block other threads)
1075                   * as well as handle any incoming reqs, early replies, etc.
1076                   * That means we always need at least 2 service threads. */
1077                 spin_unlock(&svc->srv_lock);
1078                 RETURN(0);
1079         }
1080
1081         request = list_entry (svc->srv_request_queue.next,
1082                               struct ptlrpc_request, rq_list);
1083         list_del_init (&request->rq_list);
1084         svc->srv_n_queued_reqs--;
1085         svc->srv_n_active_reqs++;
1086
1087         spin_unlock(&svc->srv_lock);
1088
1089         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1090                 libcfs_debug_dumplog();
1091
1092         do_gettimeofday(&work_start);
1093         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1094         if (likely(svc->srv_stats != NULL)) {
1095                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1096                                     timediff);
1097                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1098                                     svc->srv_n_queued_reqs);
1099                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1100                                     svc->srv_n_active_reqs);
1101                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1102                                     at_get(&svc->srv_at_estimate));
1103         }
1104
1105         rc = lu_context_init(&request->rq_session, LCT_SESSION);
1106         if (rc) {
1107                 CERROR("Failure to initialize session: %d\n", rc);
1108                 goto out_req;
1109         }
1110         request->rq_session.lc_thread = thread;
1111         lu_context_enter(&request->rq_session);
1112
1113         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1114
1115         request->rq_svc_thread = thread;
1116         if (thread)
1117                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1118
1119         request->rq_export = class_conn2export(
1120                                      lustre_msg_get_handle(request->rq_reqmsg));
1121
1122         if (likely(request->rq_export)) {
1123                 if (unlikely(ptlrpc_check_req(request)))
1124                         goto put_conn;
1125                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1126                 export = class_export_rpc_get(request->rq_export);
1127         }
1128
1129         /* Discard requests queued for longer than the deadline.
1130            The deadline is increased if we send an early reply. */
1131         if (cfs_time_current_sec() > request->rq_deadline) {
1132                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1133                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1134                           libcfs_id2str(request->rq_peer),
1135                           cfs_time_sub(request->rq_deadline,
1136                           request->rq_arrival_time.tv_sec),
1137                           cfs_time_sub(cfs_time_current_sec(),
1138                           request->rq_deadline));
1139                 goto put_rpc_export;
1140         }
1141
1142         request->rq_phase = RQ_PHASE_INTERPRET;
1143
1144         CDEBUG(D_RPCTRACE, "Handling 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         OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1155
1156         rc = svc->srv_handler(request);
1157
1158         request->rq_phase = RQ_PHASE_COMPLETE;
1159
1160         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1161                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1162                (request->rq_export ?
1163                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1164                (request->rq_export ?
1165                 atomic_read(&request->rq_export->exp_refcount) : -99),
1166                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1167                libcfs_id2str(request->rq_peer),
1168                lustre_msg_get_opc(request->rq_reqmsg));
1169
1170 put_rpc_export:
1171         if (export != NULL)
1172                 class_export_rpc_put(export);
1173 put_conn:
1174         if (likely(request->rq_export != NULL))
1175                 class_export_put(request->rq_export);
1176
1177         lu_context_exit(&request->rq_session);
1178         lu_context_fini(&request->rq_session);
1179
1180         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1181                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1182                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1183                           " client may timeout.",
1184                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1185                           request->rq_arrival_time.tv_sec),
1186                           cfs_time_sub(cfs_time_current_sec(),
1187                           request->rq_deadline));
1188         }
1189
1190         do_gettimeofday(&work_end);
1191         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1192         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1193                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1194                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1195                libcfs_id2str(request->rq_peer), timediff,
1196                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1197                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1198                request->rq_transno, request->rq_status,
1199                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg):
1200                -999);
1201         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1202                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1203                 int opc = opcode_offset(op);
1204                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1205                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1206                         lprocfs_counter_add(svc->srv_stats,
1207                                             opc + EXTRA_MAX_OPCODES,
1208                                             timediff);
1209                 }
1210         }
1211         if (unlikely(request->rq_early_count)) {
1212                 DEBUG_REQ(D_ADAPTTO, request,
1213                           "sent %d early replies before finishing in "
1214                           CFS_DURATION_T"s",
1215                           request->rq_early_count,
1216                           cfs_time_sub(work_end.tv_sec,
1217                           request->rq_arrival_time.tv_sec));
1218         }
1219
1220 out_req:
1221         ptlrpc_server_finish_request(request);
1222
1223         RETURN(1);
1224 }
1225
1226 static int
1227 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
1228 {
1229         struct ptlrpc_reply_state *rs;
1230         struct obd_export         *exp;
1231         struct obd_device         *obd;
1232         int                        nlocks;
1233         int                        been_handled;
1234         ENTRY;
1235
1236         spin_lock(&svc->srv_lock);
1237         if (list_empty (&svc->srv_reply_queue)) {
1238                 spin_unlock(&svc->srv_lock);
1239                 RETURN(0);
1240         }
1241
1242         rs = list_entry (svc->srv_reply_queue.next,
1243                          struct ptlrpc_reply_state, rs_list);
1244
1245         exp = rs->rs_export;
1246         obd = exp->exp_obd;
1247
1248         LASSERT (rs->rs_difficult);
1249         LASSERT (rs->rs_scheduled);
1250
1251         list_del_init (&rs->rs_list);
1252
1253         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
1254         spin_unlock(&svc->srv_lock);
1255
1256         spin_lock (&obd->obd_uncommitted_replies_lock);
1257         /* Noop if removed already */
1258         list_del_init (&rs->rs_obd_list);
1259         spin_unlock (&obd->obd_uncommitted_replies_lock);
1260
1261         spin_lock (&exp->exp_lock);
1262         /* Noop if removed already */
1263         list_del_init (&rs->rs_exp_list);
1264         spin_unlock (&exp->exp_lock);
1265
1266         spin_lock(&svc->srv_lock);
1267
1268         been_handled = rs->rs_handled;
1269         rs->rs_handled = 1;
1270
1271         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1272         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1273
1274         if (nlocks == 0 && !been_handled) {
1275                 /* If we see this, we should already have seen the warning
1276                  * in mds_steal_ack_locks()  */
1277                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1278                       " o%d NID %s\n",
1279                       rs,
1280                       rs->rs_xid, rs->rs_transno,
1281                       lustre_msg_get_opc(rs->rs_msg),
1282                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1283         }
1284
1285         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1286                 spin_unlock(&svc->srv_lock);
1287
1288                 if (!been_handled && rs->rs_on_net) {
1289                         LNetMDUnlink(rs->rs_md_h);
1290                         /* Ignore return code; we're racing with
1291                          * completion... */
1292                 }
1293
1294                 while (nlocks-- > 0)
1295                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1296                                          rs->rs_modes[nlocks]);
1297
1298                 spin_lock(&svc->srv_lock);
1299         }
1300
1301         rs->rs_scheduled = 0;
1302
1303         if (!rs->rs_on_net) {
1304                 /* Off the net */
1305                 svc->srv_n_difficult_replies--;
1306                 if (svc->srv_n_difficult_replies == 0 && svc->srv_is_stopping)
1307                         /* wake up threads that are being stopped by
1308                            ptlrpc_unregister_service/ptlrpc_stop_threads
1309                            and sleep waiting svr_n_difficult_replies == 0 */
1310                         cfs_waitq_broadcast(&svc->srv_waitq);
1311                 spin_unlock(&svc->srv_lock);
1312
1313                 class_export_put (exp);
1314                 rs->rs_export = NULL;
1315                 ptlrpc_rs_decref (rs);
1316                 atomic_dec (&svc->srv_outstanding_replies);
1317                 RETURN(1);
1318         }
1319
1320         /* still on the net; callback will schedule */
1321         spin_unlock(&svc->srv_lock);
1322         RETURN(1);
1323 }
1324
1325 #ifndef __KERNEL__
1326 /* FIXME make use of timeout later */
1327 int
1328 liblustre_check_services (void *arg)
1329 {
1330         int  did_something = 0;
1331         int  rc;
1332         struct list_head *tmp, *nxt;
1333         ENTRY;
1334
1335         /* I'm relying on being single threaded, not to have to lock
1336          * ptlrpc_all_services etc */
1337         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1338                 struct ptlrpc_service *svc =
1339                         list_entry (tmp, struct ptlrpc_service, srv_list);
1340
1341                 if (svc->srv_threads_running != 0)     /* I've recursed */
1342                         continue;
1343
1344                 /* service threads can block for bulk, so this limits us
1345                  * (arbitrarily) to recursing 1 stack frame per service.
1346                  * Note that the problem with recursion is that we have to
1347                  * unwind completely before our caller can resume. */
1348
1349                 svc->srv_threads_running++;
1350
1351                 do {
1352                         rc = ptlrpc_server_handle_req_in(svc);
1353                         rc |= ptlrpc_server_handle_reply(svc);
1354                         rc |= ptlrpc_at_check_timed(svc);
1355                         rc |= ptlrpc_server_handle_request(svc, NULL);
1356                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1357                         did_something |= rc;
1358                 } while (rc);
1359
1360                 svc->srv_threads_running--;
1361         }
1362
1363         RETURN(did_something);
1364 }
1365 #define ptlrpc_stop_all_threads(s) do {} while (0)
1366
1367 #else /* __KERNEL__ */
1368
1369 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
1370 void ptlrpc_daemonize(char *name)
1371 {
1372         struct fs_struct *fs = current->fs;
1373
1374         atomic_inc(&fs->count);
1375         cfs_daemonize(name);
1376         exit_fs(cfs_current());
1377         current->fs = fs;
1378         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
1379 }
1380
1381 static void
1382 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1383 {
1384         int avail = svc->srv_nrqbd_receiving;
1385         int low_water = test_req_buffer_pressure ? 0 :
1386                         svc->srv_nbuf_per_group/2;
1387
1388         /* NB I'm not locking; just looking. */
1389
1390         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1391          * allowed the request history to grow out of control.  We could put a
1392          * sanity check on that here and cull some history if we need the
1393          * space. */
1394
1395         if (avail <= low_water)
1396                 ptlrpc_grow_req_bufs(svc);
1397
1398         if (svc->srv_stats)
1399                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1400                                     avail);
1401 }
1402
1403 static int
1404 ptlrpc_retry_rqbds(void *arg)
1405 {
1406         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1407
1408         svc->srv_rqbd_timeout = 0;
1409         return (-ETIMEDOUT);
1410 }
1411
1412 static int ptlrpc_main(void *arg)
1413 {
1414         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1415         struct ptlrpc_service  *svc = data->svc;
1416         struct ptlrpc_thread   *thread = data->thread;
1417         struct obd_device      *dev = data->dev;
1418         struct ptlrpc_reply_state *rs;
1419         struct lc_watchdog     *watchdog;
1420 #ifdef WITH_GROUP_INFO
1421         struct group_info *ginfo = NULL;
1422 #endif
1423         struct lu_env env;
1424         int counter = 0, rc = 0;
1425         ENTRY;
1426
1427         ptlrpc_daemonize(data->name);
1428
1429 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1430         /* we need to do this before any per-thread allocation is done so that
1431          * we get the per-thread allocations on local node.  bug 7342 */
1432         if (svc->srv_cpu_affinity) {
1433                 int cpu, num_cpu;
1434
1435                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1436                         if (!cpu_online(cpu))
1437                                 continue;
1438                         if (num_cpu == thread->t_id % num_online_cpus())
1439                                 break;
1440                         num_cpu++;
1441                 }
1442                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1443         }
1444 #endif
1445
1446 #ifdef WITH_GROUP_INFO
1447         ginfo = groups_alloc(0);
1448         if (!ginfo) {
1449                 rc = -ENOMEM;
1450                 goto out;
1451         }
1452
1453         set_current_groups(ginfo);
1454         put_group_info(ginfo);
1455 #endif
1456
1457         if (svc->srv_init != NULL) {
1458                 rc = svc->srv_init(thread);
1459                 if (rc)
1460                         goto out;
1461         }
1462
1463         rc = lu_context_init(&env.le_ctx, svc->srv_ctx_tags);
1464         if (rc)
1465                 goto out_srv_fini;
1466
1467         thread->t_env = &env;
1468         env.le_ctx.lc_thread = thread;
1469
1470         /* Alloc reply state structure for this one */
1471         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1472         if (!rs) {
1473                 rc = -ENOMEM;
1474                 goto out_srv_fini;
1475         }
1476
1477         /* Record that the thread is running */
1478         thread->t_flags = SVC_RUNNING;
1479         /*
1480          * wake up our creator. Note: @data is invalid after this point,
1481          * because it's allocated on ptlrpc_start_thread() stack.
1482          */
1483         cfs_waitq_signal(&thread->t_ctl_waitq);
1484
1485         watchdog = lc_watchdog_add(max_t(int, obd_timeout, AT_OFF ? 0 :
1486                                    at_get(&svc->srv_at_estimate)) *
1487                                    svc->srv_watchdog_factor, NULL, NULL);
1488
1489         spin_lock(&svc->srv_lock);
1490         svc->srv_threads_running++;
1491         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1492         spin_unlock(&svc->srv_lock);
1493         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1494
1495         CDEBUG(D_NET, "service thread %d (#%d)started\n", thread->t_id,
1496               svc->srv_threads_running);
1497
1498         /* XXX maintain a list of all managed devices: insert here */
1499
1500         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1501                svc->srv_n_difficult_replies != 0) {
1502                 /* Don't exit while there are replies to be handled */
1503                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1504                                                      ptlrpc_retry_rqbds, svc);
1505
1506                 lc_watchdog_disable(watchdog);
1507
1508                 cond_resched();
1509
1510                 l_wait_event_exclusive (svc->srv_waitq,
1511                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1512                                svc->srv_n_difficult_replies == 0) ||
1513                               (!list_empty(&svc->srv_idle_rqbds) &&
1514                                svc->srv_rqbd_timeout == 0) ||
1515                               !list_empty(&svc->srv_req_in_queue) ||
1516                               !list_empty(&svc->srv_reply_queue) ||
1517                               (!list_empty(&svc->srv_request_queue) &&
1518                                (svc->srv_n_active_reqs <
1519                                 (svc->srv_threads_running - 1))) ||
1520                               svc->srv_at_check,
1521                               &lwi);
1522
1523                 lc_watchdog_touch_ms(watchdog, max_t(int, obd_timeout,
1524                                      AT_OFF ? 0 :
1525                                      at_get(&svc->srv_at_estimate)) *
1526                                      svc->srv_watchdog_factor);
1527
1528                 ptlrpc_check_rqbd_pool(svc);
1529
1530                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1531                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1532                         /* Ignore return code - we tried... */
1533                         ptlrpc_start_thread(dev, svc);
1534                 }
1535
1536                 if (!list_empty(&svc->srv_reply_queue))
1537                         ptlrpc_server_handle_reply(svc);
1538
1539                 if (!list_empty(&svc->srv_req_in_queue)) {
1540                         /* Process all incoming reqs before handling any */
1541                         ptlrpc_server_handle_req_in(svc);
1542                         /* but limit ourselves in case of flood */
1543                         if (counter++ < 1000)
1544                                 continue;
1545                         counter = 0;
1546                 }
1547
1548                 if (svc->srv_at_check)
1549                         ptlrpc_at_check_timed(svc);
1550
1551                 /* don't handle requests in the last thread */
1552                 if (!list_empty (&svc->srv_request_queue) &&
1553                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
1554                         lu_context_enter(&env.le_ctx);
1555                         ptlrpc_server_handle_request(svc, thread);
1556                         lu_context_exit(&env.le_ctx);
1557                 }
1558
1559                 if (!list_empty(&svc->srv_idle_rqbds) &&
1560                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1561                         /* I just failed to repost request buffers.  Wait
1562                          * for a timeout (unless something else happens)
1563                          * before I try again */
1564                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1565                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1566                                svc->srv_nrqbd_receiving);
1567                 }
1568         }
1569
1570         lc_watchdog_delete(watchdog);
1571
1572 out_srv_fini:
1573         /*
1574          * deconstruct service specific state created by ptlrpc_start_thread()
1575          */
1576         if (svc->srv_done != NULL)
1577                 svc->srv_done(thread);
1578
1579         lu_context_fini(&env.le_ctx);
1580 out:
1581         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1582
1583         spin_lock(&svc->srv_lock);
1584         svc->srv_threads_running--; /* must know immediately */
1585         thread->t_id = rc;
1586         thread->t_flags = SVC_STOPPED;
1587
1588         cfs_waitq_signal(&thread->t_ctl_waitq);
1589         spin_unlock(&svc->srv_lock);
1590
1591         return rc;
1592 }
1593
1594 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1595                                struct ptlrpc_thread *thread)
1596 {
1597         struct l_wait_info lwi = { 0 };
1598         ENTRY;
1599
1600         CDEBUG(D_RPCTRACE, "Stopping thread %p\n", thread);
1601         spin_lock(&svc->srv_lock);
1602         thread->t_flags = SVC_STOPPING;
1603         spin_unlock(&svc->srv_lock);
1604
1605         cfs_waitq_broadcast(&svc->srv_waitq);
1606         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1607                      &lwi);
1608
1609         spin_lock(&svc->srv_lock);
1610         list_del(&thread->t_link);
1611         spin_unlock(&svc->srv_lock);
1612
1613         OBD_FREE_PTR(thread);
1614         EXIT;
1615 }
1616
1617 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1618 {
1619         struct ptlrpc_thread *thread;
1620         ENTRY;
1621
1622         spin_lock(&svc->srv_lock);
1623         while (!list_empty(&svc->srv_threads)) {
1624                 thread = list_entry(svc->srv_threads.next,
1625                                     struct ptlrpc_thread, t_link);
1626
1627                 spin_unlock(&svc->srv_lock);
1628                 ptlrpc_stop_thread(svc, thread);
1629                 spin_lock(&svc->srv_lock);
1630         }
1631
1632         spin_unlock(&svc->srv_lock);
1633         EXIT;
1634 }
1635
1636 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1637 {
1638         int i, rc = 0;
1639         ENTRY;
1640
1641         /* We require 2 threads min - see note in
1642            ptlrpc_server_handle_request */
1643         LASSERT(svc->srv_threads_min >= 2);
1644         for (i = 0; i < svc->srv_threads_min; i++) {
1645                 rc = ptlrpc_start_thread(dev, svc);
1646                 /* We have enough threads, don't start more.  b=15759 */
1647                 if (rc == -EMFILE)
1648                         break;
1649                 if (rc) {
1650                         CERROR("cannot start %s thread #%d: rc %d\n",
1651                                svc->srv_thread_name, i, rc);
1652                         ptlrpc_stop_all_threads(svc);
1653                 }
1654         }
1655         RETURN(rc);
1656 }
1657
1658 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1659 {
1660         struct l_wait_info lwi = { 0 };
1661         struct ptlrpc_svc_data d;
1662         struct ptlrpc_thread *thread;
1663         char name[32];
1664         int id, rc;
1665         ENTRY;
1666
1667         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1668                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1669                svc->srv_threads_max, svc->srv_threads_running);
1670         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
1671             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
1672              svc->srv_threads_started == svc->srv_threads_min - 1))
1673                 RETURN(-EMFILE);
1674
1675         OBD_ALLOC_PTR(thread);
1676         if (thread == NULL)
1677                 RETURN(-ENOMEM);
1678         cfs_waitq_init(&thread->t_ctl_waitq);
1679
1680         spin_lock(&svc->srv_lock);
1681         if (svc->srv_threads_started >= svc->srv_threads_max) {
1682                 spin_unlock(&svc->srv_lock);
1683                 OBD_FREE_PTR(thread);
1684                 RETURN(-EMFILE);
1685         }
1686         list_add(&thread->t_link, &svc->srv_threads);
1687         id = svc->srv_threads_started++;
1688         spin_unlock(&svc->srv_lock);
1689
1690         thread->t_id = id;
1691         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1692         d.dev = dev;
1693         d.svc = svc;
1694         d.name = name;
1695         d.thread = thread;
1696
1697         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1698
1699           /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1700          * just drop the VM and FILES in ptlrpc_daemonize() right away.
1701          */
1702         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1703         if (rc < 0) {
1704                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1705
1706                 spin_lock(&svc->srv_lock);
1707                 list_del(&thread->t_link);
1708                 --svc->srv_threads_started;
1709                 spin_unlock(&svc->srv_lock);
1710
1711                 OBD_FREE(thread, sizeof(*thread));
1712                 RETURN(rc);
1713         }
1714         l_wait_event(thread->t_ctl_waitq,
1715                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1716
1717         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1718         RETURN(rc);
1719 }
1720 #endif
1721
1722 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1723 {
1724         int                   rc;
1725         struct l_wait_info    lwi;
1726         struct list_head     *tmp;
1727         struct ptlrpc_reply_state *rs, *t;
1728         ENTRY;
1729
1730         service->srv_is_stopping = 1;
1731         cfs_timer_disarm(&service->srv_at_timer);
1732
1733         ptlrpc_stop_all_threads(service);
1734         LASSERT(list_empty(&service->srv_threads));
1735
1736         spin_lock (&ptlrpc_all_services_lock);
1737         list_del_init (&service->srv_list);
1738         spin_unlock (&ptlrpc_all_services_lock);
1739
1740         ptlrpc_lprocfs_unregister_service(service);
1741
1742         /* All history will be culled when the next request buffer is
1743          * freed */
1744         service->srv_max_history_rqbds = 0;
1745
1746         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1747
1748         rc = LNetClearLazyPortal(service->srv_req_portal);
1749         LASSERT (rc == 0);
1750
1751         /* Unlink all the request buffers.  This forces a 'final' event with
1752          * its 'unlink' flag set for each posted rqbd */
1753         list_for_each(tmp, &service->srv_active_rqbds) {
1754                 struct ptlrpc_request_buffer_desc *rqbd =
1755                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
1756                                    rqbd_list);
1757
1758                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1759                 LASSERT (rc == 0 || rc == -ENOENT);
1760         }
1761
1762         /* Wait for the network to release any buffers it's currently
1763          * filling */
1764         for (;;) {
1765                 spin_lock(&service->srv_lock);
1766                 rc = service->srv_nrqbd_receiving;
1767                 spin_unlock(&service->srv_lock);
1768
1769                 if (rc == 0)
1770                         break;
1771
1772                 /* Network access will complete in finite time but the HUGE
1773                  * timeout lets us CWARN for visibility of sluggish NALs */
1774                 lwi = LWI_TIMEOUT(cfs_time_seconds(LONG_UNLINK), NULL, NULL);
1775                 rc = l_wait_event(service->srv_waitq,
1776                                   service->srv_nrqbd_receiving == 0,
1777                                   &lwi);
1778                 if (rc == -ETIMEDOUT)
1779                         CWARN("Service %s waiting for request buffers\n",
1780                               service->srv_name);
1781         }
1782
1783         /* schedule all outstanding replies to terminate them */
1784         spin_lock(&service->srv_lock);
1785         while (!list_empty(&service->srv_active_replies)) {
1786                 struct ptlrpc_reply_state *rs =
1787                         list_entry(service->srv_active_replies.next,
1788                                    struct ptlrpc_reply_state, rs_list);
1789                 ptlrpc_schedule_difficult_reply(rs);
1790         }
1791         spin_unlock(&service->srv_lock);
1792
1793         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1794          * and no service threads, so I'm the only thread noodling the
1795          * request queue now */
1796         while (!list_empty(&service->srv_req_in_queue)) {
1797                 struct ptlrpc_request *req =
1798                         list_entry(service->srv_req_in_queue.next,
1799                                    struct ptlrpc_request,
1800                                    rq_list);
1801
1802                 list_del(&req->rq_list);
1803                 service->srv_n_queued_reqs--;
1804                 service->srv_n_active_reqs++;
1805                 ptlrpc_server_finish_request(req);
1806         }
1807         while (!list_empty(&service->srv_request_queue)) {
1808                 struct ptlrpc_request *req =
1809                         list_entry(service->srv_request_queue.next,
1810                                    struct ptlrpc_request,
1811                                    rq_list);
1812
1813                 list_del(&req->rq_list);
1814                 service->srv_n_queued_reqs--;
1815                 service->srv_n_active_reqs++;
1816
1817                 ptlrpc_server_finish_request(req);
1818         }
1819         LASSERT(service->srv_n_queued_reqs == 0);
1820         LASSERT(service->srv_n_active_reqs == 0);
1821         LASSERT(service->srv_n_history_rqbds == 0);
1822         LASSERT(list_empty(&service->srv_active_rqbds));
1823
1824         /* Now free all the request buffers since nothing references them
1825          * any more... */
1826         while (!list_empty(&service->srv_idle_rqbds)) {
1827                 struct ptlrpc_request_buffer_desc *rqbd =
1828                         list_entry(service->srv_idle_rqbds.next,
1829                                    struct ptlrpc_request_buffer_desc,
1830                                    rqbd_list);
1831
1832                 ptlrpc_free_rqbd(rqbd);
1833         }
1834
1835         /* wait for all outstanding replies to complete (they were
1836          * scheduled having been flagged to abort above) */
1837         while (atomic_read(&service->srv_outstanding_replies) != 0) {
1838                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
1839
1840                 rc = l_wait_event(service->srv_waitq,
1841                                   !list_empty(&service->srv_reply_queue), &lwi);
1842                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1843
1844                 if (rc == 0) {
1845                         ptlrpc_server_handle_reply(service);
1846                         continue;
1847                 }
1848                 CWARN("Unexpectedly long timeout %p\n", service);
1849         }
1850
1851         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
1852                 list_del(&rs->rs_list);
1853                 OBD_FREE(rs, service->srv_max_reply_size);
1854         }
1855
1856         /* In case somebody rearmed this in the meantime */
1857         cfs_timer_disarm(&service->srv_at_timer);
1858
1859         OBD_FREE_PTR(service);
1860         RETURN(0);
1861 }
1862
1863 /* Returns 0 if the service is healthy.
1864  *
1865  * Right now, it just checks to make sure that requests aren't languishing
1866  * in the queue.  We'll use this health check to govern whether a node needs
1867  * to be shot, so it's intentionally non-aggressive. */
1868 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
1869 {
1870         struct ptlrpc_request *request;
1871         struct timeval         right_now;
1872         long                   timediff;
1873
1874         if (svc == NULL)
1875                 return 0;
1876
1877         do_gettimeofday(&right_now);
1878
1879         spin_lock(&svc->srv_lock);
1880         if (list_empty(&svc->srv_request_queue)) {
1881                 spin_unlock(&svc->srv_lock);
1882                 return 0;
1883         }
1884
1885         /* How long has the next entry been waiting? */
1886         request = list_entry(svc->srv_request_queue.next,
1887                              struct ptlrpc_request, rq_list);
1888         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
1889         spin_unlock(&svc->srv_lock);
1890
1891         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
1892                                         at_max)) {
1893                 CERROR("%s: unhealthy - request has been waiting %lds\n",
1894                        svc->srv_name, timediff / ONE_MILLION);
1895                 return (-1);
1896         }
1897
1898         return 0;
1899 }