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