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