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