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