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