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