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