Whamcloud - gitweb
2f3b02f1a319be95bb458d4d38706665e466cddd
[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  *  Copyright (C) 2002 Cluster File Systems, Inc.
5  *
6  *   This file is part of the Lustre file system, http://www.lustre.org
7  *   Lustre is a trademark of Cluster File Systems, Inc.
8  *
9  *   You may have signed or agreed to another license before downloading
10  *   this software.  If so, you are bound by the terms and conditions
11  *   of that agreement, and the following does not apply to you.  See the
12  *   LICENSE file included with this distribution for more information.
13  *
14  *   If you did not agree to a different license, then this copy of Lustre
15  *   is open source software; you can redistribute it and/or modify it
16  *   under the terms of version 2 of the GNU General Public License as
17  *   published by the Free Software Foundation.
18  *
19  *   In either case, Lustre is distributed in the hope that it will be
20  *   useful, but WITHOUT ANY WARRANTY; without even the implied warranty
21  *   of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   license text for more details.
23  *
24  */
25
26 #define DEBUG_SUBSYSTEM S_RPC
27 #ifndef __KERNEL__
28 #include <liblustre.h>
29 #include <libcfs/kp30.h>
30 #endif
31 #include <obd_support.h>
32 #include <obd_class.h>
33 #include <lustre_net.h>
34 #include <lu_object.h>
35 #include <lnet/types.h>
36 #include "ptlrpc_internal.h"
37
38 int test_req_buffer_pressure = 0;
39 CFS_MODULE_PARM(test_req_buffer_pressure, "i", int, 0444,
40                 "set non-zero to put pressure on request buffer pools");
41
42 /* forward ref */
43 static int ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc);
44
45 static CFS_LIST_HEAD (ptlrpc_all_services);
46 spinlock_t ptlrpc_all_services_lock;
47
48 static char *
49 ptlrpc_alloc_request_buffer (int size)
50 {
51         char *ptr;
52
53         if (size > SVC_BUF_VMALLOC_THRESHOLD)
54                 OBD_VMALLOC(ptr, size);
55         else
56                 OBD_ALLOC(ptr, size);
57
58         return (ptr);
59 }
60
61 static void
62 ptlrpc_free_request_buffer (char *ptr, int size)
63 {
64         if (size > SVC_BUF_VMALLOC_THRESHOLD)
65                 OBD_VFREE(ptr, size);
66         else
67                 OBD_FREE(ptr, size);
68 }
69
70 struct ptlrpc_request_buffer_desc *
71 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
72 {
73         struct ptlrpc_request_buffer_desc *rqbd;
74
75         OBD_ALLOC_PTR(rqbd);
76         if (rqbd == NULL)
77                 return (NULL);
78
79         rqbd->rqbd_service = svc;
80         rqbd->rqbd_refcount = 0;
81         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
82         rqbd->rqbd_cbid.cbid_arg = rqbd;
83         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
84         rqbd->rqbd_buffer = ptlrpc_alloc_request_buffer(svc->srv_buf_size);
85
86         if (rqbd->rqbd_buffer == NULL) {
87                 OBD_FREE_PTR(rqbd);
88                 return (NULL);
89         }
90
91         spin_lock(&svc->srv_lock);
92         list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
93         svc->srv_nbufs++;
94         spin_unlock(&svc->srv_lock);
95
96         return (rqbd);
97 }
98
99 void
100 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
101 {
102         struct ptlrpc_service *svc = rqbd->rqbd_service;
103
104         LASSERT (rqbd->rqbd_refcount == 0);
105         LASSERT (list_empty(&rqbd->rqbd_reqs));
106
107         spin_lock(&svc->srv_lock);
108         list_del(&rqbd->rqbd_list);
109         svc->srv_nbufs--;
110         spin_unlock(&svc->srv_lock);
111
112         ptlrpc_free_request_buffer (rqbd->rqbd_buffer, svc->srv_buf_size);
113         OBD_FREE_PTR(rqbd);
114 }
115
116 int
117 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
118 {
119         struct ptlrpc_request_buffer_desc *rqbd;
120         int                                i;
121
122         CDEBUG(D_RPCTRACE, "%s: allocate %d new %d-byte reqbufs (%d/%d left)\n",
123                svc->srv_name, svc->srv_nbuf_per_group, svc->srv_buf_size,
124                svc->srv_nrqbd_receiving, svc->srv_nbufs);
125         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
126                 rqbd = ptlrpc_alloc_rqbd(svc);
127
128                 if (rqbd == NULL) {
129                         CERROR ("%s: Can't allocate request buffer\n",
130                                 svc->srv_name);
131                         return (-ENOMEM);
132                 }
133
134                 if (ptlrpc_server_post_idle_rqbds(svc) < 0)
135                         return (-EAGAIN);
136         }
137
138         return (0);
139 }
140
141 void
142 ptlrpc_save_lock (struct ptlrpc_request *req,
143                   struct lustre_handle *lock, int mode)
144 {
145         struct ptlrpc_reply_state *rs = req->rq_reply_state;
146         int                        idx;
147
148         LASSERT(rs != NULL);
149         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
150
151         idx = rs->rs_nlocks++;
152         rs->rs_locks[idx] = *lock;
153         rs->rs_modes[idx] = mode;
154         rs->rs_difficult = 1;
155 }
156
157 void
158 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
159 {
160         struct ptlrpc_service *svc = rs->rs_service;
161
162 #ifdef CONFIG_SMP
163         LASSERT (spin_is_locked (&svc->srv_lock));
164 #endif
165         LASSERT (rs->rs_difficult);
166         rs->rs_scheduled_ever = 1;              /* flag any notification attempt */
167
168         if (rs->rs_scheduled)                   /* being set up or already notified */
169                 return;
170
171         rs->rs_scheduled = 1;
172         list_del (&rs->rs_list);
173         list_add (&rs->rs_list, &svc->srv_reply_queue);
174         cfs_waitq_signal (&svc->srv_waitq);
175 }
176
177 void
178 ptlrpc_commit_replies (struct obd_device *obd)
179 {
180         struct list_head   *tmp;
181         struct list_head   *nxt;
182
183         /* Find any replies that have been committed and get their service
184          * to attend to complete them. */
185
186         /* CAVEAT EMPTOR: spinlock ordering!!! */
187         spin_lock(&obd->obd_uncommitted_replies_lock);
188
189         list_for_each_safe (tmp, nxt, &obd->obd_uncommitted_replies) {
190                 struct ptlrpc_reply_state *rs =
191                         list_entry(tmp, struct ptlrpc_reply_state, rs_obd_list);
192
193                 LASSERT (rs->rs_difficult);
194
195                 if (rs->rs_transno <= obd->obd_last_committed) {
196                         struct ptlrpc_service *svc = rs->rs_service;
197
198                         spin_lock (&svc->srv_lock);
199                         list_del_init (&rs->rs_obd_list);
200                         ptlrpc_schedule_difficult_reply (rs);
201                         spin_unlock (&svc->srv_lock);
202                 }
203         }
204
205         spin_unlock(&obd->obd_uncommitted_replies_lock);
206 }
207
208 static int
209 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
210 {
211         struct ptlrpc_request_buffer_desc *rqbd;
212         int                                rc;
213         int                                posted = 0;
214
215         for (;;) {
216                 spin_lock(&svc->srv_lock);
217
218                 if (list_empty (&svc->srv_idle_rqbds)) {
219                         spin_unlock(&svc->srv_lock);
220                         return (posted);
221                 }
222
223                 rqbd = list_entry(svc->srv_idle_rqbds.next,
224                                   struct ptlrpc_request_buffer_desc,
225                                   rqbd_list);
226                 list_del (&rqbd->rqbd_list);
227
228                 /* assume we will post successfully */
229                 svc->srv_nrqbd_receiving++;
230                 list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
231
232                 spin_unlock(&svc->srv_lock);
233
234                 rc = ptlrpc_register_rqbd(rqbd);
235                 if (rc != 0)
236                         break;
237
238                 posted = 1;
239         }
240
241         spin_lock(&svc->srv_lock);
242
243         svc->srv_nrqbd_receiving--;
244         list_del(&rqbd->rqbd_list);
245         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
246
247         /* Don't complain if no request buffers are posted right now; LNET
248          * won't drop requests because we set the portal lazy! */
249
250         spin_unlock(&svc->srv_lock);
251
252         return (-1);
253 }
254
255 struct ptlrpc_service *ptlrpc_init_svc_conf(struct ptlrpc_service_conf *c,
256                                             svc_handler_t h, char *name,
257                                             struct proc_dir_entry *proc_entry,
258                                             svcreq_printfn_t prntfn,
259                                             char *threadname)
260 {
261         return ptlrpc_init_svc(c->psc_nbufs, c->psc_bufsize,
262                                c->psc_max_req_size, c->psc_max_reply_size,
263                                c->psc_req_portal, c->psc_rep_portal,
264                                c->psc_watchdog_timeout,
265                                h, name, proc_entry,
266                                prntfn, c->psc_min_threads, c->psc_max_threads,
267                                threadname, c->psc_ctx_tags);
268 }
269 EXPORT_SYMBOL(ptlrpc_init_svc_conf);
270
271 /* @threadname should be 11 characters or less - 3 will be added on */
272 struct ptlrpc_service *
273 ptlrpc_init_svc(int nbufs, int bufsize, int max_req_size, int max_reply_size,
274                 int req_portal, int rep_portal, int watchdog_timeout,
275                 svc_handler_t handler, char *name,
276                 cfs_proc_dir_entry_t *proc_entry,
277                 svcreq_printfn_t svcreq_printfn,
278                 int min_threads, int max_threads,
279                 char *threadname, __u32 ctx_tags)
280 {
281         int                    rc;
282         struct ptlrpc_service *service;
283         ENTRY;
284
285         LASSERT (nbufs > 0);
286         LASSERT (bufsize >= max_req_size + SPTLRPC_MAX_PAYLOAD);
287         LASSERT (ctx_tags != 0);
288
289         OBD_ALLOC_PTR(service);
290         if (service == NULL)
291                 RETURN(NULL);
292
293         /* First initialise enough for early teardown */
294
295         service->srv_name = name;
296         spin_lock_init(&service->srv_lock);
297         CFS_INIT_LIST_HEAD(&service->srv_threads);
298         cfs_waitq_init(&service->srv_waitq);
299
300         service->srv_nbuf_per_group = test_req_buffer_pressure ? 1 : nbufs;
301         service->srv_max_req_size = max_req_size + SPTLRPC_MAX_PAYLOAD;
302         service->srv_buf_size = bufsize;
303         service->srv_rep_portal = rep_portal;
304         service->srv_req_portal = req_portal;
305         service->srv_watchdog_timeout = watchdog_timeout;
306         service->srv_handler = handler;
307         service->srv_request_history_print_fn = svcreq_printfn;
308         service->srv_request_seq = 1;           /* valid seq #s start at 1 */
309         service->srv_request_max_cull_seq = 0;
310         service->srv_threads_min = min_threads;
311         service->srv_threads_max = max_threads;
312         service->srv_thread_name = threadname;
313         service->srv_ctx_tags = ctx_tags;
314
315         rc = LNetSetLazyPortal(service->srv_req_portal);
316         LASSERT (rc == 0);
317
318         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
319         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
320         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
321         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
322         CFS_INIT_LIST_HEAD(&service->srv_request_history);
323         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
324         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
325         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
326         cfs_waitq_init(&service->srv_free_rs_waitq);
327
328         spin_lock (&ptlrpc_all_services_lock);
329         list_add (&service->srv_list, &ptlrpc_all_services);
330         spin_unlock (&ptlrpc_all_services_lock);
331
332         /* Now allocate the request buffers */
333         rc = ptlrpc_grow_req_bufs(service);
334         /* We shouldn't be under memory pressure at startup, so
335          * fail if we can't post all our buffers at this time. */
336         if (rc != 0)
337                 GOTO(failed, NULL);
338
339         /* Now allocate pool of reply buffers */
340         /* Increase max reply size to next power of two */
341         service->srv_max_reply_size = 1;
342         while (service->srv_max_reply_size <
343                max_reply_size + SPTLRPC_MAX_PAYLOAD)
344                 service->srv_max_reply_size <<= 1;
345
346         if (proc_entry != NULL)
347                 ptlrpc_lprocfs_register_service(proc_entry, service);
348
349         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
350                service->srv_name, service->srv_req_portal);
351
352         RETURN(service);
353 failed:
354         ptlrpc_unregister_service(service);
355         return NULL;
356 }
357
358 static void __ptlrpc_server_free_request(struct ptlrpc_request *req)
359 {
360         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
361
362         list_del(&req->rq_list);
363
364         if (req->rq_reply_state != NULL) {
365                 ptlrpc_rs_decref(req->rq_reply_state);
366                 req->rq_reply_state = NULL;
367         }
368
369         sptlrpc_svc_ctx_decref(req);
370
371         if (req != &rqbd->rqbd_req) {
372                 /* NB request buffers use an embedded
373                  * req if the incoming req unlinked the
374                  * MD; this isn't one of them! */
375                 OBD_FREE(req, sizeof(*req));
376         }
377 }
378
379 static void
380 ptlrpc_server_free_request(struct ptlrpc_request *req)
381 {
382         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
383         struct ptlrpc_service             *svc = rqbd->rqbd_service;
384         int                                refcount;
385         struct list_head                  *tmp;
386         struct list_head                  *nxt;
387
388         spin_lock(&svc->srv_lock);
389
390         svc->srv_n_active_reqs--;
391         list_add(&req->rq_list, &rqbd->rqbd_reqs);
392
393         refcount = --(rqbd->rqbd_refcount);
394         if (refcount == 0) {
395                 /* request buffer is now idle: add to history */
396                 list_del(&rqbd->rqbd_list);
397                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
398                 svc->srv_n_history_rqbds++;
399
400                 /* cull some history?
401                  * I expect only about 1 or 2 rqbds need to be recycled here */
402                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
403                         rqbd = list_entry(svc->srv_history_rqbds.next,
404                                           struct ptlrpc_request_buffer_desc,
405                                           rqbd_list);
406
407                         list_del(&rqbd->rqbd_list);
408                         svc->srv_n_history_rqbds--;
409
410                         /* remove rqbd's reqs from svc's req history while
411                          * I've got the service lock */
412                         list_for_each(tmp, &rqbd->rqbd_reqs) {
413                                 req = list_entry(tmp, struct ptlrpc_request,
414                                                  rq_list);
415                                 /* Track the highest culled req seq */
416                                 if (req->rq_history_seq >
417                                     svc->srv_request_max_cull_seq)
418                                         svc->srv_request_max_cull_seq =
419                                                 req->rq_history_seq;
420                                 list_del(&req->rq_history_list);
421                         }
422
423                         spin_unlock(&svc->srv_lock);
424
425                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
426                                 req = list_entry(rqbd->rqbd_reqs.next,
427                                                  struct ptlrpc_request,
428                                                  rq_list);
429                                 __ptlrpc_server_free_request(req);
430                         }
431
432                         spin_lock(&svc->srv_lock);
433
434                         /* schedule request buffer for re-use.
435                          * NB I can only do this after I've disposed of their
436                          * reqs; particularly the embedded req */
437                         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
438                 }
439         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
440                  /* If we are low on memory, we are not interested in
441                     history */
442                 list_del(&req->rq_history_list);
443                 __ptlrpc_server_free_request(req);
444         }
445
446         spin_unlock(&svc->srv_lock);
447
448 }
449
450 /* This function makes sure dead exports are evicted in a timely manner.
451    This function is only called when some export receives a message (i.e.,
452    the network is up.) */
453 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
454 {
455         struct obd_export *oldest_exp;
456         time_t oldest_time;
457
458         ENTRY;
459
460         LASSERT(exp);
461
462         /* Compensate for slow machines, etc, by faking our request time
463            into the future.  Although this can break the strict time-ordering
464            of the list, we can be really lazy here - we don't have to evict
465            at the exact right moment.  Eventually, all silent exports
466            will make it to the top of the list. */
467         exp->exp_last_request_time = max(exp->exp_last_request_time,
468                                          (time_t)CURRENT_SECONDS + extra_delay);
469
470         CDEBUG(D_HA, "updating export %s at %ld exp %p\n",
471                exp->exp_client_uuid.uuid,
472                exp->exp_last_request_time, exp);
473
474         /* exports may get disconnected from the chain even though the
475            export has references, so we must keep the spin lock while
476            manipulating the lists */
477         spin_lock(&exp->exp_obd->obd_dev_lock);
478
479         if (list_empty(&exp->exp_obd_chain_timed)) {
480                 /* this one is not timed */
481                 spin_unlock(&exp->exp_obd->obd_dev_lock);
482                 EXIT;
483                 return;
484         }
485
486         list_move_tail(&exp->exp_obd_chain_timed,
487                        &exp->exp_obd->obd_exports_timed);
488
489         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
490                                 struct obd_export, exp_obd_chain_timed);
491         oldest_time = oldest_exp->exp_last_request_time;
492         spin_unlock(&exp->exp_obd->obd_dev_lock);
493
494         if (exp->exp_obd->obd_recovering) {
495                 /* be nice to everyone during recovery */
496                 EXIT;
497                 return;
498         }
499
500         /* Note - racing to start/reset the obd_eviction timer is safe */
501         if (exp->exp_obd->obd_eviction_timer == 0) {
502                 /* Check if the oldest entry is expired. */
503                 if (CURRENT_SECONDS > (oldest_time +
504                                        (3 * obd_timeout / 2) + extra_delay)) {
505                         /* We need a second timer, in case the net was down and
506                          * it just came back. Since the pinger may skip every
507                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
508                          * we better wait for 3. */
509                         exp->exp_obd->obd_eviction_timer = CURRENT_SECONDS +
510                                 3 * PING_INTERVAL;
511                         CDEBUG(D_HA, "%s: Think about evicting %s from %ld\n",
512                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
513                                oldest_time);
514                 }
515         } else {
516                 if (CURRENT_SECONDS > (exp->exp_obd->obd_eviction_timer +
517                                        extra_delay)) {
518                         /* The evictor won't evict anyone who we've heard from
519                          * recently, so we don't have to check before we start
520                          * it. */
521                         if (!ping_evictor_wake(exp))
522                                 exp->exp_obd->obd_eviction_timer = 0;
523                 }
524         }
525
526         EXIT;
527 }
528
529 #ifndef __KERNEL__
530 int lu_context_init(struct lu_context *ctx, __u32 tags)
531 {
532         return 0;
533 }
534
535 void lu_context_fini(struct lu_context *ctx)
536 {
537 }
538
539 void lu_context_enter(struct lu_context *ctx)
540 {
541 }
542
543 void lu_context_exit(struct lu_context *ctx)
544 {
545 }
546
547 #endif
548
549 static int
550 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
551                              struct ptlrpc_thread *thread)
552 {
553         struct obd_export     *export = NULL;
554         struct ptlrpc_request *request;
555         struct timeval         work_start;
556         struct timeval         work_end;
557         long                   timediff;
558         int                    rc, reply;
559         ENTRY;
560
561         LASSERT(svc);
562
563         spin_lock(&svc->srv_lock);
564         if (unlikely(list_empty (&svc->srv_request_queue) ||
565                      (svc->srv_n_difficult_replies != 0 &&
566                       svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
567                 /* If all the other threads are handling requests, I must
568                  * remain free to handle any 'difficult' reply that might
569                  * block them */
570                 spin_unlock(&svc->srv_lock);
571                 RETURN(0);
572         }
573
574         request = list_entry (svc->srv_request_queue.next,
575                               struct ptlrpc_request, rq_list);
576         list_del_init (&request->rq_list);
577         svc->srv_n_queued_reqs--;
578         svc->srv_n_active_reqs++;
579
580         spin_unlock(&svc->srv_lock);
581
582         do_gettimeofday(&work_start);
583         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
584         if (likely(svc->srv_stats != NULL)) {
585                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
586                                     timediff);
587                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
588                                     svc->srv_n_queued_reqs);
589                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
590                                     svc->srv_n_active_reqs);
591         }
592
593         /* go through security check/transform */
594         request->rq_auth_uid = INVALID_UID;
595         request->rq_auth_mapped_uid = INVALID_UID;
596
597         rc = sptlrpc_svc_unwrap_request(request);
598         switch (rc) {
599         case SECSVC_OK:
600                 break;
601         case SECSVC_COMPLETE:
602                 target_send_reply(request, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
603                 goto put_conn;
604         case SECSVC_DROP:
605                 goto out_req;
606         default:
607                 LBUG();
608         }
609
610 #if SWAB_PARANOIA
611         /* Clear request swab mask; this is a new request */
612         request->rq_req_swab_mask = 0;
613 #endif
614         rc = lustre_unpack_msg(request->rq_reqmsg, request->rq_reqlen);
615         if (rc != 0) {
616                 CERROR ("error unpacking request: ptl %d from %s"
617                         " xid "LPU64"\n", svc->srv_req_portal,
618                         libcfs_id2str(request->rq_peer), request->rq_xid);
619                 goto out_req;
620         }
621
622         rc = lustre_unpack_req_ptlrpc_body(request, MSG_PTLRPC_BODY_OFF);
623         if (rc) {
624                 CERROR ("error unpacking ptlrpc body: ptl %d from %s"
625                         " xid "LPU64"\n", svc->srv_req_portal,
626                         libcfs_id2str(request->rq_peer), request->rq_xid);
627                 goto out_req;
628         }
629
630         rc = -EINVAL;
631         if (lustre_msg_get_type(request->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
632                 CERROR("wrong packet type received (type=%u) from %s\n",
633                        lustre_msg_get_type(request->rq_reqmsg),
634                        libcfs_id2str(request->rq_peer));
635                 goto out_req;
636         }
637
638         rc = lu_context_init(&request->rq_session, LCT_SESSION);
639         if (rc) {
640                 CERROR("Failure to initialize session: %d\n", rc);
641                 goto out_req;
642         }
643         request->rq_session.lc_thread = thread;
644         lu_context_enter(&request->rq_session);
645
646         CDEBUG(D_NET, "got req "LPD64"\n", request->rq_xid);
647
648         request->rq_svc_thread = thread;
649         if (thread)
650                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
651
652         request->rq_export = class_conn2export(
653                                      lustre_msg_get_handle(request->rq_reqmsg));
654
655         if (likely(request->rq_export)) {
656                 if (unlikely(lustre_msg_get_conn_cnt(request->rq_reqmsg) <
657                              request->rq_export->exp_conn_cnt)) {
658                         DEBUG_REQ(D_ERROR, request,
659                                   "DROPPING req from old connection %d < %d",
660                                   lustre_msg_get_conn_cnt(request->rq_reqmsg),
661                                   request->rq_export->exp_conn_cnt);
662                         goto put_conn;
663                 }
664                 if (unlikely(request->rq_export->exp_obd &&
665                              request->rq_export->exp_obd->obd_fail)) {
666                         /* Failing over, don't handle any more reqs, send
667                            error response instead. */
668                         CDEBUG(D_HA, "Dropping req %p for failed obd %s\n",
669                                request, request->rq_export->exp_obd->obd_name);
670                         request->rq_status = -ENODEV;
671                         ptlrpc_error(request);
672                         goto put_conn;
673                 }
674
675                 rc = sptlrpc_target_export_check(request->rq_export, request);
676                 if (unlikely(rc)) {
677                         DEBUG_REQ(D_ERROR, request,
678                                   "DROPPING req with illeagle security flavor");
679                         goto put_conn;
680                 }
681
682                 ptlrpc_update_export_timer(request->rq_export, timediff/500000);
683                 export = class_export_rpc_get(request->rq_export);
684         }
685
686         /* Discard requests queued for longer than my timeout.  If the
687          * client's timeout is similar to mine, she'll be timing out this
688          * REQ anyway (bug 1502) */
689         if (unlikely(timediff / 1000000 > (long)obd_timeout)) {
690                 CERROR("Dropping timed-out opc %d request from %s"
691                        ": %ld seconds old\n",
692                        lustre_msg_get_opc(request->rq_reqmsg),
693                        libcfs_id2str(request->rq_peer),
694                        timediff / 1000000);
695                 goto put_rpc_export;
696         }
697
698         request->rq_phase = RQ_PHASE_INTERPRET;
699
700         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
701                "%s:%s+%d:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
702                (request->rq_export ?
703                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
704                (request->rq_export ?
705                 atomic_read(&request->rq_export->exp_refcount) : -99),
706                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
707                libcfs_id2str(request->rq_peer),
708                lustre_msg_get_opc(request->rq_reqmsg));
709
710         rc = svc->srv_handler(request);
711
712         request->rq_phase = RQ_PHASE_COMPLETE;
713
714         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
715                "%s:%s+%d:%d:"LPU64":%s:%d\n", cfs_curproc_comm(),
716                (request->rq_export ?
717                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
718                (request->rq_export ?
719                 atomic_read(&request->rq_export->exp_refcount) : -99),
720                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
721                libcfs_id2str(request->rq_peer),
722                lustre_msg_get_opc(request->rq_reqmsg));
723
724 put_rpc_export:
725         if (export != NULL)
726                 class_export_rpc_put(export);
727 put_conn:
728         if (likely(request->rq_export != NULL))
729                 class_export_put(request->rq_export);
730
731         lu_context_exit(&request->rq_session);
732         lu_context_fini(&request->rq_session);
733
734         reply = request->rq_reply_state && request->rq_repmsg;  /* bug 11169 */
735
736         do_gettimeofday(&work_end);
737
738         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
739
740         if (unlikely(timediff / 1000000 > (long)obd_timeout))
741                 CERROR("request "LPU64" opc %u from %s processed in %lds "
742                        "trans "LPU64" rc %d/%d\n",
743                        request->rq_xid,
744                        request->rq_reqmsg ?
745                                 lustre_msg_get_opc(request->rq_reqmsg) : 0,
746                        libcfs_id2str(request->rq_peer),
747                        cfs_timeval_sub(&work_end, &request->rq_arrival_time,
748                                        NULL) / 1000000,
749                        reply ? lustre_msg_get_transno(request->rq_repmsg) :
750                                request->rq_transno, request->rq_status,
751                        reply ? lustre_msg_get_status(request->rq_repmsg) : -999);
752         else
753                 CDEBUG(D_HA, "request "LPU64" opc %u from %s processed in "
754                        "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
755                        request->rq_xid,
756                        request->rq_reqmsg ?
757                                 lustre_msg_get_opc(request->rq_reqmsg) : 0,
758                        libcfs_id2str(request->rq_peer), timediff,
759                        cfs_timeval_sub(&work_end, &request->rq_arrival_time,
760                                        NULL),
761                        request->rq_transno, request->rq_status,
762                        reply ? lustre_msg_get_status(request->rq_repmsg) : -999);
763
764         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
765                 int opc = opcode_offset(lustre_msg_get_opc(request->rq_reqmsg));
766                 if (opc > 0) {
767                         LASSERT(opc < LUSTRE_MAX_OPCODES);
768                         lprocfs_counter_add(svc->srv_stats,
769                                             opc + PTLRPC_LAST_CNTR,
770                                             timediff);
771                 }
772         }
773
774 out_req:
775         ptlrpc_server_free_request(request);
776
777         RETURN(1);
778 }
779
780 static int
781 ptlrpc_server_handle_reply (struct ptlrpc_service *svc)
782 {
783         struct ptlrpc_reply_state *rs;
784         struct obd_export         *exp;
785         struct obd_device         *obd;
786         int                        nlocks;
787         int                        been_handled;
788         ENTRY;
789
790         spin_lock(&svc->srv_lock);
791         if (list_empty (&svc->srv_reply_queue)) {
792                 spin_unlock(&svc->srv_lock);
793                 RETURN(0);
794         }
795
796         rs = list_entry (svc->srv_reply_queue.next,
797                          struct ptlrpc_reply_state, rs_list);
798
799         exp = rs->rs_export;
800         obd = exp->exp_obd;
801
802         LASSERT (rs->rs_difficult);
803         LASSERT (rs->rs_scheduled);
804
805         list_del_init (&rs->rs_list);
806
807         /* Disengage from notifiers carefully (lock order - irqrestore below!)*/
808         spin_unlock(&svc->srv_lock);
809
810         spin_lock (&obd->obd_uncommitted_replies_lock);
811         /* Noop if removed already */
812         list_del_init (&rs->rs_obd_list);
813         spin_unlock (&obd->obd_uncommitted_replies_lock);
814
815         spin_lock (&exp->exp_lock);
816         /* Noop if removed already */
817         list_del_init (&rs->rs_exp_list);
818         spin_unlock (&exp->exp_lock);
819
820         spin_lock(&svc->srv_lock);
821
822         been_handled = rs->rs_handled;
823         rs->rs_handled = 1;
824
825         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
826         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
827
828         if (nlocks == 0 && !been_handled) {
829                 /* If we see this, we should already have seen the warning
830                  * in mds_steal_ack_locks()  */
831                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
832                       " o%d NID %s\n",
833                       rs,
834                       rs->rs_xid, rs->rs_transno,
835                       lustre_msg_get_opc(rs->rs_msg),
836                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
837         }
838
839         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
840                 spin_unlock(&svc->srv_lock);
841
842                 if (!been_handled && rs->rs_on_net) {
843                         LNetMDUnlink(rs->rs_md_h);
844                         /* Ignore return code; we're racing with
845                          * completion... */
846                 }
847
848                 while (nlocks-- > 0)
849                         ldlm_lock_decref(&rs->rs_locks[nlocks],
850                                          rs->rs_modes[nlocks]);
851
852                 spin_lock(&svc->srv_lock);
853         }
854
855         rs->rs_scheduled = 0;
856
857         if (!rs->rs_on_net) {
858                 /* Off the net */
859                 svc->srv_n_difficult_replies--;
860                 spin_unlock(&svc->srv_lock);
861
862                 class_export_put (exp);
863                 rs->rs_export = NULL;
864                 ptlrpc_rs_decref (rs);
865                 atomic_dec (&svc->srv_outstanding_replies);
866                 RETURN(1);
867         }
868
869         /* still on the net; callback will schedule */
870         spin_unlock(&svc->srv_lock);
871         RETURN(1);
872 }
873
874 #ifndef __KERNEL__
875 /* FIXME make use of timeout later */
876 int
877 liblustre_check_services (void *arg)
878 {
879         int  did_something = 0;
880         int  rc;
881         struct list_head *tmp, *nxt;
882         ENTRY;
883
884         /* I'm relying on being single threaded, not to have to lock
885          * ptlrpc_all_services etc */
886         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
887                 struct ptlrpc_service *svc =
888                         list_entry (tmp, struct ptlrpc_service, srv_list);
889
890                 if (svc->srv_threads_running != 0)     /* I've recursed */
891                         continue;
892
893                 /* service threads can block for bulk, so this limits us
894                  * (arbitrarily) to recursing 1 stack frame per service.
895                  * Note that the problem with recursion is that we have to
896                  * unwind completely before our caller can resume. */
897
898                 svc->srv_threads_running++;
899
900                 do {
901                         rc = ptlrpc_server_handle_reply(svc);
902                         rc |= ptlrpc_server_handle_request(svc, NULL);
903                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
904                         did_something |= rc;
905                 } while (rc);
906
907                 svc->srv_threads_running--;
908         }
909
910         RETURN(did_something);
911 }
912 #define ptlrpc_stop_all_threads(s) do {} while (0)
913
914 #else /* __KERNEL__ */
915
916 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
917 void ptlrpc_daemonize(char *name)
918 {
919         struct fs_struct *fs = current->fs;
920
921         atomic_inc(&fs->count);
922         cfs_daemonize(name);
923         exit_fs(cfs_current());
924         current->fs = fs;
925         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
926 }
927
928 static void
929 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
930 {
931         int avail = svc->srv_nrqbd_receiving;
932         int low_water = test_req_buffer_pressure ? 0 :
933                         svc->srv_nbuf_per_group/2;
934
935         /* NB I'm not locking; just looking. */
936
937         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
938          * allowed the request history to grow out of control.  We could put a
939          * sanity check on that here and cull some history if we need the
940          * space. */
941
942         if (avail <= low_water)
943                 ptlrpc_grow_req_bufs(svc);
944
945         if (svc->srv_stats)
946                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
947                                     avail);
948 }
949
950 static int
951 ptlrpc_retry_rqbds(void *arg)
952 {
953         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
954
955         svc->srv_rqbd_timeout = 0;
956         return (-ETIMEDOUT);
957 }
958
959 static int ptlrpc_main(void *arg)
960 {
961         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
962         struct ptlrpc_service  *svc = data->svc;
963         struct ptlrpc_thread   *thread = data->thread;
964         struct obd_device      *dev = data->dev;
965         struct ptlrpc_reply_state *rs;
966         struct lc_watchdog     *watchdog;
967 #ifdef WITH_GROUP_INFO
968         struct group_info *ginfo = NULL;
969 #endif
970         struct lu_env env;
971         int rc = 0;
972         ENTRY;
973
974         ptlrpc_daemonize(data->name);
975
976 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
977         /* we need to do this before any per-thread allocation is done so that
978          * we get the per-thread allocations on local node.  bug 7342 */
979         if (svc->srv_cpu_affinity) {
980                 int cpu, num_cpu;
981
982                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
983                         if (!cpu_online(cpu))
984                                 continue;
985                         if (num_cpu == thread->t_id % num_online_cpus())
986                                 break;
987                         num_cpu++;
988                 }
989                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
990         }
991 #endif
992
993 #ifdef WITH_GROUP_INFO
994         ginfo = groups_alloc(0);
995         if (!ginfo) {
996                 rc = -ENOMEM;
997                 goto out;
998         }
999
1000         set_current_groups(ginfo);
1001         put_group_info(ginfo);
1002 #endif
1003
1004         if (svc->srv_init != NULL) {
1005                 rc = svc->srv_init(thread);
1006                 if (rc)
1007                         goto out;
1008         }
1009
1010         rc = lu_context_init(&env.le_ctx, svc->srv_ctx_tags);
1011         if (rc)
1012                 goto out_srv_fini;
1013
1014         thread->t_env = &env;
1015         env.le_ctx.lc_thread = thread;
1016
1017         /* Alloc reply state structure for this one */
1018         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1019         if (!rs) {
1020                 rc = -ENOMEM;
1021                 goto out_srv_fini;
1022         }
1023
1024         /* Record that the thread is running */
1025         thread->t_flags = SVC_RUNNING;
1026         /*
1027          * wake up our creator. Note: @data is invalid after this point,
1028          * because it's allocated on ptlrpc_start_thread() stack.
1029          */
1030         cfs_waitq_signal(&thread->t_ctl_waitq);
1031
1032         watchdog = lc_watchdog_add(svc->srv_watchdog_timeout, NULL, NULL);
1033
1034         spin_lock(&svc->srv_lock);
1035         svc->srv_threads_running++;
1036         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1037         spin_unlock(&svc->srv_lock);
1038         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1039
1040         CDEBUG(D_NET, "service thread %d (#%d)started\n", thread->t_id,
1041               svc->srv_threads_running);
1042
1043         /* XXX maintain a list of all managed devices: insert here */
1044
1045         while ((thread->t_flags & SVC_STOPPING) == 0 ||
1046                svc->srv_n_difficult_replies != 0) {
1047                 /* Don't exit while there are replies to be handled */
1048                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1049                                                      ptlrpc_retry_rqbds, svc);
1050
1051                 lc_watchdog_disable(watchdog);
1052
1053                 cond_resched();
1054
1055                 l_wait_event_exclusive (svc->srv_waitq,
1056                               ((thread->t_flags & SVC_STOPPING) != 0 &&
1057                                svc->srv_n_difficult_replies == 0) ||
1058                               (!list_empty(&svc->srv_idle_rqbds) &&
1059                                svc->srv_rqbd_timeout == 0) ||
1060                               !list_empty (&svc->srv_reply_queue) ||
1061                               (!list_empty (&svc->srv_request_queue) &&
1062                                (svc->srv_n_difficult_replies == 0 ||
1063                                 svc->srv_n_active_reqs <
1064                                 (svc->srv_threads_running - 1))),
1065                               &lwi);
1066
1067                 lc_watchdog_touch(watchdog);
1068
1069                 ptlrpc_check_rqbd_pool(svc);
1070
1071                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1072                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1073                         /* Ignore return code - we tried... */
1074                         ptlrpc_start_thread(dev, svc);
1075                 }
1076
1077                 if (!list_empty (&svc->srv_reply_queue))
1078                         ptlrpc_server_handle_reply (svc);
1079
1080                 /* only handle requests if there are no difficult replies
1081                  * outstanding, or I'm not the last thread handling
1082                  * requests */
1083                 if (!list_empty (&svc->srv_request_queue) &&
1084                     (svc->srv_n_difficult_replies == 0 ||
1085                      svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
1086                         lu_context_enter(&env.le_ctx);
1087                         ptlrpc_server_handle_request(svc, thread);
1088                         lu_context_exit(&env.le_ctx);
1089                 }
1090
1091                 if (!list_empty(&svc->srv_idle_rqbds) &&
1092                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
1093                         /* I just failed to repost request buffers.  Wait
1094                          * for a timeout (unless something else happens)
1095                          * before I try again */
1096                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
1097                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
1098                                svc->srv_nrqbd_receiving);
1099                 }
1100         }
1101
1102         lc_watchdog_delete(watchdog);
1103
1104 out_srv_fini:
1105         /*
1106          * deconstruct service specific state created by ptlrpc_start_thread()
1107          */
1108         if (svc->srv_done != NULL)
1109                 svc->srv_done(thread);
1110
1111         lu_env_fini(&env);
1112 out:
1113         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
1114
1115         spin_lock(&svc->srv_lock);
1116         svc->srv_threads_running--; /* must know immediately */
1117         thread->t_id = rc;
1118         thread->t_flags = SVC_STOPPED;
1119
1120         cfs_waitq_signal(&thread->t_ctl_waitq);
1121         spin_unlock(&svc->srv_lock);
1122
1123         return rc;
1124 }
1125
1126 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
1127                                struct ptlrpc_thread *thread)
1128 {
1129         struct l_wait_info lwi = { 0 };
1130
1131         spin_lock(&svc->srv_lock);
1132         thread->t_flags = SVC_STOPPING;
1133         spin_unlock(&svc->srv_lock);
1134
1135         cfs_waitq_broadcast(&svc->srv_waitq);
1136         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
1137                      &lwi);
1138
1139         spin_lock(&svc->srv_lock);
1140         list_del(&thread->t_link);
1141         spin_unlock(&svc->srv_lock);
1142
1143         OBD_FREE_PTR(thread);
1144 }
1145
1146 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
1147 {
1148         struct ptlrpc_thread *thread;
1149
1150         spin_lock(&svc->srv_lock);
1151         while (!list_empty(&svc->srv_threads)) {
1152                 thread = list_entry(svc->srv_threads.next,
1153                                     struct ptlrpc_thread, t_link);
1154
1155                 spin_unlock(&svc->srv_lock);
1156                 ptlrpc_stop_thread(svc, thread);
1157                 spin_lock(&svc->srv_lock);
1158         }
1159
1160         spin_unlock(&svc->srv_lock);
1161 }
1162
1163 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
1164 {
1165         int i, rc = 0;
1166         ENTRY;
1167
1168         LASSERT(svc->srv_threads_min > 0);
1169         for (i = 0; i < svc->srv_threads_min; i++) {
1170                 rc = ptlrpc_start_thread(dev, svc);
1171                 if (rc) {
1172                         CERROR("cannot start %s thread #%d: rc %d\n", 
1173                                svc->srv_thread_name, i, rc);
1174                         ptlrpc_stop_all_threads(svc);
1175                 }
1176         }
1177         RETURN(rc);
1178 }
1179
1180 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
1181 {
1182         struct l_wait_info lwi = { 0 };
1183         struct ptlrpc_svc_data d;
1184         struct ptlrpc_thread *thread;
1185         char name[32];
1186         int id, rc;
1187         ENTRY;
1188
1189         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
1190                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
1191                svc->srv_threads_max, svc->srv_threads_running);
1192         if (svc->srv_threads_started >= svc->srv_threads_max)
1193                 RETURN(-EMFILE);
1194
1195         OBD_ALLOC_PTR(thread);
1196         if (thread == NULL)
1197                 RETURN(-ENOMEM);
1198         cfs_waitq_init(&thread->t_ctl_waitq);
1199
1200         spin_lock(&svc->srv_lock);
1201         if (svc->srv_threads_started >= svc->srv_threads_max) {
1202                 spin_unlock(&svc->srv_lock);
1203                 OBD_FREE_PTR(thread);
1204                 RETURN(-EMFILE);
1205         }
1206         list_add(&thread->t_link, &svc->srv_threads);
1207         id = svc->srv_threads_started++;
1208         spin_unlock(&svc->srv_lock);
1209
1210         thread->t_id = id;
1211         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
1212         d.dev = dev;
1213         d.svc = svc;
1214         d.name = name;
1215         d.thread = thread;
1216
1217         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
1218         
1219           /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
1220          * just drop the VM and FILES in ptlrpc_daemonize() right away.
1221          */
1222         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
1223         if (rc < 0) {
1224                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
1225
1226                 spin_lock(&svc->srv_lock);
1227                 list_del(&thread->t_link);
1228                 --svc->srv_threads_started;
1229                 spin_unlock(&svc->srv_lock);
1230
1231                 OBD_FREE(thread, sizeof(*thread));
1232                 RETURN(rc);
1233         }
1234         l_wait_event(thread->t_ctl_waitq,
1235                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
1236
1237         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
1238         RETURN(rc);
1239 }
1240 #endif
1241
1242 int ptlrpc_unregister_service(struct ptlrpc_service *service)
1243 {
1244         int                   rc;
1245         struct l_wait_info    lwi;
1246         struct list_head     *tmp;
1247         struct ptlrpc_reply_state *rs, *t;
1248
1249         ptlrpc_stop_all_threads(service);
1250         LASSERT(list_empty(&service->srv_threads));
1251
1252         spin_lock (&ptlrpc_all_services_lock);
1253         list_del_init (&service->srv_list);
1254         spin_unlock (&ptlrpc_all_services_lock);
1255
1256         ptlrpc_lprocfs_unregister_service(service);
1257
1258         /* All history will be culled when the next request buffer is
1259          * freed */
1260         service->srv_max_history_rqbds = 0;
1261
1262         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
1263
1264         rc = LNetClearLazyPortal(service->srv_req_portal);
1265         LASSERT (rc == 0);
1266
1267         /* Unlink all the request buffers.  This forces a 'final' event with
1268          * its 'unlink' flag set for each posted rqbd */
1269         list_for_each(tmp, &service->srv_active_rqbds) {
1270                 struct ptlrpc_request_buffer_desc *rqbd =
1271                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
1272                                    rqbd_list);
1273
1274                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
1275                 LASSERT (rc == 0 || rc == -ENOENT);
1276         }
1277
1278         /* Wait for the network to release any buffers it's currently
1279          * filling */
1280         for (;;) {
1281                 spin_lock(&service->srv_lock);
1282                 rc = service->srv_nrqbd_receiving;
1283                 spin_unlock(&service->srv_lock);
1284
1285                 if (rc == 0)
1286                         break;
1287
1288                 /* Network access will complete in finite time but the HUGE
1289                  * timeout lets us CWARN for visibility of sluggish NALs */
1290                 lwi = LWI_TIMEOUT(cfs_time_seconds(300), NULL, NULL);
1291                 rc = l_wait_event(service->srv_waitq,
1292                                   service->srv_nrqbd_receiving == 0,
1293                                   &lwi);
1294                 if (rc == -ETIMEDOUT)
1295                         CWARN("Service %s waiting for request buffers\n",
1296                               service->srv_name);
1297         }
1298
1299         /* schedule all outstanding replies to terminate them */
1300         spin_lock(&service->srv_lock);
1301         while (!list_empty(&service->srv_active_replies)) {
1302                 struct ptlrpc_reply_state *rs =
1303                         list_entry(service->srv_active_replies.next,
1304                                    struct ptlrpc_reply_state, rs_list);
1305                 ptlrpc_schedule_difficult_reply(rs);
1306         }
1307         spin_unlock(&service->srv_lock);
1308
1309         /* purge the request queue.  NB No new replies (rqbds all unlinked)
1310          * and no service threads, so I'm the only thread noodling the
1311          * request queue now */
1312         while (!list_empty(&service->srv_request_queue)) {
1313                 struct ptlrpc_request *req =
1314                         list_entry(service->srv_request_queue.next,
1315                                    struct ptlrpc_request,
1316                                    rq_list);
1317
1318                 list_del(&req->rq_list);
1319                 service->srv_n_queued_reqs--;
1320                 service->srv_n_active_reqs++;
1321
1322                 ptlrpc_server_free_request(req);
1323         }
1324         LASSERT(service->srv_n_queued_reqs == 0);
1325         LASSERT(service->srv_n_active_reqs == 0);
1326         LASSERT(service->srv_n_history_rqbds == 0);
1327         LASSERT(list_empty(&service->srv_active_rqbds));
1328
1329         /* Now free all the request buffers since nothing references them
1330          * any more... */
1331         while (!list_empty(&service->srv_idle_rqbds)) {
1332                 struct ptlrpc_request_buffer_desc *rqbd =
1333                         list_entry(service->srv_idle_rqbds.next,
1334                                    struct ptlrpc_request_buffer_desc,
1335                                    rqbd_list);
1336
1337                 ptlrpc_free_rqbd(rqbd);
1338         }
1339
1340         /* wait for all outstanding replies to complete (they were
1341          * scheduled having been flagged to abort above) */
1342         while (atomic_read(&service->srv_outstanding_replies) != 0) {
1343                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10), NULL, NULL);
1344
1345                 rc = l_wait_event(service->srv_waitq,
1346                                   !list_empty(&service->srv_reply_queue), &lwi);
1347                 LASSERT(rc == 0 || rc == -ETIMEDOUT);
1348
1349                 if (rc == 0) {
1350                         ptlrpc_server_handle_reply(service);
1351                         continue;
1352                 }
1353                 CWARN("Unexpectedly long timeout %p\n", service);
1354         }
1355
1356         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
1357                 list_del(&rs->rs_list);
1358                 OBD_FREE(rs, service->srv_max_reply_size);
1359         }
1360
1361         OBD_FREE_PTR(service);
1362         return 0;
1363 }
1364
1365 /* Returns 0 if the service is healthy.
1366  *
1367  * Right now, it just checks to make sure that requests aren't languishing
1368  * in the queue.  We'll use this health check to govern whether a node needs
1369  * to be shot, so it's intentionally non-aggressive. */
1370 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
1371 {
1372         struct ptlrpc_request *request;
1373         struct timeval         right_now;
1374         long                   timediff, cutoff;
1375         int                    rc = 0;
1376
1377         if (svc == NULL)
1378                 return 0;
1379
1380         spin_lock(&svc->srv_lock);
1381
1382         if (list_empty(&svc->srv_request_queue))
1383                 goto out;
1384
1385         request = list_entry(svc->srv_request_queue.next,
1386                              struct ptlrpc_request, rq_list);
1387
1388         do_gettimeofday(&right_now);
1389         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
1390
1391         cutoff = obd_health_check_timeout;
1392
1393         if (timediff / 1000000 > cutoff) {
1394                 rc = -1;
1395                 goto out;
1396         }
1397
1398  out:
1399         spin_unlock(&svc->srv_lock);
1400         return rc;
1401 }