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