Whamcloud - gitweb
ORNL-22 general ptlrpcd threads pool support
[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                 LASSERT(req->rq_phase == RQ_PHASE_NEW);
254                 LASSERT(req->rq_send_state == LUSTRE_IMP_REPLAY);
255
256                 /* ptlrpc_check_set will decrease the count */
257                 cfs_atomic_inc(&req->rq_set->set_remaining);
258                 cfs_spin_unlock(&req->rq_lock);
259                 cfs_waitq_signal(&req->rq_set->set_waitq);
260                 return;
261         } else {
262                 cfs_spin_unlock(&req->rq_lock);
263         }
264
265         pc = ptlrpcd_select_pc(req, policy, idx);
266
267         DEBUG_REQ(D_INFO, req, "add req [%p] to pc [%s:%d]",
268                   req, pc->pc_name, pc->pc_index);
269
270         ptlrpc_set_add_new_req(pc, req);
271 }
272
273 static inline void ptlrpc_reqset_get(struct ptlrpc_request_set *set)
274 {
275         cfs_atomic_inc(&set->set_refcount);
276 }
277
278 /**
279  * Check if there is more work to do on ptlrpcd set.
280  * Returns 1 if yes.
281  */
282 static int ptlrpcd_check(const struct lu_env *env, struct ptlrpcd_ctl *pc)
283 {
284         cfs_list_t *tmp, *pos;
285         struct ptlrpc_request *req;
286         struct ptlrpc_request_set *set = pc->pc_set;
287         int rc = 0;
288         ENTRY;
289
290         if (cfs_atomic_read(&set->set_new_count)) {
291                 cfs_spin_lock(&set->set_new_req_lock);
292                 if (likely(!cfs_list_empty(&set->set_new_requests))) {
293                         cfs_list_splice_init(&set->set_new_requests,
294                                              &set->set_requests);
295                         cfs_atomic_add(cfs_atomic_read(&set->set_new_count),
296                                        &set->set_remaining);
297                         cfs_atomic_set(&set->set_new_count, 0);
298                         /*
299                          * Need to calculate its timeout.
300                          */
301                         rc = 1;
302                 }
303                 cfs_spin_unlock(&set->set_new_req_lock);
304         }
305
306         if (cfs_atomic_read(&set->set_remaining))
307                 rc |= ptlrpc_check_set(env, set);
308
309         if (!cfs_list_empty(&set->set_requests)) {
310                 /*
311                  * XXX: our set never completes, so we prune the completed
312                  * reqs after each iteration. boy could this be smarter.
313                  */
314                 cfs_list_for_each_safe(pos, tmp, &set->set_requests) {
315                         req = cfs_list_entry(pos, struct ptlrpc_request,
316                                              rq_set_chain);
317                         if (req->rq_phase != RQ_PHASE_COMPLETE)
318                                 continue;
319
320                         cfs_list_del_init(&req->rq_set_chain);
321                         req->rq_set = NULL;
322                         ptlrpc_req_finished(req);
323                 }
324         }
325
326         if (rc == 0) {
327                 /*
328                  * If new requests have been added, make sure to wake up.
329                  */
330                 rc = cfs_atomic_read(&set->set_new_count);
331
332 #ifdef __KERNEL__
333                 if (rc == 0 && pc->pc_npartners > 0) {
334                         struct ptlrpcd_ctl *partner;
335                         struct ptlrpc_request_set *ps;
336                         int first = pc->pc_cursor;
337
338                         do {
339                                 partner = pc->pc_partners[pc->pc_cursor++];
340                                 if (pc->pc_cursor >= pc->pc_npartners)
341                                         pc->pc_cursor = 0;
342                                 if (partner == NULL)
343                                         continue;
344
345                                 cfs_spin_lock(&partner->pc_lock);
346                                 ps = partner->pc_set;
347                                 if (ps == NULL) {
348                                         cfs_spin_unlock(&partner->pc_lock);
349                                         continue;
350                                 }
351
352                                 ptlrpc_reqset_get(ps);
353                                 cfs_spin_unlock(&partner->pc_lock);
354
355                                 if (cfs_atomic_read(&ps->set_new_count)) {
356                                         rc = ptlrpcd_steal_rqset(set, ps);
357                                         if (rc > 0)
358                                                 CDEBUG(D_RPCTRACE, "transfer %d"
359                                                        " async RPCs [%d->%d]\n",
360                                                         rc, pc->pc_index,
361                                                         partner->pc_index);
362                                 }
363                                 ptlrpc_reqset_put(ps);
364                         } while (rc == 0 && pc->pc_cursor != first);
365                 }
366 #endif
367         }
368
369         RETURN(rc);
370 }
371
372 #ifdef __KERNEL__
373 /**
374  * Main ptlrpcd thread.
375  * ptlrpc's code paths like to execute in process context, so we have this
376  * thread which spins on a set which contains the rpcs and sends them.
377  *
378  */
379 static int ptlrpcd(void *arg)
380 {
381         struct ptlrpcd_ctl *pc = arg;
382         struct ptlrpc_request_set *set = pc->pc_set;
383         struct lu_env env = { .le_ses = NULL };
384         int rc, exit = 0;
385         ENTRY;
386
387         cfs_daemonize_ctxt(pc->pc_name);
388 #if defined(CONFIG_SMP) && defined(HAVE_NODE_TO_CPUMASK)
389         if (cfs_test_bit(LIOD_BIND, &pc->pc_flags)) {
390                 int index = pc->pc_index;
391
392                 if (index >= 0 && index < cfs_num_possible_cpus()) {
393                         while (!cfs_cpu_online(index)) {
394                                 if (++index >= cfs_num_possible_cpus())
395                                         index = 0;
396                         }
397                         cfs_set_cpus_allowed(cfs_current(),
398                                      node_to_cpumask(cpu_to_node(index)));
399                 }
400         }
401 #endif
402         /*
403          * XXX So far only "client" ptlrpcd uses an environment. In
404          * the future, ptlrpcd thread (or a thread-set) has to given
405          * an argument, describing its "scope".
406          */
407         rc = lu_context_init(&env.le_ctx,
408                              LCT_CL_THREAD|LCT_REMEMBER|LCT_NOREF);
409         cfs_complete(&pc->pc_starting);
410
411         if (rc != 0)
412                 RETURN(rc);
413
414         /*
415          * This mainloop strongly resembles ptlrpc_set_wait() except that our
416          * set never completes.  ptlrpcd_check() calls ptlrpc_check_set() when
417          * there are requests in the set. New requests come in on the set's
418          * new_req_list and ptlrpcd_check() moves them into the set.
419          */
420         do {
421                 struct l_wait_info lwi;
422                 int timeout;
423
424                 rc = lu_env_refill(&env);
425                 if (rc != 0) {
426                         /*
427                          * XXX This is very awkward situation, because
428                          * execution can neither continue (request
429                          * interpreters assume that env is set up), nor repeat
430                          * the loop (as this potentially results in a tight
431                          * loop of -ENOMEM's).
432                          *
433                          * Fortunately, refill only ever does something when
434                          * new modules are loaded, i.e., early during boot up.
435                          */
436                         CERROR("Failure to refill session: %d\n", rc);
437                         continue;
438                 }
439
440                 timeout = ptlrpc_set_next_timeout(set);
441                 lwi = LWI_TIMEOUT(cfs_time_seconds(timeout ? timeout : 1),
442                                   ptlrpc_expired_set, set);
443
444                 lu_context_enter(&env.le_ctx);
445                 l_wait_event(set->set_waitq,
446                              ptlrpcd_check(&env, pc), &lwi);
447                 lu_context_exit(&env.le_ctx);
448
449                 /*
450                  * Abort inflight rpcs for forced stop case.
451                  */
452                 if (cfs_test_bit(LIOD_STOP, &pc->pc_flags)) {
453                         if (cfs_test_bit(LIOD_FORCE, &pc->pc_flags))
454                                 ptlrpc_abort_set(set);
455                         exit++;
456                 }
457
458                 /*
459                  * Let's make one more loop to make sure that ptlrpcd_check()
460                  * copied all raced new rpcs into the set so we can kill them.
461                  */
462         } while (exit < 2);
463
464         /*
465          * Wait for inflight requests to drain.
466          */
467         if (!cfs_list_empty(&set->set_requests))
468                 ptlrpc_set_wait(set);
469         lu_context_fini(&env.le_ctx);
470         cfs_complete(&pc->pc_finishing);
471
472         cfs_clear_bit(LIOD_START, &pc->pc_flags);
473         cfs_clear_bit(LIOD_STOP, &pc->pc_flags);
474         cfs_clear_bit(LIOD_FORCE, &pc->pc_flags);
475         cfs_clear_bit(LIOD_BIND, &pc->pc_flags);
476         return 0;
477 }
478
479 /* XXX: We want multiple CPU cores to share the async RPC load. So we start many
480  *      ptlrpcd threads. We also want to reduce the ptlrpcd overhead caused by
481  *      data transfer cross-CPU cores. So we bind ptlrpcd thread to specified
482  *      CPU core. But binding all ptlrpcd threads maybe cause response delay
483  *      because of some CPU core(s) busy with other loads.
484  *
485  *      For example: "ls -l", some async RPCs for statahead are assigned to
486  *      ptlrpcd_0, and ptlrpcd_0 is bound to CPU_0, but CPU_0 may be quite busy
487  *      with other non-ptlrpcd, like "ls -l" itself (we want to the "ls -l"
488  *      thread, statahead thread, and ptlrpcd thread can run in parallel), under
489  *      such case, the statahead async RPCs can not be processed in time, it is
490  *      unexpected. If ptlrpcd_0 can be re-scheduled on other CPU core, it may
491  *      be better. But it breaks former data transfer policy.
492  *
493  *      So we shouldn't be blind for avoiding the data transfer. We make some
494  *      compromise: divide the ptlrpcd threds pool into two parts. One part is
495  *      for bound mode, each ptlrpcd thread in this part is bound to some CPU
496  *      core. The other part is for free mode, all the ptlrpcd threads in the
497  *      part can be scheduled on any CPU core. We specify some partnership
498  *      between bound mode ptlrpcd thread(s) and free mode ptlrpcd thread(s),
499  *      and the async RPC load within the partners are shared.
500  *
501  *      It can partly avoid data transfer cross-CPU (if the bound mode ptlrpcd
502  *      thread can be scheduled in time), and try to guarantee the async RPC
503  *      processed ASAP (as long as the free mode ptlrpcd thread can be scheduled
504  *      on any CPU core).
505  *
506  *      As for how to specify the partnership between bound mode ptlrpcd
507  *      thread(s) and free mode ptlrpcd thread(s), the simplest way is to use
508  *      <free bound> pair. In future, we can specify some more complex
509  *      partnership based on the patches for CPU partition. But before such
510  *      patches are available, we prefer to use the simplest one.
511  */
512 # ifdef CFS_CPU_MODE_NUMA
513 # warning "fix ptlrpcd_bind() to use new CPU partition APIs"
514 # endif
515 static int ptlrpcd_bind(int index, int max)
516 {
517         struct ptlrpcd_ctl *pc;
518         int rc = 0;
519         ENTRY;
520
521         LASSERT(index <= max - 1);
522         pc = &ptlrpcds->pd_threads[index];
523         switch (ptlrpcd_bind_policy) {
524         case PDB_POLICY_NONE:
525                 pc->pc_npartners = -1;
526                 break;
527         case PDB_POLICY_FULL:
528                 pc->pc_npartners = 0;
529                 cfs_set_bit(LIOD_BIND, &pc->pc_flags);
530                 break;
531         case PDB_POLICY_PAIR:
532                 LASSERT(max % 2 == 0);
533                 pc->pc_npartners = 1;
534                 break;
535         case PDB_POLICY_NEIGHBOR:
536                 LASSERT(max >= 3);
537                 pc->pc_npartners = 2;
538                 break;
539         default:
540                 CERROR("unknown ptlrpcd bind policy %d\n", ptlrpcd_bind_policy);
541                 rc = -EINVAL;
542         }
543
544         if (rc == 0 && pc->pc_npartners > 0) {
545                 OBD_ALLOC(pc->pc_partners,
546                           sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
547                 if (pc->pc_partners == NULL) {
548                         pc->pc_npartners = 0;
549                         rc = -ENOMEM;
550                 } else {
551                         if (index & 0x1)
552                                 cfs_set_bit(LIOD_BIND, &pc->pc_flags);
553
554                         switch (ptlrpcd_bind_policy) {
555                         case PDB_POLICY_PAIR:
556                                 if (index & 0x1) {
557                                         pc->pc_partners[0] = &ptlrpcds->
558                                                 pd_threads[index - 1];
559                                         ptlrpcds->pd_threads[index - 1].
560                                                 pc_partners[0] = pc;
561                                 }
562                                 break;
563                         case PDB_POLICY_NEIGHBOR:
564                                 if (index > 0) {
565                                         pc->pc_partners[0] = &ptlrpcds->
566                                                 pd_threads[index - 1];
567                                         ptlrpcds->pd_threads[index - 1].
568                                                 pc_partners[1] = pc;
569                                         if (index == max - 1) {
570                                                 pc->pc_partners[1] =
571                                                 &ptlrpcds->pd_threads[0];
572                                                 ptlrpcds->pd_threads[0].
573                                                 pc_partners[0] = pc;
574                                         }
575                                 }
576                                 break;
577                         }
578                 }
579         }
580
581         RETURN(rc);
582 }
583
584 #else /* !__KERNEL__ */
585
586 /**
587  * In liblustre we do not have separate threads, so this function
588  * is called from time to time all across common code to see
589  * if something needs to be processed on ptlrpcd set.
590  */
591 int ptlrpcd_check_async_rpcs(void *arg)
592 {
593         struct ptlrpcd_ctl *pc = arg;
594         int                 rc = 0;
595
596         /*
597          * Single threaded!!
598          */
599         pc->pc_recurred++;
600
601         if (pc->pc_recurred == 1) {
602                 rc = lu_env_refill(&pc->pc_env);
603                 if (rc == 0) {
604                         lu_context_enter(&pc->pc_env.le_ctx);
605                         rc = ptlrpcd_check(&pc->pc_env, pc);
606                         if (!rc)
607                                 ptlrpc_expired_set(pc->pc_set);
608                         /*
609                          * XXX: send replay requests.
610                          */
611                         if (cfs_test_bit(LIOD_RECOVERY, &pc->pc_flags))
612                                 rc = ptlrpcd_check(&pc->pc_env, pc);
613                         lu_context_exit(&pc->pc_env.le_ctx);
614                 }
615         }
616
617         pc->pc_recurred--;
618         return rc;
619 }
620
621 int ptlrpcd_idle(void *arg)
622 {
623         struct ptlrpcd_ctl *pc = arg;
624
625         return (cfs_atomic_read(&pc->pc_set->set_new_count) == 0 &&
626                 cfs_atomic_read(&pc->pc_set->set_remaining) == 0);
627 }
628
629 #endif
630
631 int ptlrpcd_start(int index, int max, const char *name, struct ptlrpcd_ctl *pc)
632 {
633         int rc;
634         int env = 0;
635         ENTRY;
636
637         /*
638          * Do not allow start second thread for one pc.
639          */
640         if (cfs_test_and_set_bit(LIOD_START, &pc->pc_flags)) {
641                 CWARN("Starting second thread (%s) for same pc %p\n",
642                        name, pc);
643                 RETURN(0);
644         }
645
646         pc->pc_index = index;
647         cfs_init_completion(&pc->pc_starting);
648         cfs_init_completion(&pc->pc_finishing);
649         cfs_spin_lock_init(&pc->pc_lock);
650         strncpy(pc->pc_name, name, sizeof(pc->pc_name) - 1);
651         pc->pc_set = ptlrpc_prep_set();
652         if (pc->pc_set == NULL)
653                 GOTO(out, rc = -ENOMEM);
654         /*
655          * So far only "client" ptlrpcd uses an environment. In the future,
656          * ptlrpcd thread (or a thread-set) has to be given an argument,
657          * describing its "scope".
658          */
659         rc = lu_context_init(&pc->pc_env.le_ctx, LCT_CL_THREAD|LCT_REMEMBER);
660         if (rc != 0)
661                 GOTO(out, rc);
662
663         env = 1;
664 #ifdef __KERNEL__
665         if (index >= 0) {
666                 rc = ptlrpcd_bind(index, max);
667                 if (rc < 0)
668                         GOTO(out, rc);
669         }
670
671         rc = cfs_create_thread(ptlrpcd, pc, 0);
672         if (rc < 0)
673                 GOTO(out, rc);
674
675         rc = 0;
676         cfs_wait_for_completion(&pc->pc_starting);
677 #else
678         pc->pc_wait_callback =
679                 liblustre_register_wait_callback("ptlrpcd_check_async_rpcs",
680                                                  &ptlrpcd_check_async_rpcs, pc);
681         pc->pc_idle_callback =
682                 liblustre_register_idle_callback("ptlrpcd_check_idle_rpcs",
683                                                  &ptlrpcd_idle, pc);
684 #endif
685 out:
686         if (rc) {
687 #ifdef __KERNEL__
688                 if (pc->pc_set != NULL) {
689                         struct ptlrpc_request_set *set = pc->pc_set;
690
691                         cfs_spin_lock(&pc->pc_lock);
692                         pc->pc_set = NULL;
693                         cfs_spin_unlock(&pc->pc_lock);
694                         ptlrpc_set_destroy(set);
695                 }
696                 if (env != 0)
697                         lu_context_fini(&pc->pc_env.le_ctx);
698                 cfs_clear_bit(LIOD_BIND, &pc->pc_flags);
699 #endif
700                 cfs_clear_bit(LIOD_START, &pc->pc_flags);
701         }
702         RETURN(rc);
703 }
704
705 void ptlrpcd_stop(struct ptlrpcd_ctl *pc, int force)
706 {
707        struct ptlrpc_request_set *set = pc->pc_set;
708         ENTRY;
709
710         if (!cfs_test_bit(LIOD_START, &pc->pc_flags)) {
711                 CWARN("Thread for pc %p was not started\n", pc);
712                 goto out;
713         }
714
715         cfs_set_bit(LIOD_STOP, &pc->pc_flags);
716         if (force)
717                 cfs_set_bit(LIOD_FORCE, &pc->pc_flags);
718         cfs_waitq_signal(&pc->pc_set->set_waitq);
719 #ifdef __KERNEL__
720         cfs_wait_for_completion(&pc->pc_finishing);
721 #else
722         liblustre_deregister_wait_callback(pc->pc_wait_callback);
723         liblustre_deregister_idle_callback(pc->pc_idle_callback);
724 #endif
725         lu_context_fini(&pc->pc_env.le_ctx);
726
727         cfs_spin_lock(&pc->pc_lock);
728         pc->pc_set = NULL;
729         cfs_spin_unlock(&pc->pc_lock);
730         ptlrpc_set_destroy(set);
731
732 out:
733 #ifdef __KERNEL__
734         if (pc->pc_npartners > 0) {
735                 LASSERT(pc->pc_partners != NULL);
736
737                 OBD_FREE(pc->pc_partners,
738                          sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
739                 pc->pc_partners = NULL;
740         }
741         pc->pc_npartners = 0;
742 #endif
743         EXIT;
744 }
745
746 static void ptlrpcd_fini(void)
747 {
748         int i;
749         ENTRY;
750
751         if (ptlrpcds != NULL) {
752                 for (i = 0; i < ptlrpcds->pd_nthreads; i++)
753                         ptlrpcd_stop(&ptlrpcds->pd_threads[i], 0);
754                 ptlrpcd_stop(&ptlrpcds->pd_thread_rcv, 0);
755                 OBD_FREE(ptlrpcds, ptlrpcds->pd_size);
756                 ptlrpcds = NULL;
757         }
758
759         EXIT;
760 }
761
762 static int ptlrpcd_init(void)
763 {
764         int nthreads = cfs_num_online_cpus();
765         char name[16];
766         int size, i = -1, j, rc = 0;
767         ENTRY;
768
769 #ifdef __KERNEL__
770         if (max_ptlrpcds > 0 && max_ptlrpcds < nthreads)
771                 nthreads = max_ptlrpcds;
772         if (nthreads < 2)
773                 nthreads = 2;
774         if (nthreads < 3 && ptlrpcd_bind_policy == PDB_POLICY_NEIGHBOR)
775                 ptlrpcd_bind_policy = PDB_POLICY_PAIR;
776         else if (nthreads % 2 != 0 && ptlrpcd_bind_policy == PDB_POLICY_PAIR)
777                 nthreads &= ~1; /* make sure it is even */
778 #else
779         nthreads = 1;
780 #endif
781
782         size = offsetof(struct ptlrpcd, pd_threads[nthreads]);
783         OBD_ALLOC(ptlrpcds, size);
784         if (ptlrpcds == NULL)
785                 GOTO(out, rc = -ENOMEM);
786
787         snprintf(name, 15, "ptlrpcd_rcv");
788         cfs_set_bit(LIOD_RECOVERY, &ptlrpcds->pd_thread_rcv.pc_flags);
789         rc = ptlrpcd_start(-1, nthreads, name, &ptlrpcds->pd_thread_rcv);
790         if (rc < 0)
791                 GOTO(out, rc);
792
793         /* XXX: We start nthreads ptlrpc daemons. Each of them can process any
794          *      non-recovery async RPC to improve overall async RPC efficiency.
795          *
796          *      But there are some issues with async I/O RPCs and async non-I/O
797          *      RPCs processed in the same set under some cases. The ptlrpcd may
798          *      be blocked by some async I/O RPC(s), then will cause other async
799          *      non-I/O RPC(s) can not be processed in time.
800          *
801          *      Maybe we should distinguish blocked async RPCs from non-blocked
802          *      async RPCs, and process them in different ptlrpcd sets to avoid
803          *      unnecessary dependency. But how to distribute async RPCs load
804          *      among all the ptlrpc daemons becomes another trouble. */
805         for (i = 0; i < nthreads; i++) {
806                 snprintf(name, 15, "ptlrpcd_%d", i);
807                 rc = ptlrpcd_start(i, nthreads, name, &ptlrpcds->pd_threads[i]);
808                 if (rc < 0)
809                         GOTO(out, rc);
810         }
811
812         ptlrpcds->pd_size = size;
813         ptlrpcds->pd_index = 0;
814         ptlrpcds->pd_nthreads = nthreads;
815
816 out:
817         if (rc != 0 && ptlrpcds != NULL) {
818                 for (j = 0; j <= i; j++)
819                         ptlrpcd_stop(&ptlrpcds->pd_threads[j], 0);
820                 ptlrpcd_stop(&ptlrpcds->pd_thread_rcv, 0);
821                 OBD_FREE(ptlrpcds, size);
822                 ptlrpcds = NULL;
823         }
824
825         RETURN(0);
826 }
827
828 int ptlrpcd_addref(void)
829 {
830         int rc = 0;
831         ENTRY;
832
833         cfs_mutex_down(&ptlrpcd_sem);
834         if (++ptlrpcd_users == 1)
835                 rc = ptlrpcd_init();
836         cfs_mutex_up(&ptlrpcd_sem);
837         RETURN(rc);
838 }
839
840 void ptlrpcd_decref(void)
841 {
842         cfs_mutex_down(&ptlrpcd_sem);
843         if (--ptlrpcd_users == 0)
844                 ptlrpcd_fini();
845         cfs_mutex_up(&ptlrpcd_sem);
846 }
847 /** @} ptlrpcd */