Whamcloud - gitweb
b=17491
[fs/lustre-release.git] / lustre / ptlrpc / service.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  */
36
37 #define DEBUG_SUBSYSTEM S_RPC
38 #ifndef __KERNEL__
39 #include <liblustre.h>
40 #endif
41 #include <obd_support.h>
42 #include <obd_class.h>
43 #include <lustre_net.h>
44 #include <lu_object.h>
45 #include <lnet/types.h>
46 #include "ptlrpc_internal.h"
47
48 /* The following are visible and mutable through /sys/module/ptlrpc */
49 int test_req_buffer_pressure = 0;
50 CFS_MODULE_PARM(test_req_buffer_pressure, "i", int, 0444,
51                 "set non-zero to put pressure on request buffer pools");
52 unsigned int at_min = 0;
53 CFS_MODULE_PARM(at_min, "i", int, 0644,
54                 "Adaptive timeout minimum (sec)");
55 unsigned int at_max = 600;
56 EXPORT_SYMBOL(at_max);
57 CFS_MODULE_PARM(at_max, "i", int, 0644,
58                 "Adaptive timeout maximum (sec)");
59 unsigned int at_history = 600;
60 CFS_MODULE_PARM(at_history, "i", int, 0644,
61                 "Adaptive timeouts remember the slowest event that took place "
62                 "within this period (sec)");
63 static int at_early_margin = 5;
64 CFS_MODULE_PARM(at_early_margin, "i", int, 0644,
65                 "How soon before an RPC deadline to send an early reply");
66 static int at_extra = 30;
67 CFS_MODULE_PARM(at_extra, "i", int, 0644,
68                 "How much extra time to give with each early reply");
69
70
71 /* forward ref */
72 static int ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc);
73
74 static CFS_LIST_HEAD(ptlrpc_all_services);
75 spinlock_t ptlrpc_all_services_lock;
76
77 static char *
78 ptlrpc_alloc_request_buffer (int size)
79 {
80         char *ptr;
81
82         if (size > SVC_BUF_VMALLOC_THRESHOLD)
83                 OBD_VMALLOC(ptr, size);
84         else
85                 OBD_ALLOC(ptr, size);
86
87         return (ptr);
88 }
89
90 static void
91 ptlrpc_free_request_buffer (char *ptr, int size)
92 {
93         if (size > SVC_BUF_VMALLOC_THRESHOLD)
94                 OBD_VFREE(ptr, size);
95         else
96                 OBD_FREE(ptr, size);
97 }
98
99 struct ptlrpc_request_buffer_desc *
100 ptlrpc_alloc_rqbd (struct ptlrpc_service *svc)
101 {
102         struct ptlrpc_request_buffer_desc *rqbd;
103
104         OBD_ALLOC_PTR(rqbd);
105         if (rqbd == NULL)
106                 return (NULL);
107
108         rqbd->rqbd_service = svc;
109         rqbd->rqbd_refcount = 0;
110         rqbd->rqbd_cbid.cbid_fn = request_in_callback;
111         rqbd->rqbd_cbid.cbid_arg = rqbd;
112         CFS_INIT_LIST_HEAD(&rqbd->rqbd_reqs);
113         rqbd->rqbd_buffer = ptlrpc_alloc_request_buffer(svc->srv_buf_size);
114
115         if (rqbd->rqbd_buffer == NULL) {
116                 OBD_FREE_PTR(rqbd);
117                 return (NULL);
118         }
119
120         spin_lock(&svc->srv_lock);
121         list_add(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
122         svc->srv_nbufs++;
123         spin_unlock(&svc->srv_lock);
124
125         return (rqbd);
126 }
127
128 void
129 ptlrpc_free_rqbd (struct ptlrpc_request_buffer_desc *rqbd)
130 {
131         struct ptlrpc_service *svc = rqbd->rqbd_service;
132
133         LASSERT (rqbd->rqbd_refcount == 0);
134         LASSERT (list_empty(&rqbd->rqbd_reqs));
135
136         spin_lock(&svc->srv_lock);
137         list_del(&rqbd->rqbd_list);
138         svc->srv_nbufs--;
139         spin_unlock(&svc->srv_lock);
140
141         ptlrpc_free_request_buffer (rqbd->rqbd_buffer, svc->srv_buf_size);
142         OBD_FREE_PTR(rqbd);
143 }
144
145 int
146 ptlrpc_grow_req_bufs(struct ptlrpc_service *svc)
147 {
148         struct ptlrpc_request_buffer_desc *rqbd;
149         int                                i;
150
151         CDEBUG(D_RPCTRACE, "%s: allocate %d new %d-byte reqbufs (%d/%d left)\n",
152                svc->srv_name, svc->srv_nbuf_per_group, svc->srv_buf_size,
153                svc->srv_nrqbd_receiving, svc->srv_nbufs);
154         for (i = 0; i < svc->srv_nbuf_per_group; i++) {
155                 rqbd = ptlrpc_alloc_rqbd(svc);
156
157                 if (rqbd == NULL) {
158                         CERROR ("%s: Can't allocate request buffer\n",
159                                 svc->srv_name);
160                         return (-ENOMEM);
161                 }
162
163                 if (ptlrpc_server_post_idle_rqbds(svc) < 0)
164                         return (-EAGAIN);
165         }
166
167         return (0);
168 }
169
170 void
171 ptlrpc_save_lock (struct ptlrpc_request *req,
172                   struct lustre_handle *lock, int mode, int no_ack)
173 {
174         struct ptlrpc_reply_state *rs = req->rq_reply_state;
175         int                        idx;
176
177         LASSERT(rs != NULL);
178         LASSERT(rs->rs_nlocks < RS_MAX_LOCKS);
179
180         idx = rs->rs_nlocks++;
181         rs->rs_locks[idx] = *lock;
182         rs->rs_modes[idx] = mode;
183         rs->rs_difficult = 1;
184         rs->rs_no_ack = !!no_ack;
185 }
186
187 #ifdef __KERNEL__
188
189 #define HRT_RUNNING 0
190 #define HRT_STOPPING 1
191
192 struct ptlrpc_hr_thread {
193         spinlock_t        hrt_lock;
194         unsigned long     hrt_flags;
195         cfs_waitq_t       hrt_wait;
196         struct list_head  hrt_queue;
197         struct completion hrt_completion;
198 };
199
200 struct ptlrpc_hr_service {
201         int                     hr_index;
202         int                     hr_n_threads;
203         int                     hr_size;
204         struct ptlrpc_hr_thread hr_threads[0];
205 };
206
207 struct rs_batch {
208         struct list_head        rsb_replies;
209         struct ptlrpc_service  *rsb_svc;
210         unsigned int            rsb_n_replies;
211 };
212
213 /**
214  *  A pointer to per-node reply handling service.
215  */
216 static struct ptlrpc_hr_service *ptlrpc_hr = NULL;
217
218 /**
219  * maximum mumber of replies scheduled in one batch
220  */
221 #define MAX_SCHEDULED 256
222
223 /**
224  * Initialize a reply batch.
225  *
226  * \param b batch
227  */
228 static void rs_batch_init(struct rs_batch *b)
229 {
230         memset(b, 0, sizeof *b);
231         CFS_INIT_LIST_HEAD(&b->rsb_replies);
232 }
233
234 /**
235  * Dispatch all replies accumulated in the batch to one from
236  * dedicated reply handing threads.
237  *
238  * \param b batch
239  */
240 static void rs_batch_dispatch(struct rs_batch *b)
241 {
242         if (b->rsb_n_replies != 0) {
243                 struct ptlrpc_hr_service *hr = ptlrpc_hr;
244                 int idx;
245
246                 idx = hr->hr_index++;
247                 if (hr->hr_index >= hr->hr_n_threads)
248                         hr->hr_index = 0;
249
250                 spin_lock(&hr->hr_threads[idx].hrt_lock);
251                 list_splice_init(&b->rsb_replies,
252                                  &hr->hr_threads[idx].hrt_queue);
253                 spin_unlock(&hr->hr_threads[idx].hrt_lock);
254                 cfs_waitq_signal(&hr->hr_threads[idx].hrt_wait);
255                 b->rsb_n_replies = 0;
256         }
257 }
258
259 /**
260  * Add a reply to a batch.
261  * Add one reply object to a batch, schedule batched replies if overload.
262  *
263  * \param b batch
264  * \param rs reply
265  */
266 static void rs_batch_add(struct rs_batch *b, struct ptlrpc_reply_state *rs)
267 {
268         struct ptlrpc_service *svc = rs->rs_service;
269
270         if (svc != b->rsb_svc || b->rsb_n_replies >= MAX_SCHEDULED) {
271                 if (b->rsb_svc != NULL) {
272                         rs_batch_dispatch(b);
273                         spin_unlock(&b->rsb_svc->srv_lock);
274                 }
275                 spin_lock(&svc->srv_lock);
276                 b->rsb_svc = svc;
277         }
278         spin_lock(&rs->rs_lock);
279         rs->rs_scheduled_ever = 1;
280         if (rs->rs_scheduled == 0) {
281                 list_move(&rs->rs_list, &b->rsb_replies);
282                 rs->rs_scheduled = 1;
283                 b->rsb_n_replies++;
284         }
285         spin_unlock(&rs->rs_lock);
286 }
287
288 /**
289  * Reply batch finalization.
290  * Dispatch remaining replies from the batch
291  * and release remaining spinlock.
292  *
293  * \param b batch
294  */
295 static void rs_batch_fini(struct rs_batch *b)
296 {
297         if (b->rsb_svc != 0) {
298                 rs_batch_dispatch(b);
299                 spin_unlock(&b->rsb_svc->srv_lock);
300         }
301 }
302
303 #define DECLARE_RS_BATCH(b)     struct rs_batch b
304
305 #else /* __KERNEL__ */
306
307 #define rs_batch_init(b)        do{}while(0)
308 #define rs_batch_fini(b)        do{}while(0)
309 #define rs_batch_add(b, r)      ptlrpc_schedule_difficult_reply(r)
310 #define DECLARE_RS_BATCH(b)
311
312 #endif /* __KERNEL__ */
313
314 void ptlrpc_dispatch_difficult_reply(struct ptlrpc_reply_state *rs)
315 {
316 #ifdef __KERNEL__
317         struct ptlrpc_hr_service *hr = ptlrpc_hr;
318         int idx;
319         ENTRY;
320
321         LASSERT(list_empty(&rs->rs_list));
322
323         idx = hr->hr_index++;
324         if (hr->hr_index >= hr->hr_n_threads)
325                 hr->hr_index = 0;
326         spin_lock(&hr->hr_threads[idx].hrt_lock);
327         list_add_tail(&rs->rs_list, &hr->hr_threads[idx].hrt_queue);
328         spin_unlock(&hr->hr_threads[idx].hrt_lock);
329         cfs_waitq_signal(&hr->hr_threads[idx].hrt_wait);
330         EXIT;
331 #else
332         list_add_tail(&rs->rs_list, &rs->rs_service->srv_reply_queue);
333 #endif
334 }
335
336 void
337 ptlrpc_schedule_difficult_reply (struct ptlrpc_reply_state *rs)
338 {
339         ENTRY;
340
341         LASSERT_SPIN_LOCKED(&rs->rs_service->srv_lock);
342         LASSERT_SPIN_LOCKED(&rs->rs_lock);
343         LASSERT (rs->rs_difficult);
344         rs->rs_scheduled_ever = 1;              /* flag any notification attempt */
345
346         if (rs->rs_scheduled) {                  /* being set up or already notified */
347                 EXIT;
348                 return;
349         }
350
351         rs->rs_scheduled = 1;
352         list_del_init(&rs->rs_list);
353         ptlrpc_dispatch_difficult_reply(rs);
354         EXIT;
355 }
356
357 void
358 ptlrpc_commit_replies (struct obd_device *obd)
359 {
360         struct list_head   *tmp;
361         struct list_head   *nxt;
362         DECLARE_RS_BATCH(batch);
363         ENTRY;
364
365         rs_batch_init(&batch);
366         /* Find any replies that have been committed and get their service
367          * to attend to complete them. */
368
369         /* CAVEAT EMPTOR: spinlock ordering!!! */
370         spin_lock(&obd->obd_uncommitted_replies_lock);
371         list_for_each_safe (tmp, nxt, &obd->obd_uncommitted_replies) {
372                 struct ptlrpc_reply_state *rs =
373                         list_entry(tmp, struct ptlrpc_reply_state, rs_obd_list);
374
375                 LASSERT (rs->rs_difficult);
376
377                 if (rs->rs_transno <= obd->obd_last_committed) {
378                         list_del_init(&rs->rs_obd_list);
379                         rs_batch_add(&batch, rs);
380                 }
381         }
382         spin_unlock(&obd->obd_uncommitted_replies_lock);
383         rs_batch_fini(&batch);
384         EXIT;
385 }
386
387 static int
388 ptlrpc_server_post_idle_rqbds (struct ptlrpc_service *svc)
389 {
390         struct ptlrpc_request_buffer_desc *rqbd;
391         int                                rc;
392         int                                posted = 0;
393
394         for (;;) {
395                 spin_lock(&svc->srv_lock);
396
397                 if (list_empty (&svc->srv_idle_rqbds)) {
398                         spin_unlock(&svc->srv_lock);
399                         return (posted);
400                 }
401
402                 rqbd = list_entry(svc->srv_idle_rqbds.next,
403                                   struct ptlrpc_request_buffer_desc,
404                                   rqbd_list);
405                 list_del (&rqbd->rqbd_list);
406
407                 /* assume we will post successfully */
408                 svc->srv_nrqbd_receiving++;
409                 list_add (&rqbd->rqbd_list, &svc->srv_active_rqbds);
410
411                 spin_unlock(&svc->srv_lock);
412
413                 rc = ptlrpc_register_rqbd(rqbd);
414                 if (rc != 0)
415                         break;
416
417                 posted = 1;
418         }
419
420         spin_lock(&svc->srv_lock);
421
422         svc->srv_nrqbd_receiving--;
423         list_del(&rqbd->rqbd_list);
424         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
425
426         /* Don't complain if no request buffers are posted right now; LNET
427          * won't drop requests because we set the portal lazy! */
428
429         spin_unlock(&svc->srv_lock);
430
431         return (-1);
432 }
433
434 struct ptlrpc_service *ptlrpc_init_svc_conf(struct ptlrpc_service_conf *c,
435                                             svc_handler_t h, char *name,
436                                             struct proc_dir_entry *proc_entry,
437                                             svcreq_printfn_t prntfn,
438                                             char *threadname)
439 {
440         return ptlrpc_init_svc(c->psc_nbufs, c->psc_bufsize,
441                                c->psc_max_req_size, c->psc_max_reply_size,
442                                c->psc_req_portal, c->psc_rep_portal,
443                                c->psc_watchdog_factor,
444                                h, name, proc_entry,
445                                prntfn, c->psc_min_threads, c->psc_max_threads,
446                                threadname, c->psc_ctx_tags, NULL);
447 }
448 EXPORT_SYMBOL(ptlrpc_init_svc_conf);
449
450 static void ptlrpc_at_timer(unsigned long castmeharder)
451 {
452         struct ptlrpc_service *svc = (struct ptlrpc_service *)castmeharder;
453         svc->srv_at_check = 1;
454         svc->srv_at_checktime = cfs_time_current();
455         cfs_waitq_signal(&svc->srv_waitq);
456 }
457
458 /* @threadname should be 11 characters or less - 3 will be added on */
459 struct ptlrpc_service *
460 ptlrpc_init_svc(int nbufs, int bufsize, int max_req_size, int max_reply_size,
461                 int req_portal, int rep_portal, int watchdog_factor,
462                 svc_handler_t handler, char *name,
463                 cfs_proc_dir_entry_t *proc_entry,
464                 svcreq_printfn_t svcreq_printfn,
465                 int min_threads, int max_threads,
466                 char *threadname, __u32 ctx_tags,
467                 svc_hpreq_handler_t hp_handler)
468 {
469         int                     rc;
470         struct ptlrpc_at_array *array;
471         struct ptlrpc_service  *service;
472         unsigned int            size, index;
473         ENTRY;
474
475         LASSERT (nbufs > 0);
476         LASSERT (bufsize >= max_req_size + SPTLRPC_MAX_PAYLOAD);
477         LASSERT (ctx_tags != 0);
478
479         OBD_ALLOC_PTR(service);
480         if (service == NULL)
481                 RETURN(NULL);
482
483         /* First initialise enough for early teardown */
484
485         service->srv_name = name;
486         spin_lock_init(&service->srv_lock);
487         CFS_INIT_LIST_HEAD(&service->srv_threads);
488         cfs_waitq_init(&service->srv_waitq);
489
490         service->srv_nbuf_per_group = test_req_buffer_pressure ? 1 : nbufs;
491         service->srv_max_req_size = max_req_size + SPTLRPC_MAX_PAYLOAD;
492         service->srv_buf_size = bufsize;
493         service->srv_rep_portal = rep_portal;
494         service->srv_req_portal = req_portal;
495         service->srv_watchdog_factor = watchdog_factor;
496         service->srv_handler = handler;
497         service->srv_request_history_print_fn = svcreq_printfn;
498         service->srv_request_seq = 1;           /* valid seq #s start at 1 */
499         service->srv_request_max_cull_seq = 0;
500         service->srv_threads_min = min_threads;
501         service->srv_threads_max = max_threads;
502         service->srv_thread_name = threadname;
503         service->srv_ctx_tags = ctx_tags;
504         service->srv_hpreq_handler = hp_handler;
505         service->srv_hpreq_ratio = PTLRPC_SVC_HP_RATIO;
506         service->srv_hpreq_count = 0;
507         service->srv_n_hpreq = 0;
508
509         rc = LNetSetLazyPortal(service->srv_req_portal);
510         LASSERT (rc == 0);
511
512         CFS_INIT_LIST_HEAD(&service->srv_request_queue);
513         CFS_INIT_LIST_HEAD(&service->srv_request_hpq);
514         CFS_INIT_LIST_HEAD(&service->srv_idle_rqbds);
515         CFS_INIT_LIST_HEAD(&service->srv_active_rqbds);
516         CFS_INIT_LIST_HEAD(&service->srv_history_rqbds);
517         CFS_INIT_LIST_HEAD(&service->srv_request_history);
518         CFS_INIT_LIST_HEAD(&service->srv_active_replies);
519 #ifndef __KERNEL__
520         CFS_INIT_LIST_HEAD(&service->srv_reply_queue);
521 #endif
522         CFS_INIT_LIST_HEAD(&service->srv_free_rs_list);
523         cfs_waitq_init(&service->srv_free_rs_waitq);
524         atomic_set(&service->srv_n_difficult_replies, 0);
525
526         spin_lock_init(&service->srv_at_lock);
527         CFS_INIT_LIST_HEAD(&service->srv_req_in_queue);
528
529         array = &service->srv_at_array;
530         size = at_est2timeout(at_max);
531         array->paa_size = size;
532         array->paa_count = 0;
533         array->paa_deadline = -1;
534
535         /* allocate memory for srv_at_array (ptlrpc_at_array) */ 
536         OBD_ALLOC(array->paa_reqs_array, sizeof(struct list_head) * size);
537         if (array->paa_reqs_array == NULL)
538                 GOTO(failed, NULL);
539
540         for (index = 0; index < size; index++)
541                 CFS_INIT_LIST_HEAD(&array->paa_reqs_array[index]);
542         
543         OBD_ALLOC(array->paa_reqs_count, sizeof(__u32) * size);
544         if (array->paa_reqs_count == NULL)
545                 GOTO(failed, NULL);
546
547         cfs_timer_init(&service->srv_at_timer, ptlrpc_at_timer, service);
548         /* At SOW, service time should be quick; 10s seems generous. If client
549            timeout is less than this, we'll be sending an early reply. */
550         at_init(&service->srv_at_estimate, 10, 0);
551
552         spin_lock (&ptlrpc_all_services_lock);
553         list_add (&service->srv_list, &ptlrpc_all_services);
554         spin_unlock (&ptlrpc_all_services_lock);
555
556         /* Now allocate the request buffers */
557         rc = ptlrpc_grow_req_bufs(service);
558         /* We shouldn't be under memory pressure at startup, so
559          * fail if we can't post all our buffers at this time. */
560         if (rc != 0)
561                 GOTO(failed, NULL);
562
563         /* Now allocate pool of reply buffers */
564         /* Increase max reply size to next power of two */
565         service->srv_max_reply_size = 1;
566         while (service->srv_max_reply_size <
567                max_reply_size + SPTLRPC_MAX_PAYLOAD)
568                 service->srv_max_reply_size <<= 1;
569
570         if (proc_entry != NULL)
571                 ptlrpc_lprocfs_register_service(proc_entry, service);
572
573         CDEBUG(D_NET, "%s: Started, listening on portal %d\n",
574                service->srv_name, service->srv_req_portal);
575
576         RETURN(service);
577 failed:
578         ptlrpc_unregister_service(service);
579         return NULL;
580 }
581
582 /**
583  * to actually free the request, must be called without holding svc_lock.
584  * note it's caller's responsibility to unlink req->rq_list.
585  */
586 static void ptlrpc_server_free_request(struct ptlrpc_request *req)
587 {
588         LASSERT(atomic_read(&req->rq_refcount) == 0);
589         LASSERT(list_empty(&req->rq_timed_list));
590
591          /* DEBUG_REQ() assumes the reply state of a request with a valid
592           * ref will not be destroyed until that reference is dropped. */
593         ptlrpc_req_drop_rs(req);
594
595         sptlrpc_svc_ctx_decref(req);
596
597         if (req != &req->rq_rqbd->rqbd_req) {
598                 /* NB request buffers use an embedded
599                  * req if the incoming req unlinked the
600                  * MD; this isn't one of them! */
601                 OBD_FREE(req, sizeof(*req));
602         }
603 }
604
605 /**
606  * drop a reference count of the request. if it reaches 0, we either
607  * put it into history list, or free it immediately.
608  */
609 static void ptlrpc_server_drop_request(struct ptlrpc_request *req)
610 {
611         struct ptlrpc_request_buffer_desc *rqbd = req->rq_rqbd;
612         struct ptlrpc_service             *svc = rqbd->rqbd_service;
613         int                                refcount;
614         struct list_head                  *tmp;
615         struct list_head                  *nxt;
616
617         if (!atomic_dec_and_test(&req->rq_refcount))
618                 return;
619
620         spin_lock(&svc->srv_lock);
621
622         svc->srv_n_active_reqs--;
623         list_add(&req->rq_list, &rqbd->rqbd_reqs);
624
625         refcount = --(rqbd->rqbd_refcount);
626         if (refcount == 0) {
627                 /* request buffer is now idle: add to history */
628                 list_del(&rqbd->rqbd_list);
629                 list_add_tail(&rqbd->rqbd_list, &svc->srv_history_rqbds);
630                 svc->srv_n_history_rqbds++;
631
632                 /* cull some history?
633                  * I expect only about 1 or 2 rqbds need to be recycled here */
634                 while (svc->srv_n_history_rqbds > svc->srv_max_history_rqbds) {
635                         rqbd = list_entry(svc->srv_history_rqbds.next,
636                                           struct ptlrpc_request_buffer_desc,
637                                           rqbd_list);
638
639                         list_del(&rqbd->rqbd_list);
640                         svc->srv_n_history_rqbds--;
641
642                         /* remove rqbd's reqs from svc's req history while
643                          * I've got the service lock */
644                         list_for_each(tmp, &rqbd->rqbd_reqs) {
645                                 req = list_entry(tmp, struct ptlrpc_request,
646                                                  rq_list);
647                                 /* Track the highest culled req seq */
648                                 if (req->rq_history_seq >
649                                     svc->srv_request_max_cull_seq)
650                                         svc->srv_request_max_cull_seq =
651                                                 req->rq_history_seq;
652                                 list_del(&req->rq_history_list);
653                         }
654
655                         spin_unlock(&svc->srv_lock);
656
657                         list_for_each_safe(tmp, nxt, &rqbd->rqbd_reqs) {
658                                 req = list_entry(rqbd->rqbd_reqs.next,
659                                                  struct ptlrpc_request,
660                                                  rq_list);
661                                 list_del(&req->rq_list);
662                                 ptlrpc_server_free_request(req);
663                         }
664
665                         spin_lock(&svc->srv_lock);
666                         /*
667                          * now all reqs including the embedded req has been
668                          * disposed, schedule request buffer for re-use.
669                          */
670                         LASSERT(atomic_read(&rqbd->rqbd_req.rq_refcount) == 0);
671                         list_add_tail(&rqbd->rqbd_list, &svc->srv_idle_rqbds);
672                 }
673
674                 spin_unlock(&svc->srv_lock);
675         } else if (req->rq_reply_state && req->rq_reply_state->rs_prealloc) {
676                 /* If we are low on memory, we are not interested in history */
677                 list_del(&req->rq_list);
678                 list_del_init(&req->rq_history_list);
679                 spin_unlock(&svc->srv_lock);
680
681                 ptlrpc_server_free_request(req);
682         } else {
683                 spin_unlock(&svc->srv_lock);
684         }
685 }
686
687 /**
688  * to finish a request: stop sending more early replies, and release
689  * the request. should be called after we finished handling the request.
690  */
691 static void ptlrpc_server_finish_request(struct ptlrpc_request *req)
692 {
693         struct ptlrpc_service  *svc = req->rq_rqbd->rqbd_service;
694
695         if (req->rq_export) {
696                 class_export_put(req->rq_export);
697                 req->rq_export = NULL;
698         }
699
700         if (req->rq_phase != RQ_PHASE_NEW) /* incorrect message magic */
701                 DEBUG_REQ(D_INFO, req, "free req");
702
703         spin_lock(&svc->srv_at_lock);
704         req->rq_sent_final = 1;
705         list_del_init(&req->rq_timed_list);
706         if (req->rq_at_linked) {
707                 struct ptlrpc_at_array *array = &svc->srv_at_array;
708                 __u32 index = req->rq_at_index;
709         
710                 req->rq_at_linked = 0;        
711                 array->paa_reqs_count[index]--;
712                 array->paa_count--;
713         }
714         spin_unlock(&svc->srv_at_lock);
715
716         ptlrpc_server_drop_request(req);
717 }
718
719 /* This function makes sure dead exports are evicted in a timely manner.
720    This function is only called when some export receives a message (i.e.,
721    the network is up.) */
722 static void ptlrpc_update_export_timer(struct obd_export *exp, long extra_delay)
723 {
724         struct obd_export *oldest_exp;
725         time_t oldest_time, new_time;
726
727         ENTRY;
728
729         LASSERT(exp);
730
731         /* Compensate for slow machines, etc, by faking our request time
732            into the future.  Although this can break the strict time-ordering
733            of the list, we can be really lazy here - we don't have to evict
734            at the exact right moment.  Eventually, all silent exports
735            will make it to the top of the list. */
736
737         /* Do not pay attention on 1sec or smaller renewals. */
738         new_time = cfs_time_current_sec() + extra_delay;
739         if (exp->exp_last_request_time + 1 /*second */ >= new_time)
740                 RETURN_EXIT;
741
742         exp->exp_last_request_time = new_time;
743         CDEBUG(D_HA, "updating export %s at "CFS_TIME_T" exp %p\n",
744                exp->exp_client_uuid.uuid,
745                exp->exp_last_request_time, exp);
746
747         /* exports may get disconnected from the chain even though the
748            export has references, so we must keep the spin lock while
749            manipulating the lists */
750         spin_lock(&exp->exp_obd->obd_dev_lock);
751
752         if (list_empty(&exp->exp_obd_chain_timed)) {
753                 /* this one is not timed */
754                 spin_unlock(&exp->exp_obd->obd_dev_lock);
755                 RETURN_EXIT;
756         }
757
758         list_move_tail(&exp->exp_obd_chain_timed,
759                        &exp->exp_obd->obd_exports_timed);
760
761         oldest_exp = list_entry(exp->exp_obd->obd_exports_timed.next,
762                                 struct obd_export, exp_obd_chain_timed);
763         oldest_time = oldest_exp->exp_last_request_time;
764         spin_unlock(&exp->exp_obd->obd_dev_lock);
765
766         if (exp->exp_obd->obd_recovering) {
767                 /* be nice to everyone during recovery */
768                 EXIT;
769                 return;
770         }
771
772         /* Note - racing to start/reset the obd_eviction timer is safe */
773         if (exp->exp_obd->obd_eviction_timer == 0) {
774                 /* Check if the oldest entry is expired. */
775                 if (cfs_time_current_sec() > (oldest_time + PING_EVICT_TIMEOUT +
776                                               extra_delay)) {
777                         /* We need a second timer, in case the net was down and
778                          * it just came back. Since the pinger may skip every
779                          * other PING_INTERVAL (see note in ptlrpc_pinger_main),
780                          * we better wait for 3. */
781                         exp->exp_obd->obd_eviction_timer =
782                                 cfs_time_current_sec() + 3 * PING_INTERVAL;
783                         CDEBUG(D_HA, "%s: Think about evicting %s from "CFS_TIME_T"\n",
784                                exp->exp_obd->obd_name, obd_export_nid2str(exp),
785                                oldest_time);
786                 }
787         } else {
788                 if (cfs_time_current_sec() >
789                     (exp->exp_obd->obd_eviction_timer + extra_delay)) {
790                         /* The evictor won't evict anyone who we've heard from
791                          * recently, so we don't have to check before we start
792                          * it. */
793                         if (!ping_evictor_wake(exp))
794                                 exp->exp_obd->obd_eviction_timer = 0;
795                 }
796         }
797
798         EXIT;
799 }
800
801 static int ptlrpc_check_req(struct ptlrpc_request *req)
802 {
803         if (unlikely(lustre_msg_get_conn_cnt(req->rq_reqmsg) <
804                      req->rq_export->exp_conn_cnt)) {
805                 DEBUG_REQ(D_ERROR, req,
806                           "DROPPING req from old connection %d < %d",
807                           lustre_msg_get_conn_cnt(req->rq_reqmsg),
808                           req->rq_export->exp_conn_cnt);
809                 return -EEXIST;
810         }
811         if (unlikely(req->rq_export->exp_obd &&
812                      req->rq_export->exp_obd->obd_fail)) {
813              /* Failing over, don't handle any more reqs, send
814                 error response instead. */
815                 CDEBUG(D_RPCTRACE, "Dropping req %p for failed obd %s\n",
816                        req, req->rq_export->exp_obd->obd_name);
817                 req->rq_status = -ENODEV;
818                 ptlrpc_error(req);
819                 return -ENODEV;
820         }
821
822         return 0;
823 }
824
825 static void ptlrpc_at_set_timer(struct ptlrpc_service *svc)
826 {
827         struct ptlrpc_at_array *array = &svc->srv_at_array;
828         __s32 next;
829
830         spin_lock(&svc->srv_at_lock);
831         if (array->paa_count == 0) {
832                 cfs_timer_disarm(&svc->srv_at_timer);
833                 spin_unlock(&svc->srv_at_lock);
834                 return;
835         }
836
837         /* Set timer for closest deadline */
838         next = (__s32)(array->paa_deadline - cfs_time_current_sec() -
839                        at_early_margin);
840         if (next <= 0)
841                 ptlrpc_at_timer((unsigned long)svc);
842         else
843                 cfs_timer_arm(&svc->srv_at_timer, cfs_time_shift(next));
844         spin_unlock(&svc->srv_at_lock);
845         CDEBUG(D_INFO, "armed %s at %+ds\n", svc->srv_name, next);
846 }
847
848 /* Add rpc to early reply check list */
849 static int ptlrpc_at_add_timed(struct ptlrpc_request *req)
850 {
851         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
852         struct ptlrpc_request *rq = NULL;
853         struct ptlrpc_at_array *array = &svc->srv_at_array;
854         __u32 index, wtimes;
855         int found = 0;
856
857         if (AT_OFF)
858                 return(0);
859
860         if (req->rq_no_reply)
861                 return 0;
862
863         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0)
864                 return(-ENOSYS);
865
866         spin_lock(&svc->srv_at_lock);
867
868         if (unlikely(req->rq_sent_final)) {
869                 spin_unlock(&svc->srv_at_lock);
870                 return 0;
871         }
872
873         LASSERT(list_empty(&req->rq_timed_list));
874
875         wtimes = req->rq_deadline / array->paa_size;
876         index = req->rq_deadline % array->paa_size;
877         if (array->paa_reqs_count[index] > 0)
878                 rq = list_entry(array->paa_reqs_array[index].next, 
879                                 struct ptlrpc_request, rq_timed_list);
880
881         if (rq != NULL && (rq->rq_deadline / array->paa_size) < wtimes) {
882                 /* latest rpcs will have the latest deadlines in the list,
883                  * so search backward. */
884                 list_for_each_entry_reverse(rq, &array->paa_reqs_array[index], 
885                                             rq_timed_list) {
886                         if (req->rq_deadline >= rq->rq_deadline) {
887                                 list_add(&req->rq_timed_list, 
888                                          &rq->rq_timed_list);
889                                 break;
890                         }
891                 }
892
893                 /* AT array is corrupted? */
894                 LASSERT(!list_empty(&req->rq_timed_list));
895         } else {
896                 /* Add the request at the head of the list */
897                 list_add(&req->rq_timed_list, &array->paa_reqs_array[index]);
898         }
899
900         req->rq_at_linked = 1;
901         req->rq_at_index = index;
902         array->paa_reqs_count[index]++;
903         array->paa_count++;
904         if (array->paa_count == 1 || array->paa_deadline > req->rq_deadline) {
905                 array->paa_deadline = req->rq_deadline;
906                 found = 1;
907         }
908         spin_unlock(&svc->srv_at_lock);
909
910         if (found)
911                 ptlrpc_at_set_timer(svc);
912
913         return 0;
914 }
915
916 static int ptlrpc_at_send_early_reply(struct ptlrpc_request *req,
917                                       int extra_time)
918 {
919         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
920         struct ptlrpc_request *reqcopy;
921         struct lustre_msg *reqmsg;
922         cfs_duration_t olddl = req->rq_deadline - cfs_time_current_sec();
923         time_t newdl;
924         int rc;
925         ENTRY;
926
927         /* deadline is when the client expects us to reply, margin is the
928            difference between clients' and servers' expectations */
929         DEBUG_REQ(D_ADAPTTO, req,
930                   "%ssending early reply (deadline %+lds, margin %+lds) for "
931                   "%d+%d", AT_OFF ? "AT off - not " : "",
932                   olddl, olddl - at_get(&svc->srv_at_estimate),
933                   at_get(&svc->srv_at_estimate), extra_time);
934
935         if (AT_OFF)
936                 RETURN(0);
937
938         if (olddl < 0) {
939                 DEBUG_REQ(D_WARNING, req, "Already past deadline (%+lds), "
940                           "not sending early reply. Consider increasing "
941                           "at_early_margin (%d)?", olddl, at_early_margin);
942
943                 /* Return an error so we're not re-added to the timed list. */
944                 RETURN(-ETIMEDOUT);
945         }
946
947         if ((lustre_msghdr_get_flags(req->rq_reqmsg) & MSGHDR_AT_SUPPORT) == 0){
948                 DEBUG_REQ(D_INFO, req, "Wanted to ask client for more time, "
949                           "but no AT support");
950                 RETURN(-ENOSYS);
951         }
952
953         if (req->rq_export && req->rq_export->exp_in_recovery) {
954                 /* don't increase server estimates during recovery, and give
955                    clients the full recovery time. */
956                 newdl = cfs_time_current_sec() +
957                         req->rq_export->exp_obd->obd_recovery_timeout;
958         } else {
959                 if (extra_time) {
960                         /* Fake our processing time into the future to ask the
961                            clients for some extra amount of time */
962                         extra_time += cfs_time_current_sec() -
963                                 req->rq_arrival_time.tv_sec;
964                         at_add(&svc->srv_at_estimate, extra_time);
965                 }
966                 newdl = req->rq_arrival_time.tv_sec +
967                         at_get(&svc->srv_at_estimate);
968         }
969         if (req->rq_deadline >= newdl) {
970                 /* We're not adding any time, no need to send an early reply
971                    (e.g. maybe at adaptive_max) */
972                 DEBUG_REQ(D_WARNING, req, "Couldn't add any time ("
973                           CFS_DURATION_T"/"CFS_DURATION_T"), "
974                           "not sending early reply\n", olddl,
975                           cfs_time_sub(newdl, cfs_time_current_sec()));
976                 RETURN(-ETIMEDOUT);
977         }
978
979         OBD_ALLOC(reqcopy, sizeof *reqcopy);
980         if (reqcopy == NULL)
981                 RETURN(-ENOMEM);
982         OBD_ALLOC(reqmsg, req->rq_reqlen);
983         if (!reqmsg) {
984                 OBD_FREE(reqcopy, sizeof *reqcopy);
985                 RETURN(-ENOMEM);
986         }
987
988         *reqcopy = *req;
989         reqcopy->rq_reply_state = NULL;
990         reqcopy->rq_rep_swab_mask = 0;
991         reqcopy->rq_pack_bulk = 0;
992         reqcopy->rq_pack_udesc = 0;
993         reqcopy->rq_packed_final = 0;
994         sptlrpc_svc_ctx_addref(reqcopy);
995         /* We only need the reqmsg for the magic */
996         reqcopy->rq_reqmsg = reqmsg;
997         memcpy(reqmsg, req->rq_reqmsg, req->rq_reqlen);
998
999         if (req->rq_sent_final) {
1000                 DEBUG_REQ(D_ADAPTTO, reqcopy, "Normal reply already sent out, "
1001                           "abort sending early reply\n");
1002                 GOTO(out, rc = 0);
1003         }
1004
1005         /* Connection ref */
1006         reqcopy->rq_export = class_conn2export(
1007                                      lustre_msg_get_handle(reqcopy->rq_reqmsg));
1008         if (reqcopy->rq_export == NULL)
1009                 GOTO(out, rc = -ENODEV);
1010
1011         /* RPC ref */
1012         class_export_rpc_get(reqcopy->rq_export);
1013         if (reqcopy->rq_export->exp_obd &&
1014             reqcopy->rq_export->exp_obd->obd_fail)
1015                 GOTO(out_put, rc = -ENODEV);
1016
1017         rc = lustre_pack_reply_flags(reqcopy, 1, NULL, NULL, LPRFL_EARLY_REPLY);
1018         if (rc)
1019                 GOTO(out_put, rc);
1020
1021         rc = ptlrpc_send_reply(reqcopy, PTLRPC_REPLY_EARLY);
1022
1023         if (!rc) {
1024                 /* Adjust our own deadline to what we told the client */
1025                 req->rq_deadline = newdl;
1026                 req->rq_early_count++; /* number sent, server side */
1027         } else {
1028                 DEBUG_REQ(D_ERROR, req, "Early reply send failed %d", rc);
1029         }
1030
1031         /* Free the (early) reply state from lustre_pack_reply.
1032            (ptlrpc_send_reply takes it's own rs ref, so this is safe here) */
1033         ptlrpc_req_drop_rs(reqcopy);
1034
1035 out_put:
1036         class_export_rpc_put(reqcopy->rq_export);
1037         class_export_put(reqcopy->rq_export);
1038 out:
1039         sptlrpc_svc_ctx_decref(reqcopy);
1040         OBD_FREE(reqmsg, req->rq_reqlen);
1041         OBD_FREE(reqcopy, sizeof *reqcopy);
1042         RETURN(rc);
1043 }
1044
1045 /* Send early replies to everybody expiring within at_early_margin
1046    asking for at_extra time */
1047 static int ptlrpc_at_check_timed(struct ptlrpc_service *svc)
1048 {
1049         struct ptlrpc_request *rq, *n;
1050         struct list_head work_list;
1051         struct ptlrpc_at_array *array = &svc->srv_at_array;
1052         __u32  index, count;
1053         time_t deadline;
1054         time_t now = cfs_time_current_sec();
1055         cfs_duration_t delay;
1056         int first, counter = 0;
1057         ENTRY;
1058
1059         spin_lock(&svc->srv_at_lock);
1060         if (svc->srv_at_check == 0) {
1061                 spin_unlock(&svc->srv_at_lock);
1062                 RETURN(0);
1063         }
1064         delay = cfs_time_sub(cfs_time_current(), svc->srv_at_checktime);
1065         svc->srv_at_check = 0;
1066
1067         if (array->paa_count == 0) {
1068                 spin_unlock(&svc->srv_at_lock);
1069                 RETURN(0);
1070         }
1071
1072         /* The timer went off, but maybe the nearest rpc already completed. */
1073         first = array->paa_deadline - now;
1074         if (first > at_early_margin) {
1075                 /* We've still got plenty of time.  Reset the timer. */
1076                 spin_unlock(&svc->srv_at_lock);
1077                 ptlrpc_at_set_timer(svc);
1078                 RETURN(0);
1079         }
1080
1081         /* We're close to a timeout, and we don't know how much longer the
1082            server will take. Send early replies to everyone expiring soon. */
1083         CFS_INIT_LIST_HEAD(&work_list);
1084         deadline = -1;
1085         index = array->paa_deadline % array->paa_size;
1086         count = array->paa_count;
1087         while (count > 0) {
1088                 count -= array->paa_reqs_count[index];
1089                 list_for_each_entry_safe(rq, n, &array->paa_reqs_array[index], 
1090                                          rq_timed_list) {
1091                         if (rq->rq_deadline <= now + at_early_margin) {
1092                                 list_move(&rq->rq_timed_list, &work_list);
1093                                 counter++;
1094                                 array->paa_reqs_count[index]--;
1095                                 array->paa_count--;
1096                                 rq->rq_at_linked = 0;
1097                                 continue;
1098                         }
1099                         
1100                         /* update the earliest deadline */
1101                         if (deadline == -1 || rq->rq_deadline < deadline)
1102                                 deadline = rq->rq_deadline;
1103
1104                         break;
1105                 }
1106
1107                 if (++index >= array->paa_size)
1108                         index = 0;
1109         }
1110         array->paa_deadline = deadline;
1111         spin_unlock(&svc->srv_at_lock);
1112
1113         /* we have a new earliest deadline, restart the timer */
1114         ptlrpc_at_set_timer(svc);
1115
1116         CDEBUG(D_ADAPTTO, "timeout in %+ds, asking for %d secs on %d early "
1117                "replies\n", first, at_extra, counter);
1118         if (first < 0) {
1119                 /* We're already past request deadlines before we even get a
1120                    chance to send early replies */
1121                 LCONSOLE_WARN("%s: This server is not able to keep up with "
1122                               "request traffic (cpu-bound).\n", svc->srv_name);
1123                 CWARN("earlyQ=%d reqQ=%d recA=%d, svcEst=%d, "
1124                       "delay="CFS_DURATION_T"(jiff)\n",
1125                       counter, svc->srv_n_queued_reqs, svc->srv_n_active_reqs,
1126                       at_get(&svc->srv_at_estimate), delay);
1127         }
1128
1129         /* ptlrpc_server_finish_request may delete an entry out of
1130          * the work list */
1131         spin_lock(&svc->srv_at_lock);
1132         while (!list_empty(&work_list)) {
1133                 rq = list_entry(work_list.next, struct ptlrpc_request,
1134                                 rq_timed_list);
1135                 list_del_init(&rq->rq_timed_list);
1136                 /* if the entry is still in the worklist, it hasn't been
1137                    deleted, and is safe to take a ref to keep the req around */
1138                 atomic_inc(&rq->rq_refcount);
1139                 spin_unlock(&svc->srv_at_lock);
1140
1141                 if (ptlrpc_at_send_early_reply(rq, at_extra) == 0)
1142                         ptlrpc_at_add_timed(rq);
1143
1144                 ptlrpc_server_drop_request(rq);
1145                 spin_lock(&svc->srv_at_lock);
1146         }
1147         spin_unlock(&svc->srv_at_lock);
1148
1149         RETURN(0);
1150 }
1151
1152 /**
1153  * Put the request to the export list if the request may become
1154  * a high priority one.
1155  */
1156 static int ptlrpc_hpreq_init(struct ptlrpc_service *svc,
1157                              struct ptlrpc_request *req)
1158 {
1159         int rc;
1160         ENTRY;
1161
1162         if (svc->srv_hpreq_handler) {
1163                 rc = svc->srv_hpreq_handler(req);
1164                 if (rc)
1165                         RETURN(rc);
1166         }
1167         if (req->rq_export && req->rq_ops) {
1168                 spin_lock(&req->rq_export->exp_lock);
1169                 list_add(&req->rq_exp_list, &req->rq_export->exp_queued_rpc);
1170                 spin_unlock(&req->rq_export->exp_lock);
1171         }
1172
1173         RETURN(0);
1174 }
1175
1176 /** Remove the request from the export list. */
1177 static void ptlrpc_hpreq_fini(struct ptlrpc_request *req)
1178 {
1179         ENTRY;
1180         if (req->rq_export && req->rq_ops) {
1181                 spin_lock(&req->rq_export->exp_lock);
1182                 list_del_init(&req->rq_exp_list);
1183                 spin_unlock(&req->rq_export->exp_lock);
1184         }
1185         EXIT;
1186 }
1187
1188 /**
1189  * Make the request a high priority one.
1190  *
1191  * All the high priority requests are queued in a separate FIFO
1192  * ptlrpc_service::srv_request_hpq list which is parallel to
1193  * ptlrpc_service::srv_request_queue list but has a higher priority
1194  * for handling.
1195  *
1196  * \see ptlrpc_server_handle_request().
1197  */
1198 static void ptlrpc_hpreq_reorder_nolock(struct ptlrpc_service *svc,
1199                                         struct ptlrpc_request *req)
1200 {
1201         ENTRY;
1202         LASSERT(svc != NULL);
1203         spin_lock(&req->rq_lock);
1204         if (req->rq_hp == 0) {
1205                 int opc = lustre_msg_get_opc(req->rq_reqmsg);
1206
1207                 /* Add to the high priority queue. */
1208                 list_move_tail(&req->rq_list, &svc->srv_request_hpq);
1209                 req->rq_hp = 1;
1210                 if (opc != OBD_PING)
1211                         DEBUG_REQ(D_NET, req, "high priority req");
1212         }
1213         spin_unlock(&req->rq_lock);
1214         EXIT;
1215 }
1216
1217 void ptlrpc_hpreq_reorder(struct ptlrpc_request *req)
1218 {
1219         struct ptlrpc_service *svc = req->rq_rqbd->rqbd_service;
1220         ENTRY;
1221
1222         spin_lock(&svc->srv_lock);
1223         /* It may happen that the request is already taken for the processing
1224          * but still in the export list, do not re-add it into the HP list. */
1225         if (req->rq_phase == RQ_PHASE_NEW)
1226                 ptlrpc_hpreq_reorder_nolock(svc, req);
1227         spin_unlock(&svc->srv_lock);
1228         EXIT;
1229 }
1230
1231 /** Check if the request if a high priority one. */
1232 static int ptlrpc_server_hpreq_check(struct ptlrpc_request *req)
1233 {
1234         int opc, rc = 0;
1235         ENTRY;
1236
1237         /* Check by request opc. */
1238         opc = lustre_msg_get_opc(req->rq_reqmsg);
1239         if (opc == OBD_PING)
1240                 RETURN(1);
1241
1242         /* Perform request specific check. */
1243         if (req->rq_ops && req->rq_ops->hpreq_check)
1244                 rc = req->rq_ops->hpreq_check(req);
1245         RETURN(rc);
1246 }
1247
1248 /** Check if a request is a high priority one. */
1249 static int ptlrpc_server_request_add(struct ptlrpc_service *svc,
1250                                      struct ptlrpc_request *req)
1251 {
1252         int rc;
1253         ENTRY;
1254
1255         rc = ptlrpc_server_hpreq_check(req);
1256         if (rc < 0)
1257                 RETURN(rc);
1258
1259         spin_lock(&svc->srv_lock);
1260         /* Before inserting the request into the queue, check if it is not
1261          * inserted yet, or even already handled -- it may happen due to
1262          * a racing ldlm_server_blocking_ast(). */
1263         if (req->rq_phase == RQ_PHASE_NEW && list_empty(&req->rq_list)) {
1264                 if (rc)
1265                         ptlrpc_hpreq_reorder_nolock(svc, req);
1266                 else
1267                         list_add_tail(&req->rq_list, &svc->srv_request_queue);
1268         }
1269         spin_unlock(&svc->srv_lock);
1270
1271         RETURN(0);
1272 }
1273
1274 /* Only allow normal priority requests on a service that has a high-priority
1275  * queue if forced (i.e. cleanup), if there are other high priority requests
1276  * already being processed (i.e. those threads can service more high-priority
1277  * requests), or if there are enough idle threads that a later thread can do
1278  * a high priority request. */
1279 static int ptlrpc_server_allow_normal(struct ptlrpc_service *svc, int force)
1280 {
1281         return force || !svc->srv_hpreq_handler || svc->srv_n_hpreq > 0 ||
1282                svc->srv_n_active_reqs < svc->srv_threads_running - 2;
1283 }
1284
1285 static struct ptlrpc_request *
1286 ptlrpc_server_request_get(struct ptlrpc_service *svc, int force)
1287 {
1288         struct ptlrpc_request *req = NULL;
1289         ENTRY;
1290
1291         if (ptlrpc_server_allow_normal(svc, force) &&
1292             !list_empty(&svc->srv_request_queue) &&
1293             (list_empty(&svc->srv_request_hpq) ||
1294              svc->srv_hpreq_count >= svc->srv_hpreq_ratio)) {
1295                 req = list_entry(svc->srv_request_queue.next,
1296                                  struct ptlrpc_request, rq_list);
1297                 svc->srv_hpreq_count = 0;
1298         } else if (!list_empty(&svc->srv_request_hpq)) {
1299                 req = list_entry(svc->srv_request_hpq.next,
1300                                  struct ptlrpc_request, rq_list);
1301                 svc->srv_hpreq_count++;
1302         }
1303         RETURN(req);
1304 }
1305
1306 static int ptlrpc_server_request_pending(struct ptlrpc_service *svc, int force)
1307 {
1308         return ((ptlrpc_server_allow_normal(svc, force) &&
1309                  !list_empty(&svc->srv_request_queue)) ||
1310                 !list_empty(&svc->srv_request_hpq));
1311 }
1312
1313 /* Handle freshly incoming reqs, add to timed early reply list,
1314    pass on to regular request queue */
1315 static int
1316 ptlrpc_server_handle_req_in(struct ptlrpc_service *svc)
1317 {
1318         struct ptlrpc_request *req;
1319         __u32                  deadline;
1320         int                    rc;
1321         ENTRY;
1322
1323         LASSERT(svc);
1324
1325         spin_lock(&svc->srv_lock);
1326         if (list_empty(&svc->srv_req_in_queue)) {
1327                 spin_unlock(&svc->srv_lock);
1328                 RETURN(0);
1329         }
1330
1331         req = list_entry(svc->srv_req_in_queue.next,
1332                          struct ptlrpc_request, rq_list);
1333         list_del_init (&req->rq_list);
1334         /* Consider this still a "queued" request as far as stats are
1335            concerned */
1336         spin_unlock(&svc->srv_lock);
1337
1338         /* go through security check/transform */
1339         rc = sptlrpc_svc_unwrap_request(req);
1340         switch (rc) {
1341         case SECSVC_OK:
1342                 break;
1343         case SECSVC_COMPLETE:
1344                 target_send_reply(req, 0, OBD_FAIL_MDS_ALL_REPLY_NET);
1345                 goto err_req;
1346         case SECSVC_DROP:
1347                 goto err_req;
1348         default:
1349                 LBUG();
1350         }
1351
1352         /* Clear request swab mask; this is a new request */
1353         req->rq_req_swab_mask = 0;
1354
1355         rc = lustre_unpack_msg(req->rq_reqmsg, req->rq_reqlen);
1356         if (rc != 0) {
1357                 CERROR("error unpacking request: ptl %d from %s x"LPU64"\n",
1358                        svc->srv_req_portal, libcfs_id2str(req->rq_peer),
1359                        req->rq_xid);
1360                 goto err_req;
1361         }
1362
1363         rc = lustre_unpack_req_ptlrpc_body(req, MSG_PTLRPC_BODY_OFF);
1364         if (rc) {
1365                 CERROR ("error unpacking ptlrpc body: ptl %d from %s x"
1366                         LPU64"\n", svc->srv_req_portal,
1367                         libcfs_id2str(req->rq_peer), req->rq_xid);
1368                 goto err_req;
1369         }
1370
1371         rc = -EINVAL;
1372         if (lustre_msg_get_type(req->rq_reqmsg) != PTL_RPC_MSG_REQUEST) {
1373                 CERROR("wrong packet type received (type=%u) from %s\n",
1374                        lustre_msg_get_type(req->rq_reqmsg),
1375                        libcfs_id2str(req->rq_peer));
1376                 goto err_req;
1377         }
1378
1379         switch(lustre_msg_get_opc(req->rq_reqmsg)) {
1380         case MDS_WRITEPAGE:
1381         case OST_WRITE:
1382                 req->rq_bulk_write = 1;
1383                 break;
1384         case MDS_READPAGE:
1385         case OST_READ:
1386                 req->rq_bulk_read = 1;
1387                 break;
1388         }
1389
1390         CDEBUG(D_NET, "got req "LPD64"\n", req->rq_xid);
1391
1392         req->rq_export = class_conn2export(
1393                 lustre_msg_get_handle(req->rq_reqmsg));
1394         if (req->rq_export) {
1395                 rc = ptlrpc_check_req(req);
1396                 if (rc == 0) {
1397                         rc = sptlrpc_target_export_check(req->rq_export, req);
1398                         if (rc)
1399                                 DEBUG_REQ(D_ERROR, req, "DROPPING req with "
1400                                           "illegal security flavor,");
1401                 }
1402
1403                 if (rc)
1404                         goto err_req;
1405                 ptlrpc_update_export_timer(req->rq_export, 0);
1406         }
1407
1408         /* req_in handling should/must be fast */
1409         if (cfs_time_current_sec() - req->rq_arrival_time.tv_sec > 5)
1410                 DEBUG_REQ(D_WARNING, req, "Slow req_in handling "CFS_DURATION_T"s",
1411                           cfs_time_sub(cfs_time_current_sec(),
1412                                        req->rq_arrival_time.tv_sec));
1413
1414         /* Set rpc server deadline and add it to the timed list */
1415         deadline = (lustre_msghdr_get_flags(req->rq_reqmsg) &
1416                     MSGHDR_AT_SUPPORT) ?
1417                    /* The max time the client expects us to take */
1418                    lustre_msg_get_timeout(req->rq_reqmsg) : obd_timeout;
1419         req->rq_deadline = req->rq_arrival_time.tv_sec + deadline;
1420         if (unlikely(deadline == 0)) {
1421                 DEBUG_REQ(D_ERROR, req, "Dropping request with 0 timeout");
1422                 goto err_req;
1423         }
1424
1425         ptlrpc_at_add_timed(req);
1426         rc = ptlrpc_hpreq_init(svc, req);
1427         if (rc)
1428                 GOTO(err_req, rc);
1429
1430         /* Move it over to the request processing queue */
1431         rc = ptlrpc_server_request_add(svc, req);
1432         if (rc)
1433                 GOTO(err_req, rc);
1434         cfs_waitq_signal(&svc->srv_waitq);
1435         RETURN(1);
1436
1437 err_req:
1438         spin_lock(&svc->srv_lock);
1439         svc->srv_n_queued_reqs--;
1440         svc->srv_n_active_reqs++;
1441         spin_unlock(&svc->srv_lock);
1442         ptlrpc_server_finish_request(req);
1443
1444         RETURN(1);
1445 }
1446
1447 static int
1448 ptlrpc_server_handle_request(struct ptlrpc_service *svc,
1449                              struct ptlrpc_thread *thread)
1450 {
1451         struct obd_export     *export = NULL;
1452         struct ptlrpc_request *request;
1453         struct timeval         work_start;
1454         struct timeval         work_end;
1455         long                   timediff;
1456         int                    opc, rc;
1457         int                    fail_opc = 0;
1458         ENTRY;
1459
1460         LASSERT(svc);
1461
1462         spin_lock(&svc->srv_lock);
1463         if (unlikely(!ptlrpc_server_request_pending(svc, 0) ||
1464             (
1465 #ifndef __KERNEL__
1466              /* !@%$# liblustre only has 1 thread */
1467              atomic_read(&svc->srv_n_difficult_replies) != 0 &&
1468 #endif
1469              svc->srv_n_active_reqs >= (svc->srv_threads_running - 1)))) {
1470                  /* Don't handle regular requests in the last thread, in order               * re
1471                   * to handle difficult replies (which might block other threads)
1472                   * as well as handle any incoming reqs, early replies, etc.
1473                   * That means we always need at least 2 service threads. */
1474                 spin_unlock(&svc->srv_lock);
1475                 RETURN(0);
1476              }
1477
1478         request = ptlrpc_server_request_get(svc, 0);
1479         if  (request == NULL) {
1480                 spin_unlock(&svc->srv_lock);
1481                 RETURN(0);
1482         }
1483
1484         opc = lustre_msg_get_opc(request->rq_reqmsg);
1485         if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT))
1486                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT;
1487         else if (OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_HPREQ_TIMEOUT))
1488                 fail_opc = OBD_FAIL_PTLRPC_HPREQ_TIMEOUT;
1489
1490         if (unlikely(fail_opc)) {
1491                 if (request->rq_export && request->rq_ops) {
1492                         spin_unlock(&svc->srv_lock);
1493                         OBD_FAIL_TIMEOUT(fail_opc, 4);
1494                         spin_lock(&svc->srv_lock);
1495                         request = ptlrpc_server_request_get(svc, 0);
1496                         if  (request == NULL) {
1497                                 spin_unlock(&svc->srv_lock);
1498                                 RETURN(0);
1499                         }
1500                         LASSERT(ptlrpc_server_request_pending(svc, 0));
1501                 }
1502         }
1503
1504         list_del_init(&request->rq_list);
1505         svc->srv_n_queued_reqs--;
1506         svc->srv_n_active_reqs++;
1507         if (request->rq_hp)
1508                 svc->srv_n_hpreq++;
1509
1510         /* The phase is changed under the lock here because we need to know
1511          * the request is under processing (see ptlrpc_hpreq_reorder()). */
1512         ptlrpc_rqphase_move(request, RQ_PHASE_INTERPRET);
1513         spin_unlock(&svc->srv_lock);
1514
1515         ptlrpc_hpreq_fini(request);
1516
1517         if(OBD_FAIL_CHECK(OBD_FAIL_PTLRPC_DUMP_LOG))
1518                 libcfs_debug_dumplog();
1519
1520         do_gettimeofday(&work_start);
1521         timediff = cfs_timeval_sub(&work_start, &request->rq_arrival_time,NULL);
1522         if (likely(svc->srv_stats != NULL)) {
1523                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQWAIT_CNTR,
1524                                     timediff);
1525                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQQDEPTH_CNTR,
1526                                     svc->srv_n_queued_reqs);
1527                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQACTIVE_CNTR,
1528                                     svc->srv_n_active_reqs);
1529                 lprocfs_counter_add(svc->srv_stats, PTLRPC_TIMEOUT,
1530                                     at_get(&svc->srv_at_estimate));
1531         }
1532
1533         rc = lu_context_init(&request->rq_session,
1534                              LCT_SESSION|LCT_REMEMBER|LCT_NOREF);
1535         if (rc) {
1536                 CERROR("Failure to initialize session: %d\n", rc);
1537                 goto out_req;
1538         }
1539         request->rq_session.lc_thread = thread;
1540         request->rq_session.lc_cookie = 0x5;
1541         lu_context_enter(&request->rq_session);
1542
1543         CDEBUG(D_NET, "got req "LPU64"\n", request->rq_xid);
1544
1545         request->rq_svc_thread = thread;
1546         if (thread)
1547                 request->rq_svc_thread->t_env->le_ses = &request->rq_session;
1548
1549         if (likely(request->rq_export)) {
1550                 if (unlikely(ptlrpc_check_req(request)))
1551                         goto put_conn;
1552                 ptlrpc_update_export_timer(request->rq_export, timediff >> 19);
1553                 export = class_export_rpc_get(request->rq_export);
1554         }
1555
1556         /* Discard requests queued for longer than the deadline.
1557            The deadline is increased if we send an early reply. */
1558         if (cfs_time_current_sec() > request->rq_deadline) {
1559                 DEBUG_REQ(D_ERROR, request, "Dropping timed-out request from %s"
1560                           ": deadline "CFS_DURATION_T":"CFS_DURATION_T"s ago\n",
1561                           libcfs_id2str(request->rq_peer),
1562                           cfs_time_sub(request->rq_deadline,
1563                           request->rq_arrival_time.tv_sec),
1564                           cfs_time_sub(cfs_time_current_sec(),
1565                           request->rq_deadline));
1566                 goto put_rpc_export;
1567         }
1568
1569         CDEBUG(D_RPCTRACE, "Handling RPC pname:cluuid+ref:pid:xid:nid:opc "
1570                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1571                (request->rq_export ?
1572                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1573                (request->rq_export ?
1574                 atomic_read(&request->rq_export->exp_refcount) : -99),
1575                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1576                libcfs_id2str(request->rq_peer),
1577                lustre_msg_get_opc(request->rq_reqmsg));
1578
1579         OBD_FAIL_TIMEOUT_MS(OBD_FAIL_PTLRPC_PAUSE_REQ, obd_fail_val);
1580
1581         rc = svc->srv_handler(request);
1582
1583         ptlrpc_rqphase_move(request, RQ_PHASE_COMPLETE);
1584
1585         CDEBUG(D_RPCTRACE, "Handled RPC pname:cluuid+ref:pid:xid:nid:opc "
1586                "%s:%s+%d:%d:x"LPU64":%s:%d\n", cfs_curproc_comm(),
1587                (request->rq_export ?
1588                 (char *)request->rq_export->exp_client_uuid.uuid : "0"),
1589                (request->rq_export ?
1590                 atomic_read(&request->rq_export->exp_refcount) : -99),
1591                lustre_msg_get_status(request->rq_reqmsg), request->rq_xid,
1592                libcfs_id2str(request->rq_peer),
1593                lustre_msg_get_opc(request->rq_reqmsg));
1594
1595 put_rpc_export:
1596         if (export != NULL)
1597                 class_export_rpc_put(export);
1598 put_conn:
1599         lu_context_exit(&request->rq_session);
1600         lu_context_fini(&request->rq_session);
1601
1602         if (unlikely(cfs_time_current_sec() > request->rq_deadline)) {
1603                 DEBUG_REQ(D_WARNING, request, "Request x"LPU64" took longer "
1604                           "than estimated ("CFS_DURATION_T":"CFS_DURATION_T"s);"
1605                           " client may timeout.",
1606                           request->rq_xid, cfs_time_sub(request->rq_deadline,
1607                           request->rq_arrival_time.tv_sec),
1608                           cfs_time_sub(cfs_time_current_sec(),
1609                           request->rq_deadline));
1610         }
1611
1612         do_gettimeofday(&work_end);
1613         timediff = cfs_timeval_sub(&work_end, &work_start, NULL);
1614         CDEBUG(D_RPCTRACE, "request x"LPU64" opc %u from %s processed in "
1615                "%ldus (%ldus total) trans "LPU64" rc %d/%d\n",
1616                request->rq_xid, lustre_msg_get_opc(request->rq_reqmsg),
1617                libcfs_id2str(request->rq_peer), timediff,
1618                cfs_timeval_sub(&work_end, &request->rq_arrival_time, NULL),
1619                request->rq_repmsg ? lustre_msg_get_transno(request->rq_repmsg) :
1620                request->rq_transno, request->rq_status,
1621                request->rq_repmsg ? lustre_msg_get_status(request->rq_repmsg):
1622                -999);
1623         if (likely(svc->srv_stats != NULL && request->rq_reqmsg != NULL)) {
1624                 __u32 op = lustre_msg_get_opc(request->rq_reqmsg);
1625                 int opc = opcode_offset(op);
1626                 if (opc > 0 && !(op == LDLM_ENQUEUE || op == MDS_REINT)) {
1627                         LASSERT(opc < LUSTRE_MAX_OPCODES);
1628                         lprocfs_counter_add(svc->srv_stats,
1629                                             opc + EXTRA_MAX_OPCODES,
1630                                             timediff);
1631                 }
1632         }
1633         if (unlikely(request->rq_early_count)) {
1634                 DEBUG_REQ(D_ADAPTTO, request,
1635                           "sent %d early replies before finishing in "
1636                           CFS_DURATION_T"s",
1637                           request->rq_early_count,
1638                           cfs_time_sub(work_end.tv_sec,
1639                           request->rq_arrival_time.tv_sec));
1640         }
1641
1642 out_req:
1643         spin_lock(&svc->srv_lock);
1644         if (request->rq_hp)
1645                 svc->srv_n_hpreq--;
1646         spin_unlock(&svc->srv_lock);
1647         ptlrpc_server_finish_request(request);
1648
1649         RETURN(1);
1650 }
1651
1652 /**
1653  * An internal function to process a single reply state object.
1654  */
1655 static int
1656 ptlrpc_handle_rs (struct ptlrpc_reply_state *rs)
1657 {
1658         struct ptlrpc_service     *svc = rs->rs_service;
1659         struct obd_export         *exp;
1660         struct obd_device         *obd;
1661         int                        nlocks;
1662         int                        been_handled;
1663         ENTRY;
1664
1665         exp = rs->rs_export;
1666         obd = exp->exp_obd;
1667
1668         LASSERT (rs->rs_difficult);
1669         LASSERT (rs->rs_scheduled);
1670         LASSERT (list_empty(&rs->rs_list));
1671
1672         spin_lock (&exp->exp_lock);
1673         /* Noop if removed already */
1674         list_del_init (&rs->rs_exp_list);
1675         spin_unlock (&exp->exp_lock);
1676
1677         /* Avoid obd_uncommitted_replies_lock contention if we 100% sure that
1678          * rs has been removed from the list already */
1679         if (!list_empty_careful(&rs->rs_obd_list)) {
1680                 spin_lock(&obd->obd_uncommitted_replies_lock);
1681                 list_del_init(&rs->rs_obd_list);
1682                 spin_unlock(&obd->obd_uncommitted_replies_lock);
1683         }
1684
1685         spin_lock(&rs->rs_lock);
1686
1687         been_handled = rs->rs_handled;
1688         rs->rs_handled = 1;
1689
1690         nlocks = rs->rs_nlocks;                 /* atomic "steal", but */
1691         rs->rs_nlocks = 0;                      /* locks still on rs_locks! */
1692
1693         if (nlocks == 0 && !been_handled) {
1694                 /* If we see this, we should already have seen the warning
1695                  * in mds_steal_ack_locks()  */
1696                 CWARN("All locks stolen from rs %p x"LPD64".t"LPD64
1697                       " o%d NID %s\n",
1698                       rs,
1699                       rs->rs_xid, rs->rs_transno,
1700                       lustre_msg_get_opc(rs->rs_msg),
1701                       libcfs_nid2str(exp->exp_connection->c_peer.nid));
1702         }
1703
1704         if ((!been_handled && rs->rs_on_net) || nlocks > 0) {
1705                 spin_unlock(&rs->rs_lock);
1706
1707                 if (!been_handled && rs->rs_on_net) {
1708                         LNetMDUnlink(rs->rs_md_h);
1709                         /* Ignore return code; we're racing with
1710                          * completion... */
1711                 }
1712
1713                 while (nlocks-- > 0)
1714                         ldlm_lock_decref(&rs->rs_locks[nlocks],
1715                                          rs->rs_modes[nlocks]);
1716
1717                 spin_lock(&rs->rs_lock);
1718         }
1719
1720         rs->rs_scheduled = 0;
1721
1722         if (!rs->rs_on_net) {
1723                 /* Off the net */
1724                 spin_unlock(&rs->rs_lock);
1725
1726                 class_export_put (exp);
1727                 rs->rs_export = NULL;
1728                 ptlrpc_rs_decref (rs);
1729                 atomic_dec (&svc->srv_outstanding_replies);
1730                 if (atomic_dec_and_test(&svc->srv_n_difficult_replies) &&
1731                     svc->srv_is_stopping)
1732                         cfs_waitq_broadcast(&svc->srv_waitq);
1733                 RETURN(1);
1734         }
1735
1736         /* still on the net; callback will schedule */
1737         spin_unlock(&rs->rs_lock);
1738         RETURN(1);
1739 }
1740
1741 #ifndef __KERNEL__
1742
1743 /**
1744  * Check whether given service has a reply available for processing
1745  * and process it.
1746  *
1747  * \param svc a ptlrpc service
1748  * \retval 0 no replies processes
1749  * \retval 1 one reply processed
1750  */
1751 static int
1752 ptlrpc_server_handle_reply(struct ptlrpc_service *svc)
1753 {
1754         struct ptlrpc_reply_state *rs = NULL;
1755         ENTRY;
1756
1757         spin_lock(&svc->srv_lock);
1758         if (!list_empty(&svc->srv_reply_queue)) {
1759                 rs = list_entry(svc->srv_reply_queue.prev,
1760                                 struct ptlrpc_reply_state,
1761                                 rs_list);
1762                 list_del_init(&rs->rs_list);
1763         }
1764         spin_unlock(&svc->srv_lock);
1765         if (rs != NULL)
1766                 ptlrpc_handle_rs(rs);
1767         RETURN(rs != NULL);
1768 }
1769
1770 /* FIXME make use of timeout later */
1771 int
1772 liblustre_check_services (void *arg)
1773 {
1774         int  did_something = 0;
1775         int  rc;
1776         struct list_head *tmp, *nxt;
1777         ENTRY;
1778
1779         /* I'm relying on being single threaded, not to have to lock
1780          * ptlrpc_all_services etc */
1781         list_for_each_safe (tmp, nxt, &ptlrpc_all_services) {
1782                 struct ptlrpc_service *svc =
1783                         list_entry (tmp, struct ptlrpc_service, srv_list);
1784
1785                 if (svc->srv_threads_running != 0)     /* I've recursed */
1786                         continue;
1787
1788                 /* service threads can block for bulk, so this limits us
1789                  * (arbitrarily) to recursing 1 stack frame per service.
1790                  * Note that the problem with recursion is that we have to
1791                  * unwind completely before our caller can resume. */
1792
1793                 svc->srv_threads_running++;
1794
1795                 do {
1796                         rc = ptlrpc_server_handle_req_in(svc);
1797                         rc |= ptlrpc_server_handle_reply(svc);
1798                         rc |= ptlrpc_at_check_timed(svc);
1799                         rc |= ptlrpc_server_handle_request(svc, NULL);
1800                         rc |= (ptlrpc_server_post_idle_rqbds(svc) > 0);
1801                         did_something |= rc;
1802                 } while (rc);
1803
1804                 svc->srv_threads_running--;
1805         }
1806
1807         RETURN(did_something);
1808 }
1809 #define ptlrpc_stop_all_threads(s) do {} while (0)
1810
1811 #else /* __KERNEL__ */
1812
1813 /* Don't use daemonize, it removes fs struct from new thread (bug 418) */
1814 void ptlrpc_daemonize(char *name)
1815 {
1816         struct fs_struct *fs = current->fs;
1817
1818         atomic_inc(&fs->count);
1819         cfs_daemonize(name);
1820         exit_fs(cfs_current());
1821         current->fs = fs;
1822         ll_set_fs_pwd(current->fs, init_task.fs->pwdmnt, init_task.fs->pwd);
1823 }
1824
1825 static void
1826 ptlrpc_check_rqbd_pool(struct ptlrpc_service *svc)
1827 {
1828         int avail = svc->srv_nrqbd_receiving;
1829         int low_water = test_req_buffer_pressure ? 0 :
1830                         svc->srv_nbuf_per_group/2;
1831
1832         /* NB I'm not locking; just looking. */
1833
1834         /* CAVEAT EMPTOR: We might be allocating buffers here because we've
1835          * allowed the request history to grow out of control.  We could put a
1836          * sanity check on that here and cull some history if we need the
1837          * space. */
1838
1839         if (avail <= low_water)
1840                 ptlrpc_grow_req_bufs(svc);
1841
1842         if (svc->srv_stats)
1843                 lprocfs_counter_add(svc->srv_stats, PTLRPC_REQBUF_AVAIL_CNTR,
1844                                     avail);
1845 }
1846
1847 static int
1848 ptlrpc_retry_rqbds(void *arg)
1849 {
1850         struct ptlrpc_service *svc = (struct ptlrpc_service *)arg;
1851
1852         svc->srv_rqbd_timeout = 0;
1853         return (-ETIMEDOUT);
1854 }
1855
1856 static int ptlrpc_main(void *arg)
1857 {
1858         struct ptlrpc_svc_data *data = (struct ptlrpc_svc_data *)arg;
1859         struct ptlrpc_service  *svc = data->svc;
1860         struct ptlrpc_thread   *thread = data->thread;
1861         struct obd_device      *dev = data->dev;
1862         struct ptlrpc_reply_state *rs;
1863 #ifdef WITH_GROUP_INFO
1864         struct group_info *ginfo = NULL;
1865 #endif
1866         struct lu_env env;
1867         int counter = 0, rc = 0;
1868         ENTRY;
1869
1870         ptlrpc_daemonize(data->name);
1871
1872 #if defined(HAVE_NODE_TO_CPUMASK) && defined(CONFIG_NUMA)
1873         /* we need to do this before any per-thread allocation is done so that
1874          * we get the per-thread allocations on local node.  bug 7342 */
1875         if (svc->srv_cpu_affinity) {
1876                 int cpu, num_cpu;
1877
1878                 for (cpu = 0, num_cpu = 0; cpu < num_possible_cpus(); cpu++) {
1879                         if (!cpu_online(cpu))
1880                                 continue;
1881                         if (num_cpu == thread->t_id % num_online_cpus())
1882                                 break;
1883                         num_cpu++;
1884                 }
1885                 set_cpus_allowed(cfs_current(), node_to_cpumask(cpu_to_node(cpu)));
1886         }
1887 #endif
1888
1889 #ifdef WITH_GROUP_INFO
1890         ginfo = groups_alloc(0);
1891         if (!ginfo) {
1892                 rc = -ENOMEM;
1893                 goto out;
1894         }
1895
1896         set_current_groups(ginfo);
1897         put_group_info(ginfo);
1898 #endif
1899
1900         if (svc->srv_init != NULL) {
1901                 rc = svc->srv_init(thread);
1902                 if (rc)
1903                         goto out;
1904         }
1905
1906         rc = lu_context_init(&env.le_ctx,
1907                              svc->srv_ctx_tags|LCT_REMEMBER|LCT_NOREF);
1908         if (rc)
1909                 goto out_srv_fini;
1910
1911         thread->t_env = &env;
1912         env.le_ctx.lc_thread = thread;
1913         env.le_ctx.lc_cookie = 0x6;
1914
1915         /* Alloc reply state structure for this one */
1916         OBD_ALLOC_GFP(rs, svc->srv_max_reply_size, CFS_ALLOC_STD);
1917         if (!rs) {
1918                 rc = -ENOMEM;
1919                 goto out_srv_fini;
1920         }
1921
1922         /* Record that the thread is running */
1923         thread->t_flags = SVC_RUNNING;
1924         /*
1925          * wake up our creator. Note: @data is invalid after this point,
1926          * because it's allocated on ptlrpc_start_thread() stack.
1927          */
1928         cfs_waitq_signal(&thread->t_ctl_waitq);
1929
1930         thread->t_watchdog = lc_watchdog_add(max_t(int, obd_timeout, AT_OFF ? 0 :
1931                                                    at_get(&svc->srv_at_estimate))
1932                                              *  svc->srv_watchdog_factor,
1933                                              NULL, NULL);
1934
1935         spin_lock(&svc->srv_lock);
1936         svc->srv_threads_running++;
1937         list_add(&rs->rs_list, &svc->srv_free_rs_list);
1938         spin_unlock(&svc->srv_lock);
1939         cfs_waitq_signal(&svc->srv_free_rs_waitq);
1940
1941         CDEBUG(D_NET, "service thread %d (#%d) started\n", thread->t_id,
1942                svc->srv_threads_running);
1943
1944         /* XXX maintain a list of all managed devices: insert here */
1945
1946         while ((thread->t_flags & SVC_STOPPING) == 0) {
1947                 /* Don't exit while there are replies to be handled */
1948                 struct l_wait_info lwi = LWI_TIMEOUT(svc->srv_rqbd_timeout,
1949                                                      ptlrpc_retry_rqbds, svc);
1950
1951                 lc_watchdog_disable(thread->t_watchdog);
1952
1953                 cond_resched();
1954
1955                 l_wait_event_exclusive (svc->srv_waitq,
1956                               ((thread->t_flags & SVC_STOPPING) != 0) ||
1957                               (!list_empty(&svc->srv_idle_rqbds) &&
1958                                svc->srv_rqbd_timeout == 0) ||
1959                               !list_empty(&svc->srv_req_in_queue) ||
1960                               (ptlrpc_server_request_pending(svc, 0) &&
1961                                (svc->srv_n_active_reqs <
1962                                 (svc->srv_threads_running - 1))) ||
1963                               svc->srv_at_check,
1964                               &lwi);
1965
1966                 lc_watchdog_touch_ms(thread->t_watchdog, max_t(int, obd_timeout,
1967                                      AT_OFF ? 0 :
1968                                      at_get(&svc->srv_at_estimate)) *
1969                                      svc->srv_watchdog_factor);
1970
1971                 ptlrpc_check_rqbd_pool(svc);
1972
1973                 if ((svc->srv_threads_started < svc->srv_threads_max) &&
1974                     (svc->srv_n_active_reqs >= (svc->srv_threads_started - 1))){
1975                         /* Ignore return code - we tried... */
1976                         ptlrpc_start_thread(dev, svc);
1977                 }
1978
1979                 if (!list_empty(&svc->srv_req_in_queue)) {
1980                         /* Process all incoming reqs before handling any */
1981                         ptlrpc_server_handle_req_in(svc);
1982                         /* but limit ourselves in case of flood */
1983                         if (counter++ < 1000)
1984                                 continue;
1985                         counter = 0;
1986                 }
1987
1988                 if (svc->srv_at_check)
1989                         ptlrpc_at_check_timed(svc);
1990
1991                 /* don't handle requests in the last thread */
1992                 if (ptlrpc_server_request_pending(svc, 0) &&
1993                     (svc->srv_n_active_reqs < (svc->srv_threads_running - 1))) {
1994                         lu_context_enter(&env.le_ctx);
1995                         ptlrpc_server_handle_request(svc, thread);
1996                         lu_context_exit(&env.le_ctx);
1997                 }
1998
1999                 if (!list_empty(&svc->srv_idle_rqbds) &&
2000                     ptlrpc_server_post_idle_rqbds(svc) < 0) {
2001                         /* I just failed to repost request buffers.  Wait
2002                          * for a timeout (unless something else happens)
2003                          * before I try again */
2004                         svc->srv_rqbd_timeout = cfs_time_seconds(1)/10;
2005                         CDEBUG(D_RPCTRACE,"Posted buffers: %d\n",
2006                                svc->srv_nrqbd_receiving);
2007                 }
2008         }
2009
2010         lc_watchdog_delete(thread->t_watchdog);
2011         thread->t_watchdog = NULL;
2012
2013 out_srv_fini:
2014         /*
2015          * deconstruct service specific state created by ptlrpc_start_thread()
2016          */
2017         if (svc->srv_done != NULL)
2018                 svc->srv_done(thread);
2019
2020         lu_context_fini(&env.le_ctx);
2021 out:
2022         CDEBUG(D_NET, "service thread %d exiting: rc %d\n", thread->t_id, rc);
2023
2024         spin_lock(&svc->srv_lock);
2025         svc->srv_threads_running--; /* must know immediately */
2026         thread->t_id = rc;
2027         thread->t_flags = SVC_STOPPED;
2028
2029         cfs_waitq_signal(&thread->t_ctl_waitq);
2030         spin_unlock(&svc->srv_lock);
2031
2032         return rc;
2033 }
2034
2035 struct ptlrpc_hr_args {
2036         int                       thread_index;
2037         int                       cpu_index;
2038         struct ptlrpc_hr_service *hrs;
2039 };
2040
2041 static int hrt_dont_sleep(struct ptlrpc_hr_thread *t,
2042                           struct list_head *replies)
2043 {
2044         int result;
2045
2046         spin_lock(&t->hrt_lock);
2047         list_splice_init(&t->hrt_queue, replies);
2048         result = test_bit(HRT_STOPPING, &t->hrt_flags) ||
2049                 !list_empty(replies);
2050         spin_unlock(&t->hrt_lock);
2051         return result;
2052 }
2053
2054 static int ptlrpc_hr_main(void *arg)
2055 {
2056         struct ptlrpc_hr_args * hr_args = arg;
2057         struct ptlrpc_hr_service *hr = hr_args->hrs;
2058         struct ptlrpc_hr_thread *t = &hr->hr_threads[hr_args->thread_index];
2059         char threadname[20];
2060         CFS_LIST_HEAD(replies);
2061
2062         snprintf(threadname, sizeof(threadname),
2063                  "ptlrpc_hr_%d", hr_args->thread_index);
2064
2065         ptlrpc_daemonize(threadname);
2066 #if defined(HAVE_NODE_TO_CPUMASK)
2067         set_cpus_allowed(cfs_current(),
2068                          node_to_cpumask(cpu_to_node(hr_args->cpu_index)));
2069 #endif
2070         set_bit(HRT_RUNNING, &t->hrt_flags);
2071         cfs_waitq_signal(&t->hrt_wait);
2072
2073         while (!test_bit(HRT_STOPPING, &t->hrt_flags)) {
2074
2075                 cfs_wait_event(t->hrt_wait, hrt_dont_sleep(t, &replies));
2076                 while (!list_empty(&replies)) {
2077                         struct ptlrpc_reply_state *rs;
2078
2079                         rs = list_entry(replies.prev,
2080                                         struct ptlrpc_reply_state,
2081                                         rs_list);
2082                         list_del_init(&rs->rs_list);
2083                         ptlrpc_handle_rs(rs);
2084                 }
2085         }
2086
2087         clear_bit(HRT_RUNNING, &t->hrt_flags);
2088         complete(&t->hrt_completion);
2089
2090         return 0;
2091 }
2092
2093 static int ptlrpc_start_hr_thread(struct ptlrpc_hr_service *hr, int n, int cpu)
2094 {
2095         struct ptlrpc_hr_thread *t = &hr->hr_threads[n];
2096         struct ptlrpc_hr_args args;
2097         int rc;
2098         ENTRY;
2099
2100         args.thread_index = n;
2101         args.cpu_index = cpu;
2102         args.hrs = hr;
2103
2104         rc = cfs_kernel_thread(ptlrpc_hr_main, (void*)&args,
2105                                CLONE_VM|CLONE_FILES);
2106         if (rc < 0) {
2107                 complete(&t->hrt_completion);
2108                 GOTO(out, rc);
2109         }
2110         cfs_wait_event(t->hrt_wait, test_bit(HRT_RUNNING, &t->hrt_flags));
2111         RETURN(0);
2112  out:
2113         return rc;
2114 }
2115
2116 static void ptlrpc_stop_hr_thread(struct ptlrpc_hr_thread *t)
2117 {
2118         ENTRY;
2119
2120         set_bit(HRT_STOPPING, &t->hrt_flags);
2121         cfs_waitq_signal(&t->hrt_wait);
2122         wait_for_completion(&t->hrt_completion);
2123
2124         EXIT;
2125 }
2126
2127 static void ptlrpc_stop_hr_threads(struct ptlrpc_hr_service *hrs)
2128 {
2129         int n;
2130         ENTRY;
2131
2132         for (n = 0; n < hrs->hr_n_threads; n++)
2133                 ptlrpc_stop_hr_thread(&hrs->hr_threads[n]);
2134
2135         EXIT;
2136 }
2137
2138 static int ptlrpc_start_hr_threads(struct ptlrpc_hr_service *hr)
2139 {
2140         int rc = -ENOMEM;
2141         int n, cpu, threads_started = 0;
2142         ENTRY;
2143
2144         LASSERT(hr != NULL);
2145         LASSERT(hr->hr_n_threads > 0);
2146
2147         for (n = 0, cpu = 0; n < hr->hr_n_threads; n++) {
2148 #if defined(HAVE_NODE_TO_CPUMASK)
2149                 while(!cpu_online(cpu)) {
2150                         cpu++;
2151                         if (cpu >= num_possible_cpus())
2152                                 cpu = 0;
2153                 }
2154 #endif
2155                 rc = ptlrpc_start_hr_thread(hr, n, cpu);
2156                 if (rc != 0)
2157                         break;
2158                 threads_started++;
2159                 cpu++;
2160         }
2161         if (threads_started == 0) {
2162                 CERROR("No reply handling threads started\n");
2163                 RETURN(-ESRCH);
2164         }
2165         if (threads_started < hr->hr_n_threads) {
2166                 CWARN("Started only %d reply handling threads from %d\n",
2167                       threads_started, hr->hr_n_threads);
2168                 hr->hr_n_threads = threads_started;
2169         }
2170         RETURN(0);
2171 }
2172
2173 static void ptlrpc_stop_thread(struct ptlrpc_service *svc,
2174                                struct ptlrpc_thread *thread)
2175 {
2176         struct l_wait_info lwi = { 0 };
2177         ENTRY;
2178
2179         CDEBUG(D_RPCTRACE, "Stopping thread %p\n", thread);
2180         spin_lock(&svc->srv_lock);
2181         thread->t_flags = SVC_STOPPING;
2182         spin_unlock(&svc->srv_lock);
2183
2184         cfs_waitq_broadcast(&svc->srv_waitq);
2185         l_wait_event(thread->t_ctl_waitq, (thread->t_flags & SVC_STOPPED),
2186                      &lwi);
2187
2188         spin_lock(&svc->srv_lock);
2189         list_del(&thread->t_link);
2190         spin_unlock(&svc->srv_lock);
2191
2192         OBD_FREE_PTR(thread);
2193         EXIT;
2194 }
2195
2196 void ptlrpc_stop_all_threads(struct ptlrpc_service *svc)
2197 {
2198         struct ptlrpc_thread *thread;
2199         ENTRY;
2200
2201         spin_lock(&svc->srv_lock);
2202         while (!list_empty(&svc->srv_threads)) {
2203                 thread = list_entry(svc->srv_threads.next,
2204                                     struct ptlrpc_thread, t_link);
2205
2206                 spin_unlock(&svc->srv_lock);
2207                 ptlrpc_stop_thread(svc, thread);
2208                 spin_lock(&svc->srv_lock);
2209         }
2210
2211         spin_unlock(&svc->srv_lock);
2212         EXIT;
2213 }
2214
2215 int ptlrpc_start_threads(struct obd_device *dev, struct ptlrpc_service *svc)
2216 {
2217         int i, rc = 0;
2218         ENTRY;
2219
2220         /* We require 2 threads min - see note in
2221            ptlrpc_server_handle_request */
2222         LASSERT(svc->srv_threads_min >= 2);
2223         for (i = 0; i < svc->srv_threads_min; i++) {
2224                 rc = ptlrpc_start_thread(dev, svc);
2225                 /* We have enough threads, don't start more.  b=15759 */
2226                 if (rc == -EMFILE)
2227                         break;
2228                 if (rc) {
2229                         CERROR("cannot start %s thread #%d: rc %d\n",
2230                                svc->srv_thread_name, i, rc);
2231                         ptlrpc_stop_all_threads(svc);
2232                 }
2233         }
2234         RETURN(rc);
2235 }
2236
2237 int ptlrpc_start_thread(struct obd_device *dev, struct ptlrpc_service *svc)
2238 {
2239         struct l_wait_info lwi = { 0 };
2240         struct ptlrpc_svc_data d;
2241         struct ptlrpc_thread *thread;
2242         char name[32];
2243         int id, rc;
2244         ENTRY;
2245
2246         CDEBUG(D_RPCTRACE, "%s started %d min %d max %d running %d\n",
2247                svc->srv_name, svc->srv_threads_started, svc->srv_threads_min,
2248                svc->srv_threads_max, svc->srv_threads_running);
2249         if (unlikely(svc->srv_threads_started >= svc->srv_threads_max) ||
2250             (OBD_FAIL_CHECK(OBD_FAIL_TGT_TOOMANY_THREADS) &&
2251              svc->srv_threads_started == svc->srv_threads_min - 1))
2252                 RETURN(-EMFILE);
2253
2254         OBD_ALLOC_PTR(thread);
2255         if (thread == NULL)
2256                 RETURN(-ENOMEM);
2257         cfs_waitq_init(&thread->t_ctl_waitq);
2258
2259         spin_lock(&svc->srv_lock);
2260         if (svc->srv_threads_started >= svc->srv_threads_max) {
2261                 spin_unlock(&svc->srv_lock);
2262                 OBD_FREE_PTR(thread);
2263                 RETURN(-EMFILE);
2264         }
2265         list_add(&thread->t_link, &svc->srv_threads);
2266         id = svc->srv_threads_started++;
2267         spin_unlock(&svc->srv_lock);
2268
2269         thread->t_id = id;
2270         sprintf(name, "%s_%02d", svc->srv_thread_name, id);
2271         d.dev = dev;
2272         d.svc = svc;
2273         d.name = name;
2274         d.thread = thread;
2275
2276         CDEBUG(D_RPCTRACE, "starting thread '%s'\n", name);
2277
2278           /* CLONE_VM and CLONE_FILES just avoid a needless copy, because we
2279          * just drop the VM and FILES in ptlrpc_daemonize() right away.
2280          */
2281         rc = cfs_kernel_thread(ptlrpc_main, &d, CLONE_VM | CLONE_FILES);
2282         if (rc < 0) {
2283                 CERROR("cannot start thread '%s': rc %d\n", name, rc);
2284
2285                 spin_lock(&svc->srv_lock);
2286                 list_del(&thread->t_link);
2287                 --svc->srv_threads_started;
2288                 spin_unlock(&svc->srv_lock);
2289
2290                 OBD_FREE(thread, sizeof(*thread));
2291                 RETURN(rc);
2292         }
2293         l_wait_event(thread->t_ctl_waitq,
2294                      thread->t_flags & (SVC_RUNNING | SVC_STOPPED), &lwi);
2295
2296         rc = (thread->t_flags & SVC_STOPPED) ? thread->t_id : 0;
2297         RETURN(rc);
2298 }
2299
2300
2301 int ptlrpc_hr_init(void)
2302 {
2303         int i;
2304         int n_cpus = num_online_cpus();
2305         struct ptlrpc_hr_service *hr;
2306         int size;
2307         ENTRY;
2308
2309         LASSERT(ptlrpc_hr == NULL);
2310
2311         size = offsetof(struct ptlrpc_hr_service, hr_threads[n_cpus]);
2312         OBD_ALLOC(hr, size);
2313         if (hr == NULL)
2314                 RETURN(-ENOMEM);
2315         for (i = 0; i < n_cpus; i++) {
2316                 struct ptlrpc_hr_thread *t = &hr->hr_threads[i];
2317
2318                 spin_lock_init(&t->hrt_lock);
2319                 cfs_waitq_init(&t->hrt_wait);
2320                 CFS_INIT_LIST_HEAD(&t->hrt_queue);
2321                 init_completion(&t->hrt_completion);
2322         }
2323         hr->hr_n_threads = n_cpus;
2324         hr->hr_size = size;
2325         ptlrpc_hr = hr;
2326
2327         RETURN(ptlrpc_start_hr_threads(hr));
2328 }
2329
2330 void ptlrpc_hr_fini(void)
2331 {
2332         if (ptlrpc_hr != NULL) {
2333                 ptlrpc_stop_hr_threads(ptlrpc_hr);
2334                 OBD_FREE(ptlrpc_hr, ptlrpc_hr->hr_size);
2335                 ptlrpc_hr = NULL;
2336         }
2337 }
2338
2339 #endif /* __KERNEL__ */
2340
2341 /**
2342  * Wait until all already scheduled replies are processed.
2343  */
2344 static void ptlrpc_wait_replies(struct ptlrpc_service *svc)
2345 {
2346         while (1) {
2347                 int rc;
2348                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(10),
2349                                                      NULL, NULL);
2350                 rc = l_wait_event(svc->srv_waitq,
2351                                   atomic_read(&svc->srv_n_difficult_replies) == 0,
2352                                   &lwi);
2353                 if (rc == 0)
2354                         break;
2355                 CWARN("Unexpectedly long timeout %p\n", svc);
2356         }
2357 }
2358
2359 int ptlrpc_unregister_service(struct ptlrpc_service *service)
2360 {
2361         int                   rc;
2362         struct l_wait_info    lwi;
2363         struct list_head     *tmp;
2364         struct ptlrpc_reply_state *rs, *t;
2365         struct ptlrpc_at_array *array = &service->srv_at_array;
2366         ENTRY;
2367
2368         service->srv_is_stopping = 1;
2369         cfs_timer_disarm(&service->srv_at_timer);
2370
2371         ptlrpc_stop_all_threads(service);
2372         LASSERT(list_empty(&service->srv_threads));
2373
2374         spin_lock (&ptlrpc_all_services_lock);
2375         list_del_init (&service->srv_list);
2376         spin_unlock (&ptlrpc_all_services_lock);
2377
2378         ptlrpc_lprocfs_unregister_service(service);
2379
2380         /* All history will be culled when the next request buffer is
2381          * freed */
2382         service->srv_max_history_rqbds = 0;
2383
2384         CDEBUG(D_NET, "%s: tearing down\n", service->srv_name);
2385
2386         rc = LNetClearLazyPortal(service->srv_req_portal);
2387         LASSERT (rc == 0);
2388
2389         /* Unlink all the request buffers.  This forces a 'final' event with
2390          * its 'unlink' flag set for each posted rqbd */
2391         list_for_each(tmp, &service->srv_active_rqbds) {
2392                 struct ptlrpc_request_buffer_desc *rqbd =
2393                         list_entry(tmp, struct ptlrpc_request_buffer_desc,
2394                                    rqbd_list);
2395
2396                 rc = LNetMDUnlink(rqbd->rqbd_md_h);
2397                 LASSERT (rc == 0 || rc == -ENOENT);
2398         }
2399
2400         /* Wait for the network to release any buffers it's currently
2401          * filling */
2402         for (;;) {
2403                 spin_lock(&service->srv_lock);
2404                 rc = service->srv_nrqbd_receiving;
2405                 spin_unlock(&service->srv_lock);
2406
2407                 if (rc == 0)
2408                         break;
2409
2410                 /* Network access will complete in finite time but the HUGE
2411                  * timeout lets us CWARN for visibility of sluggish NALs */
2412                 lwi = LWI_TIMEOUT_INTERVAL(cfs_time_seconds(LONG_UNLINK),
2413                                            cfs_time_seconds(1), NULL, NULL);
2414                 rc = l_wait_event(service->srv_waitq,
2415                                   service->srv_nrqbd_receiving == 0,
2416                                   &lwi);
2417                 if (rc == -ETIMEDOUT)
2418                         CWARN("Service %s waiting for request buffers\n",
2419                               service->srv_name);
2420         }
2421
2422         /* schedule all outstanding replies to terminate them */
2423         spin_lock(&service->srv_lock);
2424         while (!list_empty(&service->srv_active_replies)) {
2425                 struct ptlrpc_reply_state *rs =
2426                         list_entry(service->srv_active_replies.next,
2427                                    struct ptlrpc_reply_state, rs_list);
2428                 spin_lock(&rs->rs_lock);
2429                 ptlrpc_schedule_difficult_reply(rs);
2430                 spin_unlock(&rs->rs_lock);
2431         }
2432         spin_unlock(&service->srv_lock);
2433
2434         /* purge the request queue.  NB No new replies (rqbds all unlinked)
2435          * and no service threads, so I'm the only thread noodling the
2436          * request queue now */
2437         while (!list_empty(&service->srv_req_in_queue)) {
2438                 struct ptlrpc_request *req =
2439                         list_entry(service->srv_req_in_queue.next,
2440                                    struct ptlrpc_request,
2441                                    rq_list);
2442
2443                 list_del(&req->rq_list);
2444                 service->srv_n_queued_reqs--;
2445                 service->srv_n_active_reqs++;
2446                 ptlrpc_server_finish_request(req);
2447         }
2448         while (ptlrpc_server_request_pending(service, 1)) {
2449                 struct ptlrpc_request *req;
2450
2451                 req = ptlrpc_server_request_get(service, 1);
2452                 list_del(&req->rq_list);
2453                 service->srv_n_queued_reqs--;
2454                 service->srv_n_active_reqs++;
2455                 ptlrpc_hpreq_fini(req);
2456                 ptlrpc_server_finish_request(req);
2457         }
2458         LASSERT(service->srv_n_queued_reqs == 0);
2459         LASSERT(service->srv_n_active_reqs == 0);
2460         LASSERT(service->srv_n_history_rqbds == 0);
2461         LASSERT(list_empty(&service->srv_active_rqbds));
2462
2463         /* Now free all the request buffers since nothing references them
2464          * any more... */
2465         while (!list_empty(&service->srv_idle_rqbds)) {
2466                 struct ptlrpc_request_buffer_desc *rqbd =
2467                         list_entry(service->srv_idle_rqbds.next,
2468                                    struct ptlrpc_request_buffer_desc,
2469                                    rqbd_list);
2470
2471                 ptlrpc_free_rqbd(rqbd);
2472         }
2473
2474         ptlrpc_wait_replies(service);
2475
2476         list_for_each_entry_safe(rs, t, &service->srv_free_rs_list, rs_list) {
2477                 list_del(&rs->rs_list);
2478                 OBD_FREE(rs, service->srv_max_reply_size);
2479         }
2480
2481         /* In case somebody rearmed this in the meantime */
2482         cfs_timer_disarm(&service->srv_at_timer);
2483
2484         if (array->paa_reqs_array != NULL) {
2485                 OBD_FREE(array->paa_reqs_array, 
2486                          sizeof(struct list_head) * array->paa_size);
2487                 array->paa_reqs_array = NULL;
2488         }
2489         
2490         if (array->paa_reqs_count != NULL) {
2491                 OBD_FREE(array->paa_reqs_count, 
2492                          sizeof(__u32) * array->paa_size);
2493                 array->paa_reqs_count= NULL;
2494         }
2495        
2496         OBD_FREE_PTR(service);
2497         RETURN(0);
2498 }
2499
2500 /* Returns 0 if the service is healthy.
2501  *
2502  * Right now, it just checks to make sure that requests aren't languishing
2503  * in the queue.  We'll use this health check to govern whether a node needs
2504  * to be shot, so it's intentionally non-aggressive. */
2505 int ptlrpc_service_health_check(struct ptlrpc_service *svc)
2506 {
2507         struct ptlrpc_request *request;
2508         struct timeval         right_now;
2509         long                   timediff;
2510
2511         if (svc == NULL)
2512                 return 0;
2513
2514         do_gettimeofday(&right_now);
2515
2516         spin_lock(&svc->srv_lock);
2517         if (!ptlrpc_server_request_pending(svc, 1)) {
2518                 spin_unlock(&svc->srv_lock);
2519                 return 0;
2520         }
2521
2522         /* How long has the next entry been waiting? */
2523         if (list_empty(&svc->srv_request_queue))
2524                 request = list_entry(svc->srv_request_hpq.next,
2525                                      struct ptlrpc_request, rq_list);
2526         else
2527                 request = list_entry(svc->srv_request_queue.next,
2528                                      struct ptlrpc_request, rq_list);
2529         timediff = cfs_timeval_sub(&right_now, &request->rq_arrival_time, NULL);
2530         spin_unlock(&svc->srv_lock);
2531
2532         if ((timediff / ONE_MILLION) > (AT_OFF ? obd_timeout * 3/2 :
2533                                         at_max)) {
2534                 CERROR("%s: unhealthy - request has been waiting %lds\n",
2535                        svc->srv_name, timediff / ONE_MILLION);
2536                 return (-1);
2537         }
2538
2539         return 0;
2540 }