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