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