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