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