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