Whamcloud - gitweb
LU-56 ptlrpc: svc thread starting/stopping cleanup
[fs/lustre-release.git] / lustre / ptlrpc / ptlrpcd.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) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2012, Whamcloud, Inc.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/ptlrpc/ptlrpcd.c
37  */
38
39 /** \defgroup ptlrpcd PortalRPC daemon
40  *
41  * ptlrpcd is a special thread with its own set where other user might add
42  * requests when they don't want to wait for their completion.
43  * PtlRPCD will take care of sending such requests and then processing their
44  * replies and calling completion callbacks as necessary.
45  * The callbacks are called directly from ptlrpcd context.
46  * It is important to never significantly block (esp. on RPCs!) within such
47  * completion handler or a deadlock might occur where ptlrpcd enters some
48  * callback that attempts to send another RPC and wait for it to return,
49  * during which time ptlrpcd is completely blocked, so e.g. if import
50  * fails, recovery cannot progress because connection requests are also
51  * sent by ptlrpcd.
52  *
53  * @{
54  */
55
56 #define DEBUG_SUBSYSTEM S_RPC
57
58 #ifdef __KERNEL__
59 # include <libcfs/libcfs.h>
60 #else /* __KERNEL__ */
61 # include <liblustre.h>
62 # include <ctype.h>
63 #endif
64
65 #include <lustre_net.h>
66 # include <lustre_lib.h>
67
68 #include <lustre_ha.h>
69 #include <obd_class.h>   /* for obd_zombie */
70 #include <obd_support.h> /* for OBD_FAIL_CHECK */
71 #include <cl_object.h> /* cl_env_{get,put}() */
72 #include <lprocfs_status.h>
73
74 #include "ptlrpc_internal.h"
75
76 struct ptlrpcd {
77         int                pd_size;
78         int                pd_index;
79         int                pd_nthreads;
80         struct ptlrpcd_ctl pd_thread_rcv;
81         struct ptlrpcd_ctl pd_threads[0];
82 };
83
84 #ifdef __KERNEL__
85 static int max_ptlrpcds;
86 CFS_MODULE_PARM(max_ptlrpcds, "i", int, 0644,
87                 "Max ptlrpcd thread count to be started.");
88
89 static int ptlrpcd_bind_policy = PDB_POLICY_PAIR;
90 CFS_MODULE_PARM(ptlrpcd_bind_policy, "i", int, 0644,
91                 "Ptlrpcd threads binding mode.");
92 #endif
93 static struct ptlrpcd *ptlrpcds;
94
95 cfs_mutex_t ptlrpcd_mutex;
96 static int ptlrpcd_users = 0;
97
98 void ptlrpcd_wake(struct ptlrpc_request *req)
99 {
100         struct ptlrpc_request_set *rq_set = req->rq_set;
101
102         LASSERT(rq_set != NULL);
103
104         cfs_waitq_signal(&rq_set->set_waitq);
105 }
106
107 static struct ptlrpcd_ctl *
108 ptlrpcd_select_pc(struct ptlrpc_request *req, pdl_policy_t policy, int index)
109 {
110         int idx = 0;
111
112         if (req != NULL && req->rq_send_state != LUSTRE_IMP_FULL)
113                 return &ptlrpcds->pd_thread_rcv;
114
115 #ifdef __KERNEL__
116         switch (policy) {
117         case PDL_POLICY_SAME:
118                 idx = cfs_smp_processor_id() % ptlrpcds->pd_nthreads;
119                 break;
120         case PDL_POLICY_LOCAL:
121                 /* Before CPU partition patches available, process it the same
122                  * as "PDL_POLICY_ROUND". */
123 # ifdef CFS_CPU_MODE_NUMA
124 # warning "fix this code to use new CPU partition APIs"
125 # endif
126                 /* Fall through to PDL_POLICY_ROUND until the CPU
127                  * CPU partition patches are available. */
128                 index = -1;
129         case PDL_POLICY_PREFERRED:
130                 if (index >= 0 && index < cfs_num_online_cpus()) {
131                         idx = index % ptlrpcds->pd_nthreads;
132                         break;
133                 }
134                 /* Fall through to PDL_POLICY_ROUND for bad index. */
135         default:
136                 /* Fall through to PDL_POLICY_ROUND for unknown policy. */
137         case PDL_POLICY_ROUND:
138                 /* We do not care whether it is strict load balance. */
139                 idx = ptlrpcds->pd_index + 1;
140                 if (idx == cfs_smp_processor_id())
141                         idx++;
142                 idx %= ptlrpcds->pd_nthreads;
143                 ptlrpcds->pd_index = idx;
144                 break;
145         }
146 #endif /* __KERNEL__ */
147
148         return &ptlrpcds->pd_threads[idx];
149 }
150
151 /**
152  * Move all request from an existing request set to the ptlrpcd queue.
153  * All requests from the set must be in phase RQ_PHASE_NEW.
154  */
155 void ptlrpcd_add_rqset(struct ptlrpc_request_set *set)
156 {
157         cfs_list_t *tmp, *pos;
158 #ifdef __KERNEL__
159         struct ptlrpcd_ctl *pc;
160         struct ptlrpc_request_set *new;
161         int count, i;
162
163         pc = ptlrpcd_select_pc(NULL, PDL_POLICY_LOCAL, -1);
164         new = pc->pc_set;
165 #endif
166
167         cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
168                 struct ptlrpc_request *req =
169                         cfs_list_entry(pos, struct ptlrpc_request,
170                                        rq_set_chain);
171
172                 LASSERT(req->rq_phase == RQ_PHASE_NEW);
173 #ifdef __KERNEL__
174                 req->rq_set = new;
175                 req->rq_queued_time = cfs_time_current();
176 #else
177                 cfs_list_del_init(&req->rq_set_chain);
178                 req->rq_set = NULL;
179                 ptlrpcd_add_req(req, PDL_POLICY_LOCAL, -1);
180                 cfs_atomic_dec(&set->set_remaining);
181 #endif
182         }
183
184 #ifdef __KERNEL__
185         cfs_spin_lock(&new->set_new_req_lock);
186         cfs_list_splice_init(&set->set_requests, &new->set_new_requests);
187         i = cfs_atomic_read(&set->set_remaining);
188         count = cfs_atomic_add_return(i, &new->set_new_count);
189         cfs_atomic_set(&set->set_remaining, 0);
190         cfs_spin_unlock(&new->set_new_req_lock);
191         if (count == i) {
192                 cfs_waitq_signal(&new->set_waitq);
193
194                 /* XXX: It maybe unnecessary to wakeup all the partners. But to
195                  *      guarantee the async RPC can be processed ASAP, we have
196                  *      no other better choice. It maybe fixed in future. */
197                 for (i = 0; i < pc->pc_npartners; i++)
198                         cfs_waitq_signal(&pc->pc_partners[i]->pc_set->set_waitq);
199         }
200 #endif
201 }
202 EXPORT_SYMBOL(ptlrpcd_add_rqset);
203
204 #ifdef __KERNEL__
205 /**
206  * Return transferred RPCs count.
207  */
208 static int ptlrpcd_steal_rqset(struct ptlrpc_request_set *des,
209                                struct ptlrpc_request_set *src)
210 {
211         cfs_list_t *tmp, *pos;
212         struct ptlrpc_request *req;
213         int rc = 0;
214
215         cfs_spin_lock(&src->set_new_req_lock);
216         if (likely(!cfs_list_empty(&src->set_new_requests))) {
217                 cfs_list_for_each_safe(pos, tmp, &src->set_new_requests) {
218                         req = cfs_list_entry(pos, struct ptlrpc_request,
219                                              rq_set_chain);
220                         req->rq_set = des;
221                 }
222                 cfs_list_splice_init(&src->set_new_requests,
223                                      &des->set_requests);
224                 rc = cfs_atomic_read(&src->set_new_count);
225                 cfs_atomic_add(rc, &des->set_remaining);
226                 cfs_atomic_set(&src->set_new_count, 0);
227         }
228         cfs_spin_unlock(&src->set_new_req_lock);
229         return rc;
230 }
231 #endif
232
233 /**
234  * Requests that are added to the ptlrpcd queue are sent via
235  * ptlrpcd_check->ptlrpc_check_set().
236  */
237 void ptlrpcd_add_req(struct ptlrpc_request *req, pdl_policy_t policy, int idx)
238 {
239         struct ptlrpcd_ctl *pc;
240         char jobid[JOBSTATS_JOBID_SIZE];
241
242         if (req->rq_reqmsg) {
243                 lustre_get_jobid(jobid);
244                 lustre_msg_set_jobid(req->rq_reqmsg, jobid);
245         }
246
247         cfs_spin_lock(&req->rq_lock);
248         if (req->rq_invalid_rqset) {
249                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(5),
250                                                      back_to_sleep, NULL);
251
252                 req->rq_invalid_rqset = 0;
253                 cfs_spin_unlock(&req->rq_lock);
254                 l_wait_event(req->rq_set_waitq, (req->rq_set == NULL), &lwi);
255         } else if (req->rq_set) {
256                 /* If we have a vaid "rq_set", just reuse it to avoid double
257                  * linked. */
258                 LASSERT(req->rq_phase == RQ_PHASE_NEW);
259                 LASSERT(req->rq_send_state == LUSTRE_IMP_REPLAY);
260
261                 /* ptlrpc_check_set will decrease the count */
262                 cfs_atomic_inc(&req->rq_set->set_remaining);
263                 cfs_spin_unlock(&req->rq_lock);
264                 cfs_waitq_signal(&req->rq_set->set_waitq);
265                 return;
266         } else {
267                 cfs_spin_unlock(&req->rq_lock);
268         }
269
270         pc = ptlrpcd_select_pc(req, policy, idx);
271
272         DEBUG_REQ(D_INFO, req, "add req [%p] to pc [%s:%d]",
273                   req, pc->pc_name, pc->pc_index);
274
275         ptlrpc_set_add_new_req(pc, req);
276 }
277
278 static inline void ptlrpc_reqset_get(struct ptlrpc_request_set *set)
279 {
280         cfs_atomic_inc(&set->set_refcount);
281 }
282
283 /**
284  * Check if there is more work to do on ptlrpcd set.
285  * Returns 1 if yes.
286  */
287 static int ptlrpcd_check(struct lu_env *env, struct ptlrpcd_ctl *pc)
288 {
289         cfs_list_t *tmp, *pos;
290         struct ptlrpc_request *req;
291         struct ptlrpc_request_set *set = pc->pc_set;
292         int rc = 0;
293         int rc2;
294         ENTRY;
295
296         if (cfs_atomic_read(&set->set_new_count)) {
297                 cfs_spin_lock(&set->set_new_req_lock);
298                 if (likely(!cfs_list_empty(&set->set_new_requests))) {
299                         cfs_list_splice_init(&set->set_new_requests,
300                                              &set->set_requests);
301                         cfs_atomic_add(cfs_atomic_read(&set->set_new_count),
302                                        &set->set_remaining);
303                         cfs_atomic_set(&set->set_new_count, 0);
304                         /*
305                          * Need to calculate its timeout.
306                          */
307                         rc = 1;
308                 }
309                 cfs_spin_unlock(&set->set_new_req_lock);
310         }
311
312         /* We should call lu_env_refill() before handling new requests to make
313          * sure that env key the requests depending on really exists.
314          */
315         rc2 = lu_env_refill(env);
316         if (rc2 != 0) {
317                 /*
318                  * XXX This is very awkward situation, because
319                  * execution can neither continue (request
320                  * interpreters assume that env is set up), nor repeat
321                  * the loop (as this potentially results in a tight
322                  * loop of -ENOMEM's).
323                  *
324                  * Fortunately, refill only ever does something when
325                  * new modules are loaded, i.e., early during boot up.
326                  */
327                 CERROR("Failure to refill session: %d\n", rc2);
328                 RETURN(rc);
329         }
330
331         if (cfs_atomic_read(&set->set_remaining))
332                 rc |= ptlrpc_check_set(env, set);
333
334         if (!cfs_list_empty(&set->set_requests)) {
335                 /*
336                  * XXX: our set never completes, so we prune the completed
337                  * reqs after each iteration. boy could this be smarter.
338                  */
339                 cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
340                         req = cfs_list_entry(pos, struct ptlrpc_request,
341                                              rq_set_chain);
342                         if (req->rq_phase != RQ_PHASE_COMPLETE)
343                                 continue;
344
345                         cfs_list_del_init(&req->rq_set_chain);
346                         req->rq_set = NULL;
347                         ptlrpc_req_finished(req);
348                 }
349         }
350
351         if (rc == 0) {
352                 /*
353                  * If new requests have been added, make sure to wake up.
354                  */
355                 rc = cfs_atomic_read(&set->set_new_count);
356
357 #ifdef __KERNEL__
358                 /* If we have nothing to do, check whether we can take some
359                  * work from our partner threads. */
360                 if (rc == 0 && pc->pc_npartners > 0) {
361                         struct ptlrpcd_ctl *partner;
362                         struct ptlrpc_request_set *ps;
363                         int first = pc->pc_cursor;
364
365                         do {
366                                 partner = pc->pc_partners[pc->pc_cursor++];
367                                 if (pc->pc_cursor >= pc->pc_npartners)
368                                         pc->pc_cursor = 0;
369                                 if (partner == NULL)
370                                         continue;
371
372                                 cfs_spin_lock(&partner->pc_lock);
373                                 ps = partner->pc_set;
374                                 if (ps == NULL) {
375                                         cfs_spin_unlock(&partner->pc_lock);
376                                         continue;
377                                 }
378
379                                 ptlrpc_reqset_get(ps);
380                                 cfs_spin_unlock(&partner->pc_lock);
381
382                                 if (cfs_atomic_read(&ps->set_new_count)) {
383                                         rc = ptlrpcd_steal_rqset(set, ps);
384                                         if (rc > 0)
385                                                 CDEBUG(D_RPCTRACE, "transfer %d"
386                                                        " async RPCs [%d->%d]\n",
387                                                         rc, partner->pc_index,
388                                                         pc->pc_index);
389                                 }
390                                 ptlrpc_reqset_put(ps);
391                         } while (rc == 0 && pc->pc_cursor != first);
392                 }
393 #endif
394         }
395
396         RETURN(rc);
397 }
398
399 #ifdef __KERNEL__
400 /**
401  * Main ptlrpcd thread.
402  * ptlrpc's code paths like to execute in process context, so we have this
403  * thread which spins on a set which contains the rpcs and sends them.
404  *
405  */
406 static int ptlrpcd(void *arg)
407 {
408         struct ptlrpcd_ctl *pc = arg;
409         struct ptlrpc_request_set *set = pc->pc_set;
410         struct lu_env env = { .le_ses = NULL };
411         int rc, exit = 0;
412         ENTRY;
413
414         cfs_daemonize_ctxt(pc->pc_name);
415 #if defined(CONFIG_SMP) && defined(HAVE_NODE_TO_CPUMASK)
416         if (cfs_test_bit(LIOD_BIND, &pc->pc_flags)) {
417                 int index = pc->pc_index;
418
419                 if (index >= 0 && index < cfs_num_possible_cpus()) {
420                         while (!cpu_online(index)) {
421                                 if (++index >= cfs_num_possible_cpus())
422                                         index = 0;
423                         }
424                         cfs_set_cpus_allowed(cfs_current(),
425                                      node_to_cpumask(cpu_to_node(index)));
426                 }
427         }
428 #endif
429         /*
430          * XXX So far only "client" ptlrpcd uses an environment. In
431          * the future, ptlrpcd thread (or a thread-set) has to given
432          * an argument, describing its "scope".
433          */
434         rc = lu_context_init(&env.le_ctx,
435                              LCT_CL_THREAD|LCT_REMEMBER|LCT_NOREF);
436         cfs_complete(&pc->pc_starting);
437
438         if (rc != 0)
439                 RETURN(rc);
440
441         /*
442          * This mainloop strongly resembles ptlrpc_set_wait() except that our
443          * set never completes.  ptlrpcd_check() calls ptlrpc_check_set() when
444          * there are requests in the set. New requests come in on the set's
445          * new_req_list and ptlrpcd_check() moves them into the set.
446          */
447         do {
448                 struct l_wait_info lwi;
449                 int timeout;
450
451                 timeout = ptlrpc_set_next_timeout(set);
452                 lwi = LWI_TIMEOUT(cfs_time_seconds(timeout ? timeout : 1),
453                                   ptlrpc_expired_set, set);
454
455                 lu_context_enter(&env.le_ctx);
456                 l_wait_event(set->set_waitq,
457                              ptlrpcd_check(&env, pc), &lwi);
458                 lu_context_exit(&env.le_ctx);
459
460                 /*
461                  * Abort inflight rpcs for forced stop case.
462                  */
463                 if (cfs_test_bit(LIOD_STOP, &pc->pc_flags)) {
464                         if (cfs_test_bit(LIOD_FORCE, &pc->pc_flags))
465                                 ptlrpc_abort_set(set);
466                         exit++;
467                 }
468
469                 /*
470                  * Let's make one more loop to make sure that ptlrpcd_check()
471                  * copied all raced new rpcs into the set so we can kill them.
472                  */
473         } while (exit < 2);
474
475         /*
476          * Wait for inflight requests to drain.
477          */
478         if (!cfs_list_empty(&set->set_requests))
479                 ptlrpc_set_wait(set);
480         lu_context_fini(&env.le_ctx);
481         cfs_complete(&pc->pc_finishing);
482
483         cfs_clear_bit(LIOD_START, &pc->pc_flags);
484         cfs_clear_bit(LIOD_STOP, &pc->pc_flags);
485         cfs_clear_bit(LIOD_FORCE, &pc->pc_flags);
486         cfs_clear_bit(LIOD_BIND, &pc->pc_flags);
487         return 0;
488 }
489
490 /* XXX: We want multiple CPU cores to share the async RPC load. So we start many
491  *      ptlrpcd threads. We also want to reduce the ptlrpcd overhead caused by
492  *      data transfer cross-CPU cores. So we bind ptlrpcd thread to specified
493  *      CPU core. But binding all ptlrpcd threads maybe cause response delay
494  *      because of some CPU core(s) busy with other loads.
495  *
496  *      For example: "ls -l", some async RPCs for statahead are assigned to
497  *      ptlrpcd_0, and ptlrpcd_0 is bound to CPU_0, but CPU_0 may be quite busy
498  *      with other non-ptlrpcd, like "ls -l" itself (we want to the "ls -l"
499  *      thread, statahead thread, and ptlrpcd thread can run in parallel), under
500  *      such case, the statahead async RPCs can not be processed in time, it is
501  *      unexpected. If ptlrpcd_0 can be re-scheduled on other CPU core, it may
502  *      be better. But it breaks former data transfer policy.
503  *
504  *      So we shouldn't be blind for avoiding the data transfer. We make some
505  *      compromise: divide the ptlrpcd threds pool into two parts. One part is
506  *      for bound mode, each ptlrpcd thread in this part is bound to some CPU
507  *      core. The other part is for free mode, all the ptlrpcd threads in the
508  *      part can be scheduled on any CPU core. We specify some partnership
509  *      between bound mode ptlrpcd thread(s) and free mode ptlrpcd thread(s),
510  *      and the async RPC load within the partners are shared.
511  *
512  *      It can partly avoid data transfer cross-CPU (if the bound mode ptlrpcd
513  *      thread can be scheduled in time), and try to guarantee the async RPC
514  *      processed ASAP (as long as the free mode ptlrpcd thread can be scheduled
515  *      on any CPU core).
516  *
517  *      As for how to specify the partnership between bound mode ptlrpcd
518  *      thread(s) and free mode ptlrpcd thread(s), the simplest way is to use
519  *      <free bound> pair. In future, we can specify some more complex
520  *      partnership based on the patches for CPU partition. But before such
521  *      patches are available, we prefer to use the simplest one.
522  */
523 # ifdef CFS_CPU_MODE_NUMA
524 # warning "fix ptlrpcd_bind() to use new CPU partition APIs"
525 # endif
526 static int ptlrpcd_bind(int index, int max)
527 {
528         struct ptlrpcd_ctl *pc;
529         int rc = 0;
530 #if defined(CONFIG_NUMA) && defined(HAVE_NODE_TO_CPUMASK)
531         struct ptlrpcd_ctl *ppc;
532         int node, i, pidx;
533         cpumask_t mask;
534 #endif
535         ENTRY;
536
537         LASSERT(index <= max - 1);
538         pc = &ptlrpcds->pd_threads[index];
539         switch (ptlrpcd_bind_policy) {
540         case PDB_POLICY_NONE:
541                 pc->pc_npartners = -1;
542                 break;
543         case PDB_POLICY_FULL:
544                 pc->pc_npartners = 0;
545                 cfs_set_bit(LIOD_BIND, &pc->pc_flags);
546                 break;
547         case PDB_POLICY_PAIR:
548                 LASSERT(max % 2 == 0);
549                 pc->pc_npartners = 1;
550                 break;
551         case PDB_POLICY_NEIGHBOR:
552 #if defined(CONFIG_NUMA) && defined(HAVE_NODE_TO_CPUMASK)
553                 node = cpu_to_node(index);
554                 mask = node_to_cpumask(node);
555                 for (i = max; i < cfs_num_online_cpus(); i++)
556                         cpu_clear(i, mask);
557                 pc->pc_npartners = cpus_weight(mask) - 1;
558                 cfs_set_bit(LIOD_BIND, &pc->pc_flags);
559 #else
560                 LASSERT(max >= 3);
561                 pc->pc_npartners = 2;
562 #endif
563                 break;
564         default:
565                 CERROR("unknown ptlrpcd bind policy %d\n", ptlrpcd_bind_policy);
566                 rc = -EINVAL;
567         }
568
569         if (rc == 0 && pc->pc_npartners > 0) {
570                 OBD_ALLOC(pc->pc_partners,
571                           sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
572                 if (pc->pc_partners == NULL) {
573                         pc->pc_npartners = 0;
574                         rc = -ENOMEM;
575                 } else {
576                         switch (ptlrpcd_bind_policy) {
577                         case PDB_POLICY_PAIR:
578                                 if (index & 0x1) {
579                                         cfs_set_bit(LIOD_BIND, &pc->pc_flags);
580                                         pc->pc_partners[0] = &ptlrpcds->
581                                                 pd_threads[index - 1];
582                                         ptlrpcds->pd_threads[index - 1].
583                                                 pc_partners[0] = pc;
584                                 }
585                                 break;
586                         case PDB_POLICY_NEIGHBOR:
587 #if defined(CONFIG_NUMA) && defined(HAVE_NODE_TO_CPUMASK)
588                                 /* partners are cores in the same NUMA node.
589                                  * setup partnership only with ptlrpcd threads
590                                  * that are already initialized
591                                  */
592                                 for (pidx = 0, i = 0; i < index; i++) {
593                                         if (cpu_isset(i, mask)) {
594                                                 ppc = &ptlrpcds->pd_threads[i];
595                                                 pc->pc_partners[pidx++] = ppc;
596                                                 ppc->pc_partners[ppc->
597                                                           pc_npartners++] = pc;
598                                         }
599                                 }
600                                 /* adjust number of partners to the number
601                                  * of partnership really setup */
602                                 pc->pc_npartners = pidx;
603 #else
604                                 if (index & 0x1)
605                                         cfs_set_bit(LIOD_BIND, &pc->pc_flags);
606                                 if (index > 0) {
607                                         pc->pc_partners[0] = &ptlrpcds->
608                                                 pd_threads[index - 1];
609                                         ptlrpcds->pd_threads[index - 1].
610                                                 pc_partners[1] = pc;
611                                         if (index == max - 1) {
612                                                 pc->pc_partners[1] =
613                                                 &ptlrpcds->pd_threads[0];
614                                                 ptlrpcds->pd_threads[0].
615                                                 pc_partners[0] = pc;
616                                         }
617                                 }
618 #endif
619                                 break;
620                         }
621                 }
622         }
623
624         RETURN(rc);
625 }
626
627 #else /* !__KERNEL__ */
628
629 /**
630  * In liblustre we do not have separate threads, so this function
631  * is called from time to time all across common code to see
632  * if something needs to be processed on ptlrpcd set.
633  */
634 int ptlrpcd_check_async_rpcs(void *arg)
635 {
636         struct ptlrpcd_ctl *pc = arg;
637         int                 rc = 0;
638
639         /*
640          * Single threaded!!
641          */
642         pc->pc_recurred++;
643
644         if (pc->pc_recurred == 1) {
645                 rc = lu_env_refill(&pc->pc_env);
646                 if (rc == 0) {
647                         lu_context_enter(&pc->pc_env.le_ctx);
648                         rc = ptlrpcd_check(&pc->pc_env, pc);
649                         if (!rc)
650                                 ptlrpc_expired_set(pc->pc_set);
651                         /*
652                          * XXX: send replay requests.
653                          */
654                         if (cfs_test_bit(LIOD_RECOVERY, &pc->pc_flags))
655                                 rc = ptlrpcd_check(&pc->pc_env, pc);
656                         lu_context_exit(&pc->pc_env.le_ctx);
657                 }
658         }
659
660         pc->pc_recurred--;
661         return rc;
662 }
663
664 int ptlrpcd_idle(void *arg)
665 {
666         struct ptlrpcd_ctl *pc = arg;
667
668         return (cfs_atomic_read(&pc->pc_set->set_new_count) == 0 &&
669                 cfs_atomic_read(&pc->pc_set->set_remaining) == 0);
670 }
671
672 #endif
673
674 int ptlrpcd_start(int index, int max, const char *name, struct ptlrpcd_ctl *pc)
675 {
676         int rc;
677         int env = 0;
678         ENTRY;
679
680         /*
681          * Do not allow start second thread for one pc.
682          */
683         if (cfs_test_and_set_bit(LIOD_START, &pc->pc_flags)) {
684                 CWARN("Starting second thread (%s) for same pc %p\n",
685                        name, pc);
686                 RETURN(0);
687         }
688
689         pc->pc_index = index;
690         cfs_init_completion(&pc->pc_starting);
691         cfs_init_completion(&pc->pc_finishing);
692         cfs_spin_lock_init(&pc->pc_lock);
693         strncpy(pc->pc_name, name, sizeof(pc->pc_name) - 1);
694         pc->pc_set = ptlrpc_prep_set();
695         if (pc->pc_set == NULL)
696                 GOTO(out, rc = -ENOMEM);
697         /*
698          * So far only "client" ptlrpcd uses an environment. In the future,
699          * ptlrpcd thread (or a thread-set) has to be given an argument,
700          * describing its "scope".
701          */
702         rc = lu_context_init(&pc->pc_env.le_ctx, LCT_CL_THREAD|LCT_REMEMBER);
703         if (rc != 0)
704                 GOTO(out, rc);
705
706         env = 1;
707 #ifdef __KERNEL__
708         if (index >= 0) {
709                 rc = ptlrpcd_bind(index, max);
710                 if (rc < 0)
711                         GOTO(out, rc);
712         }
713
714         rc = cfs_create_thread(ptlrpcd, pc, 0);
715         if (rc < 0)
716                 GOTO(out, rc);
717
718         rc = 0;
719         cfs_wait_for_completion(&pc->pc_starting);
720 #else
721         pc->pc_wait_callback =
722                 liblustre_register_wait_callback("ptlrpcd_check_async_rpcs",
723                                                  &ptlrpcd_check_async_rpcs, pc);
724         pc->pc_idle_callback =
725                 liblustre_register_idle_callback("ptlrpcd_check_idle_rpcs",
726                                                  &ptlrpcd_idle, pc);
727 #endif
728 out:
729         if (rc) {
730 #ifdef __KERNEL__
731                 if (pc->pc_set != NULL) {
732                         struct ptlrpc_request_set *set = pc->pc_set;
733
734                         cfs_spin_lock(&pc->pc_lock);
735                         pc->pc_set = NULL;
736                         cfs_spin_unlock(&pc->pc_lock);
737                         ptlrpc_set_destroy(set);
738                 }
739                 if (env != 0)
740                         lu_context_fini(&pc->pc_env.le_ctx);
741                 cfs_clear_bit(LIOD_BIND, &pc->pc_flags);
742 #else
743                 SET_BUT_UNUSED(env);
744 #endif
745                 cfs_clear_bit(LIOD_START, &pc->pc_flags);
746         }
747         RETURN(rc);
748 }
749
750 void ptlrpcd_stop(struct ptlrpcd_ctl *pc, int force)
751 {
752        struct ptlrpc_request_set *set = pc->pc_set;
753         ENTRY;
754
755         if (!cfs_test_bit(LIOD_START, &pc->pc_flags)) {
756                 CWARN("Thread for pc %p was not started\n", pc);
757                 goto out;
758         }
759
760         cfs_set_bit(LIOD_STOP, &pc->pc_flags);
761         if (force)
762                 cfs_set_bit(LIOD_FORCE, &pc->pc_flags);
763         cfs_waitq_signal(&pc->pc_set->set_waitq);
764 #ifdef __KERNEL__
765         cfs_wait_for_completion(&pc->pc_finishing);
766 #else
767         liblustre_deregister_wait_callback(pc->pc_wait_callback);
768         liblustre_deregister_idle_callback(pc->pc_idle_callback);
769 #endif
770         lu_context_fini(&pc->pc_env.le_ctx);
771
772         cfs_spin_lock(&pc->pc_lock);
773         pc->pc_set = NULL;
774         cfs_spin_unlock(&pc->pc_lock);
775         ptlrpc_set_destroy(set);
776
777 out:
778 #ifdef __KERNEL__
779         if (pc->pc_npartners > 0) {
780                 LASSERT(pc->pc_partners != NULL);
781
782                 OBD_FREE(pc->pc_partners,
783                          sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
784                 pc->pc_partners = NULL;
785         }
786         pc->pc_npartners = 0;
787 #endif
788         EXIT;
789 }
790
791 static void ptlrpcd_fini(void)
792 {
793         int i;
794         ENTRY;
795
796         if (ptlrpcds != NULL) {
797                 for (i = 0; i < ptlrpcds->pd_nthreads; i++)
798                         ptlrpcd_stop(&ptlrpcds->pd_threads[i], 0);
799                 ptlrpcd_stop(&ptlrpcds->pd_thread_rcv, 0);
800                 OBD_FREE(ptlrpcds, ptlrpcds->pd_size);
801                 ptlrpcds = NULL;
802         }
803
804         EXIT;
805 }
806
807 static int ptlrpcd_init(void)
808 {
809         int nthreads = cfs_num_online_cpus();
810         char name[16];
811         int size, i = -1, j, rc = 0;
812         ENTRY;
813
814 #ifdef __KERNEL__
815         if (max_ptlrpcds > 0 && max_ptlrpcds < nthreads)
816                 nthreads = max_ptlrpcds;
817         if (nthreads < 2)
818                 nthreads = 2;
819         if (nthreads < 3 && ptlrpcd_bind_policy == PDB_POLICY_NEIGHBOR)
820                 ptlrpcd_bind_policy = PDB_POLICY_PAIR;
821         else if (nthreads % 2 != 0 && ptlrpcd_bind_policy == PDB_POLICY_PAIR)
822                 nthreads &= ~1; /* make sure it is even */
823 #else
824         nthreads = 1;
825 #endif
826
827         size = offsetof(struct ptlrpcd, pd_threads[nthreads]);
828         OBD_ALLOC(ptlrpcds, size);
829         if (ptlrpcds == NULL)
830                 GOTO(out, rc = -ENOMEM);
831
832         snprintf(name, 15, "ptlrpcd_rcv");
833         cfs_set_bit(LIOD_RECOVERY, &ptlrpcds->pd_thread_rcv.pc_flags);
834         rc = ptlrpcd_start(-1, nthreads, name, &ptlrpcds->pd_thread_rcv);
835         if (rc < 0)
836                 GOTO(out, rc);
837
838         /* XXX: We start nthreads ptlrpc daemons. Each of them can process any
839          *      non-recovery async RPC to improve overall async RPC efficiency.
840          *
841          *      But there are some issues with async I/O RPCs and async non-I/O
842          *      RPCs processed in the same set under some cases. The ptlrpcd may
843          *      be blocked by some async I/O RPC(s), then will cause other async
844          *      non-I/O RPC(s) can not be processed in time.
845          *
846          *      Maybe we should distinguish blocked async RPCs from non-blocked
847          *      async RPCs, and process them in different ptlrpcd sets to avoid
848          *      unnecessary dependency. But how to distribute async RPCs load
849          *      among all the ptlrpc daemons becomes another trouble. */
850         for (i = 0; i < nthreads; i++) {
851                 snprintf(name, 15, "ptlrpcd_%d", i);
852                 rc = ptlrpcd_start(i, nthreads, name, &ptlrpcds->pd_threads[i]);
853                 if (rc < 0)
854                         GOTO(out, rc);
855         }
856
857         ptlrpcds->pd_size = size;
858         ptlrpcds->pd_index = 0;
859         ptlrpcds->pd_nthreads = nthreads;
860
861 out:
862         if (rc != 0 && ptlrpcds != NULL) {
863                 for (j = 0; j <= i; j++)
864                         ptlrpcd_stop(&ptlrpcds->pd_threads[j], 0);
865                 ptlrpcd_stop(&ptlrpcds->pd_thread_rcv, 0);
866                 OBD_FREE(ptlrpcds, size);
867                 ptlrpcds = NULL;
868         }
869
870         RETURN(0);
871 }
872
873 int ptlrpcd_addref(void)
874 {
875         int rc = 0;
876         ENTRY;
877
878         cfs_mutex_lock(&ptlrpcd_mutex);
879         if (++ptlrpcd_users == 1)
880                 rc = ptlrpcd_init();
881         cfs_mutex_unlock(&ptlrpcd_mutex);
882         RETURN(rc);
883 }
884
885 void ptlrpcd_decref(void)
886 {
887         cfs_mutex_lock(&ptlrpcd_mutex);
888         if (--ptlrpcd_users == 0)
889                 ptlrpcd_fini();
890         cfs_mutex_unlock(&ptlrpcd_mutex);
891 }
892 /** @} ptlrpcd */