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