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