Whamcloud - gitweb
76c906640b70a549dd4ecef9cb89e595af4f76a6
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2015, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/ptlrpc/ptlrpcd.c
33  */
34
35 /** \defgroup ptlrpcd PortalRPC daemon
36  *
37  * ptlrpcd is a special thread with its own set where other user might add
38  * requests when they don't want to wait for their completion.
39  * PtlRPCD will take care of sending such requests and then processing their
40  * replies and calling completion callbacks as necessary.
41  * The callbacks are called directly from ptlrpcd context.
42  * It is important to never significantly block (esp. on RPCs!) within such
43  * completion handler or a deadlock might occur where ptlrpcd enters some
44  * callback that attempts to send another RPC and wait for it to return,
45  * during which time ptlrpcd is completely blocked, so e.g. if import
46  * fails, recovery cannot progress because connection requests are also
47  * sent by ptlrpcd.
48  *
49  * @{
50  */
51
52 #define DEBUG_SUBSYSTEM S_RPC
53
54 #include <linux/kthread.h>
55 #include <libcfs/libcfs.h>
56 #include <lustre_net.h>
57 #include <lustre_lib.h>
58 #include <lustre_ha.h>
59 #include <obd_class.h>   /* for obd_zombie */
60 #include <obd_support.h> /* for OBD_FAIL_CHECK */
61 #include <cl_object.h> /* cl_env_{get,put}() */
62 #include <lprocfs_status.h>
63
64 #include "ptlrpc_internal.h"
65
66 /* One of these per CPT. */
67 struct ptlrpcd {
68         int                     pd_size;
69         int                     pd_index;
70         int                     pd_cpt;
71         int                     pd_cursor;
72         int                     pd_nthreads;
73         int                     pd_groupsize;
74         struct ptlrpcd_ctl      pd_threads[0];
75 };
76
77 /*
78  * max_ptlrpcds is obsolete, but retained to ensure that the kernel
79  * module will load on a system where it has been tuned.
80  * A value other than 0 implies it was tuned, in which case the value
81  * is used to derive a setting for ptlrpcd_per_cpt_max.
82  */
83 static int max_ptlrpcds;
84 module_param(max_ptlrpcds, int, 0644);
85 MODULE_PARM_DESC(max_ptlrpcds, "Max ptlrpcd thread count to be started.");
86
87 /*
88  * ptlrpcd_bind_policy is obsolete, but retained to ensure that
89  * the kernel module will load on a system where it has been tuned.
90  * A value other than 0 implies it was tuned, in which case the value
91  * is used to derive a setting for ptlrpcd_partner_group_size.
92  */
93 static int ptlrpcd_bind_policy;
94 module_param(ptlrpcd_bind_policy, int, 0644);
95 MODULE_PARM_DESC(ptlrpcd_bind_policy,
96                  "Ptlrpcd threads binding mode (obsolete).");
97
98 /*
99  * ptlrpcd_per_cpt_max: The maximum number of ptlrpcd threads to run
100  * in a CPT.
101  */
102 static int ptlrpcd_per_cpt_max;
103 MODULE_PARM_DESC(ptlrpcd_per_cpt_max,
104                  "Max ptlrpcd thread count to be started per cpt.");
105
106 /*
107  * ptlrpcd_partner_group_size: The desired number of threads in each
108  * ptlrpcd partner thread group. Default is 2, corresponding to the
109  * old PDB_POLICY_PAIR. A negative value makes all ptlrpcd threads in
110  * a CPT partners of each other.
111  */
112 static int ptlrpcd_partner_group_size;
113 module_param(ptlrpcd_partner_group_size, int, 0644);
114 MODULE_PARM_DESC(ptlrpcd_partner_group_size,
115                  "Number of ptlrpcd threads in a partner group.");
116
117 /*
118  * ptlrpcd_cpts: A CPT string describing the CPU partitions that
119  * ptlrpcd threads should run on. Used to make ptlrpcd threads run on
120  * a subset of all CPTs.
121  *
122  * ptlrpcd_cpts=2
123  * ptlrpcd_cpts=[2]
124  *   run ptlrpcd threads only on CPT 2.
125  *
126  * ptlrpcd_cpts=0-3
127  * ptlrpcd_cpts=[0-3]
128  *   run ptlrpcd threads on CPTs 0, 1, 2, and 3.
129  *
130  * ptlrpcd_cpts=[0-3,5,7]
131  *   run ptlrpcd threads on CPTS 0, 1, 2, 3, 5, and 7.
132  */
133 static char *ptlrpcd_cpts;
134 module_param(ptlrpcd_cpts, charp, 0644);
135 MODULE_PARM_DESC(ptlrpcd_cpts,
136                  "CPU partitions ptlrpcd threads should run in");
137
138 /* ptlrpcds_cpt_idx maps cpt numbers to an index in the ptlrpcds array. */
139 static int              *ptlrpcds_cpt_idx;
140
141 /* ptlrpcds_num is the number of entries in the ptlrpcds array. */
142 static int              ptlrpcds_num;
143 static struct ptlrpcd   **ptlrpcds;
144
145 /*
146  * In addition to the regular thread pool above, there is a single
147  * global recovery thread. Recovery isn't critical for performance,
148  * and doesn't block, but must always be able to proceed, and it is
149  * possible that all normal ptlrpcd threads are blocked. Hence the
150  * need for a dedicated thread.
151  */
152 static struct ptlrpcd_ctl ptlrpcd_rcv;
153
154 struct mutex ptlrpcd_mutex;
155 static int ptlrpcd_users = 0;
156
157 void ptlrpcd_wake(struct ptlrpc_request *req)
158 {
159         struct ptlrpc_request_set *set = req->rq_set;
160
161         LASSERT(set != NULL);
162         wake_up(&set->set_waitq);
163 }
164 EXPORT_SYMBOL(ptlrpcd_wake);
165
166 static struct ptlrpcd_ctl *
167 ptlrpcd_select_pc(struct ptlrpc_request *req)
168 {
169         struct ptlrpcd  *pd;
170         int             cpt;
171         int             idx;
172
173         if (req != NULL && req->rq_send_state != LUSTRE_IMP_FULL)
174                 return &ptlrpcd_rcv;
175
176         cpt = cfs_cpt_current(cfs_cpt_table, 1);
177         if (ptlrpcds_cpt_idx == NULL)
178                 idx = cpt;
179         else
180                 idx = ptlrpcds_cpt_idx[cpt];
181         pd = ptlrpcds[idx];
182
183         /* We do not care whether it is strict load balance. */
184         idx = pd->pd_cursor;
185         if (++idx == pd->pd_nthreads)
186                 idx = 0;
187         pd->pd_cursor = idx;
188
189         return &pd->pd_threads[idx];
190 }
191
192 /**
193  * Move all request from an existing request set to the ptlrpcd queue.
194  * All requests from the set must be in phase RQ_PHASE_NEW.
195  */
196 void ptlrpcd_add_rqset(struct ptlrpc_request_set *set)
197 {
198         struct list_head *tmp, *pos;
199         struct ptlrpcd_ctl *pc;
200         struct ptlrpc_request_set *new;
201         int count, i;
202
203         pc = ptlrpcd_select_pc(NULL);
204         new = pc->pc_set;
205
206         list_for_each_safe(pos, tmp, &set->set_requests) {
207                 struct ptlrpc_request *req =
208                         list_entry(pos, struct ptlrpc_request,
209                                    rq_set_chain);
210
211                 LASSERT(req->rq_phase == RQ_PHASE_NEW);
212                 req->rq_set = new;
213                 req->rq_queued_time = cfs_time_current();
214         }
215
216         spin_lock(&new->set_new_req_lock);
217         list_splice_init(&set->set_requests, &new->set_new_requests);
218         i = atomic_read(&set->set_remaining);
219         count = atomic_add_return(i, &new->set_new_count);
220         atomic_set(&set->set_remaining, 0);
221         spin_unlock(&new->set_new_req_lock);
222         if (count == i) {
223                 wake_up(&new->set_waitq);
224
225                 /* XXX: It maybe unnecessary to wakeup all the partners. But to
226                  *      guarantee the async RPC can be processed ASAP, we have
227                  *      no other better choice. It maybe fixed in future. */
228                 for (i = 0; i < pc->pc_npartners; i++)
229                         wake_up(&pc->pc_partners[i]->pc_set->set_waitq);
230         }
231 }
232
233 /**
234  * Return transferred RPCs count.
235  */
236 static int ptlrpcd_steal_rqset(struct ptlrpc_request_set *des,
237                                struct ptlrpc_request_set *src)
238 {
239         struct list_head *tmp, *pos;
240         struct ptlrpc_request *req;
241         int rc = 0;
242
243         spin_lock(&src->set_new_req_lock);
244         if (likely(!list_empty(&src->set_new_requests))) {
245                 list_for_each_safe(pos, tmp, &src->set_new_requests) {
246                         req = list_entry(pos, struct ptlrpc_request,
247                                          rq_set_chain);
248                         req->rq_set = des;
249                 }
250                 list_splice_init(&src->set_new_requests,
251                                  &des->set_requests);
252                 rc = atomic_read(&src->set_new_count);
253                 atomic_add(rc, &des->set_remaining);
254                 atomic_set(&src->set_new_count, 0);
255         }
256         spin_unlock(&src->set_new_req_lock);
257         return rc;
258 }
259
260 /**
261  * Requests that are added to the ptlrpcd queue are sent via
262  * ptlrpcd_check->ptlrpc_check_set().
263  */
264 void ptlrpcd_add_req(struct ptlrpc_request *req)
265 {
266         struct ptlrpcd_ctl *pc;
267
268         if (req->rq_reqmsg)
269                 lustre_msg_set_jobid(req->rq_reqmsg, NULL);
270
271         spin_lock(&req->rq_lock);
272         if (req->rq_invalid_rqset) {
273                 struct l_wait_info lwi = LWI_TIMEOUT(cfs_time_seconds(5),
274                                                      back_to_sleep, NULL);
275
276                 req->rq_invalid_rqset = 0;
277                 spin_unlock(&req->rq_lock);
278                 l_wait_event(req->rq_set_waitq, (req->rq_set == NULL), &lwi);
279         } else if (req->rq_set) {
280                 /* If we have a vaid "rq_set", just reuse it to avoid double
281                  * linked. */
282                 LASSERT(req->rq_phase == RQ_PHASE_NEW);
283                 LASSERT(req->rq_send_state == LUSTRE_IMP_REPLAY);
284
285                 /* ptlrpc_check_set will decrease the count */
286                 atomic_inc(&req->rq_set->set_remaining);
287                 spin_unlock(&req->rq_lock);
288                 wake_up(&req->rq_set->set_waitq);
289                 return;
290         } else {
291                 spin_unlock(&req->rq_lock);
292         }
293
294         pc = ptlrpcd_select_pc(req);
295
296         DEBUG_REQ(D_INFO, req, "add req [%p] to pc [%s:%d]",
297                   req, pc->pc_name, pc->pc_index);
298
299         ptlrpc_set_add_new_req(pc, req);
300 }
301 EXPORT_SYMBOL(ptlrpcd_add_req);
302
303 static inline void ptlrpc_reqset_get(struct ptlrpc_request_set *set)
304 {
305         atomic_inc(&set->set_refcount);
306 }
307
308 /**
309  * Check if there is more work to do on ptlrpcd set.
310  * Returns 1 if yes.
311  */
312 static int ptlrpcd_check(struct lu_env *env, struct ptlrpcd_ctl *pc)
313 {
314         struct list_head *tmp, *pos;
315         struct ptlrpc_request *req;
316         struct ptlrpc_request_set *set = pc->pc_set;
317         int rc = 0;
318         int rc2;
319         ENTRY;
320
321         if (atomic_read(&set->set_new_count)) {
322                 spin_lock(&set->set_new_req_lock);
323                 if (likely(!list_empty(&set->set_new_requests))) {
324                         list_splice_init(&set->set_new_requests,
325                                              &set->set_requests);
326                         atomic_add(atomic_read(&set->set_new_count),
327                                    &set->set_remaining);
328                         atomic_set(&set->set_new_count, 0);
329                         /*
330                          * Need to calculate its timeout.
331                          */
332                         rc = 1;
333                 }
334                 spin_unlock(&set->set_new_req_lock);
335         }
336
337         /* We should call lu_env_refill() before handling new requests to make
338          * sure that env key the requests depending on really exists.
339          */
340         rc2 = lu_env_refill(env);
341         if (rc2 != 0) {
342                 /*
343                  * XXX This is very awkward situation, because
344                  * execution can neither continue (request
345                  * interpreters assume that env is set up), nor repeat
346                  * the loop (as this potentially results in a tight
347                  * loop of -ENOMEM's).
348                  *
349                  * Fortunately, refill only ever does something when
350                  * new modules are loaded, i.e., early during boot up.
351                  */
352                 CERROR("Failure to refill session: %d\n", rc2);
353                 RETURN(rc);
354         }
355
356         if (atomic_read(&set->set_remaining))
357                 rc |= ptlrpc_check_set(env, set);
358
359         /* NB: ptlrpc_check_set has already moved complted request at the
360          * head of seq::set_requests */
361         list_for_each_safe(pos, tmp, &set->set_requests) {
362                 req = list_entry(pos, struct ptlrpc_request, rq_set_chain);
363                 if (req->rq_phase != RQ_PHASE_COMPLETE)
364                         break;
365
366                 list_del_init(&req->rq_set_chain);
367                 req->rq_set = NULL;
368                 ptlrpc_req_finished(req);
369         }
370
371         if (rc == 0) {
372                 /*
373                  * If new requests have been added, make sure to wake up.
374                  */
375                 rc = atomic_read(&set->set_new_count);
376
377                 /* If we have nothing to do, check whether we can take some
378                  * work from our partner threads. */
379                 if (rc == 0 && pc->pc_npartners > 0) {
380                         struct ptlrpcd_ctl *partner;
381                         struct ptlrpc_request_set *ps;
382                         int first = pc->pc_cursor;
383
384                         do {
385                                 partner = pc->pc_partners[pc->pc_cursor++];
386                                 if (pc->pc_cursor >= pc->pc_npartners)
387                                         pc->pc_cursor = 0;
388                                 if (partner == NULL)
389                                         continue;
390
391                                 spin_lock(&partner->pc_lock);
392                                 ps = partner->pc_set;
393                                 if (ps == NULL) {
394                                         spin_unlock(&partner->pc_lock);
395                                         continue;
396                                 }
397
398                                 ptlrpc_reqset_get(ps);
399                                 spin_unlock(&partner->pc_lock);
400
401                                 if (atomic_read(&ps->set_new_count)) {
402                                         rc = ptlrpcd_steal_rqset(set, ps);
403                                         if (rc > 0)
404                                                 CDEBUG(D_RPCTRACE, "transfer %d"
405                                                        " async RPCs [%d->%d]\n",
406                                                        rc, partner->pc_index,
407                                                        pc->pc_index);
408                                 }
409                                 ptlrpc_reqset_put(ps);
410                         } while (rc == 0 && pc->pc_cursor != first);
411                 }
412         }
413
414         RETURN(rc);
415 }
416
417 /**
418  * Main ptlrpcd thread.
419  * ptlrpc's code paths like to execute in process context, so we have this
420  * thread which spins on a set which contains the rpcs and sends them.
421  *
422  */
423 static int ptlrpcd(void *arg)
424 {
425         struct ptlrpcd_ctl              *pc = arg;
426         struct ptlrpc_request_set       *set;
427         struct lu_context               ses = { 0 };
428         struct lu_env                   env = { .le_ses = &ses };
429         int                             rc = 0;
430         int                             exit = 0;
431         ENTRY;
432
433         unshare_fs_struct();
434
435         if (cfs_cpt_bind(cfs_cpt_table, pc->pc_cpt) != 0)
436                 CWARN("Failed to bind %s on CPT %d\n", pc->pc_name, pc->pc_cpt);
437
438         /*
439          * Allocate the request set after the thread has been bound
440          * above. This is safe because no requests will be queued
441          * until all ptlrpcd threads have confirmed that they have
442          * successfully started.
443          */
444         set = ptlrpc_prep_set();
445         if (set == NULL)
446                 GOTO(failed, rc = -ENOMEM);
447         spin_lock(&pc->pc_lock);
448         pc->pc_set = set;
449         spin_unlock(&pc->pc_lock);
450
451         /* Both client and server (MDT/OST) may use the environment. */
452         rc = lu_context_init(&env.le_ctx, LCT_MD_THREAD |
453                                           LCT_DT_THREAD |
454                                           LCT_CL_THREAD |
455                                           LCT_REMEMBER  |
456                                           LCT_NOREF);
457         if (rc != 0)
458                 GOTO(failed, rc);
459         rc = lu_context_init(env.le_ses, LCT_SESSION  |
460                                          LCT_REMEMBER |
461                                          LCT_NOREF);
462         if (rc != 0) {
463                 lu_context_fini(&env.le_ctx);
464                 GOTO(failed, rc);
465         }
466
467         complete(&pc->pc_starting);
468
469         /*
470          * This mainloop strongly resembles ptlrpc_set_wait() except that our
471          * set never completes.  ptlrpcd_check() calls ptlrpc_check_set() when
472          * there are requests in the set. New requests come in on the set's
473          * new_req_list and ptlrpcd_check() moves them into the set.
474          */
475         do {
476                 struct l_wait_info lwi;
477                 int timeout;
478
479                 timeout = ptlrpc_set_next_timeout(set);
480                 lwi = LWI_TIMEOUT(cfs_time_seconds(timeout ? timeout : 1),
481                                   ptlrpc_expired_set, set);
482
483                 lu_context_enter(&env.le_ctx);
484                 lu_context_enter(env.le_ses);
485                 l_wait_event(set->set_waitq, ptlrpcd_check(&env, pc), &lwi);
486                 lu_context_exit(&env.le_ctx);
487                 lu_context_exit(env.le_ses);
488
489                 /*
490                  * Abort inflight rpcs for forced stop case.
491                  */
492                 if (test_bit(LIOD_STOP, &pc->pc_flags)) {
493                         if (test_bit(LIOD_FORCE, &pc->pc_flags))
494                                 ptlrpc_abort_set(set);
495                         exit++;
496                 }
497
498                 /*
499                  * Let's make one more loop to make sure that ptlrpcd_check()
500                  * copied all raced new rpcs into the set so we can kill them.
501                  */
502         } while (exit < 2);
503
504         /*
505          * Wait for inflight requests to drain.
506          */
507         if (!list_empty(&set->set_requests))
508                 ptlrpc_set_wait(set);
509         lu_context_fini(&env.le_ctx);
510         lu_context_fini(env.le_ses);
511
512         complete(&pc->pc_finishing);
513
514         return 0;
515
516 failed:
517         pc->pc_error = rc;
518         complete(&pc->pc_starting);
519         RETURN(rc);
520 }
521
522 static void ptlrpcd_ctl_init(struct ptlrpcd_ctl *pc, int index, int cpt)
523 {
524         ENTRY;
525
526         pc->pc_index = index;
527         pc->pc_cpt = cpt;
528         init_completion(&pc->pc_starting);
529         init_completion(&pc->pc_finishing);
530         spin_lock_init(&pc->pc_lock);
531
532         if (index < 0) {
533                 /* Recovery thread. */
534                 snprintf(pc->pc_name, sizeof(pc->pc_name), "ptlrpcd_rcv");
535         } else {
536                 /* Regular thread. */
537                 snprintf(pc->pc_name, sizeof(pc->pc_name),
538                          "ptlrpcd_%02d_%02d", cpt, index);
539         }
540
541         EXIT;
542 }
543
544 /* XXX: We want multiple CPU cores to share the async RPC load. So we
545  *      start many ptlrpcd threads. We also want to reduce the ptlrpcd
546  *      overhead caused by data transfer cross-CPU cores. So we bind
547  *      all ptlrpcd threads to a CPT, in the expectation that CPTs
548  *      will be defined in a way that matches these boundaries. Within
549  *      a CPT a ptlrpcd thread can be scheduled on any available core.
550  *
551  *      Each ptlrpcd thread has its own request queue. This can cause
552  *      response delay if the thread is already busy. To help with
553  *      this we define partner threads: these are other threads bound
554  *      to the same CPT which will check for work in each other's
555  *      request queues if they have no work to do.
556  *
557  *      The desired number of partner threads can be tuned by setting
558  *      ptlrpcd_partner_group_size. The default is to create pairs of
559  *      partner threads.
560  */
561 static int ptlrpcd_partners(struct ptlrpcd *pd, int index)
562 {
563         struct ptlrpcd_ctl      *pc;
564         struct ptlrpcd_ctl      **ppc;
565         int                     first;
566         int                     i;
567         int                     rc = 0;
568         ENTRY;
569
570         LASSERT(index >= 0 && index < pd->pd_nthreads);
571         pc = &pd->pd_threads[index];
572         pc->pc_npartners = pd->pd_groupsize - 1;
573
574         if (pc->pc_npartners <= 0)
575                 GOTO(out, rc);
576
577         OBD_CPT_ALLOC(pc->pc_partners, cfs_cpt_table, pc->pc_cpt,
578                       sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
579         if (pc->pc_partners == NULL) {
580                 pc->pc_npartners = 0;
581                 GOTO(out, rc = -ENOMEM);
582         }
583
584         first = index - index % pd->pd_groupsize;
585         ppc = pc->pc_partners;
586         for (i = first; i < first + pd->pd_groupsize; i++) {
587                 if (i != index)
588                         *ppc++ = &pd->pd_threads[i];
589         }
590 out:
591         RETURN(rc);
592 }
593
594 int ptlrpcd_start(struct ptlrpcd_ctl *pc)
595 {
596         struct task_struct      *task;
597         int                     rc = 0;
598         ENTRY;
599
600         /*
601          * Do not allow starting a second thread for one pc.
602          */
603         if (test_and_set_bit(LIOD_START, &pc->pc_flags)) {
604                 CWARN("Starting second thread (%s) for same pc %p\n",
605                       pc->pc_name, pc);
606                 RETURN(0);
607         }
608
609         task = kthread_run(ptlrpcd, pc, pc->pc_name);
610         if (IS_ERR(task))
611                 GOTO(out_set, rc = PTR_ERR(task));
612
613         wait_for_completion(&pc->pc_starting);
614         rc = pc->pc_error;
615         if (rc != 0)
616                 GOTO(out_set, rc);
617
618         RETURN(0);
619
620 out_set:
621         if (pc->pc_set != NULL) {
622                 struct ptlrpc_request_set *set = pc->pc_set;
623
624                 spin_lock(&pc->pc_lock);
625                 pc->pc_set = NULL;
626                 spin_unlock(&pc->pc_lock);
627                 ptlrpc_set_destroy(set);
628         }
629         clear_bit(LIOD_START, &pc->pc_flags);
630         RETURN(rc);
631 }
632
633 void ptlrpcd_stop(struct ptlrpcd_ctl *pc, int force)
634 {
635         ENTRY;
636
637         if (!test_bit(LIOD_START, &pc->pc_flags)) {
638                 CWARN("Thread for pc %p was not started\n", pc);
639                 goto out;
640         }
641
642         set_bit(LIOD_STOP, &pc->pc_flags);
643         if (force)
644                 set_bit(LIOD_FORCE, &pc->pc_flags);
645         wake_up(&pc->pc_set->set_waitq);
646
647 out:
648         EXIT;
649 }
650
651 void ptlrpcd_free(struct ptlrpcd_ctl *pc)
652 {
653         struct ptlrpc_request_set *set = pc->pc_set;
654         ENTRY;
655
656         if (!test_bit(LIOD_START, &pc->pc_flags)) {
657                 CWARN("Thread for pc %p was not started\n", pc);
658                 goto out;
659         }
660
661         wait_for_completion(&pc->pc_finishing);
662
663         spin_lock(&pc->pc_lock);
664         pc->pc_set = NULL;
665         spin_unlock(&pc->pc_lock);
666         ptlrpc_set_destroy(set);
667
668         clear_bit(LIOD_START, &pc->pc_flags);
669         clear_bit(LIOD_STOP, &pc->pc_flags);
670         clear_bit(LIOD_FORCE, &pc->pc_flags);
671
672 out:
673         if (pc->pc_npartners > 0) {
674                 LASSERT(pc->pc_partners != NULL);
675
676                 OBD_FREE(pc->pc_partners,
677                          sizeof(struct ptlrpcd_ctl *) * pc->pc_npartners);
678                 pc->pc_partners = NULL;
679         }
680         pc->pc_npartners = 0;
681         pc->pc_error = 0;
682         EXIT;
683 }
684
685 static void ptlrpcd_fini(void)
686 {
687         int     i;
688         int     j;
689         int     ncpts;
690         ENTRY;
691
692         if (ptlrpcds != NULL) {
693                 for (i = 0; i < ptlrpcds_num; i++) {
694                         if (ptlrpcds[i] == NULL)
695                                 break;
696                         for (j = 0; j < ptlrpcds[i]->pd_nthreads; j++)
697                                 ptlrpcd_stop(&ptlrpcds[i]->pd_threads[j], 0);
698                         for (j = 0; j < ptlrpcds[i]->pd_nthreads; j++)
699                                 ptlrpcd_free(&ptlrpcds[i]->pd_threads[j]);
700                         OBD_FREE(ptlrpcds[i], ptlrpcds[i]->pd_size);
701                         ptlrpcds[i] = NULL;
702                 }
703                 OBD_FREE(ptlrpcds, sizeof(ptlrpcds[0]) * ptlrpcds_num);
704         }
705         ptlrpcds_num = 0;
706
707         ptlrpcd_stop(&ptlrpcd_rcv, 0);
708         ptlrpcd_free(&ptlrpcd_rcv);
709
710         if (ptlrpcds_cpt_idx != NULL) {
711                 ncpts = cfs_cpt_number(cfs_cpt_table);
712                 OBD_FREE(ptlrpcds_cpt_idx, ncpts * sizeof(ptlrpcds_cpt_idx[0]));
713                 ptlrpcds_cpt_idx = NULL;
714         }
715
716         EXIT;
717 }
718
719 static int ptlrpcd_init(void)
720 {
721         int                     nthreads;
722         int                     groupsize;
723         int                     size;
724         int                     i;
725         int                     j;
726         int                     rc = 0;
727         struct cfs_cpt_table    *cptable;
728         __u32                   *cpts = NULL;
729         int                     ncpts;
730         int                     cpt;
731         struct ptlrpcd          *pd;
732         ENTRY;
733
734         /*
735          * Determine the CPTs that ptlrpcd threads will run on.
736          */
737         cptable = cfs_cpt_table;
738         ncpts = cfs_cpt_number(cptable);
739         if (ptlrpcd_cpts != NULL) {
740                 struct cfs_expr_list    *el;
741
742                 size = ncpts * sizeof(ptlrpcds_cpt_idx[0]);
743                 OBD_ALLOC(ptlrpcds_cpt_idx, size);
744                 if (ptlrpcds_cpt_idx == NULL)
745                         GOTO(out, rc = -ENOMEM);
746
747                 rc = cfs_expr_list_parse(ptlrpcd_cpts,
748                                          strlen(ptlrpcd_cpts),
749                                          0, ncpts - 1, &el);
750                 if (rc != 0) {
751                         CERROR("%s: invalid CPT pattern string: %s",
752                                "ptlrpcd_cpts", ptlrpcd_cpts);
753                         GOTO(out, rc = -EINVAL);
754                 }
755
756                 rc = cfs_expr_list_values(el, ncpts, &cpts);
757                 cfs_expr_list_free(el);
758                 if (rc <= 0) {
759                         CERROR("%s: failed to parse CPT array %s: %d\n",
760                                "ptlrpcd_cpts", ptlrpcd_cpts, rc);
761                         if (rc == 0)
762                                 rc = -EINVAL;
763                         GOTO(out, rc);
764                 }
765
766                 /*
767                  * Create the cpt-to-index map. When there is no match
768                  * in the cpt table, pick a cpt at random. This could
769                  * be changed to take the topology of the system into
770                  * account.
771                  */
772                 for (cpt = 0; cpt < ncpts; cpt++) {
773                         for (i = 0; i < rc; i++)
774                                 if (cpts[i] == cpt)
775                                         break;
776                         if (i >= rc)
777                                 i = cpt % rc;
778                         ptlrpcds_cpt_idx[cpt] = i;
779                 }
780
781                 cfs_expr_list_values_free(cpts, rc);
782                 ncpts = rc;
783         }
784         ptlrpcds_num = ncpts;
785
786         size = ncpts * sizeof(ptlrpcds[0]);
787         OBD_ALLOC(ptlrpcds, size);
788         if (ptlrpcds == NULL)
789                 GOTO(out, rc = -ENOMEM);
790
791         /*
792          * The max_ptlrpcds parameter is obsolete, but do something
793          * sane if it has been tuned, and complain if
794          * ptlrpcd_per_cpt_max has also been tuned.
795          */
796         if (max_ptlrpcds != 0) {
797                 CWARN("max_ptlrpcds is obsolete.\n");
798                 if (ptlrpcd_per_cpt_max == 0) {
799                         ptlrpcd_per_cpt_max = max_ptlrpcds / ncpts;
800                         /* Round up if there is a remainder. */
801                         if (max_ptlrpcds % ncpts != 0)
802                                 ptlrpcd_per_cpt_max++;
803                         CWARN("Setting ptlrpcd_per_cpt_max = %d\n",
804                               ptlrpcd_per_cpt_max);
805                 } else {
806                         CWARN("ptlrpd_per_cpt_max is also set!\n");
807                 }
808         }
809
810         /*
811          * The ptlrpcd_bind_policy parameter is obsolete, but do
812          * something sane if it has been tuned, and complain if
813          * ptlrpcd_partner_group_size is also tuned.
814          */
815         if (ptlrpcd_bind_policy != 0) {
816                 CWARN("ptlrpcd_bind_policy is obsolete.\n");
817                 if (ptlrpcd_partner_group_size == 0) {
818                         switch (ptlrpcd_bind_policy) {
819                         case 1: /* PDB_POLICY_NONE */
820                         case 2: /* PDB_POLICY_FULL */
821                                 ptlrpcd_partner_group_size = 1;
822                                 break;
823                         case 3: /* PDB_POLICY_PAIR */
824                                 ptlrpcd_partner_group_size = 2;
825                                 break;
826                         case 4: /* PDB_POLICY_NEIGHBOR */
827 #ifdef CONFIG_NUMA
828                                 ptlrpcd_partner_group_size = -1; /* CPT */
829 #else
830                                 ptlrpcd_partner_group_size = 3; /* Triplets */
831 #endif
832                                 break;
833                         default: /* Illegal value, use the default. */
834                                 ptlrpcd_partner_group_size = 2;
835                                 break;
836                         }
837                         CWARN("Setting ptlrpcd_partner_group_size = %d\n",
838                               ptlrpcd_partner_group_size);
839                 } else {
840                         CWARN("ptlrpcd_partner_group_size is also set!\n");
841                 }
842         }
843
844         if (ptlrpcd_partner_group_size == 0)
845                 ptlrpcd_partner_group_size = 2;
846         else if (ptlrpcd_partner_group_size < 0)
847                 ptlrpcd_partner_group_size = -1;
848         else if (ptlrpcd_per_cpt_max > 0 &&
849                  ptlrpcd_partner_group_size > ptlrpcd_per_cpt_max)
850                 ptlrpcd_partner_group_size = ptlrpcd_per_cpt_max;
851
852         /*
853          * Start the recovery thread first.
854          */
855         set_bit(LIOD_RECOVERY, &ptlrpcd_rcv.pc_flags);
856         ptlrpcd_ctl_init(&ptlrpcd_rcv, -1, CFS_CPT_ANY);
857         rc = ptlrpcd_start(&ptlrpcd_rcv);
858         if (rc < 0)
859                 GOTO(out, rc);
860
861         for (i = 0; i < ncpts; i++) {
862                 if (cpts == NULL)
863                         cpt = i;
864                 else
865                         cpt = cpts[i];
866
867                 nthreads = cfs_cpt_weight(cptable, cpt);
868                 if (ptlrpcd_per_cpt_max > 0 && ptlrpcd_per_cpt_max < nthreads)
869                         nthreads = ptlrpcd_per_cpt_max;
870                 if (nthreads < 2)
871                         nthreads = 2;
872
873                 if (ptlrpcd_partner_group_size <= 0) {
874                         groupsize = nthreads;
875                 } else if (nthreads <= ptlrpcd_partner_group_size) {
876                         groupsize = nthreads;
877                 } else {
878                         groupsize = ptlrpcd_partner_group_size;
879                         if (nthreads % groupsize != 0)
880                                 nthreads += groupsize - (nthreads % groupsize);
881                 }
882
883                 size = offsetof(struct ptlrpcd, pd_threads[nthreads]);
884                 OBD_CPT_ALLOC(pd, cptable, cpt, size);
885                 if (!pd)
886                         GOTO(out, rc = -ENOMEM);
887                 pd->pd_size      = size;
888                 pd->pd_index     = i;
889                 pd->pd_cpt       = cpt;
890                 pd->pd_cursor    = 0;
891                 pd->pd_nthreads  = nthreads;
892                 pd->pd_groupsize = groupsize;
893                 ptlrpcds[i] = pd;
894
895                 /*
896                  * The ptlrpcd threads in a partner group can access
897                  * each other's struct ptlrpcd_ctl, so these must be
898                  * initialized before any thead is started.
899                  */
900                 for (j = 0; j < nthreads; j++) {
901                         ptlrpcd_ctl_init(&pd->pd_threads[j], j, cpt);
902                         rc = ptlrpcd_partners(pd, j);
903                         if (rc < 0)
904                                 GOTO(out, rc);
905                 }
906
907                 /* XXX: We start nthreads ptlrpc daemons on this cpt.
908                  *      Each of them can process any non-recovery
909                  *      async RPC to improve overall async RPC
910                  *      efficiency.
911                  *
912                  *      But there are some issues with async I/O RPCs
913                  *      and async non-I/O RPCs processed in the same
914                  *      set under some cases. The ptlrpcd may be
915                  *      blocked by some async I/O RPC(s), then will
916                  *      cause other async non-I/O RPC(s) can not be
917                  *      processed in time.
918                  *
919                  *      Maybe we should distinguish blocked async RPCs
920                  *      from non-blocked async RPCs, and process them
921                  *      in different ptlrpcd sets to avoid unnecessary
922                  *      dependency. But how to distribute async RPCs
923                  *      load among all the ptlrpc daemons becomes
924                  *      another trouble.
925                  */
926                 for (j = 0; j < nthreads; j++) {
927                         rc = ptlrpcd_start(&pd->pd_threads[j]);
928                         if (rc < 0)
929                                 GOTO(out, rc);
930                 }
931         }
932 out:
933         if (rc != 0)
934                 ptlrpcd_fini();
935
936         RETURN(rc);
937 }
938
939 int ptlrpcd_addref(void)
940 {
941         int rc = 0;
942         ENTRY;
943
944         mutex_lock(&ptlrpcd_mutex);
945         if (++ptlrpcd_users == 1) {
946                 rc = ptlrpcd_init();
947                 if (rc < 0)
948                         ptlrpcd_users--;
949         }
950         mutex_unlock(&ptlrpcd_mutex);
951         RETURN(rc);
952 }
953 EXPORT_SYMBOL(ptlrpcd_addref);
954
955 void ptlrpcd_decref(void)
956 {
957         mutex_lock(&ptlrpcd_mutex);
958         if (--ptlrpcd_users == 0)
959                 ptlrpcd_fini();
960         mutex_unlock(&ptlrpcd_mutex);
961 }
962 EXPORT_SYMBOL(ptlrpcd_decref);
963 /** @} ptlrpcd */