Whamcloud - gitweb
LU-17705 ptlrpc: replace synchronize_rcu() with rcu_barrier()
[fs/lustre-release.git] / lnet / lnet / api-ni.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, 2017, 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
33 #define DEBUG_SUBSYSTEM S_LNET
34
35 #include <linux/ctype.h>
36 #include <linux/log2.h>
37 #include <linux/ktime.h>
38 #include <linux/moduleparam.h>
39 #include <linux/uaccess.h>
40 #ifdef HAVE_SCHED_HEADERS
41 #include <linux/sched/signal.h>
42 #endif
43
44 #include <lnet/lib-lnet.h>
45
46 #define D_LNI D_CONSOLE
47
48 /*
49  * initialize ln_api_mutex statically, since it needs to be used in
50  * discovery_set callback. That module parameter callback can be called
51  * before module init completes. The mutex needs to be ready for use then.
52  */
53 struct lnet the_lnet = {
54         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
55 };              /* THE state of the network */
56 EXPORT_SYMBOL(the_lnet);
57
58 static char *ip2nets = "";
59 module_param(ip2nets, charp, 0444);
60 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
61
62 static char *networks = "";
63 module_param(networks, charp, 0444);
64 MODULE_PARM_DESC(networks, "local networks");
65
66 static char *routes = "";
67 module_param(routes, charp, 0444);
68 MODULE_PARM_DESC(routes, "routes to non-local networks");
69
70 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
71 module_param(rnet_htable_size, int, 0444);
72 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
73
74 static int use_tcp_bonding = false;
75 module_param(use_tcp_bonding, int, 0444);
76 MODULE_PARM_DESC(use_tcp_bonding,
77                  "Set to 1 to use socklnd bonding. 0 to use Multi-Rail");
78
79 unsigned int lnet_numa_range = 0;
80 module_param(lnet_numa_range, uint, 0444);
81 MODULE_PARM_DESC(lnet_numa_range,
82                 "NUMA range to consider during Multi-Rail selection");
83
84 /*
85  * lnet_health_sensitivity determines by how much we decrement the health
86  * value on sending error. The value defaults to 100, which means health
87  * interface health is decremented by 100 points every failure.
88  */
89 unsigned int lnet_health_sensitivity = 100;
90 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
91 #ifdef HAVE_KERNEL_PARAM_OPS
92 static struct kernel_param_ops param_ops_health_sensitivity = {
93         .set = sensitivity_set,
94         .get = param_get_int,
95 };
96 #define param_check_health_sensitivity(name, p) \
97                 __param_check(name, p, int)
98 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
99 #else
100 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
101                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
102 #endif
103 MODULE_PARM_DESC(lnet_health_sensitivity,
104                 "Value to decrement the health value by on error");
105
106 /*
107  * lnet_recovery_interval determines how often we should perform recovery
108  * on unhealthy interfaces.
109  */
110 unsigned int lnet_recovery_interval = 1;
111 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
112 #ifdef HAVE_KERNEL_PARAM_OPS
113 static struct kernel_param_ops param_ops_recovery_interval = {
114         .set = recovery_interval_set,
115         .get = param_get_int,
116 };
117 #define param_check_recovery_interval(name, p) \
118                 __param_check(name, p, int)
119 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
120 #else
121 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
122                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
123 #endif
124 MODULE_PARM_DESC(lnet_recovery_interval,
125                 "Interval to recover unhealthy interfaces in seconds");
126
127 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
128 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
129
130 static struct kernel_param_ops param_ops_interfaces_max = {
131         .set = intf_max_set,
132         .get = param_get_int,
133 };
134
135 #define param_check_interfaces_max(name, p) \
136                 __param_check(name, p, int)
137
138 #ifdef HAVE_KERNEL_PARAM_OPS
139 module_param(lnet_interfaces_max, interfaces_max, 0644);
140 #else
141 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
142                   &param_ops_interfaces_max, 0644);
143 #endif
144 MODULE_PARM_DESC(lnet_interfaces_max,
145                 "Maximum number of interfaces in a node.");
146
147 unsigned lnet_peer_discovery_disabled = 0;
148 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
149
150 static struct kernel_param_ops param_ops_discovery_disabled = {
151         .set = discovery_set,
152         .get = param_get_int,
153 };
154
155 #define param_check_discovery_disabled(name, p) \
156                 __param_check(name, p, int)
157 #ifdef HAVE_KERNEL_PARAM_OPS
158 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
159 #else
160 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
161                   &param_ops_discovery_disabled, 0644);
162 #endif
163 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
164                 "Set to 1 to disable peer discovery on this node.");
165
166 unsigned int lnet_drop_asym_route;
167 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
168
169 static struct kernel_param_ops param_ops_drop_asym_route = {
170         .set = drop_asym_route_set,
171         .get = param_get_int,
172 };
173
174 #define param_check_drop_asym_route(name, p)    \
175         __param_check(name, p, int)
176 #ifdef HAVE_KERNEL_PARAM_OPS
177 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
178 #else
179 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
180                   &param_ops_drop_asym_route, 0644);
181 #endif
182 MODULE_PARM_DESC(lnet_drop_asym_route,
183                  "Set to 1 to drop asymmetrical route messages.");
184
185 #define LNET_TRANSACTION_TIMEOUT_DEFAULT 50
186 unsigned int lnet_transaction_timeout = LNET_TRANSACTION_TIMEOUT_DEFAULT;
187 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
188 #ifdef HAVE_KERNEL_PARAM_OPS
189 static struct kernel_param_ops param_ops_transaction_timeout = {
190         .set = transaction_to_set,
191         .get = param_get_int,
192 };
193
194 #define param_check_transaction_timeout(name, p) \
195                 __param_check(name, p, int)
196 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
197 #else
198 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
199                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
200 #endif
201 MODULE_PARM_DESC(lnet_transaction_timeout,
202                 "Maximum number of seconds to wait for a peer response.");
203
204 #define LNET_RETRY_COUNT_DEFAULT 2
205 unsigned int lnet_retry_count = LNET_RETRY_COUNT_DEFAULT;
206 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
207 #ifdef HAVE_KERNEL_PARAM_OPS
208 static struct kernel_param_ops param_ops_retry_count = {
209         .set = retry_count_set,
210         .get = param_get_int,
211 };
212
213 #define param_check_retry_count(name, p) \
214                 __param_check(name, p, int)
215 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
216 #else
217 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
218                   &lnet_retry_count, S_IRUGO|S_IWUSR);
219 #endif
220 MODULE_PARM_DESC(lnet_retry_count,
221                  "Maximum number of times to retry transmitting a message");
222
223 unsigned int lnet_response_tracking = 3;
224 static int response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp);
225
226 #ifdef HAVE_KERNEL_PARAM_OPS
227 static struct kernel_param_ops param_ops_response_tracking = {
228         .set = response_tracking_set,
229         .get = param_get_int,
230 };
231
232 #define param_check_response_tracking(name, p)  \
233         __param_check(name, p, int)
234 module_param(lnet_response_tracking, response_tracking, 0644);
235 #else
236 module_param_call(lnet_response_tracking, response_tracking_set, param_get_int,
237                   &lnet_response_tracking, 0644);
238 #endif
239 MODULE_PARM_DESC(lnet_response_tracking,
240                  "(0|1|2|3) LNet Internal Only|GET Reply only|PUT ACK only|Full Tracking (default)");
241
242 #define LNET_LND_TIMEOUT_DEFAULT ((LNET_TRANSACTION_TIMEOUT_DEFAULT - 1) / \
243                                   (LNET_RETRY_COUNT_DEFAULT + 1))
244 unsigned int lnet_lnd_timeout = LNET_LND_TIMEOUT_DEFAULT;
245 static void lnet_set_lnd_timeout(void)
246 {
247         lnet_lnd_timeout = (lnet_transaction_timeout - 1) /
248                            (lnet_retry_count + 1);
249 }
250
251 unsigned int lnet_current_net_count;
252
253 /*
254  * This sequence number keeps track of how many times DLC was used to
255  * update the local NIs. It is incremented when a NI is added or
256  * removed and checked when sending a message to determine if there is
257  * a need to re-run the selection algorithm. See lnet_select_pathway()
258  * for more details on its usage.
259  */
260 static atomic_t lnet_dlc_seq_no = ATOMIC_INIT(0);
261
262 static int lnet_ping(struct lnet_process_id id, signed long timeout,
263                      struct lnet_process_id __user *ids, int n_ids);
264
265 static int lnet_discover(struct lnet_process_id id, __u32 force,
266                          struct lnet_process_id __user *ids, int n_ids);
267
268 static int
269 sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp)
270 {
271         int rc;
272         unsigned *sensitivity = (unsigned *)kp->arg;
273         unsigned long value;
274
275         rc = kstrtoul(val, 0, &value);
276         if (rc) {
277                 CERROR("Invalid module parameter value for 'lnet_health_sensitivity'\n");
278                 return rc;
279         }
280
281         /*
282          * The purpose of locking the api_mutex here is to ensure that
283          * the correct value ends up stored properly.
284          */
285         mutex_lock(&the_lnet.ln_api_mutex);
286
287         if (value > LNET_MAX_HEALTH_VALUE) {
288                 mutex_unlock(&the_lnet.ln_api_mutex);
289                 CERROR("Invalid health value. Maximum: %d value = %lu\n",
290                        LNET_MAX_HEALTH_VALUE, value);
291                 return -EINVAL;
292         }
293
294         if (*sensitivity != 0 && value == 0 && lnet_retry_count != 0) {
295                 lnet_retry_count = 0;
296                 lnet_set_lnd_timeout();
297         }
298
299         *sensitivity = value;
300
301         mutex_unlock(&the_lnet.ln_api_mutex);
302
303         return 0;
304 }
305
306 static int
307 recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp)
308 {
309         int rc;
310         unsigned *interval = (unsigned *)kp->arg;
311         unsigned long value;
312
313         rc = kstrtoul(val, 0, &value);
314         if (rc) {
315                 CERROR("Invalid module parameter value for 'lnet_recovery_interval'\n");
316                 return rc;
317         }
318
319         if (value < 1) {
320                 CERROR("lnet_recovery_interval must be at least 1 second\n");
321                 return -EINVAL;
322         }
323
324         /*
325          * The purpose of locking the api_mutex here is to ensure that
326          * the correct value ends up stored properly.
327          */
328         mutex_lock(&the_lnet.ln_api_mutex);
329
330         *interval = value;
331
332         mutex_unlock(&the_lnet.ln_api_mutex);
333
334         return 0;
335 }
336
337 static int
338 discovery_set(const char *val, cfs_kernel_param_arg_t *kp)
339 {
340         int rc;
341         unsigned *discovery_off = (unsigned *)kp->arg;
342         unsigned long value;
343         struct lnet_ping_buffer *pbuf;
344
345         rc = kstrtoul(val, 0, &value);
346         if (rc) {
347                 CERROR("Invalid module parameter value for 'lnet_peer_discovery_disabled'\n");
348                 return rc;
349         }
350
351         value = (value) ? 1 : 0;
352
353         /*
354          * The purpose of locking the api_mutex here is to ensure that
355          * the correct value ends up stored properly.
356          */
357         mutex_lock(&the_lnet.ln_api_mutex);
358
359         if (value == *discovery_off) {
360                 mutex_unlock(&the_lnet.ln_api_mutex);
361                 return 0;
362         }
363
364         /*
365          * We still want to set the discovery value even when LNet is not
366          * running. This is the case when LNet is being loaded and we want
367          * the module parameters to take effect. Otherwise if we're
368          * changing the value dynamically, we want to set it after
369          * updating the peers
370          */
371         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
372                 *discovery_off = value;
373                 mutex_unlock(&the_lnet.ln_api_mutex);
374                 return 0;
375         }
376
377         /* tell peers that discovery setting has changed */
378         lnet_net_lock(LNET_LOCK_EX);
379         pbuf = the_lnet.ln_ping_target;
380         if (value)
381                 pbuf->pb_info.pi_features &= ~LNET_PING_FEAT_DISCOVERY;
382         else
383                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
384         lnet_net_unlock(LNET_LOCK_EX);
385
386         /* only send a push when we're turning off discovery */
387         if (*discovery_off <= 0 && value > 0)
388                 lnet_push_update_to_peers(1);
389         *discovery_off = value;
390
391         mutex_unlock(&the_lnet.ln_api_mutex);
392
393         return 0;
394 }
395
396 static int
397 drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp)
398 {
399         int rc;
400         unsigned int *drop_asym_route = (unsigned int *)kp->arg;
401         unsigned long value;
402
403         rc = kstrtoul(val, 0, &value);
404         if (rc) {
405                 CERROR("Invalid module parameter value for "
406                        "'lnet_drop_asym_route'\n");
407                 return rc;
408         }
409
410         /*
411          * The purpose of locking the api_mutex here is to ensure that
412          * the correct value ends up stored properly.
413          */
414         mutex_lock(&the_lnet.ln_api_mutex);
415
416         if (value == *drop_asym_route) {
417                 mutex_unlock(&the_lnet.ln_api_mutex);
418                 return 0;
419         }
420
421         *drop_asym_route = value;
422
423         mutex_unlock(&the_lnet.ln_api_mutex);
424
425         return 0;
426 }
427
428 static int
429 transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp)
430 {
431         int rc;
432         unsigned *transaction_to = (unsigned *)kp->arg;
433         unsigned long value;
434
435         rc = kstrtoul(val, 0, &value);
436         if (rc) {
437                 CERROR("Invalid module parameter value for 'lnet_transaction_timeout'\n");
438                 return rc;
439         }
440
441         /*
442          * The purpose of locking the api_mutex here is to ensure that
443          * the correct value ends up stored properly.
444          */
445         mutex_lock(&the_lnet.ln_api_mutex);
446
447         if (value <= lnet_retry_count || value == 0) {
448                 mutex_unlock(&the_lnet.ln_api_mutex);
449                 CERROR("Invalid value for lnet_transaction_timeout (%lu). "
450                        "Has to be greater than lnet_retry_count (%u)\n",
451                        value, lnet_retry_count);
452                 return -EINVAL;
453         }
454
455         if (value == *transaction_to) {
456                 mutex_unlock(&the_lnet.ln_api_mutex);
457                 return 0;
458         }
459
460         *transaction_to = value;
461         /* Update the lnet_lnd_timeout now that we've modified the
462          * transaction timeout
463          */
464         lnet_set_lnd_timeout();
465
466         mutex_unlock(&the_lnet.ln_api_mutex);
467
468         return 0;
469 }
470
471 static int
472 retry_count_set(const char *val, cfs_kernel_param_arg_t *kp)
473 {
474         int rc;
475         unsigned *retry_count = (unsigned *)kp->arg;
476         unsigned long value;
477
478         rc = kstrtoul(val, 0, &value);
479         if (rc) {
480                 CERROR("Invalid module parameter value for 'lnet_retry_count'\n");
481                 return rc;
482         }
483
484         /*
485          * The purpose of locking the api_mutex here is to ensure that
486          * the correct value ends up stored properly.
487          */
488         mutex_lock(&the_lnet.ln_api_mutex);
489
490         if (lnet_health_sensitivity == 0 && value > 0) {
491                 mutex_unlock(&the_lnet.ln_api_mutex);
492                 CERROR("Can not set lnet_retry_count when health feature is turned off\n");
493                 return -EINVAL;
494         }
495
496         if (value > lnet_transaction_timeout) {
497                 mutex_unlock(&the_lnet.ln_api_mutex);
498                 CERROR("Invalid value for lnet_retry_count (%lu). "
499                        "Has to be smaller than lnet_transaction_timeout (%u)\n",
500                        value, lnet_transaction_timeout);
501                 return -EINVAL;
502         }
503
504         *retry_count = value;
505
506         /* Update the lnet_lnd_timeout now that we've modified the
507          * retry count
508          */
509         lnet_set_lnd_timeout();
510
511         mutex_unlock(&the_lnet.ln_api_mutex);
512
513         return 0;
514 }
515
516 static int
517 intf_max_set(const char *val, cfs_kernel_param_arg_t *kp)
518 {
519         int value, rc;
520
521         rc = kstrtoint(val, 0, &value);
522         if (rc) {
523                 CERROR("Invalid module parameter value for 'lnet_interfaces_max'\n");
524                 return rc;
525         }
526
527         if (value < LNET_INTERFACES_MIN) {
528                 CWARN("max interfaces provided are too small, setting to %d\n",
529                       LNET_INTERFACES_MAX_DEFAULT);
530                 value = LNET_INTERFACES_MAX_DEFAULT;
531         }
532
533         *(int *)kp->arg = value;
534
535         return 0;
536 }
537
538 static int
539 response_tracking_set(const char *val, cfs_kernel_param_arg_t *kp)
540 {
541         int rc;
542         unsigned long new_value;
543
544         rc = kstrtoul(val, 0, &new_value);
545         if (rc) {
546                 CERROR("Invalid value for 'lnet_response_tracking'\n");
547                 return -EINVAL;
548         }
549
550         if (new_value < 0 || new_value > 3) {
551                 CWARN("Invalid value (%lu) for 'lnet_response_tracking'\n",
552                       new_value);
553                 return -EINVAL;
554         }
555
556         lnet_response_tracking = new_value;
557
558         return 0;
559 }
560
561 static const char *
562 lnet_get_routes(void)
563 {
564         return routes;
565 }
566
567 static const char *
568 lnet_get_networks(void)
569 {
570         const char *nets;
571         int rc;
572
573         if (*networks != 0 && *ip2nets != 0) {
574                 LCONSOLE_ERROR_MSG(0x101, "Please specify EITHER 'networks' or "
575                                    "'ip2nets' but not both at once\n");
576                 return NULL;
577         }
578
579         if (*ip2nets != 0) {
580                 rc = lnet_parse_ip2nets(&nets, ip2nets);
581                 return (rc == 0) ? nets : NULL;
582         }
583
584         if (*networks != 0)
585                 return networks;
586
587         return "tcp";
588 }
589
590 static void
591 lnet_init_locks(void)
592 {
593         spin_lock_init(&the_lnet.ln_eq_wait_lock);
594         spin_lock_init(&the_lnet.ln_msg_resend_lock);
595         init_completion(&the_lnet.ln_mt_wait_complete);
596         mutex_init(&the_lnet.ln_lnd_mutex);
597 }
598
599 struct kmem_cache *lnet_mes_cachep;        /* MEs kmem_cache */
600 struct kmem_cache *lnet_small_mds_cachep;  /* <= LNET_SMALL_MD_SIZE bytes
601                                             *  MDs kmem_cache */
602 struct kmem_cache *lnet_rspt_cachep;       /* response tracker cache */
603 struct kmem_cache *lnet_msg_cachep;
604
605 static int
606 lnet_slab_setup(void)
607 {
608         /* create specific kmem_cache for MEs and small MDs (i.e., originally
609          * allocated in <size-xxx> kmem_cache).
610          */
611         lnet_mes_cachep = kmem_cache_create("lnet_MEs", sizeof(struct lnet_me),
612                                             0, 0, NULL);
613         if (!lnet_mes_cachep)
614                 return -ENOMEM;
615
616         lnet_small_mds_cachep = kmem_cache_create("lnet_small_MDs",
617                                                   LNET_SMALL_MD_SIZE, 0, 0,
618                                                   NULL);
619         if (!lnet_small_mds_cachep)
620                 return -ENOMEM;
621
622         lnet_rspt_cachep = kmem_cache_create("lnet_rspt", sizeof(struct lnet_rsp_tracker),
623                                             0, 0, NULL);
624         if (!lnet_rspt_cachep)
625                 return -ENOMEM;
626
627         lnet_msg_cachep = kmem_cache_create("lnet_msg", sizeof(struct lnet_msg),
628                                             0, 0, NULL);
629         if (!lnet_msg_cachep)
630                 return -ENOMEM;
631
632         return 0;
633 }
634
635 static void
636 lnet_slab_cleanup(void)
637 {
638         if (lnet_msg_cachep) {
639                 kmem_cache_destroy(lnet_msg_cachep);
640                 lnet_msg_cachep = NULL;
641         }
642
643
644         if (lnet_rspt_cachep) {
645                 kmem_cache_destroy(lnet_rspt_cachep);
646                 lnet_rspt_cachep = NULL;
647         }
648
649         if (lnet_small_mds_cachep) {
650                 kmem_cache_destroy(lnet_small_mds_cachep);
651                 lnet_small_mds_cachep = NULL;
652         }
653
654         if (lnet_mes_cachep) {
655                 kmem_cache_destroy(lnet_mes_cachep);
656                 lnet_mes_cachep = NULL;
657         }
658 }
659
660 static int
661 lnet_create_remote_nets_table(void)
662 {
663         int               i;
664         struct list_head *hash;
665
666         LASSERT(the_lnet.ln_remote_nets_hash == NULL);
667         LASSERT(the_lnet.ln_remote_nets_hbits > 0);
668         CFS_ALLOC_PTR_ARRAY(hash, LNET_REMOTE_NETS_HASH_SIZE);
669         if (hash == NULL) {
670                 CERROR("Failed to create remote nets hash table\n");
671                 return -ENOMEM;
672         }
673
674         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
675                 INIT_LIST_HEAD(&hash[i]);
676         the_lnet.ln_remote_nets_hash = hash;
677         return 0;
678 }
679
680 static void
681 lnet_destroy_remote_nets_table(void)
682 {
683         int i;
684
685         if (the_lnet.ln_remote_nets_hash == NULL)
686                 return;
687
688         for (i = 0; i < LNET_REMOTE_NETS_HASH_SIZE; i++)
689                 LASSERT(list_empty(&the_lnet.ln_remote_nets_hash[i]));
690
691         CFS_FREE_PTR_ARRAY(the_lnet.ln_remote_nets_hash,
692                            LNET_REMOTE_NETS_HASH_SIZE);
693         the_lnet.ln_remote_nets_hash = NULL;
694 }
695
696 static void
697 lnet_destroy_locks(void)
698 {
699         if (the_lnet.ln_res_lock != NULL) {
700                 cfs_percpt_lock_free(the_lnet.ln_res_lock);
701                 the_lnet.ln_res_lock = NULL;
702         }
703
704         if (the_lnet.ln_net_lock != NULL) {
705                 cfs_percpt_lock_free(the_lnet.ln_net_lock);
706                 the_lnet.ln_net_lock = NULL;
707         }
708 }
709
710 static int
711 lnet_create_locks(void)
712 {
713         lnet_init_locks();
714
715         the_lnet.ln_res_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
716         if (the_lnet.ln_res_lock == NULL)
717                 goto failed;
718
719         the_lnet.ln_net_lock = cfs_percpt_lock_alloc(lnet_cpt_table());
720         if (the_lnet.ln_net_lock == NULL)
721                 goto failed;
722
723         return 0;
724
725  failed:
726         lnet_destroy_locks();
727         return -ENOMEM;
728 }
729
730 static void lnet_assert_wire_constants(void)
731 {
732         /* Wire protocol assertions generated by 'wirecheck'
733          * running on Linux robert.bartonsoftware.com 2.6.8-1.521
734          * #1 Mon Aug 16 09:01:18 EDT 2004 i686 athlon i386 GNU/Linux
735          * with gcc version 3.3.3 20040412 (Red Hat Linux 3.3.3-7) */
736
737         /* Constants... */
738         BUILD_BUG_ON(LNET_PROTO_TCP_MAGIC != 0xeebc0ded);
739         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MAJOR != 1);
740         BUILD_BUG_ON(LNET_PROTO_TCP_VERSION_MINOR != 0);
741         BUILD_BUG_ON(LNET_MSG_ACK != 0);
742         BUILD_BUG_ON(LNET_MSG_PUT != 1);
743         BUILD_BUG_ON(LNET_MSG_GET != 2);
744         BUILD_BUG_ON(LNET_MSG_REPLY != 3);
745         BUILD_BUG_ON(LNET_MSG_HELLO != 4);
746
747         /* Checks for struct lnet_handle_wire */
748         BUILD_BUG_ON((int)sizeof(struct lnet_handle_wire) != 16);
749         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
750                                    wh_interface_cookie) != 0);
751         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_interface_cookie) != 8);
752         BUILD_BUG_ON((int)offsetof(struct lnet_handle_wire,
753                                    wh_object_cookie) != 8);
754         BUILD_BUG_ON((int)sizeof(((struct lnet_handle_wire *)0)->wh_object_cookie) != 8);
755
756         /* Checks for struct struct lnet_magicversion */
757         BUILD_BUG_ON((int)sizeof(struct lnet_magicversion) != 8);
758         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, magic) != 0);
759         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->magic) != 4);
760         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion, version_major) != 4);
761         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_major) != 2);
762         BUILD_BUG_ON((int)offsetof(struct lnet_magicversion,
763                                    version_minor) != 6);
764         BUILD_BUG_ON((int)sizeof(((struct lnet_magicversion *)0)->version_minor) != 2);
765
766         /* Checks for struct struct lnet_hdr */
767         BUILD_BUG_ON((int)sizeof(struct lnet_hdr) != 72);
768         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, dest_nid) != 0);
769         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->dest_nid) != 8);
770         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, src_nid) != 8);
771         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->src_nid) != 8);
772         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, dest_pid) != 16);
773         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->dest_pid) != 4);
774         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, src_pid) != 20);
775         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->src_pid) != 4);
776         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, type) != 24);
777         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->type) != 4);
778         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, payload_length) != 28);
779         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->payload_length) != 4);
780         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg) != 32);
781         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg) != 40);
782
783         /* Ack */
784         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.dst_wmd) != 32);
785         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.dst_wmd) != 16);
786         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.match_bits) != 48);
787         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.match_bits) != 8);
788         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.ack.mlength) != 56);
789         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.ack.mlength) != 4);
790
791         /* Put */
792         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.ack_wmd) != 32);
793         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.ack_wmd) != 16);
794         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.match_bits) != 48);
795         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.match_bits) != 8);
796         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.hdr_data) != 56);
797         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.hdr_data) != 8);
798         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.ptl_index) != 64);
799         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.ptl_index) != 4);
800         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.put.offset) != 68);
801         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.put.offset) != 4);
802
803         /* Get */
804         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.return_wmd) != 32);
805         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.return_wmd) != 16);
806         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.match_bits) != 48);
807         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.match_bits) != 8);
808         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.ptl_index) != 56);
809         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.ptl_index) != 4);
810         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.src_offset) != 60);
811         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.src_offset) != 4);
812         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.get.sink_length) != 64);
813         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.get.sink_length) != 4);
814
815         /* Reply */
816         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.reply.dst_wmd) != 32);
817         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.reply.dst_wmd) != 16);
818
819         /* Hello */
820         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.hello.incarnation) != 32);
821         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.hello.incarnation) != 8);
822         BUILD_BUG_ON((int)offsetof(struct lnet_hdr, msg.hello.type) != 40);
823         BUILD_BUG_ON((int)sizeof(((struct lnet_hdr *)0)->msg.hello.type) != 4);
824
825         /* Checks for struct lnet_ni_status and related constants */
826         BUILD_BUG_ON(LNET_NI_STATUS_INVALID != 0x00000000);
827         BUILD_BUG_ON(LNET_NI_STATUS_UP != 0x15aac0de);
828         BUILD_BUG_ON(LNET_NI_STATUS_DOWN != 0xdeadface);
829
830         /* Checks for struct lnet_ni_status */
831         BUILD_BUG_ON((int)sizeof(struct lnet_ni_status) != 16);
832         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_nid) != 0);
833         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_nid) != 8);
834         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_status) != 8);
835         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_status) != 4);
836         BUILD_BUG_ON((int)offsetof(struct lnet_ni_status, ns_unused) != 12);
837         BUILD_BUG_ON((int)sizeof(((struct lnet_ni_status *)0)->ns_unused) != 4);
838
839         /* Checks for struct lnet_ping_info and related constants */
840         BUILD_BUG_ON(LNET_PROTO_PING_MAGIC != 0x70696E67);
841         BUILD_BUG_ON(LNET_PING_FEAT_INVAL != 0);
842         BUILD_BUG_ON(LNET_PING_FEAT_BASE != 1);
843         BUILD_BUG_ON(LNET_PING_FEAT_NI_STATUS != 2);
844         BUILD_BUG_ON(LNET_PING_FEAT_RTE_DISABLED != 4);
845         BUILD_BUG_ON(LNET_PING_FEAT_MULTI_RAIL != 8);
846         BUILD_BUG_ON(LNET_PING_FEAT_DISCOVERY != 16);
847         BUILD_BUG_ON(LNET_PING_FEAT_BITS != 31);
848
849         /* Checks for struct lnet_ping_info */
850         BUILD_BUG_ON((int)sizeof(struct lnet_ping_info) != 16);
851         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_magic) != 0);
852         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_magic) != 4);
853         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_features) != 4);
854         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_features) != 4);
855         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_pid) != 8);
856         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_pid) != 4);
857         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_nnis) != 12);
858         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_nnis) != 4);
859         BUILD_BUG_ON((int)offsetof(struct lnet_ping_info, pi_ni) != 16);
860         BUILD_BUG_ON((int)sizeof(((struct lnet_ping_info *)0)->pi_ni) != 0);
861 }
862
863 static const struct lnet_lnd *lnet_find_lnd_by_type(__u32 type)
864 {
865         const struct lnet_lnd *lnd;
866
867         /* holding lnd mutex */
868         if (type >= NUM_LNDS)
869                 return NULL;
870         lnd = the_lnet.ln_lnds[type];
871         LASSERT(!lnd || lnd->lnd_type == type);
872
873         return lnd;
874 }
875
876 unsigned int
877 lnet_get_lnd_timeout(void)
878 {
879         return lnet_lnd_timeout;
880 }
881 EXPORT_SYMBOL(lnet_get_lnd_timeout);
882
883 void
884 lnet_register_lnd(const struct lnet_lnd *lnd)
885 {
886         mutex_lock(&the_lnet.ln_lnd_mutex);
887
888         LASSERT(libcfs_isknown_lnd(lnd->lnd_type));
889         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == NULL);
890
891         the_lnet.ln_lnds[lnd->lnd_type] = lnd;
892
893         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
894
895         mutex_unlock(&the_lnet.ln_lnd_mutex);
896 }
897 EXPORT_SYMBOL(lnet_register_lnd);
898
899 void
900 lnet_unregister_lnd(const struct lnet_lnd *lnd)
901 {
902         mutex_lock(&the_lnet.ln_lnd_mutex);
903
904         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
905
906         the_lnet.ln_lnds[lnd->lnd_type] = NULL;
907         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
908
909         mutex_unlock(&the_lnet.ln_lnd_mutex);
910 }
911 EXPORT_SYMBOL(lnet_unregister_lnd);
912
913 static void
914 lnet_counters_get_common_locked(struct lnet_counters_common *common)
915 {
916         struct lnet_counters *ctr;
917         int i;
918
919         /* FIXME !!! Their is no assert_lnet_net_locked() to ensure this
920          * actually called under the protection of the lnet_net_lock.
921          */
922         memset(common, 0, sizeof(*common));
923
924         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
925                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
926                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
927                 common->lcc_errors       += ctr->lct_common.lcc_errors;
928                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
929                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
930                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
931                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
932                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
933                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
934                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
935                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
936         }
937 }
938
939 void
940 lnet_counters_get_common(struct lnet_counters_common *common)
941 {
942         lnet_net_lock(LNET_LOCK_EX);
943         lnet_counters_get_common_locked(common);
944         lnet_net_unlock(LNET_LOCK_EX);
945 }
946 EXPORT_SYMBOL(lnet_counters_get_common);
947
948 int
949 lnet_counters_get(struct lnet_counters *counters)
950 {
951         struct lnet_counters *ctr;
952         struct lnet_counters_health *health = &counters->lct_health;
953         int i, rc = 0;
954
955         memset(counters, 0, sizeof(*counters));
956
957         lnet_net_lock(LNET_LOCK_EX);
958
959         if (the_lnet.ln_state != LNET_STATE_RUNNING)
960                 GOTO(out_unlock, rc = -ENODEV);
961
962         lnet_counters_get_common_locked(&counters->lct_common);
963
964         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
965                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
966                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
967                 health->lch_response_timeout_count +=
968                                 ctr->lct_health.lch_response_timeout_count;
969                 health->lch_local_interrupt_count +=
970                                 ctr->lct_health.lch_local_interrupt_count;
971                 health->lch_local_dropped_count +=
972                                 ctr->lct_health.lch_local_dropped_count;
973                 health->lch_local_aborted_count +=
974                                 ctr->lct_health.lch_local_aborted_count;
975                 health->lch_local_no_route_count +=
976                                 ctr->lct_health.lch_local_no_route_count;
977                 health->lch_local_timeout_count +=
978                                 ctr->lct_health.lch_local_timeout_count;
979                 health->lch_local_error_count +=
980                                 ctr->lct_health.lch_local_error_count;
981                 health->lch_remote_dropped_count +=
982                                 ctr->lct_health.lch_remote_dropped_count;
983                 health->lch_remote_error_count +=
984                                 ctr->lct_health.lch_remote_error_count;
985                 health->lch_remote_timeout_count +=
986                                 ctr->lct_health.lch_remote_timeout_count;
987                 health->lch_network_timeout_count +=
988                                 ctr->lct_health.lch_network_timeout_count;
989         }
990 out_unlock:
991         lnet_net_unlock(LNET_LOCK_EX);
992         return rc;
993 }
994 EXPORT_SYMBOL(lnet_counters_get);
995
996 void
997 lnet_counters_reset(void)
998 {
999         struct lnet_counters *counters;
1000         int             i;
1001
1002         lnet_net_lock(LNET_LOCK_EX);
1003
1004         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1005                 goto avoid_reset;
1006
1007         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
1008                 memset(counters, 0, sizeof(struct lnet_counters));
1009 avoid_reset:
1010         lnet_net_unlock(LNET_LOCK_EX);
1011 }
1012
1013 static char *
1014 lnet_res_type2str(int type)
1015 {
1016         switch (type) {
1017         default:
1018                 LBUG();
1019         case LNET_COOKIE_TYPE_MD:
1020                 return "MD";
1021         case LNET_COOKIE_TYPE_ME:
1022                 return "ME";
1023         case LNET_COOKIE_TYPE_EQ:
1024                 return "EQ";
1025         }
1026 }
1027
1028 static void
1029 lnet_res_container_cleanup(struct lnet_res_container *rec)
1030 {
1031         int     count = 0;
1032
1033         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
1034                 return;
1035
1036         while (!list_empty(&rec->rec_active)) {
1037                 struct list_head *e = rec->rec_active.next;
1038
1039                 list_del_init(e);
1040                 if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
1041                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
1042
1043                 } else { /* NB: Active MEs should be attached on portals */
1044                         LBUG();
1045                 }
1046                 count++;
1047         }
1048
1049         if (count > 0) {
1050                 /* Found alive MD/ME/EQ, user really should unlink/free
1051                  * all of them before finalize LNet, but if someone didn't,
1052                  * we have to recycle garbage for him */
1053                 CERROR("%d active elements on exit of %s container\n",
1054                        count, lnet_res_type2str(rec->rec_type));
1055         }
1056
1057         if (rec->rec_lh_hash != NULL) {
1058                 CFS_FREE_PTR_ARRAY(rec->rec_lh_hash, LNET_LH_HASH_SIZE);
1059                 rec->rec_lh_hash = NULL;
1060         }
1061
1062         rec->rec_type = 0; /* mark it as finalized */
1063 }
1064
1065 static int
1066 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
1067 {
1068         int     rc = 0;
1069         int     i;
1070
1071         LASSERT(rec->rec_type == 0);
1072
1073         rec->rec_type = type;
1074         INIT_LIST_HEAD(&rec->rec_active);
1075
1076         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1077
1078         /* Arbitrary choice of hash table size */
1079         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1080                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1081         if (rec->rec_lh_hash == NULL) {
1082                 rc = -ENOMEM;
1083                 goto out;
1084         }
1085
1086         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1087                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1088
1089         return 0;
1090
1091 out:
1092         CERROR("Failed to setup %s resource container\n",
1093                lnet_res_type2str(type));
1094         lnet_res_container_cleanup(rec);
1095         return rc;
1096 }
1097
1098 static void
1099 lnet_res_containers_destroy(struct lnet_res_container **recs)
1100 {
1101         struct lnet_res_container       *rec;
1102         int                             i;
1103
1104         cfs_percpt_for_each(rec, i, recs)
1105                 lnet_res_container_cleanup(rec);
1106
1107         cfs_percpt_free(recs);
1108 }
1109
1110 static struct lnet_res_container **
1111 lnet_res_containers_create(int type)
1112 {
1113         struct lnet_res_container       **recs;
1114         struct lnet_res_container       *rec;
1115         int                             rc;
1116         int                             i;
1117
1118         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1119         if (recs == NULL) {
1120                 CERROR("Failed to allocate %s resource containers\n",
1121                        lnet_res_type2str(type));
1122                 return NULL;
1123         }
1124
1125         cfs_percpt_for_each(rec, i, recs) {
1126                 rc = lnet_res_container_setup(rec, i, type);
1127                 if (rc != 0) {
1128                         lnet_res_containers_destroy(recs);
1129                         return NULL;
1130                 }
1131         }
1132
1133         return recs;
1134 }
1135
1136 struct lnet_libhandle *
1137 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1138 {
1139         /* ALWAYS called with lnet_res_lock held */
1140         struct list_head        *head;
1141         struct lnet_libhandle   *lh;
1142         unsigned int            hash;
1143
1144         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1145                 return NULL;
1146
1147         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1148         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1149
1150         list_for_each_entry(lh, head, lh_hash_chain) {
1151                 if (lh->lh_cookie == cookie)
1152                         return lh;
1153         }
1154
1155         return NULL;
1156 }
1157
1158 void
1159 lnet_res_lh_initialize(struct lnet_res_container *rec,
1160                        struct lnet_libhandle *lh)
1161 {
1162         /* ALWAYS called with lnet_res_lock held */
1163         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1164         unsigned int    hash;
1165
1166         lh->lh_cookie = rec->rec_lh_cookie;
1167         rec->rec_lh_cookie += 1 << ibits;
1168
1169         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1170
1171         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1172 }
1173
1174 struct list_head **
1175 lnet_create_array_of_queues(void)
1176 {
1177         struct list_head **qs;
1178         struct list_head *q;
1179         int i;
1180
1181         qs = cfs_percpt_alloc(lnet_cpt_table(),
1182                               sizeof(struct list_head));
1183         if (!qs) {
1184                 CERROR("Failed to allocate queues\n");
1185                 return NULL;
1186         }
1187
1188         cfs_percpt_for_each(q, i, qs)
1189                 INIT_LIST_HEAD(q);
1190
1191         return qs;
1192 }
1193
1194 static int lnet_unprepare(void);
1195
1196 static int
1197 lnet_prepare(lnet_pid_t requested_pid)
1198 {
1199         /* Prepare to bring up the network */
1200         struct lnet_res_container **recs;
1201         int                       rc = 0;
1202
1203         if (requested_pid == LNET_PID_ANY) {
1204                 /* Don't instantiate LNET just for me */
1205                 return -ENETDOWN;
1206         }
1207
1208         LASSERT(the_lnet.ln_refcount == 0);
1209
1210         the_lnet.ln_routing = 0;
1211
1212         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1213         the_lnet.ln_pid = requested_pid;
1214
1215         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1216         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1217         INIT_LIST_HEAD(&the_lnet.ln_nets);
1218         INIT_LIST_HEAD(&the_lnet.ln_routers);
1219         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1220         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1221         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1222         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1223         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1224         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1225         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1226         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1227         the_lnet.ln_mt_handler = NULL;
1228         init_completion(&the_lnet.ln_started);
1229
1230         rc = lnet_slab_setup();
1231         if (rc != 0)
1232                 goto failed;
1233
1234         rc = lnet_create_remote_nets_table();
1235         if (rc != 0)
1236                 goto failed;
1237
1238         /*
1239          * NB the interface cookie in wire handles guards against delayed
1240          * replies and ACKs appearing valid after reboot.
1241          */
1242         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1243
1244         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1245                                                 sizeof(struct lnet_counters));
1246         if (the_lnet.ln_counters == NULL) {
1247                 CERROR("Failed to allocate counters for LNet\n");
1248                 rc = -ENOMEM;
1249                 goto failed;
1250         }
1251
1252         rc = lnet_peer_tables_create();
1253         if (rc != 0)
1254                 goto failed;
1255
1256         rc = lnet_msg_containers_create();
1257         if (rc != 0)
1258                 goto failed;
1259
1260         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1261                                       LNET_COOKIE_TYPE_EQ);
1262         if (rc != 0)
1263                 goto failed;
1264
1265         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1266         if (recs == NULL) {
1267                 rc = -ENOMEM;
1268                 goto failed;
1269         }
1270
1271         the_lnet.ln_md_containers = recs;
1272
1273         rc = lnet_portals_create();
1274         if (rc != 0) {
1275                 CERROR("Failed to create portals for LNet: %d\n", rc);
1276                 goto failed;
1277         }
1278
1279         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1280         if (!the_lnet.ln_mt_zombie_rstqs) {
1281                 rc = -ENOMEM;
1282                 goto failed;
1283         }
1284
1285         return 0;
1286
1287  failed:
1288         lnet_unprepare();
1289         return rc;
1290 }
1291
1292 static int
1293 lnet_unprepare (void)
1294 {
1295         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1296          * have shut down already, so it is safe to unlink and free all
1297          * descriptors, even those that appear committed to a network op (eg MD
1298          * with non-zero pending count) */
1299
1300         lnet_fail_nid(LNET_NID_ANY, 0);
1301
1302         LASSERT(the_lnet.ln_refcount == 0);
1303         LASSERT(list_empty(&the_lnet.ln_test_peers));
1304         LASSERT(list_empty(&the_lnet.ln_nets));
1305
1306         if (the_lnet.ln_mt_zombie_rstqs) {
1307                 lnet_clean_zombie_rstqs();
1308                 the_lnet.ln_mt_zombie_rstqs = NULL;
1309         }
1310
1311         lnet_assert_handler_unused(the_lnet.ln_mt_handler);
1312         the_lnet.ln_mt_handler = NULL;
1313
1314         lnet_portals_destroy();
1315
1316         if (the_lnet.ln_md_containers != NULL) {
1317                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1318                 the_lnet.ln_md_containers = NULL;
1319         }
1320
1321         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1322
1323         lnet_msg_containers_destroy();
1324         lnet_peer_uninit();
1325         lnet_rtrpools_free(0);
1326
1327         if (the_lnet.ln_counters != NULL) {
1328                 cfs_percpt_free(the_lnet.ln_counters);
1329                 the_lnet.ln_counters = NULL;
1330         }
1331         lnet_destroy_remote_nets_table();
1332         lnet_slab_cleanup();
1333
1334         return 0;
1335 }
1336
1337 struct lnet_ni  *
1338 lnet_net2ni_locked(__u32 net_id, int cpt)
1339 {
1340         struct lnet_ni   *ni;
1341         struct lnet_net  *net;
1342
1343         LASSERT(cpt != LNET_LOCK_EX);
1344
1345         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1346                 if (net->net_id == net_id) {
1347                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1348                                         ni_netlist);
1349                         return ni;
1350                 }
1351         }
1352
1353         return NULL;
1354 }
1355
1356 struct lnet_ni *
1357 lnet_net2ni_addref(__u32 net)
1358 {
1359         struct lnet_ni *ni;
1360
1361         lnet_net_lock(0);
1362         ni = lnet_net2ni_locked(net, 0);
1363         if (ni)
1364                 lnet_ni_addref_locked(ni, 0);
1365         lnet_net_unlock(0);
1366
1367         return ni;
1368 }
1369 EXPORT_SYMBOL(lnet_net2ni_addref);
1370
1371 struct lnet_net *
1372 lnet_get_net_locked(__u32 net_id)
1373 {
1374         struct lnet_net  *net;
1375
1376         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1377                 if (net->net_id == net_id)
1378                         return net;
1379         }
1380
1381         return NULL;
1382 }
1383
1384 unsigned int
1385 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1386 {
1387         __u64           key = nid;
1388         unsigned int    val;
1389
1390         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1391
1392         if (number == 1)
1393                 return 0;
1394
1395         val = hash_long(key, LNET_CPT_BITS);
1396         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1397         if (val < number)
1398                 return val;
1399
1400         return (unsigned int)(key + val + (val >> 1)) % number;
1401 }
1402
1403 int
1404 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1405 {
1406         struct lnet_net *net;
1407
1408         /* must called with hold of lnet_net_lock */
1409         if (LNET_CPT_NUMBER == 1)
1410                 return 0; /* the only one */
1411
1412         /*
1413          * If NI is provided then use the CPT identified in the NI cpt
1414          * list if one exists. If one doesn't exist, then that NI is
1415          * associated with all CPTs and it follows that the net it belongs
1416          * to is implicitly associated with all CPTs, so just hash the nid
1417          * and return that.
1418          */
1419         if (ni != NULL) {
1420                 if (ni->ni_cpts != NULL)
1421                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1422                                                              ni->ni_ncpts)];
1423                 else
1424                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1425         }
1426
1427         /* no NI provided so look at the net */
1428         net = lnet_get_net_locked(LNET_NIDNET(nid));
1429
1430         if (net != NULL && net->net_cpts != NULL) {
1431                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1432         }
1433
1434         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1435 }
1436
1437 int
1438 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1439 {
1440         int     cpt;
1441         int     cpt2;
1442
1443         if (LNET_CPT_NUMBER == 1)
1444                 return 0; /* the only one */
1445
1446         cpt = lnet_net_lock_current();
1447
1448         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1449
1450         lnet_net_unlock(cpt);
1451
1452         return cpt2;
1453 }
1454 EXPORT_SYMBOL(lnet_cpt_of_nid);
1455
1456 int
1457 lnet_islocalnet_locked(__u32 net_id)
1458 {
1459         struct lnet_net *net;
1460         bool local;
1461
1462         net = lnet_get_net_locked(net_id);
1463
1464         local = net != NULL;
1465
1466         return local;
1467 }
1468
1469 int
1470 lnet_islocalnet(__u32 net_id)
1471 {
1472         int cpt;
1473         bool local;
1474
1475         cpt = lnet_net_lock_current();
1476
1477         local = lnet_islocalnet_locked(net_id);
1478
1479         lnet_net_unlock(cpt);
1480
1481         return local;
1482 }
1483
1484 struct lnet_ni  *
1485 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1486 {
1487         struct lnet_net  *net;
1488         struct lnet_ni   *ni;
1489
1490         LASSERT(cpt != LNET_LOCK_EX);
1491
1492         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1493                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1494                         if (ni->ni_nid == nid)
1495                                 return ni;
1496                 }
1497         }
1498
1499         return NULL;
1500 }
1501
1502 struct lnet_ni *
1503 lnet_nid2ni_addref(lnet_nid_t nid)
1504 {
1505         struct lnet_ni *ni;
1506
1507         lnet_net_lock(0);
1508         ni = lnet_nid2ni_locked(nid, 0);
1509         if (ni)
1510                 lnet_ni_addref_locked(ni, 0);
1511         lnet_net_unlock(0);
1512
1513         return ni;
1514 }
1515 EXPORT_SYMBOL(lnet_nid2ni_addref);
1516
1517 int
1518 lnet_islocalnid(lnet_nid_t nid)
1519 {
1520         struct lnet_ni  *ni;
1521         int             cpt;
1522
1523         cpt = lnet_net_lock_current();
1524         ni = lnet_nid2ni_locked(nid, cpt);
1525         lnet_net_unlock(cpt);
1526
1527         return ni != NULL;
1528 }
1529
1530 int
1531 lnet_count_acceptor_nets(void)
1532 {
1533         /* Return the # of NIs that need the acceptor. */
1534         int              count = 0;
1535         struct lnet_net  *net;
1536         int              cpt;
1537
1538         cpt = lnet_net_lock_current();
1539         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1540                 /* all socklnd type networks should have the acceptor
1541                  * thread started */
1542                 if (net->net_lnd->lnd_accept != NULL)
1543                         count++;
1544         }
1545
1546         lnet_net_unlock(cpt);
1547
1548         return count;
1549 }
1550
1551 struct lnet_ping_buffer *
1552 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1553 {
1554         struct lnet_ping_buffer *pbuf;
1555
1556         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1557         if (pbuf) {
1558                 pbuf->pb_nnis = nnis;
1559                 pbuf->pb_needs_post = false;
1560                 atomic_set(&pbuf->pb_refcnt, 1);
1561         }
1562
1563         return pbuf;
1564 }
1565
1566 void
1567 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1568 {
1569         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1570         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1571 }
1572
1573 static struct lnet_ping_buffer *
1574 lnet_ping_target_create(int nnis)
1575 {
1576         struct lnet_ping_buffer *pbuf;
1577
1578         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1579         if (pbuf == NULL) {
1580                 CERROR("Can't allocate ping source [%d]\n", nnis);
1581                 return NULL;
1582         }
1583
1584         pbuf->pb_info.pi_nnis = nnis;
1585         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1586         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1587         pbuf->pb_info.pi_features =
1588                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1589
1590         return pbuf;
1591 }
1592
1593 static inline int
1594 lnet_get_net_ni_count_locked(struct lnet_net *net)
1595 {
1596         struct lnet_ni  *ni;
1597         int             count = 0;
1598
1599         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1600                 count++;
1601
1602         return count;
1603 }
1604
1605 static inline int
1606 lnet_get_net_ni_count_pre(struct lnet_net *net)
1607 {
1608         struct lnet_ni  *ni;
1609         int             count = 0;
1610
1611         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1612                 count++;
1613
1614         return count;
1615 }
1616
1617 static inline int
1618 lnet_get_ni_count(void)
1619 {
1620         struct lnet_ni  *ni;
1621         struct lnet_net *net;
1622         int             count = 0;
1623
1624         lnet_net_lock(0);
1625
1626         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1627                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1628                         count++;
1629         }
1630
1631         lnet_net_unlock(0);
1632
1633         return count;
1634 }
1635
1636 int
1637 lnet_get_net_count(void)
1638 {
1639         struct lnet_net *net;
1640         int count = 0;
1641
1642         lnet_net_lock(0);
1643
1644         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1645                 count++;
1646         }
1647
1648         lnet_net_unlock(0);
1649
1650         return count;
1651 }
1652
1653 void
1654 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1655 {
1656         struct lnet_ni_status *stat;
1657         int nnis;
1658         int i;
1659
1660         __swab32s(&pbuf->pb_info.pi_magic);
1661         __swab32s(&pbuf->pb_info.pi_features);
1662         __swab32s(&pbuf->pb_info.pi_pid);
1663         __swab32s(&pbuf->pb_info.pi_nnis);
1664         nnis = pbuf->pb_info.pi_nnis;
1665         if (nnis > pbuf->pb_nnis)
1666                 nnis = pbuf->pb_nnis;
1667         for (i = 0; i < nnis; i++) {
1668                 stat = &pbuf->pb_info.pi_ni[i];
1669                 __swab64s(&stat->ns_nid);
1670                 __swab32s(&stat->ns_status);
1671         }
1672 }
1673
1674 int
1675 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1676 {
1677         if (!pinfo)
1678                 return -EINVAL;
1679         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1680                 return -EPROTO;
1681         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1682                 return -EPROTO;
1683         /* Loopback is guaranteed to be present */
1684         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1685                 return -ERANGE;
1686         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1687                 return -EPROTO;
1688         return 0;
1689 }
1690
1691 static void
1692 lnet_ping_target_destroy(void)
1693 {
1694         struct lnet_net *net;
1695         struct lnet_ni  *ni;
1696
1697         lnet_net_lock(LNET_LOCK_EX);
1698
1699         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1700                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1701                         lnet_ni_lock(ni);
1702                         ni->ni_status = NULL;
1703                         lnet_ni_unlock(ni);
1704                 }
1705         }
1706
1707         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1708         the_lnet.ln_ping_target = NULL;
1709
1710         lnet_net_unlock(LNET_LOCK_EX);
1711 }
1712
1713 static void
1714 lnet_ping_target_event_handler(struct lnet_event *event)
1715 {
1716         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1717
1718         if (event->unlinked)
1719                 lnet_ping_buffer_decref(pbuf);
1720 }
1721
1722 static int
1723 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1724                        struct lnet_handle_md *ping_mdh,
1725                        int ni_count, bool set_eq)
1726 {
1727         struct lnet_process_id id = {
1728                 .nid = LNET_NID_ANY,
1729                 .pid = LNET_PID_ANY
1730         };
1731         struct lnet_me *me;
1732         struct lnet_md md = { NULL };
1733         int rc;
1734
1735         if (set_eq)
1736                 the_lnet.ln_ping_target_handler =
1737                         lnet_ping_target_event_handler;
1738
1739         *ppbuf = lnet_ping_target_create(ni_count);
1740         if (*ppbuf == NULL) {
1741                 rc = -ENOMEM;
1742                 goto fail_free_eq;
1743         }
1744
1745         /* Ping target ME/MD */
1746         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1747                           LNET_PROTO_PING_MATCHBITS, 0,
1748                           LNET_UNLINK, LNET_INS_AFTER);
1749         if (IS_ERR(me)) {
1750                 rc = PTR_ERR(me);
1751                 CERROR("Can't create ping target ME: %d\n", rc);
1752                 goto fail_decref_ping_buffer;
1753         }
1754
1755         /* initialize md content */
1756         md.start     = &(*ppbuf)->pb_info;
1757         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1758         md.threshold = LNET_MD_THRESH_INF;
1759         md.max_size  = 0;
1760         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1761                        LNET_MD_MANAGE_REMOTE;
1762         md.handler   = the_lnet.ln_ping_target_handler;
1763         md.user_ptr  = *ppbuf;
1764
1765         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
1766         if (rc != 0) {
1767                 CERROR("Can't attach ping target MD: %d\n", rc);
1768                 goto fail_decref_ping_buffer;
1769         }
1770         lnet_ping_buffer_addref(*ppbuf);
1771
1772         return 0;
1773
1774 fail_decref_ping_buffer:
1775         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
1776         lnet_ping_buffer_decref(*ppbuf);
1777         *ppbuf = NULL;
1778 fail_free_eq:
1779         return rc;
1780 }
1781
1782 static void
1783 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1784                     struct lnet_handle_md *ping_mdh)
1785 {
1786         LNetMDUnlink(*ping_mdh);
1787         LNetInvalidateMDHandle(ping_mdh);
1788
1789         /* NB the MD could be busy; this just starts the unlink */
1790         wait_var_event_warning(&pbuf->pb_refcnt,
1791                                atomic_read(&pbuf->pb_refcnt) <= 1,
1792                                "Still waiting for ping data MD to unlink\n");
1793 }
1794
1795 static void
1796 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1797 {
1798         struct lnet_ni          *ni;
1799         struct lnet_net         *net;
1800         struct lnet_ni_status *ns;
1801         int                     i;
1802         int                     rc;
1803
1804         i = 0;
1805         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1806                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1807                         LASSERT(i < pbuf->pb_nnis);
1808
1809                         ns = &pbuf->pb_info.pi_ni[i];
1810
1811                         ns->ns_nid = ni->ni_nid;
1812
1813                         lnet_ni_lock(ni);
1814                         ns->ns_status = (ni->ni_status != NULL) ?
1815                                          ni->ni_status->ns_status :
1816                                                 LNET_NI_STATUS_UP;
1817                         ni->ni_status = ns;
1818                         lnet_ni_unlock(ni);
1819
1820                         i++;
1821                 }
1822         }
1823         /*
1824          * We (ab)use the ns_status of the loopback interface to
1825          * transmit the sequence number. The first interface listed
1826          * must be the loopback interface.
1827          */
1828         rc = lnet_ping_info_validate(&pbuf->pb_info);
1829         if (rc) {
1830                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1831                 LBUG();
1832         }
1833         LNET_PING_BUFFER_SEQNO(pbuf) =
1834                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1835 }
1836
1837 static void
1838 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1839                         struct lnet_handle_md ping_mdh)
1840 {
1841         struct lnet_ping_buffer *old_pbuf = NULL;
1842         struct lnet_handle_md old_ping_md;
1843
1844         /* switch the NIs to point to the new ping info created */
1845         lnet_net_lock(LNET_LOCK_EX);
1846
1847         if (!the_lnet.ln_routing)
1848                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1849         if (!lnet_peer_discovery_disabled)
1850                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1851
1852         /* Ensure only known feature bits have been set. */
1853         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1854         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1855
1856         lnet_ping_target_install_locked(pbuf);
1857
1858         if (the_lnet.ln_ping_target) {
1859                 old_pbuf = the_lnet.ln_ping_target;
1860                 old_ping_md = the_lnet.ln_ping_target_md;
1861         }
1862         the_lnet.ln_ping_target_md = ping_mdh;
1863         the_lnet.ln_ping_target = pbuf;
1864
1865         lnet_net_unlock(LNET_LOCK_EX);
1866
1867         if (old_pbuf) {
1868                 /* unlink and free the old ping info */
1869                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1870                 lnet_ping_buffer_decref(old_pbuf);
1871         }
1872
1873         lnet_push_update_to_peers(0);
1874 }
1875
1876 static void
1877 lnet_ping_target_fini(void)
1878 {
1879         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1880                             &the_lnet.ln_ping_target_md);
1881
1882         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
1883         lnet_ping_target_destroy();
1884 }
1885
1886 /* Resize the push target. */
1887 int lnet_push_target_resize(void)
1888 {
1889         struct lnet_handle_md mdh;
1890         struct lnet_handle_md old_mdh;
1891         struct lnet_ping_buffer *pbuf;
1892         struct lnet_ping_buffer *old_pbuf;
1893         int nnis;
1894         int rc;
1895
1896 again:
1897         nnis = the_lnet.ln_push_target_nnis;
1898         if (nnis <= 0) {
1899                 CDEBUG(D_NET, "Invalid nnis %d\n", nnis);
1900                 return -EINVAL;
1901         }
1902
1903         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
1904          * dropped when we need to resize again (see "old_pbuf" below) or when
1905          * LNet is shutdown (see lnet_push_target_fini())
1906          */
1907         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1908         if (!pbuf) {
1909                 CDEBUG(D_NET, "Can't allocate pbuf for nnis %d\n", nnis);
1910                 return -ENOMEM;
1911         }
1912
1913         rc = lnet_push_target_post(pbuf, &mdh);
1914         if (rc) {
1915                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
1916                 lnet_ping_buffer_decref(pbuf);
1917                 return rc;
1918         }
1919
1920         lnet_net_lock(LNET_LOCK_EX);
1921         old_pbuf = the_lnet.ln_push_target;
1922         old_mdh = the_lnet.ln_push_target_md;
1923         the_lnet.ln_push_target = pbuf;
1924         the_lnet.ln_push_target_md = mdh;
1925         lnet_net_unlock(LNET_LOCK_EX);
1926
1927         if (old_pbuf) {
1928                 LNetMDUnlink(old_mdh);
1929                 /* Drop ref set by lnet_ping_buffer_alloc() */
1930                 lnet_ping_buffer_decref(old_pbuf);
1931         }
1932
1933         /* Received another push or reply that requires a larger buffer */
1934         if (nnis < the_lnet.ln_push_target_nnis)
1935                 goto again;
1936
1937         CDEBUG(D_NET, "nnis %d success\n", nnis);
1938         return 0;
1939 }
1940
1941 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
1942                           struct lnet_handle_md *mdhp)
1943 {
1944         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1945         struct lnet_md md = { NULL };
1946         struct lnet_me *me;
1947         int rc;
1948
1949         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1950                           LNET_PROTO_PING_MATCHBITS, 0,
1951                           LNET_UNLINK, LNET_INS_AFTER);
1952         if (IS_ERR(me)) {
1953                 rc = PTR_ERR(me);
1954                 CERROR("Can't create push target ME: %d\n", rc);
1955                 return rc;
1956         }
1957
1958         pbuf->pb_needs_post = false;
1959
1960         /* This reference is dropped by lnet_push_target_event_handler() */
1961         lnet_ping_buffer_addref(pbuf);
1962
1963         /* initialize md content */
1964         md.start     = &pbuf->pb_info;
1965         md.length    = LNET_PING_INFO_SIZE(pbuf->pb_nnis);
1966         md.threshold = 1;
1967         md.max_size  = 0;
1968         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
1969         md.user_ptr  = pbuf;
1970         md.handler   = the_lnet.ln_push_target_handler;
1971
1972         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
1973         if (rc) {
1974                 CERROR("Can't attach push MD: %d\n", rc);
1975                 lnet_ping_buffer_decref(pbuf);
1976                 pbuf->pb_needs_post = true;
1977                 return rc;
1978         }
1979
1980         CDEBUG(D_NET, "posted push target %p\n", pbuf);
1981
1982         return 0;
1983 }
1984
1985 static void lnet_push_target_event_handler(struct lnet_event *ev)
1986 {
1987         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
1988
1989         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
1990                ev->unlinked);
1991
1992         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1993                 lnet_swap_pinginfo(pbuf);
1994
1995         if (ev->type == LNET_EVENT_UNLINK) {
1996                 /* Drop ref added by lnet_push_target_post() */
1997                 lnet_ping_buffer_decref(pbuf);
1998                 return;
1999         }
2000
2001         lnet_peer_push_event(ev);
2002         if (ev->unlinked)
2003                 /* Drop ref added by lnet_push_target_post */
2004                 lnet_ping_buffer_decref(pbuf);
2005 }
2006
2007 /* Initialize the push target. */
2008 static int lnet_push_target_init(void)
2009 {
2010         int rc;
2011
2012         if (the_lnet.ln_push_target)
2013                 return -EALREADY;
2014
2015         the_lnet.ln_push_target_handler =
2016                 lnet_push_target_event_handler;
2017
2018         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2019         LASSERT(rc == 0);
2020
2021         /* Start at the required minimum, we'll enlarge if required. */
2022         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
2023
2024         rc = lnet_push_target_resize();
2025
2026         if (rc) {
2027                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2028                 the_lnet.ln_push_target_handler = NULL;
2029         }
2030
2031         return rc;
2032 }
2033
2034 /* Clean up the push target. */
2035 static void lnet_push_target_fini(void)
2036 {
2037         if (!the_lnet.ln_push_target)
2038                 return;
2039
2040         /* Unlink and invalidate to prevent new references. */
2041         LNetMDUnlink(the_lnet.ln_push_target_md);
2042         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2043
2044         /* Wait for the unlink to complete. */
2045         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2046                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2047                                "Still waiting for ping data MD to unlink\n");
2048
2049         /* Drop ref set by lnet_ping_buffer_alloc() */
2050         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2051         the_lnet.ln_push_target = NULL;
2052         the_lnet.ln_push_target_nnis = 0;
2053
2054         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2055         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2056         the_lnet.ln_push_target_handler = NULL;
2057 }
2058
2059 static int
2060 lnet_ni_tq_credits(struct lnet_ni *ni)
2061 {
2062         int     credits;
2063
2064         LASSERT(ni->ni_ncpts >= 1);
2065
2066         if (ni->ni_ncpts == 1)
2067                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2068
2069         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2070         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2071         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2072
2073         return credits;
2074 }
2075
2076 static void
2077 lnet_ni_unlink_locked(struct lnet_ni *ni)
2078 {
2079         /* move it to zombie list and nobody can find it anymore */
2080         LASSERT(!list_empty(&ni->ni_netlist));
2081         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2082         lnet_ni_decref_locked(ni, 0);
2083 }
2084
2085 static void
2086 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2087 {
2088         int             i;
2089         int             islo;
2090         struct lnet_ni  *ni;
2091         struct list_head *zombie_list = &net->net_ni_zombie;
2092
2093         /*
2094          * Now wait for the NIs I just nuked to show up on the zombie
2095          * list and shut them down in guaranteed thread context
2096          */
2097         i = 2;
2098         while (!list_empty(zombie_list)) {
2099                 int     *ref;
2100                 int     j;
2101
2102                 ni = list_entry(zombie_list->next,
2103                                 struct lnet_ni, ni_netlist);
2104                 list_del_init(&ni->ni_netlist);
2105                 /* the ni should be in deleting state. If it's not it's
2106                  * a bug */
2107                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2108                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2109                         if (*ref == 0)
2110                                 continue;
2111                         /* still busy, add it back to zombie list */
2112                         list_add(&ni->ni_netlist, zombie_list);
2113                         break;
2114                 }
2115
2116                 if (!list_empty(&ni->ni_netlist)) {
2117                         lnet_net_unlock(LNET_LOCK_EX);
2118                         ++i;
2119                         if ((i & (-i)) == i) {
2120                                 CDEBUG(D_WARNING,
2121                                        "Waiting for zombie LNI %s\n",
2122                                        libcfs_nid2str(ni->ni_nid));
2123                         }
2124                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2125                         lnet_net_lock(LNET_LOCK_EX);
2126                         continue;
2127                 }
2128
2129                 lnet_net_unlock(LNET_LOCK_EX);
2130
2131                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2132
2133                 LASSERT(!in_interrupt());
2134                 /* Holding the mutex makes it safe for lnd_shutdown
2135                  * to call module_put(). Module unload cannot finish
2136                  * until lnet_unregister_lnd() completes, and that
2137                  * requires the mutex.
2138                  */
2139                 mutex_lock(&the_lnet.ln_lnd_mutex);
2140                 (net->net_lnd->lnd_shutdown)(ni);
2141                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2142
2143                 if (!islo)
2144                         CDEBUG(D_LNI, "Removed LNI %s\n",
2145                               libcfs_nid2str(ni->ni_nid));
2146
2147                 lnet_ni_free(ni);
2148                 i = 2;
2149                 lnet_net_lock(LNET_LOCK_EX);
2150         }
2151 }
2152
2153 /* shutdown down the NI and release refcount */
2154 static void
2155 lnet_shutdown_lndni(struct lnet_ni *ni)
2156 {
2157         int i;
2158         struct lnet_net *net = ni->ni_net;
2159
2160         lnet_net_lock(LNET_LOCK_EX);
2161         lnet_ni_lock(ni);
2162         ni->ni_state = LNET_NI_STATE_DELETING;
2163         lnet_ni_unlock(ni);
2164         lnet_ni_unlink_locked(ni);
2165         lnet_incr_dlc_seq();
2166         lnet_net_unlock(LNET_LOCK_EX);
2167
2168         /* clear messages for this NI on the lazy portal */
2169         for (i = 0; i < the_lnet.ln_nportals; i++)
2170                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2171
2172         lnet_net_lock(LNET_LOCK_EX);
2173         lnet_clear_zombies_nis_locked(net);
2174         lnet_net_unlock(LNET_LOCK_EX);
2175 }
2176
2177 static void
2178 lnet_shutdown_lndnet(struct lnet_net *net)
2179 {
2180         struct lnet_ni *ni;
2181
2182         lnet_net_lock(LNET_LOCK_EX);
2183
2184         list_del_init(&net->net_list);
2185
2186         while (!list_empty(&net->net_ni_list)) {
2187                 ni = list_entry(net->net_ni_list.next,
2188                                 struct lnet_ni, ni_netlist);
2189                 lnet_net_unlock(LNET_LOCK_EX);
2190                 lnet_shutdown_lndni(ni);
2191                 lnet_net_lock(LNET_LOCK_EX);
2192         }
2193
2194         lnet_net_unlock(LNET_LOCK_EX);
2195
2196         /* Do peer table cleanup for this net */
2197         lnet_peer_tables_cleanup(net);
2198
2199         lnet_net_free(net);
2200 }
2201
2202 static void
2203 lnet_shutdown_lndnets(void)
2204 {
2205         struct lnet_net *net;
2206         LIST_HEAD(resend);
2207         struct lnet_msg *msg, *tmp;
2208
2209         /* NB called holding the global mutex */
2210
2211         /* All quiet on the API front */
2212         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2213         LASSERT(the_lnet.ln_refcount == 0);
2214
2215         lnet_net_lock(LNET_LOCK_EX);
2216         the_lnet.ln_state = LNET_STATE_STOPPING;
2217
2218         /*
2219          * move the nets to the zombie list to avoid them being
2220          * picked up for new work. LONET is also included in the
2221          * Nets that will be moved to the zombie list
2222          */
2223         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2224
2225         /* Drop the cached loopback Net. */
2226         if (the_lnet.ln_loni != NULL) {
2227                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2228                 the_lnet.ln_loni = NULL;
2229         }
2230         lnet_net_unlock(LNET_LOCK_EX);
2231
2232         /* iterate through the net zombie list and delete each net */
2233         while (!list_empty(&the_lnet.ln_net_zombie)) {
2234                 net = list_entry(the_lnet.ln_net_zombie.next,
2235                                  struct lnet_net, net_list);
2236                 lnet_shutdown_lndnet(net);
2237         }
2238
2239         spin_lock(&the_lnet.ln_msg_resend_lock);
2240         list_splice(&the_lnet.ln_msg_resend, &resend);
2241         spin_unlock(&the_lnet.ln_msg_resend_lock);
2242
2243         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2244                 list_del_init(&msg->msg_list);
2245                 msg->msg_no_resend = true;
2246                 lnet_finalize(msg, -ECANCELED);
2247         }
2248
2249         lnet_net_lock(LNET_LOCK_EX);
2250         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2251         lnet_net_unlock(LNET_LOCK_EX);
2252 }
2253
2254 static int
2255 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2256 {
2257         int                     rc = -EINVAL;
2258         struct lnet_tx_queue    *tq;
2259         int                     i;
2260         struct lnet_net         *net = ni->ni_net;
2261
2262         mutex_lock(&the_lnet.ln_lnd_mutex);
2263
2264         if (tun) {
2265                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2266                 ni->ni_lnd_tunables_set = true;
2267         }
2268
2269         rc = (net->net_lnd->lnd_startup)(ni);
2270
2271         mutex_unlock(&the_lnet.ln_lnd_mutex);
2272
2273         if (rc != 0) {
2274                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2275                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2276                 goto failed0;
2277         }
2278
2279         lnet_ni_lock(ni);
2280         ni->ni_state = LNET_NI_STATE_ACTIVE;
2281         lnet_ni_unlock(ni);
2282
2283         /* We keep a reference on the loopback net through the loopback NI */
2284         if (net->net_lnd->lnd_type == LOLND) {
2285                 lnet_ni_addref(ni);
2286                 LASSERT(the_lnet.ln_loni == NULL);
2287                 the_lnet.ln_loni = ni;
2288                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2289                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2290                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2291                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2292                 return 0;
2293         }
2294
2295         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2296             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2297                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2298                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2299                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2300                                         "" : "per-peer ");
2301                 /* shutdown the NI since if we get here then it must've already
2302                  * been started
2303                  */
2304                 lnet_shutdown_lndni(ni);
2305                 return -EINVAL;
2306         }
2307
2308         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2309                 tq->tq_credits_min =
2310                 tq->tq_credits_max =
2311                 tq->tq_credits = lnet_ni_tq_credits(ni);
2312         }
2313
2314         atomic_set(&ni->ni_tx_credits,
2315                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2316         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2317
2318         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2319                 libcfs_nid2str(ni->ni_nid),
2320                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2321                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2322                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2323                 ni->ni_net->net_tunables.lct_peer_timeout);
2324
2325         return 0;
2326 failed0:
2327         lnet_ni_free(ni);
2328         return rc;
2329 }
2330
2331 static int
2332 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2333 {
2334         struct lnet_ni *ni;
2335         struct lnet_net *net_l = NULL;
2336         LIST_HEAD(local_ni_list);
2337         int rc;
2338         int ni_count = 0;
2339         __u32 lnd_type;
2340         const struct lnet_lnd  *lnd;
2341         int peer_timeout =
2342                 net->net_tunables.lct_peer_timeout;
2343         int maxtxcredits =
2344                 net->net_tunables.lct_max_tx_credits;
2345         int peerrtrcredits =
2346                 net->net_tunables.lct_peer_rtr_credits;
2347
2348         /*
2349          * make sure that this net is unique. If it isn't then
2350          * we are adding interfaces to an already existing network, and
2351          * 'net' is just a convenient way to pass in the list.
2352          * if it is unique we need to find the LND and load it if
2353          * necessary.
2354          */
2355         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2356                 lnd_type = LNET_NETTYP(net->net_id);
2357
2358                 mutex_lock(&the_lnet.ln_lnd_mutex);
2359                 lnd = lnet_find_lnd_by_type(lnd_type);
2360
2361                 if (lnd == NULL) {
2362                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2363                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2364                         mutex_lock(&the_lnet.ln_lnd_mutex);
2365
2366                         lnd = lnet_find_lnd_by_type(lnd_type);
2367                         if (lnd == NULL) {
2368                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2369                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2370                                 libcfs_lnd2str(lnd_type),
2371                                 libcfs_lnd2modname(lnd_type), rc);
2372 #ifndef HAVE_MODULE_LOADING_SUPPORT
2373                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2374                                                 "compiled with kernel module "
2375                                                 "loading support.");
2376 #endif
2377                                 rc = -EINVAL;
2378                                 goto failed0;
2379                         }
2380                 }
2381
2382                 net->net_lnd = lnd;
2383
2384                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2385
2386                 net_l = net;
2387         }
2388
2389         /*
2390          * net_l: if the network being added is unique then net_l
2391          *        will point to that network
2392          *        if the network being added is not unique then
2393          *        net_l points to the existing network.
2394          *
2395          * When we enter the loop below, we'll pick NIs off he
2396          * network beign added and start them up, then add them to
2397          * a local ni list. Once we've successfully started all
2398          * the NIs then we join the local NI list (of started up
2399          * networks) with the net_l->net_ni_list, which should
2400          * point to the correct network to add the new ni list to
2401          *
2402          * If any of the new NIs fail to start up, then we want to
2403          * iterate through the local ni list, which should include
2404          * any NIs which were successfully started up, and shut
2405          * them down.
2406          *
2407          * After than we want to delete the network being added,
2408          * to avoid a memory leak.
2409          */
2410
2411         /*
2412          * When a network uses TCP bonding then all its interfaces
2413          * must be specified when the network is first defined: the
2414          * TCP bonding code doesn't allow for interfaces to be added
2415          * or removed.
2416          */
2417         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2418             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2419                 rc = -EINVAL;
2420                 goto failed0;
2421         }
2422
2423         while (!list_empty(&net->net_ni_added)) {
2424                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2425                                 ni_netlist);
2426                 list_del_init(&ni->ni_netlist);
2427
2428                 /* make sure that the the NI we're about to start
2429                  * up is actually unique. if it's not fail. */
2430                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2431                                         ni->ni_interfaces[0])) {
2432                         rc = -EEXIST;
2433                         goto failed1;
2434                 }
2435
2436                 /* adjust the pointer the parent network, just in case it
2437                  * the net is a duplicate */
2438                 ni->ni_net = net_l;
2439
2440                 rc = lnet_startup_lndni(ni, tun);
2441
2442                 if (rc < 0)
2443                         goto failed1;
2444
2445                 lnet_ni_addref(ni);
2446                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2447
2448                 ni_count++;
2449         }
2450
2451         lnet_net_lock(LNET_LOCK_EX);
2452         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2453         lnet_incr_dlc_seq();
2454         lnet_net_unlock(LNET_LOCK_EX);
2455
2456         /* if the network is not unique then we don't want to keep
2457          * it around after we're done. Free it. Otherwise add that
2458          * net to the global the_lnet.ln_nets */
2459         if (net_l != net && net_l != NULL) {
2460                 /*
2461                  * TODO - note. currently the tunables can not be updated
2462                  * once added
2463                  */
2464                 lnet_net_free(net);
2465         } else {
2466                 /*
2467                  * restore tunables after it has been overwitten by the
2468                  * lnd
2469                  */
2470                 if (peer_timeout != -1)
2471                         net->net_tunables.lct_peer_timeout = peer_timeout;
2472                 if (maxtxcredits != -1)
2473                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2474                 if (peerrtrcredits != -1)
2475                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2476
2477                 lnet_net_lock(LNET_LOCK_EX);
2478                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2479                 lnet_net_unlock(LNET_LOCK_EX);
2480         }
2481
2482         /* update net count */
2483         lnet_current_net_count = lnet_get_net_count();
2484
2485         return ni_count;
2486
2487 failed1:
2488         /*
2489          * shutdown the new NIs that are being started up
2490          * free the NET being started
2491          */
2492         while (!list_empty(&local_ni_list)) {
2493                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2494                                 ni_netlist);
2495
2496                 lnet_shutdown_lndni(ni);
2497         }
2498
2499 failed0:
2500         lnet_net_free(net);
2501
2502         return rc;
2503 }
2504
2505 static int
2506 lnet_startup_lndnets(struct list_head *netlist)
2507 {
2508         struct lnet_net         *net;
2509         int                     rc;
2510         int                     ni_count = 0;
2511
2512         /*
2513          * Change to running state before bringing up the LNDs. This
2514          * allows lnet_shutdown_lndnets() to assert that we've passed
2515          * through here.
2516          */
2517         lnet_net_lock(LNET_LOCK_EX);
2518         the_lnet.ln_state = LNET_STATE_RUNNING;
2519         lnet_net_unlock(LNET_LOCK_EX);
2520
2521         while (!list_empty(netlist)) {
2522                 net = list_entry(netlist->next, struct lnet_net, net_list);
2523                 list_del_init(&net->net_list);
2524
2525                 rc = lnet_startup_lndnet(net, NULL);
2526
2527                 if (rc < 0)
2528                         goto failed;
2529
2530                 ni_count += rc;
2531         }
2532
2533         return ni_count;
2534 failed:
2535         lnet_shutdown_lndnets();
2536
2537         return rc;
2538 }
2539
2540 /**
2541  * Initialize LNet library.
2542  *
2543  * Automatically called at module loading time. Caller has to call
2544  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2545  * latter returned 0. It must be called exactly once.
2546  *
2547  * \retval 0 on success
2548  * \retval -ve on failures.
2549  */
2550 int lnet_lib_init(void)
2551 {
2552         int rc;
2553
2554         lnet_assert_wire_constants();
2555
2556         /* refer to global cfs_cpt_table for now */
2557         the_lnet.ln_cpt_table = cfs_cpt_tab;
2558         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2559
2560         LASSERT(the_lnet.ln_cpt_number > 0);
2561         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2562                 /* we are under risk of consuming all lh_cookie */
2563                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2564                        "please change setting of CPT-table and retry\n",
2565                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2566                 return -E2BIG;
2567         }
2568
2569         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2570                 the_lnet.ln_cpt_bits++;
2571
2572         rc = lnet_create_locks();
2573         if (rc != 0) {
2574                 CERROR("Can't create LNet global locks: %d\n", rc);
2575                 return rc;
2576         }
2577
2578         the_lnet.ln_refcount = 0;
2579         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2580         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2581
2582         /* The hash table size is the number of bits it takes to express the set
2583          * ln_num_routes, minus 1 (better to under estimate than over so we
2584          * don't waste memory). */
2585         if (rnet_htable_size <= 0)
2586                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2587         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2588                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2589         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2590                                            order_base_2(rnet_htable_size) - 1);
2591
2592         /* All LNDs apart from the LOLND are in separate modules.  They
2593          * register themselves when their module loads, and unregister
2594          * themselves when their module is unloaded. */
2595         lnet_register_lnd(&the_lolnd);
2596         return 0;
2597 }
2598
2599 /**
2600  * Finalize LNet library.
2601  *
2602  * \pre lnet_lib_init() called with success.
2603  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2604  *
2605  * As this happens at module-unload, all lnds must already be unloaded,
2606  * so they must already be unregistered.
2607  */
2608 void lnet_lib_exit(void)
2609 {
2610         int i;
2611
2612         LASSERT(the_lnet.ln_refcount == 0);
2613         lnet_unregister_lnd(&the_lolnd);
2614         for (i = 0; i < NUM_LNDS; i++)
2615                 LASSERT(!the_lnet.ln_lnds[i]);
2616         lnet_destroy_locks();
2617 }
2618
2619 /**
2620  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2621  *
2622  * Users must call this function at least once before any other functions.
2623  * For each successful call there must be a corresponding call to
2624  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2625  * ignored.
2626  *
2627  * The PID used by LNet may be different from the one requested.
2628  * See LNetGetId().
2629  *
2630  * \param requested_pid PID requested by the caller.
2631  *
2632  * \return >= 0 on success, and < 0 error code on failures.
2633  */
2634 int
2635 LNetNIInit(lnet_pid_t requested_pid)
2636 {
2637         int                     im_a_router = 0;
2638         int                     rc;
2639         int                     ni_count;
2640         struct lnet_ping_buffer *pbuf;
2641         struct lnet_handle_md   ping_mdh;
2642         LIST_HEAD(net_head);
2643         struct lnet_net         *net;
2644
2645         mutex_lock(&the_lnet.ln_api_mutex);
2646
2647         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2648
2649         if (the_lnet.ln_refcount > 0) {
2650                 rc = the_lnet.ln_refcount++;
2651                 mutex_unlock(&the_lnet.ln_api_mutex);
2652                 return rc;
2653         }
2654
2655         rc = lnet_prepare(requested_pid);
2656         if (rc != 0) {
2657                 mutex_unlock(&the_lnet.ln_api_mutex);
2658                 return rc;
2659         }
2660
2661         /* create a network for Loopback network */
2662         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2663         if (net == NULL) {
2664                 rc = -ENOMEM;
2665                 goto err_empty_list;
2666         }
2667
2668         /* Add in the loopback NI */
2669         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2670                 rc = -ENOMEM;
2671                 goto err_empty_list;
2672         }
2673
2674         /* If LNet is being initialized via DLC it is possible
2675          * that the user requests not to load module parameters (ones which
2676          * are supported by DLC) on initialization.  Therefore, make sure not
2677          * to load networks, routes and forwarding from module parameters
2678          * in this case.  On cleanup in case of failure only clean up
2679          * routes if it has been loaded */
2680         if (!the_lnet.ln_nis_from_mod_params) {
2681                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2682                                          use_tcp_bonding);
2683                 if (rc < 0)
2684                         goto err_empty_list;
2685         }
2686
2687         ni_count = lnet_startup_lndnets(&net_head);
2688         if (ni_count < 0) {
2689                 rc = ni_count;
2690                 goto err_empty_list;
2691         }
2692
2693         if (!the_lnet.ln_nis_from_mod_params) {
2694                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2695                 if (rc != 0)
2696                         goto err_shutdown_lndnis;
2697
2698                 rc = lnet_rtrpools_alloc(im_a_router);
2699                 if (rc != 0)
2700                         goto err_destroy_routes;
2701         }
2702
2703         rc = lnet_acceptor_start();
2704         if (rc != 0)
2705                 goto err_destroy_routes;
2706
2707         the_lnet.ln_refcount = 1;
2708         /* Now I may use my own API functions... */
2709
2710         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2711         if (rc != 0)
2712                 goto err_acceptor_stop;
2713
2714         lnet_ping_target_update(pbuf, ping_mdh);
2715
2716         the_lnet.ln_mt_handler = lnet_mt_event_handler;
2717
2718         rc = lnet_push_target_init();
2719         if (rc != 0)
2720                 goto err_stop_ping;
2721
2722         rc = lnet_peer_discovery_start();
2723         if (rc != 0)
2724                 goto err_destroy_push_target;
2725
2726         rc = lnet_monitor_thr_start();
2727         if (rc != 0)
2728                 goto err_stop_discovery_thr;
2729
2730         lnet_fault_init();
2731         lnet_router_debugfs_init();
2732
2733         mutex_unlock(&the_lnet.ln_api_mutex);
2734
2735         complete_all(&the_lnet.ln_started);
2736
2737         /* wait for all routers to start */
2738         lnet_wait_router_start();
2739
2740         return 0;
2741
2742 err_stop_discovery_thr:
2743         lnet_peer_discovery_stop();
2744 err_destroy_push_target:
2745         lnet_push_target_fini();
2746 err_stop_ping:
2747         lnet_ping_target_fini();
2748 err_acceptor_stop:
2749         the_lnet.ln_refcount = 0;
2750         lnet_acceptor_stop();
2751 err_destroy_routes:
2752         if (!the_lnet.ln_nis_from_mod_params)
2753                 lnet_destroy_routes();
2754 err_shutdown_lndnis:
2755         lnet_shutdown_lndnets();
2756 err_empty_list:
2757         lnet_unprepare();
2758         LASSERT(rc < 0);
2759         mutex_unlock(&the_lnet.ln_api_mutex);
2760         while (!list_empty(&net_head)) {
2761                 struct lnet_net *net;
2762
2763                 net = list_entry(net_head.next, struct lnet_net, net_list);
2764                 list_del_init(&net->net_list);
2765                 lnet_net_free(net);
2766         }
2767         return rc;
2768 }
2769 EXPORT_SYMBOL(LNetNIInit);
2770
2771 /**
2772  * Stop LNet interfaces, routing, and forwarding.
2773  *
2774  * Users must call this function once for each successful call to LNetNIInit().
2775  * Once the LNetNIFini() operation has been started, the results of pending
2776  * API operations are undefined.
2777  *
2778  * \return always 0 for current implementation.
2779  */
2780 int
2781 LNetNIFini(void)
2782 {
2783         mutex_lock(&the_lnet.ln_api_mutex);
2784
2785         LASSERT(the_lnet.ln_refcount > 0);
2786
2787         if (the_lnet.ln_refcount != 1) {
2788                 the_lnet.ln_refcount--;
2789         } else {
2790                 LASSERT(!the_lnet.ln_niinit_self);
2791
2792                 lnet_fault_fini();
2793
2794                 lnet_router_debugfs_fini();
2795                 lnet_monitor_thr_stop();
2796                 lnet_peer_discovery_stop();
2797                 lnet_push_target_fini();
2798                 lnet_ping_target_fini();
2799
2800                 /* Teardown fns that use my own API functions BEFORE here */
2801                 the_lnet.ln_refcount = 0;
2802
2803                 lnet_acceptor_stop();
2804                 lnet_destroy_routes();
2805                 lnet_shutdown_lndnets();
2806                 lnet_unprepare();
2807         }
2808
2809         mutex_unlock(&the_lnet.ln_api_mutex);
2810         return 0;
2811 }
2812 EXPORT_SYMBOL(LNetNIFini);
2813
2814 /**
2815  * Grabs the ni data from the ni structure and fills the out
2816  * parameters
2817  *
2818  * \param[in] ni network        interface structure
2819  * \param[out] cfg_ni           NI config information
2820  * \param[out] tun              network and LND tunables
2821  */
2822 static void
2823 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2824                    struct lnet_ioctl_config_lnd_tunables *tun,
2825                    struct lnet_ioctl_element_stats *stats,
2826                    __u32 tun_size)
2827 {
2828         size_t min_size = 0;
2829         int i;
2830
2831         if (!ni || !cfg_ni || !tun)
2832                 return;
2833
2834         if (ni->ni_interfaces[0] != NULL) {
2835                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2836                         if (ni->ni_interfaces[i] != NULL) {
2837                                 strncpy(cfg_ni->lic_ni_intf[i],
2838                                         ni->ni_interfaces[i],
2839                                         sizeof(cfg_ni->lic_ni_intf[i]));
2840                         }
2841                 }
2842         }
2843
2844         cfg_ni->lic_nid = ni->ni_nid;
2845         if (ni->ni_nid == LNET_NID_LO_0)
2846                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2847         else
2848                 cfg_ni->lic_status = ni->ni_status->ns_status;
2849         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2850         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2851
2852         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2853
2854         if (stats) {
2855                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2856                                                        LNET_STATS_TYPE_SEND);
2857                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2858                                                        LNET_STATS_TYPE_RECV);
2859                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2860                                                        LNET_STATS_TYPE_DROP);
2861         }
2862
2863         /*
2864          * tun->lt_tun will always be present, but in order to be
2865          * backwards compatible, we need to deal with the cases when
2866          * tun->lt_tun is smaller than what the kernel has, because it
2867          * comes from an older version of a userspace program, then we'll
2868          * need to copy as much information as we have available space.
2869          */
2870         min_size = tun_size - sizeof(tun->lt_cmn);
2871         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2872
2873         /* copy over the cpts */
2874         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2875             ni->ni_cpts == NULL)  {
2876                 for (i = 0; i < ni->ni_ncpts; i++)
2877                         cfg_ni->lic_cpts[i] = i;
2878         } else {
2879                 for (i = 0;
2880                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2881                      i < LNET_MAX_SHOW_NUM_CPT;
2882                      i++)
2883                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2884         }
2885         cfg_ni->lic_ncpts = ni->ni_ncpts;
2886 }
2887
2888 /**
2889  * NOTE: This is a legacy function left in the code to be backwards
2890  * compatible with older userspace programs. It should eventually be
2891  * removed.
2892  *
2893  * Grabs the ni data from the ni structure and fills the out
2894  * parameters
2895  *
2896  * \param[in] ni network        interface structure
2897  * \param[out] config           config information
2898  */
2899 static void
2900 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2901                          struct lnet_ioctl_config_data *config)
2902 {
2903         struct lnet_ioctl_net_config *net_config;
2904         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2905         size_t min_size, tunable_size = 0;
2906         int i;
2907
2908         if (!ni || !config)
2909                 return;
2910
2911         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2912         if (!net_config)
2913                 return;
2914
2915         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2916                      ARRAY_SIZE(net_config->ni_interfaces));
2917
2918         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2919                 if (!ni->ni_interfaces[i])
2920                         break;
2921
2922                 strncpy(net_config->ni_interfaces[i],
2923                         ni->ni_interfaces[i],
2924                         sizeof(net_config->ni_interfaces[i]));
2925         }
2926
2927         config->cfg_nid = ni->ni_nid;
2928         config->cfg_config_u.cfg_net.net_peer_timeout =
2929                 ni->ni_net->net_tunables.lct_peer_timeout;
2930         config->cfg_config_u.cfg_net.net_max_tx_credits =
2931                 ni->ni_net->net_tunables.lct_max_tx_credits;
2932         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2933                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2934         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2935                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2936
2937         if (ni->ni_nid == LNET_NID_LO_0)
2938                 net_config->ni_status = LNET_NI_STATUS_UP;
2939         else
2940                 net_config->ni_status = ni->ni_status->ns_status;
2941
2942         if (ni->ni_cpts) {
2943                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2944
2945                 for (i = 0; i < num_cpts; i++)
2946                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2947
2948                 config->cfg_ncpts = num_cpts;
2949         }
2950
2951         /*
2952          * See if user land tools sent in a newer and larger version
2953          * of struct lnet_tunables than what the kernel uses.
2954          */
2955         min_size = sizeof(*config) + sizeof(*net_config);
2956
2957         if (config->cfg_hdr.ioc_len > min_size)
2958                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2959
2960         /* Don't copy too much data to user space */
2961         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2962         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2963
2964         if (lnd_cfg && min_size) {
2965                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2966                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2967
2968                 /* Tell user land that kernel side has less data */
2969                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2970                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2971                         config->cfg_hdr.ioc_len -= min_size;
2972                 }
2973         }
2974 }
2975
2976 struct lnet_ni *
2977 lnet_get_ni_idx_locked(int idx)
2978 {
2979         struct lnet_ni          *ni;
2980         struct lnet_net         *net;
2981
2982         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2983                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2984                         if (idx-- == 0)
2985                                 return ni;
2986                 }
2987         }
2988
2989         return NULL;
2990 }
2991
2992 struct lnet_ni *
2993 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2994 {
2995         struct lnet_ni          *ni;
2996         struct lnet_net         *net = mynet;
2997
2998         /*
2999          * It is possible that the net has been cleaned out while there is
3000          * a message being sent. This function accessed the net without
3001          * checking if the list is empty
3002          */
3003         if (prev == NULL) {
3004                 if (net == NULL)
3005                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3006                                         net_list);
3007                 if (list_empty(&net->net_ni_list))
3008                         return NULL;
3009                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3010                                 ni_netlist);
3011
3012                 return ni;
3013         }
3014
3015         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3016                 /* if you reached the end of the ni list and the net is
3017                  * specified, then there are no more nis in that net */
3018                 if (net != NULL)
3019                         return NULL;
3020
3021                 /* we reached the end of this net ni list. move to the
3022                  * next net */
3023                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3024                         /* no more nets and no more NIs. */
3025                         return NULL;
3026
3027                 /* get the next net */
3028                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3029                                  net_list);
3030                 if (list_empty(&net->net_ni_list))
3031                         return NULL;
3032                 /* get the ni on it */
3033                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3034                                 ni_netlist);
3035
3036                 return ni;
3037         }
3038
3039         if (list_empty(&prev->ni_netlist))
3040                 return NULL;
3041
3042         /* there are more nis left */
3043         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3044
3045         return ni;
3046 }
3047
3048 int
3049 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3050 {
3051         struct lnet_ni *ni;
3052         int cpt;
3053         int rc = -ENOENT;
3054         int idx = config->cfg_count;
3055
3056         cpt = lnet_net_lock_current();
3057
3058         ni = lnet_get_ni_idx_locked(idx);
3059
3060         if (ni != NULL) {
3061                 rc = 0;
3062                 lnet_ni_lock(ni);
3063                 lnet_fill_ni_info_legacy(ni, config);
3064                 lnet_ni_unlock(ni);
3065         }
3066
3067         lnet_net_unlock(cpt);
3068         return rc;
3069 }
3070
3071 int
3072 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3073                    struct lnet_ioctl_config_lnd_tunables *tun,
3074                    struct lnet_ioctl_element_stats *stats,
3075                    __u32 tun_size)
3076 {
3077         struct lnet_ni          *ni;
3078         int                     cpt;
3079         int                     rc = -ENOENT;
3080
3081         if (!cfg_ni || !tun || !stats)
3082                 return -EINVAL;
3083
3084         cpt = lnet_net_lock_current();
3085
3086         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3087
3088         if (ni) {
3089                 rc = 0;
3090                 lnet_ni_lock(ni);
3091                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3092                 lnet_ni_unlock(ni);
3093         }
3094
3095         lnet_net_unlock(cpt);
3096         return rc;
3097 }
3098
3099 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3100 {
3101         struct lnet_ni *ni;
3102         int cpt;
3103         int rc = -ENOENT;
3104
3105         if (!msg_stats)
3106                 return -EINVAL;
3107
3108         cpt = lnet_net_lock_current();
3109
3110         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3111
3112         if (ni) {
3113                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3114                 rc = 0;
3115         }
3116
3117         lnet_net_unlock(cpt);
3118
3119         return rc;
3120 }
3121
3122 static int lnet_add_net_common(struct lnet_net *net,
3123                                struct lnet_ioctl_config_lnd_tunables *tun)
3124 {
3125         __u32                   net_id;
3126         struct lnet_ping_buffer *pbuf;
3127         struct lnet_handle_md   ping_mdh;
3128         int                     rc;
3129         struct lnet_remotenet *rnet;
3130         int                     net_ni_count;
3131
3132         lnet_net_lock(LNET_LOCK_EX);
3133         rnet = lnet_find_rnet_locked(net->net_id);
3134         lnet_net_unlock(LNET_LOCK_EX);
3135         /*
3136          * make sure that the net added doesn't invalidate the current
3137          * configuration LNet is keeping
3138          */
3139         if (rnet) {
3140                 CERROR("Adding net %s will invalidate routing configuration\n",
3141                        libcfs_net2str(net->net_id));
3142                 lnet_net_free(net);
3143                 return -EUSERS;
3144         }
3145
3146         /*
3147          * make sure you calculate the correct number of slots in the ping
3148          * buffer. Since the ping info is a flattened list of all the NIs,
3149          * we should allocate enough slots to accomodate the number of NIs
3150          * which will be added.
3151          *
3152          * since ni hasn't been configured yet, use
3153          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3154          */
3155         net_ni_count = lnet_get_net_ni_count_pre(net);
3156
3157         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3158                                     net_ni_count + lnet_get_ni_count(),
3159                                     false);
3160         if (rc < 0) {
3161                 lnet_net_free(net);
3162                 return rc;
3163         }
3164
3165         if (tun)
3166                 memcpy(&net->net_tunables,
3167                        &tun->lt_cmn, sizeof(net->net_tunables));
3168         else
3169                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3170
3171         net_id = net->net_id;
3172
3173         rc = lnet_startup_lndnet(net,
3174                                  (tun) ? &tun->lt_tun : NULL);
3175         if (rc < 0)
3176                 goto failed;
3177
3178         lnet_net_lock(LNET_LOCK_EX);
3179         net = lnet_get_net_locked(net_id);
3180         lnet_net_unlock(LNET_LOCK_EX);
3181
3182         LASSERT(net);
3183
3184         /*
3185          * Start the acceptor thread if this is the first network
3186          * being added that requires the thread.
3187          */
3188         if (net->net_lnd->lnd_accept) {
3189                 rc = lnet_acceptor_start();
3190                 if (rc < 0) {
3191                         /* shutdown the net that we just started */
3192                         CERROR("Failed to start up acceptor thread\n");
3193                         lnet_shutdown_lndnet(net);
3194                         goto failed;
3195                 }
3196         }
3197
3198         lnet_net_lock(LNET_LOCK_EX);
3199         lnet_peer_net_added(net);
3200         lnet_net_unlock(LNET_LOCK_EX);
3201
3202         lnet_ping_target_update(pbuf, ping_mdh);
3203
3204         return 0;
3205
3206 failed:
3207         lnet_ping_md_unlink(pbuf, &ping_mdh);
3208         lnet_ping_buffer_decref(pbuf);
3209         return rc;
3210 }
3211
3212 static void
3213 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3214 {
3215         if (tun) {
3216                 if (!tun->lt_cmn.lct_peer_timeout)
3217                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3218                 if (!tun->lt_cmn.lct_peer_tx_credits)
3219                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3220                 if (!tun->lt_cmn.lct_max_tx_credits)
3221                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3222         }
3223 }
3224
3225 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3226                                       struct lnet_ioctl_config_lnd_tunables *tun)
3227 {
3228         struct lnet_net *net;
3229         const char *nets;
3230         int rc;
3231         LIST_HEAD(net_head);
3232
3233         rc = lnet_parse_ip2nets(&nets, ip2nets);
3234         if (rc < 0)
3235                 return rc;
3236
3237         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3238         if (rc < 0)
3239                 return rc;
3240
3241         lnet_set_tune_defaults(tun);
3242
3243         mutex_lock(&the_lnet.ln_api_mutex);
3244         while (!list_empty(&net_head)) {
3245                 net = list_entry(net_head.next, struct lnet_net, net_list);
3246                 list_del_init(&net->net_list);
3247                 rc = lnet_add_net_common(net, tun);
3248                 if (rc < 0)
3249                         goto out;
3250         }
3251
3252 out:
3253         mutex_unlock(&the_lnet.ln_api_mutex);
3254
3255         while (!list_empty(&net_head)) {
3256                 net = list_entry(net_head.next, struct lnet_net, net_list);
3257                 list_del_init(&net->net_list);
3258                 lnet_net_free(net);
3259         }
3260         return rc;
3261 }
3262
3263 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3264 {
3265         struct lnet_net *net;
3266         struct lnet_ni *ni;
3267         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3268         int rc, i;
3269         __u32 net_id, lnd_type;
3270
3271         /* get the tunables if they are available */
3272         if (conf->lic_cfg_hdr.ioc_len >=
3273             sizeof(*conf) + sizeof(*tun))
3274                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3275                         conf->lic_bulk;
3276
3277         /* handle legacy ip2nets from DLC */
3278         if (conf->lic_legacy_ip2nets[0] != '\0')
3279                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3280                                                   tun);
3281
3282         net_id = LNET_NIDNET(conf->lic_nid);
3283         lnd_type = LNET_NETTYP(net_id);
3284
3285         if (!libcfs_isknown_lnd(lnd_type)) {
3286                 CERROR("No valid net and lnd information provided\n");
3287                 return -EINVAL;
3288         }
3289
3290         net = lnet_net_alloc(net_id, NULL);
3291         if (!net)
3292                 return -ENOMEM;
3293
3294         for (i = 0; i < conf->lic_ncpts; i++) {
3295                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3296                         return -EINVAL;
3297         }
3298
3299         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3300                                        conf->lic_ni_intf[0]);
3301         if (!ni)
3302                 return -ENOMEM;
3303
3304         lnet_set_tune_defaults(tun);
3305
3306         mutex_lock(&the_lnet.ln_api_mutex);
3307
3308         rc = lnet_add_net_common(net, tun);
3309
3310         mutex_unlock(&the_lnet.ln_api_mutex);
3311
3312         return rc;
3313 }
3314
3315 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3316 {
3317         struct lnet_net  *net;
3318         struct lnet_ni *ni;
3319         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3320         struct lnet_ping_buffer *pbuf;
3321         struct lnet_handle_md  ping_mdh;
3322         int               rc;
3323         int               net_count;
3324         __u32             addr;
3325
3326         /* don't allow userspace to shutdown the LOLND */
3327         if (LNET_NETTYP(net_id) == LOLND)
3328                 return -EINVAL;
3329
3330         mutex_lock(&the_lnet.ln_api_mutex);
3331
3332         lnet_net_lock(0);
3333
3334         net = lnet_get_net_locked(net_id);
3335         if (!net) {
3336                 CERROR("net %s not found\n",
3337                        libcfs_net2str(net_id));
3338                 rc = -ENOENT;
3339                 goto unlock_net;
3340         }
3341
3342         addr = LNET_NIDADDR(conf->lic_nid);
3343         if (addr == 0) {
3344                 /* remove the entire net */
3345                 net_count = lnet_get_net_ni_count_locked(net);
3346
3347                 lnet_net_unlock(0);
3348
3349                 /* create and link a new ping info, before removing the old one */
3350                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3351                                         lnet_get_ni_count() - net_count,
3352                                         false);
3353                 if (rc != 0)
3354                         goto unlock_api_mutex;
3355
3356                 lnet_shutdown_lndnet(net);
3357
3358                 lnet_acceptor_stop();
3359
3360                 lnet_ping_target_update(pbuf, ping_mdh);
3361
3362                 goto unlock_api_mutex;
3363         }
3364
3365         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3366         if (!ni) {
3367                 CERROR("nid %s not found\n",
3368                        libcfs_nid2str(conf->lic_nid));
3369                 rc = -ENOENT;
3370                 goto unlock_net;
3371         }
3372
3373         net_count = lnet_get_net_ni_count_locked(net);
3374
3375         lnet_net_unlock(0);
3376
3377         /* create and link a new ping info, before removing the old one */
3378         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3379                                   lnet_get_ni_count() - 1, false);
3380         if (rc != 0)
3381                 goto unlock_api_mutex;
3382
3383         lnet_shutdown_lndni(ni);
3384
3385         lnet_acceptor_stop();
3386
3387         lnet_ping_target_update(pbuf, ping_mdh);
3388
3389         /* check if the net is empty and remove it if it is */
3390         if (net_count == 1)
3391                 lnet_shutdown_lndnet(net);
3392
3393         goto unlock_api_mutex;
3394
3395 unlock_net:
3396         lnet_net_unlock(0);
3397 unlock_api_mutex:
3398         mutex_unlock(&the_lnet.ln_api_mutex);
3399
3400         return rc;
3401 }
3402
3403 /*
3404  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3405  * They are only expected to be called for unique networks.
3406  * That can be as a result of older DLC library
3407  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3408  */
3409 int
3410 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3411 {
3412         struct lnet_net *net;
3413         LIST_HEAD(net_head);
3414         int rc;
3415         struct lnet_ioctl_config_lnd_tunables tun;
3416         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3417
3418         /* Create a net/ni structures for the network string */
3419         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3420         if (rc <= 0)
3421                 return rc == 0 ? -EINVAL : rc;
3422
3423         mutex_lock(&the_lnet.ln_api_mutex);
3424
3425         if (rc > 1) {
3426                 rc = -EINVAL; /* only add one network per call */
3427                 goto out_unlock_clean;
3428         }
3429
3430         net = list_entry(net_head.next, struct lnet_net, net_list);
3431         list_del_init(&net->net_list);
3432
3433         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3434
3435         memset(&tun, 0, sizeof(tun));
3436
3437         tun.lt_cmn.lct_peer_timeout =
3438           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3439                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3440         tun.lt_cmn.lct_peer_tx_credits =
3441           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3442                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3443         tun.lt_cmn.lct_peer_rtr_credits =
3444           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3445         tun.lt_cmn.lct_max_tx_credits =
3446           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3447                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3448
3449         rc = lnet_add_net_common(net, &tun);
3450
3451 out_unlock_clean:
3452         mutex_unlock(&the_lnet.ln_api_mutex);
3453         while (!list_empty(&net_head)) {
3454                 /* net_head list is empty in success case */
3455                 net = list_entry(net_head.next, struct lnet_net, net_list);
3456                 list_del_init(&net->net_list);
3457                 lnet_net_free(net);
3458         }
3459         return rc;
3460 }
3461
3462 int
3463 lnet_dyn_del_net(__u32 net_id)
3464 {
3465         struct lnet_net  *net;
3466         struct lnet_ping_buffer *pbuf;
3467         struct lnet_handle_md ping_mdh;
3468         int               rc;
3469         int               net_ni_count;
3470
3471         /* don't allow userspace to shutdown the LOLND */
3472         if (LNET_NETTYP(net_id) == LOLND)
3473                 return -EINVAL;
3474
3475         mutex_lock(&the_lnet.ln_api_mutex);
3476
3477         lnet_net_lock(0);
3478
3479         net = lnet_get_net_locked(net_id);
3480         if (net == NULL) {
3481                 lnet_net_unlock(0);
3482                 rc = -EINVAL;
3483                 goto out;
3484         }
3485
3486         net_ni_count = lnet_get_net_ni_count_locked(net);
3487
3488         lnet_net_unlock(0);
3489
3490         /* create and link a new ping info, before removing the old one */
3491         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3492                                     lnet_get_ni_count() - net_ni_count, false);
3493         if (rc != 0)
3494                 goto out;
3495
3496         lnet_shutdown_lndnet(net);
3497
3498         lnet_acceptor_stop();
3499
3500         lnet_ping_target_update(pbuf, ping_mdh);
3501
3502 out:
3503         mutex_unlock(&the_lnet.ln_api_mutex);
3504
3505         return rc;
3506 }
3507
3508 void lnet_incr_dlc_seq(void)
3509 {
3510         atomic_inc(&lnet_dlc_seq_no);
3511 }
3512
3513 __u32 lnet_get_dlc_seq_locked(void)
3514 {
3515         return atomic_read(&lnet_dlc_seq_no);
3516 }
3517
3518 static void
3519 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3520 {
3521         struct lnet_net *net;
3522         struct lnet_ni *ni;
3523
3524         lnet_net_lock(LNET_LOCK_EX);
3525         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3526                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3527                         if (ni->ni_nid == nid || all) {
3528                                 atomic_set(&ni->ni_healthv, value);
3529                                 if (list_empty(&ni->ni_recovery) &&
3530                                     value < LNET_MAX_HEALTH_VALUE) {
3531                                         CERROR("manually adding local NI %s to recovery\n",
3532                                                libcfs_nid2str(ni->ni_nid));
3533                                         list_add_tail(&ni->ni_recovery,
3534                                                       &the_lnet.ln_mt_localNIRecovq);
3535                                         lnet_ni_addref_locked(ni, 0);
3536                                 }
3537                                 if (!all) {
3538                                         lnet_net_unlock(LNET_LOCK_EX);
3539                                         return;
3540                                 }
3541                         }
3542                 }
3543         }
3544         lnet_net_unlock(LNET_LOCK_EX);
3545 }
3546
3547 static int
3548 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3549 {
3550         int cpt, rc = 0;
3551         struct lnet_ni *ni;
3552         lnet_nid_t nid = stats->hlni_nid;
3553
3554         cpt = lnet_net_lock_current();
3555         ni = lnet_nid2ni_locked(nid, cpt);
3556
3557         if (!ni) {
3558                 rc = -ENOENT;
3559                 goto unlock;
3560         }
3561
3562         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3563         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3564         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3565         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3566         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3567         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3568         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3569
3570 unlock:
3571         lnet_net_unlock(cpt);
3572
3573         return rc;
3574 }
3575
3576 static int
3577 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3578 {
3579         struct lnet_ni *ni;
3580         int i = 0;
3581
3582         lnet_net_lock(LNET_LOCK_EX);
3583         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3584                 list->rlst_nid_array[i] = ni->ni_nid;
3585                 i++;
3586                 if (i >= LNET_MAX_SHOW_NUM_NID)
3587                         break;
3588         }
3589         lnet_net_unlock(LNET_LOCK_EX);
3590         list->rlst_num_nids = i;
3591
3592         return 0;
3593 }
3594
3595 static int
3596 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3597 {
3598         struct lnet_peer_ni *lpni;
3599         int i = 0;
3600
3601         lnet_net_lock(LNET_LOCK_EX);
3602         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3603                 list->rlst_nid_array[i] = lpni->lpni_nid;
3604                 i++;
3605                 if (i >= LNET_MAX_SHOW_NUM_NID)
3606                         break;
3607         }
3608         lnet_net_unlock(LNET_LOCK_EX);
3609         list->rlst_num_nids = i;
3610
3611         return 0;
3612 }
3613
3614 /**
3615  * LNet ioctl handler.
3616  *
3617  */
3618 int
3619 LNetCtl(unsigned int cmd, void *arg)
3620 {
3621         struct libcfs_ioctl_data *data = arg;
3622         struct lnet_ioctl_config_data *config;
3623         struct lnet_process_id    id = {0};
3624         struct lnet_ni           *ni;
3625         int                       rc;
3626
3627         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3628                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3629
3630         switch (cmd) {
3631         case IOC_LIBCFS_GET_NI:
3632                 rc = LNetGetId(data->ioc_count, &id);
3633                 data->ioc_nid = id.nid;
3634                 return rc;
3635
3636         case IOC_LIBCFS_FAIL_NID:
3637                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3638
3639         case IOC_LIBCFS_ADD_ROUTE: {
3640                 /* default router sensitivity to 1 */
3641                 unsigned int sensitivity = 1;
3642                 config = arg;
3643
3644                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3645                         return -EINVAL;
3646
3647                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
3648                         sensitivity =
3649                           config->cfg_config_u.cfg_route.rtr_sensitivity;
3650                 }
3651
3652                 mutex_lock(&the_lnet.ln_api_mutex);
3653                 rc = lnet_add_route(config->cfg_net,
3654                                     config->cfg_config_u.cfg_route.rtr_hop,
3655                                     config->cfg_nid,
3656                                     config->cfg_config_u.cfg_route.
3657                                         rtr_priority, sensitivity);
3658                 mutex_unlock(&the_lnet.ln_api_mutex);
3659                 return rc;
3660         }
3661
3662         case IOC_LIBCFS_DEL_ROUTE:
3663                 config = arg;
3664
3665                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3666                         return -EINVAL;
3667
3668                 mutex_lock(&the_lnet.ln_api_mutex);
3669                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3670                 mutex_unlock(&the_lnet.ln_api_mutex);
3671                 return rc;
3672
3673         case IOC_LIBCFS_GET_ROUTE:
3674                 config = arg;
3675
3676                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3677                         return -EINVAL;
3678
3679                 mutex_lock(&the_lnet.ln_api_mutex);
3680                 rc = lnet_get_route(config->cfg_count,
3681                                     &config->cfg_net,
3682                                     &config->cfg_config_u.cfg_route.rtr_hop,
3683                                     &config->cfg_nid,
3684                                     &config->cfg_config_u.cfg_route.rtr_flags,
3685                                     &config->cfg_config_u.cfg_route.
3686                                         rtr_priority,
3687                                     &config->cfg_config_u.cfg_route.
3688                                         rtr_sensitivity);
3689                 mutex_unlock(&the_lnet.ln_api_mutex);
3690                 return rc;
3691
3692         case IOC_LIBCFS_GET_LOCAL_NI: {
3693                 struct lnet_ioctl_config_ni *cfg_ni;
3694                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3695                 struct lnet_ioctl_element_stats *stats;
3696                 __u32 tun_size;
3697
3698                 cfg_ni = arg;
3699
3700                 /* get the tunables if they are available */
3701                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3702                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3703                         return -EINVAL;
3704
3705                 stats = (struct lnet_ioctl_element_stats *)
3706                         cfg_ni->lic_bulk;
3707                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3708                                 (cfg_ni->lic_bulk + sizeof(*stats));
3709
3710                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3711                         sizeof(*stats);
3712
3713                 mutex_lock(&the_lnet.ln_api_mutex);
3714                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3715                 mutex_unlock(&the_lnet.ln_api_mutex);
3716                 return rc;
3717         }
3718
3719         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3720                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3721
3722                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3723                         return -EINVAL;
3724
3725                 mutex_lock(&the_lnet.ln_api_mutex);
3726                 rc = lnet_get_ni_stats(msg_stats);
3727                 mutex_unlock(&the_lnet.ln_api_mutex);
3728
3729                 return rc;
3730         }
3731
3732         case IOC_LIBCFS_GET_NET: {
3733                 size_t total = sizeof(*config) +
3734                                sizeof(struct lnet_ioctl_net_config);
3735                 config = arg;
3736
3737                 if (config->cfg_hdr.ioc_len < total)
3738                         return -EINVAL;
3739
3740                 mutex_lock(&the_lnet.ln_api_mutex);
3741                 rc = lnet_get_net_config(config);
3742                 mutex_unlock(&the_lnet.ln_api_mutex);
3743                 return rc;
3744         }
3745
3746         case IOC_LIBCFS_GET_LNET_STATS:
3747         {
3748                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3749
3750                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3751                         return -EINVAL;
3752
3753                 mutex_lock(&the_lnet.ln_api_mutex);
3754                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
3755                 mutex_unlock(&the_lnet.ln_api_mutex);
3756                 return rc;
3757         }
3758
3759         case IOC_LIBCFS_CONFIG_RTR:
3760                 config = arg;
3761
3762                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3763                         return -EINVAL;
3764
3765                 mutex_lock(&the_lnet.ln_api_mutex);
3766                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3767                         rc = lnet_rtrpools_enable();
3768                         mutex_unlock(&the_lnet.ln_api_mutex);
3769                         return rc;
3770                 }
3771                 lnet_rtrpools_disable();
3772                 mutex_unlock(&the_lnet.ln_api_mutex);
3773                 return 0;
3774
3775         case IOC_LIBCFS_ADD_BUF:
3776                 config = arg;
3777
3778                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3779                         return -EINVAL;
3780
3781                 mutex_lock(&the_lnet.ln_api_mutex);
3782                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3783                                                 buf_tiny,
3784                                           config->cfg_config_u.cfg_buffers.
3785                                                 buf_small,
3786                                           config->cfg_config_u.cfg_buffers.
3787                                                 buf_large);
3788                 mutex_unlock(&the_lnet.ln_api_mutex);
3789                 return rc;
3790
3791         case IOC_LIBCFS_SET_NUMA_RANGE: {
3792                 struct lnet_ioctl_set_value *numa;
3793                 numa = arg;
3794                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3795                         return -EINVAL;
3796                 lnet_net_lock(LNET_LOCK_EX);
3797                 lnet_numa_range = numa->sv_value;
3798                 lnet_net_unlock(LNET_LOCK_EX);
3799                 return 0;
3800         }
3801
3802         case IOC_LIBCFS_GET_NUMA_RANGE: {
3803                 struct lnet_ioctl_set_value *numa;
3804                 numa = arg;
3805                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3806                         return -EINVAL;
3807                 numa->sv_value = lnet_numa_range;
3808                 return 0;
3809         }
3810
3811         case IOC_LIBCFS_GET_BUF: {
3812                 struct lnet_ioctl_pool_cfg *pool_cfg;
3813                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3814
3815                 config = arg;
3816
3817                 if (config->cfg_hdr.ioc_len < total)
3818                         return -EINVAL;
3819
3820                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3821
3822                 mutex_lock(&the_lnet.ln_api_mutex);
3823                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3824                 mutex_unlock(&the_lnet.ln_api_mutex);
3825                 return rc;
3826         }
3827
3828         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3829                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3830
3831                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3832                         return -EINVAL;
3833
3834                 mutex_lock(&the_lnet.ln_api_mutex);
3835                 rc = lnet_get_local_ni_hstats(stats);
3836                 mutex_unlock(&the_lnet.ln_api_mutex);
3837
3838                 return rc;
3839         }
3840
3841         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3842                 struct lnet_ioctl_recovery_list *list = arg;
3843                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3844                         return -EINVAL;
3845
3846                 mutex_lock(&the_lnet.ln_api_mutex);
3847                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3848                         rc = lnet_get_local_ni_recovery_list(list);
3849                 else
3850                         rc = lnet_get_peer_ni_recovery_list(list);
3851                 mutex_unlock(&the_lnet.ln_api_mutex);
3852                 return rc;
3853         }
3854
3855         case IOC_LIBCFS_ADD_PEER_NI: {
3856                 struct lnet_ioctl_peer_cfg *cfg = arg;
3857
3858                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3859                         return -EINVAL;
3860
3861                 mutex_lock(&the_lnet.ln_api_mutex);
3862                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3863                                       cfg->prcfg_cfg_nid,
3864                                       cfg->prcfg_mr);
3865                 mutex_unlock(&the_lnet.ln_api_mutex);
3866                 return rc;
3867         }
3868
3869         case IOC_LIBCFS_DEL_PEER_NI: {
3870                 struct lnet_ioctl_peer_cfg *cfg = arg;
3871
3872                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3873                         return -EINVAL;
3874
3875                 mutex_lock(&the_lnet.ln_api_mutex);
3876                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3877                                       cfg->prcfg_cfg_nid);
3878                 mutex_unlock(&the_lnet.ln_api_mutex);
3879                 return rc;
3880         }
3881
3882         case IOC_LIBCFS_GET_PEER_INFO: {
3883                 struct lnet_ioctl_peer *peer_info = arg;
3884
3885                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3886                         return -EINVAL;
3887
3888                 mutex_lock(&the_lnet.ln_api_mutex);
3889                 rc = lnet_get_peer_ni_info(
3890                    peer_info->pr_count,
3891                    &peer_info->pr_nid,
3892                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3893                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3894                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3895                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3896                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3897                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3898                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3899                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3900                 mutex_unlock(&the_lnet.ln_api_mutex);
3901                 return rc;
3902         }
3903
3904         case IOC_LIBCFS_GET_PEER_NI: {
3905                 struct lnet_ioctl_peer_cfg *cfg = arg;
3906
3907                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3908                         return -EINVAL;
3909
3910                 mutex_lock(&the_lnet.ln_api_mutex);
3911                 rc = lnet_get_peer_info(cfg,
3912                                         (void __user *)cfg->prcfg_bulk);
3913                 mutex_unlock(&the_lnet.ln_api_mutex);
3914                 return rc;
3915         }
3916
3917         case IOC_LIBCFS_GET_PEER_LIST: {
3918                 struct lnet_ioctl_peer_cfg *cfg = arg;
3919
3920                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3921                         return -EINVAL;
3922
3923                 mutex_lock(&the_lnet.ln_api_mutex);
3924                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3925                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3926                 mutex_unlock(&the_lnet.ln_api_mutex);
3927                 return rc;
3928         }
3929
3930         case IOC_LIBCFS_SET_HEALHV: {
3931                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3932                 int value;
3933                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3934                         return -EINVAL;
3935                 if (cfg->rh_value < 0 ||
3936                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3937                         value = LNET_MAX_HEALTH_VALUE;
3938                 else
3939                         value = cfg->rh_value;
3940                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3941                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3942                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3943                 mutex_lock(&the_lnet.ln_api_mutex);
3944                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3945                         lnet_ni_set_healthv(cfg->rh_nid, value,
3946                                              cfg->rh_all);
3947                 else
3948                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3949                                                   cfg->rh_all);
3950                 mutex_unlock(&the_lnet.ln_api_mutex);
3951                 return 0;
3952         }
3953
3954         case IOC_LIBCFS_NOTIFY_ROUTER: {
3955                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3956
3957                 /* The deadline passed in by the user should be some time in
3958                  * seconds in the future since the UNIX epoch. We have to map
3959                  * that deadline to the wall clock.
3960                  */
3961                 deadline += ktime_get_seconds();
3962                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags, false,
3963                                    deadline);
3964         }
3965
3966         case IOC_LIBCFS_LNET_DIST:
3967                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3968                 if (rc < 0 && rc != -EHOSTUNREACH)
3969                         return rc;
3970
3971                 data->ioc_u32[0] = rc;
3972                 return 0;
3973
3974         case IOC_LIBCFS_TESTPROTOCOMPAT:
3975                 the_lnet.ln_testprotocompat = data->ioc_flags;
3976                 return 0;
3977
3978         case IOC_LIBCFS_LNET_FAULT:
3979                 return lnet_fault_ctl(data->ioc_flags, data);
3980
3981         case IOC_LIBCFS_PING: {
3982                 signed long timeout;
3983
3984                 id.nid = data->ioc_nid;
3985                 id.pid = data->ioc_u32[0];
3986
3987                 /* If timeout is negative then set default of 3 minutes */
3988                 if (((s32)data->ioc_u32[1] <= 0) ||
3989                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3990                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
3991                 else
3992                         timeout = nsecs_to_jiffies(data->ioc_u32[1] * NSEC_PER_MSEC);
3993
3994                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3995                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3996
3997                 if (rc < 0)
3998                         return rc;
3999
4000                 data->ioc_count = rc;
4001                 return 0;
4002         }
4003
4004         case IOC_LIBCFS_PING_PEER: {
4005                 struct lnet_ioctl_ping_data *ping = arg;
4006                 struct lnet_peer *lp;
4007                 signed long timeout;
4008
4009                 /* If timeout is negative then set default of 3 minutes */
4010                 if (((s32)ping->op_param) <= 0 ||
4011                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4012                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4013                 else
4014                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4015
4016                 rc = lnet_ping(ping->ping_id, timeout,
4017                                ping->ping_buf,
4018                                ping->ping_count);
4019                 if (rc < 0)
4020                         return rc;
4021
4022                 mutex_lock(&the_lnet.ln_api_mutex);
4023                 lp = lnet_find_peer(ping->ping_id.nid);
4024                 if (lp) {
4025                         ping->ping_id.nid = lp->lp_primary_nid;
4026                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4027                         lnet_peer_decref_locked(lp);
4028                 }
4029                 mutex_unlock(&the_lnet.ln_api_mutex);
4030
4031                 ping->ping_count = rc;
4032                 return 0;
4033         }
4034
4035         case IOC_LIBCFS_DISCOVER: {
4036                 struct lnet_ioctl_ping_data *discover = arg;
4037                 struct lnet_peer *lp;
4038
4039                 rc = lnet_discover(discover->ping_id, discover->op_param,
4040                                    discover->ping_buf,
4041                                    discover->ping_count);
4042                 if (rc < 0)
4043                         return rc;
4044
4045                 mutex_lock(&the_lnet.ln_api_mutex);
4046                 lp = lnet_find_peer(discover->ping_id.nid);
4047                 if (lp) {
4048                         discover->ping_id.nid = lp->lp_primary_nid;
4049                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4050                         lnet_peer_decref_locked(lp);
4051                 }
4052                 mutex_unlock(&the_lnet.ln_api_mutex);
4053
4054                 discover->ping_count = rc;
4055                 return 0;
4056         }
4057
4058         default:
4059                 ni = lnet_net2ni_addref(data->ioc_net);
4060                 if (ni == NULL)
4061                         return -EINVAL;
4062
4063                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4064                         rc = -EINVAL;
4065                 else
4066                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4067
4068                 lnet_ni_decref(ni);
4069                 return rc;
4070         }
4071         /* not reached */
4072 }
4073 EXPORT_SYMBOL(LNetCtl);
4074
4075 void LNetDebugPeer(struct lnet_process_id id)
4076 {
4077         lnet_debug_peer(id.nid);
4078 }
4079 EXPORT_SYMBOL(LNetDebugPeer);
4080
4081 /**
4082  * Determine if the specified peer \a nid is on the local node.
4083  *
4084  * \param nid   peer nid to check
4085  *
4086  * \retval true         If peer NID is on the local node.
4087  * \retval false        If peer NID is not on the local node.
4088  */
4089 bool LNetIsPeerLocal(lnet_nid_t nid)
4090 {
4091         struct lnet_net *net;
4092         struct lnet_ni *ni;
4093         int cpt;
4094
4095         cpt = lnet_net_lock_current();
4096         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4097                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4098                         if (ni->ni_nid == nid) {
4099                                 lnet_net_unlock(cpt);
4100                                 return true;
4101                         }
4102                 }
4103         }
4104         lnet_net_unlock(cpt);
4105
4106         return false;
4107 }
4108 EXPORT_SYMBOL(LNetIsPeerLocal);
4109
4110 /**
4111  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
4112  * Note that all interfaces share a same PID, as requested by LNetNIInit().
4113  *
4114  * \param index Index of the interface to look up.
4115  * \param id On successful return, this location will hold the
4116  * struct lnet_process_id ID of the interface.
4117  *
4118  * \retval 0 If an interface exists at \a index.
4119  * \retval -ENOENT If no interface has been found.
4120  */
4121 int
4122 LNetGetId(unsigned int index, struct lnet_process_id *id)
4123 {
4124         struct lnet_ni   *ni;
4125         struct lnet_net  *net;
4126         int               cpt;
4127         int               rc = -ENOENT;
4128
4129         LASSERT(the_lnet.ln_refcount > 0);
4130
4131         cpt = lnet_net_lock_current();
4132
4133         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4134                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4135                         if (index-- != 0)
4136                                 continue;
4137
4138                         id->nid = ni->ni_nid;
4139                         id->pid = the_lnet.ln_pid;
4140                         rc = 0;
4141                         break;
4142                 }
4143         }
4144
4145         lnet_net_unlock(cpt);
4146         return rc;
4147 }
4148 EXPORT_SYMBOL(LNetGetId);
4149
4150 struct ping_data {
4151         int rc;
4152         int replied;
4153         struct lnet_handle_md mdh;
4154         struct completion completion;
4155 };
4156
4157 static void
4158 lnet_ping_event_handler(struct lnet_event *event)
4159 {
4160         struct ping_data *pd = event->md_user_ptr;
4161
4162         CDEBUG(D_NET, "ping event (%d %d)%s\n",
4163                event->type, event->status,
4164                event->unlinked ? " unlinked" : "");
4165
4166         if (event->status) {
4167                 if (!pd->rc)
4168                         pd->rc = event->status;
4169         } else if (event->type == LNET_EVENT_REPLY) {
4170                 pd->replied = 1;
4171                 pd->rc = event->mlength;
4172         }
4173         if (event->unlinked)
4174                 complete(&pd->completion);
4175 }
4176
4177 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4178                      struct lnet_process_id __user *ids, int n_ids)
4179 {
4180         struct lnet_md md = { NULL };
4181         struct ping_data pd = { 0 };
4182         struct lnet_ping_buffer *pbuf;
4183         struct lnet_process_id tmpid;
4184         int i;
4185         int nob;
4186         int rc;
4187         int rc2;
4188
4189         /* n_ids limit is arbitrary */
4190         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4191                 return -EINVAL;
4192
4193         /*
4194          * if the user buffer has more space than the lnet_interfaces_max
4195          * then only fill it up to lnet_interfaces_max
4196          */
4197         if (n_ids > lnet_interfaces_max)
4198                 n_ids = lnet_interfaces_max;
4199
4200         if (id.pid == LNET_PID_ANY)
4201                 id.pid = LNET_PID_LUSTRE;
4202
4203         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4204         if (!pbuf)
4205                 return -ENOMEM;
4206
4207         /* initialize md content */
4208         md.start     = &pbuf->pb_info;
4209         md.length    = LNET_PING_INFO_SIZE(n_ids);
4210         md.threshold = 2; /* GET/REPLY */
4211         md.max_size  = 0;
4212         md.options   = LNET_MD_TRUNCATE;
4213         md.user_ptr  = &pd;
4214         md.handler   = lnet_ping_event_handler;
4215
4216         init_completion(&pd.completion);
4217
4218         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
4219         if (rc != 0) {
4220                 CERROR("Can't bind MD: %d\n", rc);
4221                 goto fail_ping_buffer_decref;
4222         }
4223
4224         rc = LNetGet(LNET_NID_ANY, pd.mdh, id,
4225                      LNET_RESERVED_PORTAL,
4226                      LNET_PROTO_PING_MATCHBITS, 0, false);
4227
4228         if (rc != 0) {
4229                 /* Don't CERROR; this could be deliberate! */
4230                 rc2 = LNetMDUnlink(pd.mdh);
4231                 LASSERT(rc2 == 0);
4232
4233                 /* NB must wait for the UNLINK event below... */
4234         }
4235
4236         if (wait_for_completion_timeout(&pd.completion, timeout) == 0) {
4237                 /* Ensure completion in finite time... */
4238                 LNetMDUnlink(pd.mdh);
4239                 wait_for_completion(&pd.completion);
4240         }
4241         if (!pd.replied) {
4242                 rc = -EIO;
4243                 goto fail_ping_buffer_decref;
4244         }
4245
4246         nob = pd.rc;
4247         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4248
4249         rc = -EPROTO;           /* if I can't parse... */
4250
4251         if (nob < 8) {
4252                 CERROR("%s: ping info too short %d\n",
4253                        libcfs_id2str(id), nob);
4254                 goto fail_ping_buffer_decref;
4255         }
4256
4257         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4258                 lnet_swap_pinginfo(pbuf);
4259         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4260                 CERROR("%s: Unexpected magic %08x\n",
4261                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4262                 goto fail_ping_buffer_decref;
4263         }
4264
4265         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4266                 CERROR("%s: ping w/o NI status: 0x%x\n",
4267                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4268                 goto fail_ping_buffer_decref;
4269         }
4270
4271         if (nob < LNET_PING_INFO_SIZE(0)) {
4272                 CERROR("%s: Short reply %d(%d min)\n",
4273                        libcfs_id2str(id),
4274                        nob, (int)LNET_PING_INFO_SIZE(0));
4275                 goto fail_ping_buffer_decref;
4276         }
4277
4278         if (pbuf->pb_info.pi_nnis < n_ids)
4279                 n_ids = pbuf->pb_info.pi_nnis;
4280
4281         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4282                 CERROR("%s: Short reply %d(%d expected)\n",
4283                        libcfs_id2str(id),
4284                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4285                 goto fail_ping_buffer_decref;
4286         }
4287
4288         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4289
4290         memset(&tmpid, 0, sizeof(tmpid));
4291         for (i = 0; i < n_ids; i++) {
4292                 tmpid.pid = pbuf->pb_info.pi_pid;
4293                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4294                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4295                         goto fail_ping_buffer_decref;
4296         }
4297         rc = pbuf->pb_info.pi_nnis;
4298
4299  fail_ping_buffer_decref:
4300         lnet_ping_buffer_decref(pbuf);
4301         return rc;
4302 }
4303
4304 static int
4305 lnet_discover(struct lnet_process_id id, __u32 force,
4306               struct lnet_process_id __user *ids, int n_ids)
4307 {
4308         struct lnet_peer_ni *lpni;
4309         struct lnet_peer_ni *p;
4310         struct lnet_peer *lp;
4311         struct lnet_process_id *buf;
4312         int cpt;
4313         int i;
4314         int rc;
4315
4316         if (n_ids <= 0 ||
4317             id.nid == LNET_NID_ANY)
4318                 return -EINVAL;
4319
4320         if (id.pid == LNET_PID_ANY)
4321                 id.pid = LNET_PID_LUSTRE;
4322
4323         /*
4324          * If the user buffer has more space than the lnet_interfaces_max,
4325          * then only fill it up to lnet_interfaces_max.
4326          */
4327         if (n_ids > lnet_interfaces_max)
4328                 n_ids = lnet_interfaces_max;
4329
4330         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
4331         if (!buf)
4332                 return -ENOMEM;
4333
4334         cpt = lnet_net_lock_current();
4335         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4336         if (IS_ERR(lpni)) {
4337                 rc = PTR_ERR(lpni);
4338                 goto out;
4339         }
4340
4341         /*
4342          * Clearing the NIDS_UPTODATE flag ensures the peer will
4343          * be discovered, provided discovery has not been disabled.
4344          */
4345         lp = lpni->lpni_peer_net->lpn_peer;
4346         spin_lock(&lp->lp_lock);
4347         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4348         /* If the force flag is set, force a PING and PUSH as well. */
4349         if (force)
4350                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4351         spin_unlock(&lp->lp_lock);
4352         rc = lnet_discover_peer_locked(lpni, cpt, true);
4353         if (rc)
4354                 goto out_decref;
4355
4356         i = 0;
4357         p = NULL;
4358         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4359                 buf[i].pid = id.pid;
4360                 buf[i].nid = p->lpni_nid;
4361                 if (++i >= n_ids)
4362                         break;
4363         }
4364         rc = i;
4365
4366 out_decref:
4367         lnet_peer_ni_decref_locked(lpni);
4368 out:
4369         lnet_net_unlock(cpt);
4370
4371         if (rc >= 0)
4372                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
4373                         rc = -EFAULT;
4374         CFS_FREE_PTR_ARRAY(buf, n_ids);
4375
4376         return rc;
4377 }
4378
4379 /**
4380  * Retrieve peer discovery status.
4381  *
4382  * \retval 1 if lnet_peer_discovery_disabled is 0
4383  * \retval 0 if lnet_peer_discovery_disabled is 1
4384  */
4385 int
4386 LNetGetPeerDiscoveryStatus(void)
4387 {
4388         return !lnet_peer_discovery_disabled;
4389 }
4390 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);