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