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