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