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