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