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