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