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