Whamcloud - gitweb
LU-13669 llite: try to improve mmap performance
[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                         /* Unlock mutex while waiting to allow other
2118                          * threads to read the LNet state and fall through
2119                          * to avoid deadlock
2120                          */
2121                         lnet_net_unlock(LNET_LOCK_EX);
2122                         mutex_unlock(&the_lnet.ln_api_mutex);
2123
2124                         ++i;
2125                         if ((i & (-i)) == i) {
2126                                 CDEBUG(D_WARNING,
2127                                        "Waiting for zombie LNI %s\n",
2128                                        libcfs_nid2str(ni->ni_nid));
2129                         }
2130                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2131
2132                         mutex_lock(&the_lnet.ln_api_mutex);
2133                         lnet_net_lock(LNET_LOCK_EX);
2134                         continue;
2135                 }
2136
2137                 lnet_net_unlock(LNET_LOCK_EX);
2138
2139                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2140
2141                 LASSERT(!in_interrupt());
2142                 /* Holding the mutex makes it safe for lnd_shutdown
2143                  * to call module_put(). Module unload cannot finish
2144                  * until lnet_unregister_lnd() completes, and that
2145                  * requires the mutex.
2146                  */
2147                 mutex_lock(&the_lnet.ln_lnd_mutex);
2148                 (net->net_lnd->lnd_shutdown)(ni);
2149                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2150
2151                 if (!islo)
2152                         CDEBUG(D_LNI, "Removed LNI %s\n",
2153                               libcfs_nid2str(ni->ni_nid));
2154
2155                 lnet_ni_free(ni);
2156                 i = 2;
2157                 lnet_net_lock(LNET_LOCK_EX);
2158         }
2159 }
2160
2161 /* shutdown down the NI and release refcount */
2162 static void
2163 lnet_shutdown_lndni(struct lnet_ni *ni)
2164 {
2165         int i;
2166         struct lnet_net *net = ni->ni_net;
2167
2168         lnet_net_lock(LNET_LOCK_EX);
2169         lnet_ni_lock(ni);
2170         ni->ni_state = LNET_NI_STATE_DELETING;
2171         lnet_ni_unlock(ni);
2172         lnet_ni_unlink_locked(ni);
2173         lnet_incr_dlc_seq();
2174         lnet_net_unlock(LNET_LOCK_EX);
2175
2176         /* clear messages for this NI on the lazy portal */
2177         for (i = 0; i < the_lnet.ln_nportals; i++)
2178                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2179
2180         lnet_net_lock(LNET_LOCK_EX);
2181         lnet_clear_zombies_nis_locked(net);
2182         lnet_net_unlock(LNET_LOCK_EX);
2183 }
2184
2185 static void
2186 lnet_shutdown_lndnet(struct lnet_net *net)
2187 {
2188         struct lnet_ni *ni;
2189
2190         lnet_net_lock(LNET_LOCK_EX);
2191
2192         list_del_init(&net->net_list);
2193
2194         while (!list_empty(&net->net_ni_list)) {
2195                 ni = list_entry(net->net_ni_list.next,
2196                                 struct lnet_ni, ni_netlist);
2197                 lnet_net_unlock(LNET_LOCK_EX);
2198                 lnet_shutdown_lndni(ni);
2199                 lnet_net_lock(LNET_LOCK_EX);
2200         }
2201
2202         lnet_net_unlock(LNET_LOCK_EX);
2203
2204         /* Do peer table cleanup for this net */
2205         lnet_peer_tables_cleanup(net);
2206
2207         lnet_net_free(net);
2208 }
2209
2210 static void
2211 lnet_shutdown_lndnets(void)
2212 {
2213         struct lnet_net *net;
2214         LIST_HEAD(resend);
2215         struct lnet_msg *msg, *tmp;
2216
2217         /* NB called holding the global mutex */
2218
2219         /* All quiet on the API front */
2220         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2221         LASSERT(the_lnet.ln_refcount == 0);
2222
2223         lnet_net_lock(LNET_LOCK_EX);
2224         the_lnet.ln_state = LNET_STATE_STOPPING;
2225
2226         /*
2227          * move the nets to the zombie list to avoid them being
2228          * picked up for new work. LONET is also included in the
2229          * Nets that will be moved to the zombie list
2230          */
2231         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2232
2233         /* Drop the cached loopback Net. */
2234         if (the_lnet.ln_loni != NULL) {
2235                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2236                 the_lnet.ln_loni = NULL;
2237         }
2238         lnet_net_unlock(LNET_LOCK_EX);
2239
2240         /* iterate through the net zombie list and delete each net */
2241         while (!list_empty(&the_lnet.ln_net_zombie)) {
2242                 net = list_entry(the_lnet.ln_net_zombie.next,
2243                                  struct lnet_net, net_list);
2244                 lnet_shutdown_lndnet(net);
2245         }
2246
2247         spin_lock(&the_lnet.ln_msg_resend_lock);
2248         list_splice(&the_lnet.ln_msg_resend, &resend);
2249         spin_unlock(&the_lnet.ln_msg_resend_lock);
2250
2251         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2252                 list_del_init(&msg->msg_list);
2253                 msg->msg_no_resend = true;
2254                 lnet_finalize(msg, -ECANCELED);
2255         }
2256
2257         lnet_net_lock(LNET_LOCK_EX);
2258         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2259         lnet_net_unlock(LNET_LOCK_EX);
2260 }
2261
2262 static int
2263 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2264 {
2265         int                     rc = -EINVAL;
2266         struct lnet_tx_queue    *tq;
2267         int                     i;
2268         struct lnet_net         *net = ni->ni_net;
2269
2270         mutex_lock(&the_lnet.ln_lnd_mutex);
2271
2272         if (tun) {
2273                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2274                 ni->ni_lnd_tunables_set = true;
2275         }
2276
2277         rc = (net->net_lnd->lnd_startup)(ni);
2278
2279         mutex_unlock(&the_lnet.ln_lnd_mutex);
2280
2281         if (rc != 0) {
2282                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2283                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2284                 goto failed0;
2285         }
2286
2287         lnet_ni_lock(ni);
2288         ni->ni_state = LNET_NI_STATE_ACTIVE;
2289         lnet_ni_unlock(ni);
2290
2291         /* We keep a reference on the loopback net through the loopback NI */
2292         if (net->net_lnd->lnd_type == LOLND) {
2293                 lnet_ni_addref(ni);
2294                 LASSERT(the_lnet.ln_loni == NULL);
2295                 the_lnet.ln_loni = ni;
2296                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2297                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2298                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2299                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2300                 return 0;
2301         }
2302
2303         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2304             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2305                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2306                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2307                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2308                                         "" : "per-peer ");
2309                 /* shutdown the NI since if we get here then it must've already
2310                  * been started
2311                  */
2312                 lnet_shutdown_lndni(ni);
2313                 return -EINVAL;
2314         }
2315
2316         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2317                 tq->tq_credits_min =
2318                 tq->tq_credits_max =
2319                 tq->tq_credits = lnet_ni_tq_credits(ni);
2320         }
2321
2322         atomic_set(&ni->ni_tx_credits,
2323                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2324         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2325
2326         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2327                 libcfs_nid2str(ni->ni_nid),
2328                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2329                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2330                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2331                 ni->ni_net->net_tunables.lct_peer_timeout);
2332
2333         return 0;
2334 failed0:
2335         lnet_ni_free(ni);
2336         return rc;
2337 }
2338
2339 static int
2340 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2341 {
2342         struct lnet_ni *ni;
2343         struct lnet_net *net_l = NULL;
2344         LIST_HEAD(local_ni_list);
2345         int rc;
2346         int ni_count = 0;
2347         __u32 lnd_type;
2348         const struct lnet_lnd  *lnd;
2349         int peer_timeout =
2350                 net->net_tunables.lct_peer_timeout;
2351         int maxtxcredits =
2352                 net->net_tunables.lct_max_tx_credits;
2353         int peerrtrcredits =
2354                 net->net_tunables.lct_peer_rtr_credits;
2355
2356         /*
2357          * make sure that this net is unique. If it isn't then
2358          * we are adding interfaces to an already existing network, and
2359          * 'net' is just a convenient way to pass in the list.
2360          * if it is unique we need to find the LND and load it if
2361          * necessary.
2362          */
2363         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2364                 lnd_type = LNET_NETTYP(net->net_id);
2365
2366                 mutex_lock(&the_lnet.ln_lnd_mutex);
2367                 lnd = lnet_find_lnd_by_type(lnd_type);
2368
2369                 if (lnd == NULL) {
2370                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2371                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2372                         mutex_lock(&the_lnet.ln_lnd_mutex);
2373
2374                         lnd = lnet_find_lnd_by_type(lnd_type);
2375                         if (lnd == NULL) {
2376                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2377                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2378                                 libcfs_lnd2str(lnd_type),
2379                                 libcfs_lnd2modname(lnd_type), rc);
2380 #ifndef HAVE_MODULE_LOADING_SUPPORT
2381                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2382                                                 "compiled with kernel module "
2383                                                 "loading support.");
2384 #endif
2385                                 rc = -EINVAL;
2386                                 goto failed0;
2387                         }
2388                 }
2389
2390                 net->net_lnd = lnd;
2391
2392                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2393
2394                 net_l = net;
2395         }
2396
2397         /*
2398          * net_l: if the network being added is unique then net_l
2399          *        will point to that network
2400          *        if the network being added is not unique then
2401          *        net_l points to the existing network.
2402          *
2403          * When we enter the loop below, we'll pick NIs off he
2404          * network beign added and start them up, then add them to
2405          * a local ni list. Once we've successfully started all
2406          * the NIs then we join the local NI list (of started up
2407          * networks) with the net_l->net_ni_list, which should
2408          * point to the correct network to add the new ni list to
2409          *
2410          * If any of the new NIs fail to start up, then we want to
2411          * iterate through the local ni list, which should include
2412          * any NIs which were successfully started up, and shut
2413          * them down.
2414          *
2415          * After than we want to delete the network being added,
2416          * to avoid a memory leak.
2417          */
2418
2419         /*
2420          * When a network uses TCP bonding then all its interfaces
2421          * must be specified when the network is first defined: the
2422          * TCP bonding code doesn't allow for interfaces to be added
2423          * or removed.
2424          */
2425         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2426             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2427                 rc = -EINVAL;
2428                 goto failed0;
2429         }
2430
2431         while (!list_empty(&net->net_ni_added)) {
2432                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2433                                 ni_netlist);
2434                 list_del_init(&ni->ni_netlist);
2435
2436                 /* make sure that the the NI we're about to start
2437                  * up is actually unique. if it's not fail. */
2438                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2439                                         ni->ni_interfaces[0])) {
2440                         rc = -EEXIST;
2441                         goto failed1;
2442                 }
2443
2444                 /* adjust the pointer the parent network, just in case it
2445                  * the net is a duplicate */
2446                 ni->ni_net = net_l;
2447
2448                 rc = lnet_startup_lndni(ni, tun);
2449
2450                 if (rc < 0)
2451                         goto failed1;
2452
2453                 lnet_ni_addref(ni);
2454                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2455
2456                 ni_count++;
2457         }
2458
2459         lnet_net_lock(LNET_LOCK_EX);
2460         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2461         lnet_incr_dlc_seq();
2462         lnet_net_unlock(LNET_LOCK_EX);
2463
2464         /* if the network is not unique then we don't want to keep
2465          * it around after we're done. Free it. Otherwise add that
2466          * net to the global the_lnet.ln_nets */
2467         if (net_l != net && net_l != NULL) {
2468                 /*
2469                  * TODO - note. currently the tunables can not be updated
2470                  * once added
2471                  */
2472                 lnet_net_free(net);
2473         } else {
2474                 /*
2475                  * restore tunables after it has been overwitten by the
2476                  * lnd
2477                  */
2478                 if (peer_timeout != -1)
2479                         net->net_tunables.lct_peer_timeout = peer_timeout;
2480                 if (maxtxcredits != -1)
2481                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2482                 if (peerrtrcredits != -1)
2483                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2484
2485                 lnet_net_lock(LNET_LOCK_EX);
2486                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2487                 lnet_net_unlock(LNET_LOCK_EX);
2488         }
2489
2490         /* update net count */
2491         lnet_current_net_count = lnet_get_net_count();
2492
2493         return ni_count;
2494
2495 failed1:
2496         /*
2497          * shutdown the new NIs that are being started up
2498          * free the NET being started
2499          */
2500         while (!list_empty(&local_ni_list)) {
2501                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2502                                 ni_netlist);
2503
2504                 lnet_shutdown_lndni(ni);
2505         }
2506
2507 failed0:
2508         lnet_net_free(net);
2509
2510         return rc;
2511 }
2512
2513 static int
2514 lnet_startup_lndnets(struct list_head *netlist)
2515 {
2516         struct lnet_net         *net;
2517         int                     rc;
2518         int                     ni_count = 0;
2519
2520         /*
2521          * Change to running state before bringing up the LNDs. This
2522          * allows lnet_shutdown_lndnets() to assert that we've passed
2523          * through here.
2524          */
2525         lnet_net_lock(LNET_LOCK_EX);
2526         the_lnet.ln_state = LNET_STATE_RUNNING;
2527         lnet_net_unlock(LNET_LOCK_EX);
2528
2529         while (!list_empty(netlist)) {
2530                 net = list_entry(netlist->next, struct lnet_net, net_list);
2531                 list_del_init(&net->net_list);
2532
2533                 rc = lnet_startup_lndnet(net, NULL);
2534
2535                 if (rc < 0)
2536                         goto failed;
2537
2538                 ni_count += rc;
2539         }
2540
2541         return ni_count;
2542 failed:
2543         lnet_shutdown_lndnets();
2544
2545         return rc;
2546 }
2547
2548 /**
2549  * Initialize LNet library.
2550  *
2551  * Automatically called at module loading time. Caller has to call
2552  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2553  * latter returned 0. It must be called exactly once.
2554  *
2555  * \retval 0 on success
2556  * \retval -ve on failures.
2557  */
2558 int lnet_lib_init(void)
2559 {
2560         int rc;
2561
2562         lnet_assert_wire_constants();
2563
2564         /* refer to global cfs_cpt_table for now */
2565         the_lnet.ln_cpt_table = cfs_cpt_tab;
2566         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2567
2568         LASSERT(the_lnet.ln_cpt_number > 0);
2569         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2570                 /* we are under risk of consuming all lh_cookie */
2571                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2572                        "please change setting of CPT-table and retry\n",
2573                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2574                 return -E2BIG;
2575         }
2576
2577         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2578                 the_lnet.ln_cpt_bits++;
2579
2580         rc = lnet_create_locks();
2581         if (rc != 0) {
2582                 CERROR("Can't create LNet global locks: %d\n", rc);
2583                 return rc;
2584         }
2585
2586         the_lnet.ln_refcount = 0;
2587         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2588         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2589
2590         /* The hash table size is the number of bits it takes to express the set
2591          * ln_num_routes, minus 1 (better to under estimate than over so we
2592          * don't waste memory). */
2593         if (rnet_htable_size <= 0)
2594                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2595         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2596                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2597         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2598                                            order_base_2(rnet_htable_size) - 1);
2599
2600         /* All LNDs apart from the LOLND are in separate modules.  They
2601          * register themselves when their module loads, and unregister
2602          * themselves when their module is unloaded. */
2603         lnet_register_lnd(&the_lolnd);
2604         return 0;
2605 }
2606
2607 /**
2608  * Finalize LNet library.
2609  *
2610  * \pre lnet_lib_init() called with success.
2611  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2612  *
2613  * As this happens at module-unload, all lnds must already be unloaded,
2614  * so they must already be unregistered.
2615  */
2616 void lnet_lib_exit(void)
2617 {
2618         int i;
2619
2620         LASSERT(the_lnet.ln_refcount == 0);
2621         lnet_unregister_lnd(&the_lolnd);
2622         for (i = 0; i < NUM_LNDS; i++)
2623                 LASSERT(!the_lnet.ln_lnds[i]);
2624         lnet_destroy_locks();
2625 }
2626
2627 /**
2628  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2629  *
2630  * Users must call this function at least once before any other functions.
2631  * For each successful call there must be a corresponding call to
2632  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2633  * ignored.
2634  *
2635  * The PID used by LNet may be different from the one requested.
2636  * See LNetGetId().
2637  *
2638  * \param requested_pid PID requested by the caller.
2639  *
2640  * \return >= 0 on success, and < 0 error code on failures.
2641  */
2642 int
2643 LNetNIInit(lnet_pid_t requested_pid)
2644 {
2645         int                     im_a_router = 0;
2646         int                     rc;
2647         int                     ni_count;
2648         struct lnet_ping_buffer *pbuf;
2649         struct lnet_handle_md   ping_mdh;
2650         LIST_HEAD(net_head);
2651         struct lnet_net         *net;
2652
2653         mutex_lock(&the_lnet.ln_api_mutex);
2654
2655         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2656
2657         if (the_lnet.ln_refcount > 0) {
2658                 rc = the_lnet.ln_refcount++;
2659                 mutex_unlock(&the_lnet.ln_api_mutex);
2660                 return rc;
2661         }
2662
2663         rc = lnet_prepare(requested_pid);
2664         if (rc != 0) {
2665                 mutex_unlock(&the_lnet.ln_api_mutex);
2666                 return rc;
2667         }
2668
2669         /* create a network for Loopback network */
2670         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2671         if (net == NULL) {
2672                 rc = -ENOMEM;
2673                 goto err_empty_list;
2674         }
2675
2676         /* Add in the loopback NI */
2677         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2678                 rc = -ENOMEM;
2679                 goto err_empty_list;
2680         }
2681
2682         /* If LNet is being initialized via DLC it is possible
2683          * that the user requests not to load module parameters (ones which
2684          * are supported by DLC) on initialization.  Therefore, make sure not
2685          * to load networks, routes and forwarding from module parameters
2686          * in this case.  On cleanup in case of failure only clean up
2687          * routes if it has been loaded */
2688         if (!the_lnet.ln_nis_from_mod_params) {
2689                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2690                                          use_tcp_bonding);
2691                 if (rc < 0)
2692                         goto err_empty_list;
2693         }
2694
2695         ni_count = lnet_startup_lndnets(&net_head);
2696         if (ni_count < 0) {
2697                 rc = ni_count;
2698                 goto err_empty_list;
2699         }
2700
2701         if (!the_lnet.ln_nis_from_mod_params) {
2702                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2703                 if (rc != 0)
2704                         goto err_shutdown_lndnis;
2705
2706                 rc = lnet_rtrpools_alloc(im_a_router);
2707                 if (rc != 0)
2708                         goto err_destroy_routes;
2709         }
2710
2711         rc = lnet_acceptor_start();
2712         if (rc != 0)
2713                 goto err_destroy_routes;
2714
2715         the_lnet.ln_refcount = 1;
2716         /* Now I may use my own API functions... */
2717
2718         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2719         if (rc != 0)
2720                 goto err_acceptor_stop;
2721
2722         lnet_ping_target_update(pbuf, ping_mdh);
2723
2724         the_lnet.ln_mt_handler = lnet_mt_event_handler;
2725
2726         rc = lnet_push_target_init();
2727         if (rc != 0)
2728                 goto err_stop_ping;
2729
2730         rc = lnet_peer_discovery_start();
2731         if (rc != 0)
2732                 goto err_destroy_push_target;
2733
2734         rc = lnet_monitor_thr_start();
2735         if (rc != 0)
2736                 goto err_stop_discovery_thr;
2737
2738         lnet_fault_init();
2739         lnet_router_debugfs_init();
2740
2741         mutex_unlock(&the_lnet.ln_api_mutex);
2742
2743         complete_all(&the_lnet.ln_started);
2744
2745         /* wait for all routers to start */
2746         lnet_wait_router_start();
2747
2748         return 0;
2749
2750 err_stop_discovery_thr:
2751         lnet_peer_discovery_stop();
2752 err_destroy_push_target:
2753         lnet_push_target_fini();
2754 err_stop_ping:
2755         lnet_ping_target_fini();
2756 err_acceptor_stop:
2757         the_lnet.ln_refcount = 0;
2758         lnet_acceptor_stop();
2759 err_destroy_routes:
2760         if (!the_lnet.ln_nis_from_mod_params)
2761                 lnet_destroy_routes();
2762 err_shutdown_lndnis:
2763         lnet_shutdown_lndnets();
2764 err_empty_list:
2765         lnet_unprepare();
2766         LASSERT(rc < 0);
2767         mutex_unlock(&the_lnet.ln_api_mutex);
2768         while (!list_empty(&net_head)) {
2769                 struct lnet_net *net;
2770
2771                 net = list_entry(net_head.next, struct lnet_net, net_list);
2772                 list_del_init(&net->net_list);
2773                 lnet_net_free(net);
2774         }
2775         return rc;
2776 }
2777 EXPORT_SYMBOL(LNetNIInit);
2778
2779 /**
2780  * Stop LNet interfaces, routing, and forwarding.
2781  *
2782  * Users must call this function once for each successful call to LNetNIInit().
2783  * Once the LNetNIFini() operation has been started, the results of pending
2784  * API operations are undefined.
2785  *
2786  * \return always 0 for current implementation.
2787  */
2788 int
2789 LNetNIFini(void)
2790 {
2791         mutex_lock(&the_lnet.ln_api_mutex);
2792
2793         LASSERT(the_lnet.ln_refcount > 0);
2794
2795         if (the_lnet.ln_refcount != 1) {
2796                 the_lnet.ln_refcount--;
2797         } else {
2798                 LASSERT(!the_lnet.ln_niinit_self);
2799
2800                 lnet_fault_fini();
2801
2802                 lnet_router_debugfs_fini();
2803                 lnet_monitor_thr_stop();
2804                 lnet_peer_discovery_stop();
2805                 lnet_push_target_fini();
2806                 lnet_ping_target_fini();
2807
2808                 /* Teardown fns that use my own API functions BEFORE here */
2809                 the_lnet.ln_refcount = 0;
2810
2811                 lnet_acceptor_stop();
2812                 lnet_destroy_routes();
2813                 lnet_shutdown_lndnets();
2814                 lnet_unprepare();
2815         }
2816
2817         mutex_unlock(&the_lnet.ln_api_mutex);
2818         return 0;
2819 }
2820 EXPORT_SYMBOL(LNetNIFini);
2821
2822 /**
2823  * Grabs the ni data from the ni structure and fills the out
2824  * parameters
2825  *
2826  * \param[in] ni network        interface structure
2827  * \param[out] cfg_ni           NI config information
2828  * \param[out] tun              network and LND tunables
2829  */
2830 static void
2831 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2832                    struct lnet_ioctl_config_lnd_tunables *tun,
2833                    struct lnet_ioctl_element_stats *stats,
2834                    __u32 tun_size)
2835 {
2836         size_t min_size = 0;
2837         int i;
2838
2839         if (!ni || !cfg_ni || !tun)
2840                 return;
2841
2842         if (ni->ni_interfaces[0] != NULL) {
2843                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2844                         if (ni->ni_interfaces[i] != NULL) {
2845                                 strncpy(cfg_ni->lic_ni_intf[i],
2846                                         ni->ni_interfaces[i],
2847                                         sizeof(cfg_ni->lic_ni_intf[i]));
2848                         }
2849                 }
2850         }
2851
2852         cfg_ni->lic_nid = ni->ni_nid;
2853         if (ni->ni_nid == LNET_NID_LO_0)
2854                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2855         else
2856                 cfg_ni->lic_status = ni->ni_status->ns_status;
2857         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2858         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2859
2860         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2861
2862         if (stats) {
2863                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2864                                                        LNET_STATS_TYPE_SEND);
2865                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2866                                                        LNET_STATS_TYPE_RECV);
2867                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2868                                                        LNET_STATS_TYPE_DROP);
2869         }
2870
2871         /*
2872          * tun->lt_tun will always be present, but in order to be
2873          * backwards compatible, we need to deal with the cases when
2874          * tun->lt_tun is smaller than what the kernel has, because it
2875          * comes from an older version of a userspace program, then we'll
2876          * need to copy as much information as we have available space.
2877          */
2878         min_size = tun_size - sizeof(tun->lt_cmn);
2879         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2880
2881         /* copy over the cpts */
2882         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2883             ni->ni_cpts == NULL)  {
2884                 for (i = 0; i < ni->ni_ncpts; i++)
2885                         cfg_ni->lic_cpts[i] = i;
2886         } else {
2887                 for (i = 0;
2888                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2889                      i < LNET_MAX_SHOW_NUM_CPT;
2890                      i++)
2891                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2892         }
2893         cfg_ni->lic_ncpts = ni->ni_ncpts;
2894 }
2895
2896 /**
2897  * NOTE: This is a legacy function left in the code to be backwards
2898  * compatible with older userspace programs. It should eventually be
2899  * removed.
2900  *
2901  * Grabs the ni data from the ni structure and fills the out
2902  * parameters
2903  *
2904  * \param[in] ni network        interface structure
2905  * \param[out] config           config information
2906  */
2907 static void
2908 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2909                          struct lnet_ioctl_config_data *config)
2910 {
2911         struct lnet_ioctl_net_config *net_config;
2912         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2913         size_t min_size, tunable_size = 0;
2914         int i;
2915
2916         if (!ni || !config)
2917                 return;
2918
2919         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2920         if (!net_config)
2921                 return;
2922
2923         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2924                      ARRAY_SIZE(net_config->ni_interfaces));
2925
2926         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2927                 if (!ni->ni_interfaces[i])
2928                         break;
2929
2930                 strncpy(net_config->ni_interfaces[i],
2931                         ni->ni_interfaces[i],
2932                         sizeof(net_config->ni_interfaces[i]));
2933         }
2934
2935         config->cfg_nid = ni->ni_nid;
2936         config->cfg_config_u.cfg_net.net_peer_timeout =
2937                 ni->ni_net->net_tunables.lct_peer_timeout;
2938         config->cfg_config_u.cfg_net.net_max_tx_credits =
2939                 ni->ni_net->net_tunables.lct_max_tx_credits;
2940         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2941                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2942         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2943                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2944
2945         if (ni->ni_nid == LNET_NID_LO_0)
2946                 net_config->ni_status = LNET_NI_STATUS_UP;
2947         else
2948                 net_config->ni_status = ni->ni_status->ns_status;
2949
2950         if (ni->ni_cpts) {
2951                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2952
2953                 for (i = 0; i < num_cpts; i++)
2954                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2955
2956                 config->cfg_ncpts = num_cpts;
2957         }
2958
2959         /*
2960          * See if user land tools sent in a newer and larger version
2961          * of struct lnet_tunables than what the kernel uses.
2962          */
2963         min_size = sizeof(*config) + sizeof(*net_config);
2964
2965         if (config->cfg_hdr.ioc_len > min_size)
2966                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2967
2968         /* Don't copy too much data to user space */
2969         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2970         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2971
2972         if (lnd_cfg && min_size) {
2973                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2974                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2975
2976                 /* Tell user land that kernel side has less data */
2977                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2978                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2979                         config->cfg_hdr.ioc_len -= min_size;
2980                 }
2981         }
2982 }
2983
2984 struct lnet_ni *
2985 lnet_get_ni_idx_locked(int idx)
2986 {
2987         struct lnet_ni          *ni;
2988         struct lnet_net         *net;
2989
2990         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2991                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2992                         if (idx-- == 0)
2993                                 return ni;
2994                 }
2995         }
2996
2997         return NULL;
2998 }
2999
3000 struct lnet_ni *
3001 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3002 {
3003         struct lnet_ni          *ni;
3004         struct lnet_net         *net = mynet;
3005
3006         /*
3007          * It is possible that the net has been cleaned out while there is
3008          * a message being sent. This function accessed the net without
3009          * checking if the list is empty
3010          */
3011         if (prev == NULL) {
3012                 if (net == NULL)
3013                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3014                                         net_list);
3015                 if (list_empty(&net->net_ni_list))
3016                         return NULL;
3017                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3018                                 ni_netlist);
3019
3020                 return ni;
3021         }
3022
3023         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3024                 /* if you reached the end of the ni list and the net is
3025                  * specified, then there are no more nis in that net */
3026                 if (net != NULL)
3027                         return NULL;
3028
3029                 /* we reached the end of this net ni list. move to the
3030                  * next net */
3031                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3032                         /* no more nets and no more NIs. */
3033                         return NULL;
3034
3035                 /* get the next net */
3036                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3037                                  net_list);
3038                 if (list_empty(&net->net_ni_list))
3039                         return NULL;
3040                 /* get the ni on it */
3041                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3042                                 ni_netlist);
3043
3044                 return ni;
3045         }
3046
3047         if (list_empty(&prev->ni_netlist))
3048                 return NULL;
3049
3050         /* there are more nis left */
3051         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3052
3053         return ni;
3054 }
3055
3056 int
3057 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3058 {
3059         struct lnet_ni *ni;
3060         int cpt;
3061         int rc = -ENOENT;
3062         int idx = config->cfg_count;
3063
3064         cpt = lnet_net_lock_current();
3065
3066         ni = lnet_get_ni_idx_locked(idx);
3067
3068         if (ni != NULL) {
3069                 rc = 0;
3070                 lnet_ni_lock(ni);
3071                 lnet_fill_ni_info_legacy(ni, config);
3072                 lnet_ni_unlock(ni);
3073         }
3074
3075         lnet_net_unlock(cpt);
3076         return rc;
3077 }
3078
3079 int
3080 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3081                    struct lnet_ioctl_config_lnd_tunables *tun,
3082                    struct lnet_ioctl_element_stats *stats,
3083                    __u32 tun_size)
3084 {
3085         struct lnet_ni          *ni;
3086         int                     cpt;
3087         int                     rc = -ENOENT;
3088
3089         if (!cfg_ni || !tun || !stats)
3090                 return -EINVAL;
3091
3092         cpt = lnet_net_lock_current();
3093
3094         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3095
3096         if (ni) {
3097                 rc = 0;
3098                 lnet_ni_lock(ni);
3099                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3100                 lnet_ni_unlock(ni);
3101         }
3102
3103         lnet_net_unlock(cpt);
3104         return rc;
3105 }
3106
3107 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3108 {
3109         struct lnet_ni *ni;
3110         int cpt;
3111         int rc = -ENOENT;
3112
3113         if (!msg_stats)
3114                 return -EINVAL;
3115
3116         cpt = lnet_net_lock_current();
3117
3118         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3119
3120         if (ni) {
3121                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3122                 rc = 0;
3123         }
3124
3125         lnet_net_unlock(cpt);
3126
3127         return rc;
3128 }
3129
3130 static int lnet_add_net_common(struct lnet_net *net,
3131                                struct lnet_ioctl_config_lnd_tunables *tun)
3132 {
3133         __u32                   net_id;
3134         struct lnet_ping_buffer *pbuf;
3135         struct lnet_handle_md   ping_mdh;
3136         int                     rc;
3137         struct lnet_remotenet *rnet;
3138         int                     net_ni_count;
3139
3140         lnet_net_lock(LNET_LOCK_EX);
3141         rnet = lnet_find_rnet_locked(net->net_id);
3142         lnet_net_unlock(LNET_LOCK_EX);
3143         /*
3144          * make sure that the net added doesn't invalidate the current
3145          * configuration LNet is keeping
3146          */
3147         if (rnet) {
3148                 CERROR("Adding net %s will invalidate routing configuration\n",
3149                        libcfs_net2str(net->net_id));
3150                 lnet_net_free(net);
3151                 return -EUSERS;
3152         }
3153
3154         /*
3155          * make sure you calculate the correct number of slots in the ping
3156          * buffer. Since the ping info is a flattened list of all the NIs,
3157          * we should allocate enough slots to accomodate the number of NIs
3158          * which will be added.
3159          *
3160          * since ni hasn't been configured yet, use
3161          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3162          */
3163         net_ni_count = lnet_get_net_ni_count_pre(net);
3164
3165         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3166                                     net_ni_count + lnet_get_ni_count(),
3167                                     false);
3168         if (rc < 0) {
3169                 lnet_net_free(net);
3170                 return rc;
3171         }
3172
3173         if (tun)
3174                 memcpy(&net->net_tunables,
3175                        &tun->lt_cmn, sizeof(net->net_tunables));
3176         else
3177                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3178
3179         net_id = net->net_id;
3180
3181         rc = lnet_startup_lndnet(net,
3182                                  (tun) ? &tun->lt_tun : NULL);
3183         if (rc < 0)
3184                 goto failed;
3185
3186         lnet_net_lock(LNET_LOCK_EX);
3187         net = lnet_get_net_locked(net_id);
3188         lnet_net_unlock(LNET_LOCK_EX);
3189
3190         LASSERT(net);
3191
3192         /*
3193          * Start the acceptor thread if this is the first network
3194          * being added that requires the thread.
3195          */
3196         if (net->net_lnd->lnd_accept) {
3197                 rc = lnet_acceptor_start();
3198                 if (rc < 0) {
3199                         /* shutdown the net that we just started */
3200                         CERROR("Failed to start up acceptor thread\n");
3201                         lnet_shutdown_lndnet(net);
3202                         goto failed;
3203                 }
3204         }
3205
3206         lnet_net_lock(LNET_LOCK_EX);
3207         lnet_peer_net_added(net);
3208         lnet_net_unlock(LNET_LOCK_EX);
3209
3210         lnet_ping_target_update(pbuf, ping_mdh);
3211
3212         return 0;
3213
3214 failed:
3215         lnet_ping_md_unlink(pbuf, &ping_mdh);
3216         lnet_ping_buffer_decref(pbuf);
3217         return rc;
3218 }
3219
3220 static void
3221 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3222 {
3223         if (tun) {
3224                 if (!tun->lt_cmn.lct_peer_timeout)
3225                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3226                 if (!tun->lt_cmn.lct_peer_tx_credits)
3227                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3228                 if (!tun->lt_cmn.lct_max_tx_credits)
3229                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3230         }
3231 }
3232
3233 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3234                                       struct lnet_ioctl_config_lnd_tunables *tun)
3235 {
3236         struct lnet_net *net;
3237         const char *nets;
3238         int rc;
3239         LIST_HEAD(net_head);
3240
3241         rc = lnet_parse_ip2nets(&nets, ip2nets);
3242         if (rc < 0)
3243                 return rc;
3244
3245         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3246         if (rc < 0)
3247                 return rc;
3248
3249         lnet_set_tune_defaults(tun);
3250
3251         mutex_lock(&the_lnet.ln_api_mutex);
3252         while (!list_empty(&net_head)) {
3253                 net = list_entry(net_head.next, struct lnet_net, net_list);
3254                 list_del_init(&net->net_list);
3255                 rc = lnet_add_net_common(net, tun);
3256                 if (rc < 0)
3257                         goto out;
3258         }
3259
3260 out:
3261         mutex_unlock(&the_lnet.ln_api_mutex);
3262
3263         while (!list_empty(&net_head)) {
3264                 net = list_entry(net_head.next, struct lnet_net, net_list);
3265                 list_del_init(&net->net_list);
3266                 lnet_net_free(net);
3267         }
3268         return rc;
3269 }
3270
3271 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3272 {
3273         struct lnet_net *net;
3274         struct lnet_ni *ni;
3275         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3276         int rc, i;
3277         __u32 net_id, lnd_type;
3278
3279         /* get the tunables if they are available */
3280         if (conf->lic_cfg_hdr.ioc_len >=
3281             sizeof(*conf) + sizeof(*tun))
3282                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3283                         conf->lic_bulk;
3284
3285         /* handle legacy ip2nets from DLC */
3286         if (conf->lic_legacy_ip2nets[0] != '\0')
3287                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3288                                                   tun);
3289
3290         net_id = LNET_NIDNET(conf->lic_nid);
3291         lnd_type = LNET_NETTYP(net_id);
3292
3293         if (!libcfs_isknown_lnd(lnd_type)) {
3294                 CERROR("No valid net and lnd information provided\n");
3295                 return -EINVAL;
3296         }
3297
3298         net = lnet_net_alloc(net_id, NULL);
3299         if (!net)
3300                 return -ENOMEM;
3301
3302         for (i = 0; i < conf->lic_ncpts; i++) {
3303                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3304                         return -EINVAL;
3305         }
3306
3307         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3308                                        conf->lic_ni_intf[0]);
3309         if (!ni)
3310                 return -ENOMEM;
3311
3312         lnet_set_tune_defaults(tun);
3313
3314         mutex_lock(&the_lnet.ln_api_mutex);
3315
3316         rc = lnet_add_net_common(net, tun);
3317
3318         mutex_unlock(&the_lnet.ln_api_mutex);
3319
3320         return rc;
3321 }
3322
3323 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3324 {
3325         struct lnet_net  *net;
3326         struct lnet_ni *ni;
3327         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3328         struct lnet_ping_buffer *pbuf;
3329         struct lnet_handle_md  ping_mdh;
3330         int               rc;
3331         int               net_count;
3332         __u32             addr;
3333
3334         /* don't allow userspace to shutdown the LOLND */
3335         if (LNET_NETTYP(net_id) == LOLND)
3336                 return -EINVAL;
3337
3338         mutex_lock(&the_lnet.ln_api_mutex);
3339
3340         lnet_net_lock(0);
3341
3342         net = lnet_get_net_locked(net_id);
3343         if (!net) {
3344                 CERROR("net %s not found\n",
3345                        libcfs_net2str(net_id));
3346                 rc = -ENOENT;
3347                 goto unlock_net;
3348         }
3349
3350         addr = LNET_NIDADDR(conf->lic_nid);
3351         if (addr == 0) {
3352                 /* remove the entire net */
3353                 net_count = lnet_get_net_ni_count_locked(net);
3354
3355                 lnet_net_unlock(0);
3356
3357                 /* create and link a new ping info, before removing the old one */
3358                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3359                                         lnet_get_ni_count() - net_count,
3360                                         false);
3361                 if (rc != 0)
3362                         goto unlock_api_mutex;
3363
3364                 lnet_shutdown_lndnet(net);
3365
3366                 lnet_acceptor_stop();
3367
3368                 lnet_ping_target_update(pbuf, ping_mdh);
3369
3370                 goto unlock_api_mutex;
3371         }
3372
3373         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3374         if (!ni) {
3375                 CERROR("nid %s not found\n",
3376                        libcfs_nid2str(conf->lic_nid));
3377                 rc = -ENOENT;
3378                 goto unlock_net;
3379         }
3380
3381         net_count = lnet_get_net_ni_count_locked(net);
3382
3383         lnet_net_unlock(0);
3384
3385         /* create and link a new ping info, before removing the old one */
3386         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3387                                   lnet_get_ni_count() - 1, false);
3388         if (rc != 0)
3389                 goto unlock_api_mutex;
3390
3391         lnet_shutdown_lndni(ni);
3392
3393         lnet_acceptor_stop();
3394
3395         lnet_ping_target_update(pbuf, ping_mdh);
3396
3397         /* check if the net is empty and remove it if it is */
3398         if (net_count == 1)
3399                 lnet_shutdown_lndnet(net);
3400
3401         goto unlock_api_mutex;
3402
3403 unlock_net:
3404         lnet_net_unlock(0);
3405 unlock_api_mutex:
3406         mutex_unlock(&the_lnet.ln_api_mutex);
3407
3408         return rc;
3409 }
3410
3411 /*
3412  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3413  * They are only expected to be called for unique networks.
3414  * That can be as a result of older DLC library
3415  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3416  */
3417 int
3418 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3419 {
3420         struct lnet_net *net;
3421         LIST_HEAD(net_head);
3422         int rc;
3423         struct lnet_ioctl_config_lnd_tunables tun;
3424         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3425
3426         /* Create a net/ni structures for the network string */
3427         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3428         if (rc <= 0)
3429                 return rc == 0 ? -EINVAL : rc;
3430
3431         mutex_lock(&the_lnet.ln_api_mutex);
3432
3433         if (rc > 1) {
3434                 rc = -EINVAL; /* only add one network per call */
3435                 goto out_unlock_clean;
3436         }
3437
3438         net = list_entry(net_head.next, struct lnet_net, net_list);
3439         list_del_init(&net->net_list);
3440
3441         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3442
3443         memset(&tun, 0, sizeof(tun));
3444
3445         tun.lt_cmn.lct_peer_timeout =
3446           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3447                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3448         tun.lt_cmn.lct_peer_tx_credits =
3449           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3450                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3451         tun.lt_cmn.lct_peer_rtr_credits =
3452           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3453         tun.lt_cmn.lct_max_tx_credits =
3454           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3455                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3456
3457         rc = lnet_add_net_common(net, &tun);
3458
3459 out_unlock_clean:
3460         mutex_unlock(&the_lnet.ln_api_mutex);
3461         while (!list_empty(&net_head)) {
3462                 /* net_head list is empty in success case */
3463                 net = list_entry(net_head.next, struct lnet_net, net_list);
3464                 list_del_init(&net->net_list);
3465                 lnet_net_free(net);
3466         }
3467         return rc;
3468 }
3469
3470 int
3471 lnet_dyn_del_net(__u32 net_id)
3472 {
3473         struct lnet_net  *net;
3474         struct lnet_ping_buffer *pbuf;
3475         struct lnet_handle_md ping_mdh;
3476         int               rc;
3477         int               net_ni_count;
3478
3479         /* don't allow userspace to shutdown the LOLND */
3480         if (LNET_NETTYP(net_id) == LOLND)
3481                 return -EINVAL;
3482
3483         mutex_lock(&the_lnet.ln_api_mutex);
3484
3485         lnet_net_lock(0);
3486
3487         net = lnet_get_net_locked(net_id);
3488         if (net == NULL) {
3489                 lnet_net_unlock(0);
3490                 rc = -EINVAL;
3491                 goto out;
3492         }
3493
3494         net_ni_count = lnet_get_net_ni_count_locked(net);
3495
3496         lnet_net_unlock(0);
3497
3498         /* create and link a new ping info, before removing the old one */
3499         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3500                                     lnet_get_ni_count() - net_ni_count, false);
3501         if (rc != 0)
3502                 goto out;
3503
3504         lnet_shutdown_lndnet(net);
3505
3506         lnet_acceptor_stop();
3507
3508         lnet_ping_target_update(pbuf, ping_mdh);
3509
3510 out:
3511         mutex_unlock(&the_lnet.ln_api_mutex);
3512
3513         return rc;
3514 }
3515
3516 void lnet_incr_dlc_seq(void)
3517 {
3518         atomic_inc(&lnet_dlc_seq_no);
3519 }
3520
3521 __u32 lnet_get_dlc_seq_locked(void)
3522 {
3523         return atomic_read(&lnet_dlc_seq_no);
3524 }
3525
3526 static void
3527 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3528 {
3529         struct lnet_net *net;
3530         struct lnet_ni *ni;
3531
3532         lnet_net_lock(LNET_LOCK_EX);
3533         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3534                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3535                         if (ni->ni_nid == nid || all) {
3536                                 atomic_set(&ni->ni_healthv, value);
3537                                 if (list_empty(&ni->ni_recovery) &&
3538                                     value < LNET_MAX_HEALTH_VALUE) {
3539                                         CERROR("manually adding local NI %s to recovery\n",
3540                                                libcfs_nid2str(ni->ni_nid));
3541                                         list_add_tail(&ni->ni_recovery,
3542                                                       &the_lnet.ln_mt_localNIRecovq);
3543                                         lnet_ni_addref_locked(ni, 0);
3544                                 }
3545                                 if (!all) {
3546                                         lnet_net_unlock(LNET_LOCK_EX);
3547                                         return;
3548                                 }
3549                         }
3550                 }
3551         }
3552         lnet_net_unlock(LNET_LOCK_EX);
3553 }
3554
3555 static int
3556 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3557 {
3558         int cpt, rc = 0;
3559         struct lnet_ni *ni;
3560         lnet_nid_t nid = stats->hlni_nid;
3561
3562         cpt = lnet_net_lock_current();
3563         ni = lnet_nid2ni_locked(nid, cpt);
3564
3565         if (!ni) {
3566                 rc = -ENOENT;
3567                 goto unlock;
3568         }
3569
3570         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3571         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3572         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3573         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3574         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3575         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3576         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3577
3578 unlock:
3579         lnet_net_unlock(cpt);
3580
3581         return rc;
3582 }
3583
3584 static int
3585 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3586 {
3587         struct lnet_ni *ni;
3588         int i = 0;
3589
3590         lnet_net_lock(LNET_LOCK_EX);
3591         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3592                 list->rlst_nid_array[i] = ni->ni_nid;
3593                 i++;
3594                 if (i >= LNET_MAX_SHOW_NUM_NID)
3595                         break;
3596         }
3597         lnet_net_unlock(LNET_LOCK_EX);
3598         list->rlst_num_nids = i;
3599
3600         return 0;
3601 }
3602
3603 static int
3604 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3605 {
3606         struct lnet_peer_ni *lpni;
3607         int i = 0;
3608
3609         lnet_net_lock(LNET_LOCK_EX);
3610         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3611                 list->rlst_nid_array[i] = lpni->lpni_nid;
3612                 i++;
3613                 if (i >= LNET_MAX_SHOW_NUM_NID)
3614                         break;
3615         }
3616         lnet_net_unlock(LNET_LOCK_EX);
3617         list->rlst_num_nids = i;
3618
3619         return 0;
3620 }
3621
3622 /**
3623  * LNet ioctl handler.
3624  *
3625  */
3626 int
3627 LNetCtl(unsigned int cmd, void *arg)
3628 {
3629         struct libcfs_ioctl_data *data = arg;
3630         struct lnet_ioctl_config_data *config;
3631         struct lnet_process_id    id = {0};
3632         struct lnet_ni           *ni;
3633         int                       rc;
3634
3635         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3636                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3637
3638         switch (cmd) {
3639         case IOC_LIBCFS_GET_NI:
3640                 rc = LNetGetId(data->ioc_count, &id);
3641                 data->ioc_nid = id.nid;
3642                 return rc;
3643
3644         case IOC_LIBCFS_FAIL_NID:
3645                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3646
3647         case IOC_LIBCFS_ADD_ROUTE: {
3648                 /* default router sensitivity to 1 */
3649                 unsigned int sensitivity = 1;
3650                 config = arg;
3651
3652                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3653                         return -EINVAL;
3654
3655                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
3656                         sensitivity =
3657                           config->cfg_config_u.cfg_route.rtr_sensitivity;
3658                 }
3659
3660                 mutex_lock(&the_lnet.ln_api_mutex);
3661                 rc = lnet_add_route(config->cfg_net,
3662                                     config->cfg_config_u.cfg_route.rtr_hop,
3663                                     config->cfg_nid,
3664                                     config->cfg_config_u.cfg_route.
3665                                         rtr_priority, sensitivity);
3666                 mutex_unlock(&the_lnet.ln_api_mutex);
3667                 return rc;
3668         }
3669
3670         case IOC_LIBCFS_DEL_ROUTE:
3671                 config = arg;
3672
3673                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3674                         return -EINVAL;
3675
3676                 mutex_lock(&the_lnet.ln_api_mutex);
3677                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3678                 mutex_unlock(&the_lnet.ln_api_mutex);
3679                 return rc;
3680
3681         case IOC_LIBCFS_GET_ROUTE:
3682                 config = arg;
3683
3684                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3685                         return -EINVAL;
3686
3687                 mutex_lock(&the_lnet.ln_api_mutex);
3688                 rc = lnet_get_route(config->cfg_count,
3689                                     &config->cfg_net,
3690                                     &config->cfg_config_u.cfg_route.rtr_hop,
3691                                     &config->cfg_nid,
3692                                     &config->cfg_config_u.cfg_route.rtr_flags,
3693                                     &config->cfg_config_u.cfg_route.
3694                                         rtr_priority,
3695                                     &config->cfg_config_u.cfg_route.
3696                                         rtr_sensitivity);
3697                 mutex_unlock(&the_lnet.ln_api_mutex);
3698                 return rc;
3699
3700         case IOC_LIBCFS_GET_LOCAL_NI: {
3701                 struct lnet_ioctl_config_ni *cfg_ni;
3702                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3703                 struct lnet_ioctl_element_stats *stats;
3704                 __u32 tun_size;
3705
3706                 cfg_ni = arg;
3707
3708                 /* get the tunables if they are available */
3709                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3710                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3711                         return -EINVAL;
3712
3713                 stats = (struct lnet_ioctl_element_stats *)
3714                         cfg_ni->lic_bulk;
3715                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3716                                 (cfg_ni->lic_bulk + sizeof(*stats));
3717
3718                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3719                         sizeof(*stats);
3720
3721                 mutex_lock(&the_lnet.ln_api_mutex);
3722                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3723                 mutex_unlock(&the_lnet.ln_api_mutex);
3724                 return rc;
3725         }
3726
3727         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3728                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3729
3730                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3731                         return -EINVAL;
3732
3733                 mutex_lock(&the_lnet.ln_api_mutex);
3734                 rc = lnet_get_ni_stats(msg_stats);
3735                 mutex_unlock(&the_lnet.ln_api_mutex);
3736
3737                 return rc;
3738         }
3739
3740         case IOC_LIBCFS_GET_NET: {
3741                 size_t total = sizeof(*config) +
3742                                sizeof(struct lnet_ioctl_net_config);
3743                 config = arg;
3744
3745                 if (config->cfg_hdr.ioc_len < total)
3746                         return -EINVAL;
3747
3748                 mutex_lock(&the_lnet.ln_api_mutex);
3749                 rc = lnet_get_net_config(config);
3750                 mutex_unlock(&the_lnet.ln_api_mutex);
3751                 return rc;
3752         }
3753
3754         case IOC_LIBCFS_GET_LNET_STATS:
3755         {
3756                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3757
3758                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3759                         return -EINVAL;
3760
3761                 mutex_lock(&the_lnet.ln_api_mutex);
3762                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
3763                 mutex_unlock(&the_lnet.ln_api_mutex);
3764                 return rc;
3765         }
3766
3767         case IOC_LIBCFS_CONFIG_RTR:
3768                 config = arg;
3769
3770                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3771                         return -EINVAL;
3772
3773                 mutex_lock(&the_lnet.ln_api_mutex);
3774                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3775                         rc = lnet_rtrpools_enable();
3776                         mutex_unlock(&the_lnet.ln_api_mutex);
3777                         return rc;
3778                 }
3779                 lnet_rtrpools_disable();
3780                 mutex_unlock(&the_lnet.ln_api_mutex);
3781                 return 0;
3782
3783         case IOC_LIBCFS_ADD_BUF:
3784                 config = arg;
3785
3786                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3787                         return -EINVAL;
3788
3789                 mutex_lock(&the_lnet.ln_api_mutex);
3790                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3791                                                 buf_tiny,
3792                                           config->cfg_config_u.cfg_buffers.
3793                                                 buf_small,
3794                                           config->cfg_config_u.cfg_buffers.
3795                                                 buf_large);
3796                 mutex_unlock(&the_lnet.ln_api_mutex);
3797                 return rc;
3798
3799         case IOC_LIBCFS_SET_NUMA_RANGE: {
3800                 struct lnet_ioctl_set_value *numa;
3801                 numa = arg;
3802                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3803                         return -EINVAL;
3804                 lnet_net_lock(LNET_LOCK_EX);
3805                 lnet_numa_range = numa->sv_value;
3806                 lnet_net_unlock(LNET_LOCK_EX);
3807                 return 0;
3808         }
3809
3810         case IOC_LIBCFS_GET_NUMA_RANGE: {
3811                 struct lnet_ioctl_set_value *numa;
3812                 numa = arg;
3813                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3814                         return -EINVAL;
3815                 numa->sv_value = lnet_numa_range;
3816                 return 0;
3817         }
3818
3819         case IOC_LIBCFS_GET_BUF: {
3820                 struct lnet_ioctl_pool_cfg *pool_cfg;
3821                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3822
3823                 config = arg;
3824
3825                 if (config->cfg_hdr.ioc_len < total)
3826                         return -EINVAL;
3827
3828                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3829
3830                 mutex_lock(&the_lnet.ln_api_mutex);
3831                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3832                 mutex_unlock(&the_lnet.ln_api_mutex);
3833                 return rc;
3834         }
3835
3836         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3837                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3838
3839                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3840                         return -EINVAL;
3841
3842                 mutex_lock(&the_lnet.ln_api_mutex);
3843                 rc = lnet_get_local_ni_hstats(stats);
3844                 mutex_unlock(&the_lnet.ln_api_mutex);
3845
3846                 return rc;
3847         }
3848
3849         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3850                 struct lnet_ioctl_recovery_list *list = arg;
3851                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3852                         return -EINVAL;
3853
3854                 mutex_lock(&the_lnet.ln_api_mutex);
3855                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3856                         rc = lnet_get_local_ni_recovery_list(list);
3857                 else
3858                         rc = lnet_get_peer_ni_recovery_list(list);
3859                 mutex_unlock(&the_lnet.ln_api_mutex);
3860                 return rc;
3861         }
3862
3863         case IOC_LIBCFS_ADD_PEER_NI: {
3864                 struct lnet_ioctl_peer_cfg *cfg = arg;
3865
3866                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3867                         return -EINVAL;
3868
3869                 mutex_lock(&the_lnet.ln_api_mutex);
3870                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3871                                       cfg->prcfg_cfg_nid,
3872                                       cfg->prcfg_mr);
3873                 mutex_unlock(&the_lnet.ln_api_mutex);
3874                 return rc;
3875         }
3876
3877         case IOC_LIBCFS_DEL_PEER_NI: {
3878                 struct lnet_ioctl_peer_cfg *cfg = arg;
3879
3880                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3881                         return -EINVAL;
3882
3883                 mutex_lock(&the_lnet.ln_api_mutex);
3884                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3885                                       cfg->prcfg_cfg_nid);
3886                 mutex_unlock(&the_lnet.ln_api_mutex);
3887                 return rc;
3888         }
3889
3890         case IOC_LIBCFS_GET_PEER_INFO: {
3891                 struct lnet_ioctl_peer *peer_info = arg;
3892
3893                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3894                         return -EINVAL;
3895
3896                 mutex_lock(&the_lnet.ln_api_mutex);
3897                 rc = lnet_get_peer_ni_info(
3898                    peer_info->pr_count,
3899                    &peer_info->pr_nid,
3900                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3901                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3902                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3903                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3904                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3905                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3906                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3907                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3908                 mutex_unlock(&the_lnet.ln_api_mutex);
3909                 return rc;
3910         }
3911
3912         case IOC_LIBCFS_GET_PEER_NI: {
3913                 struct lnet_ioctl_peer_cfg *cfg = arg;
3914
3915                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3916                         return -EINVAL;
3917
3918                 mutex_lock(&the_lnet.ln_api_mutex);
3919                 rc = lnet_get_peer_info(cfg,
3920                                         (void __user *)cfg->prcfg_bulk);
3921                 mutex_unlock(&the_lnet.ln_api_mutex);
3922                 return rc;
3923         }
3924
3925         case IOC_LIBCFS_GET_PEER_LIST: {
3926                 struct lnet_ioctl_peer_cfg *cfg = arg;
3927
3928                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3929                         return -EINVAL;
3930
3931                 mutex_lock(&the_lnet.ln_api_mutex);
3932                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3933                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3934                 mutex_unlock(&the_lnet.ln_api_mutex);
3935                 return rc;
3936         }
3937
3938         case IOC_LIBCFS_SET_HEALHV: {
3939                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3940                 int value;
3941                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3942                         return -EINVAL;
3943                 if (cfg->rh_value < 0 ||
3944                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3945                         value = LNET_MAX_HEALTH_VALUE;
3946                 else
3947                         value = cfg->rh_value;
3948                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3949                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3950                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3951                 mutex_lock(&the_lnet.ln_api_mutex);
3952                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3953                         lnet_ni_set_healthv(cfg->rh_nid, value,
3954                                              cfg->rh_all);
3955                 else
3956                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3957                                                   cfg->rh_all);
3958                 mutex_unlock(&the_lnet.ln_api_mutex);
3959                 return 0;
3960         }
3961
3962         case IOC_LIBCFS_NOTIFY_ROUTER: {
3963                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3964
3965                 /* The deadline passed in by the user should be some time in
3966                  * seconds in the future since the UNIX epoch. We have to map
3967                  * that deadline to the wall clock.
3968                  */
3969                 deadline += ktime_get_seconds();
3970                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags, false,
3971                                    deadline);
3972         }
3973
3974         case IOC_LIBCFS_LNET_DIST:
3975                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3976                 if (rc < 0 && rc != -EHOSTUNREACH)
3977                         return rc;
3978
3979                 data->ioc_u32[0] = rc;
3980                 return 0;
3981
3982         case IOC_LIBCFS_TESTPROTOCOMPAT:
3983                 the_lnet.ln_testprotocompat = data->ioc_flags;
3984                 return 0;
3985
3986         case IOC_LIBCFS_LNET_FAULT:
3987                 return lnet_fault_ctl(data->ioc_flags, data);
3988
3989         case IOC_LIBCFS_PING: {
3990                 signed long timeout;
3991
3992                 id.nid = data->ioc_nid;
3993                 id.pid = data->ioc_u32[0];
3994
3995                 /* If timeout is negative then set default of 3 minutes */
3996                 if (((s32)data->ioc_u32[1] <= 0) ||
3997                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3998                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
3999                 else
4000                         timeout = nsecs_to_jiffies(data->ioc_u32[1] * NSEC_PER_MSEC);
4001
4002                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
4003                                data->ioc_plen1 / sizeof(struct lnet_process_id));
4004
4005                 if (rc < 0)
4006                         return rc;
4007
4008                 data->ioc_count = rc;
4009                 return 0;
4010         }
4011
4012         case IOC_LIBCFS_PING_PEER: {
4013                 struct lnet_ioctl_ping_data *ping = arg;
4014                 struct lnet_peer *lp;
4015                 signed long timeout;
4016
4017                 /* If timeout is negative then set default of 3 minutes */
4018                 if (((s32)ping->op_param) <= 0 ||
4019                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4020                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4021                 else
4022                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4023
4024                 rc = lnet_ping(ping->ping_id, timeout,
4025                                ping->ping_buf,
4026                                ping->ping_count);
4027                 if (rc < 0)
4028                         return rc;
4029
4030                 mutex_lock(&the_lnet.ln_api_mutex);
4031                 lp = lnet_find_peer(ping->ping_id.nid);
4032                 if (lp) {
4033                         ping->ping_id.nid = lp->lp_primary_nid;
4034                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4035                         lnet_peer_decref_locked(lp);
4036                 }
4037                 mutex_unlock(&the_lnet.ln_api_mutex);
4038
4039                 ping->ping_count = rc;
4040                 return 0;
4041         }
4042
4043         case IOC_LIBCFS_DISCOVER: {
4044                 struct lnet_ioctl_ping_data *discover = arg;
4045                 struct lnet_peer *lp;
4046
4047                 rc = lnet_discover(discover->ping_id, discover->op_param,
4048                                    discover->ping_buf,
4049                                    discover->ping_count);
4050                 if (rc < 0)
4051                         return rc;
4052
4053                 mutex_lock(&the_lnet.ln_api_mutex);
4054                 lp = lnet_find_peer(discover->ping_id.nid);
4055                 if (lp) {
4056                         discover->ping_id.nid = lp->lp_primary_nid;
4057                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4058                         lnet_peer_decref_locked(lp);
4059                 }
4060                 mutex_unlock(&the_lnet.ln_api_mutex);
4061
4062                 discover->ping_count = rc;
4063                 return 0;
4064         }
4065
4066         default:
4067                 ni = lnet_net2ni_addref(data->ioc_net);
4068                 if (ni == NULL)
4069                         return -EINVAL;
4070
4071                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4072                         rc = -EINVAL;
4073                 else
4074                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4075
4076                 lnet_ni_decref(ni);
4077                 return rc;
4078         }
4079         /* not reached */
4080 }
4081 EXPORT_SYMBOL(LNetCtl);
4082
4083 void LNetDebugPeer(struct lnet_process_id id)
4084 {
4085         lnet_debug_peer(id.nid);
4086 }
4087 EXPORT_SYMBOL(LNetDebugPeer);
4088
4089 /**
4090  * Determine if the specified peer \a nid is on the local node.
4091  *
4092  * \param nid   peer nid to check
4093  *
4094  * \retval true         If peer NID is on the local node.
4095  * \retval false        If peer NID is not on the local node.
4096  */
4097 bool LNetIsPeerLocal(lnet_nid_t nid)
4098 {
4099         struct lnet_net *net;
4100         struct lnet_ni *ni;
4101         int cpt;
4102
4103         cpt = lnet_net_lock_current();
4104         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4105                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4106                         if (ni->ni_nid == nid) {
4107                                 lnet_net_unlock(cpt);
4108                                 return true;
4109                         }
4110                 }
4111         }
4112         lnet_net_unlock(cpt);
4113
4114         return false;
4115 }
4116 EXPORT_SYMBOL(LNetIsPeerLocal);
4117
4118 /**
4119  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
4120  * Note that all interfaces share a same PID, as requested by LNetNIInit().
4121  *
4122  * \param index Index of the interface to look up.
4123  * \param id On successful return, this location will hold the
4124  * struct lnet_process_id ID of the interface.
4125  *
4126  * \retval 0 If an interface exists at \a index.
4127  * \retval -ENOENT If no interface has been found.
4128  */
4129 int
4130 LNetGetId(unsigned int index, struct lnet_process_id *id)
4131 {
4132         struct lnet_ni   *ni;
4133         struct lnet_net  *net;
4134         int               cpt;
4135         int               rc = -ENOENT;
4136
4137         LASSERT(the_lnet.ln_refcount > 0);
4138
4139         cpt = lnet_net_lock_current();
4140
4141         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4142                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4143                         if (index-- != 0)
4144                                 continue;
4145
4146                         id->nid = ni->ni_nid;
4147                         id->pid = the_lnet.ln_pid;
4148                         rc = 0;
4149                         break;
4150                 }
4151         }
4152
4153         lnet_net_unlock(cpt);
4154         return rc;
4155 }
4156 EXPORT_SYMBOL(LNetGetId);
4157
4158 struct ping_data {
4159         int rc;
4160         int replied;
4161         struct lnet_handle_md mdh;
4162         struct completion completion;
4163 };
4164
4165 static void
4166 lnet_ping_event_handler(struct lnet_event *event)
4167 {
4168         struct ping_data *pd = event->md_user_ptr;
4169
4170         CDEBUG(D_NET, "ping event (%d %d)%s\n",
4171                event->type, event->status,
4172                event->unlinked ? " unlinked" : "");
4173
4174         if (event->status) {
4175                 if (!pd->rc)
4176                         pd->rc = event->status;
4177         } else if (event->type == LNET_EVENT_REPLY) {
4178                 pd->replied = 1;
4179                 pd->rc = event->mlength;
4180         }
4181         if (event->unlinked)
4182                 complete(&pd->completion);
4183 }
4184
4185 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4186                      struct lnet_process_id __user *ids, int n_ids)
4187 {
4188         struct lnet_md md = { NULL };
4189         struct ping_data pd = { 0 };
4190         struct lnet_ping_buffer *pbuf;
4191         struct lnet_process_id tmpid;
4192         int i;
4193         int nob;
4194         int rc;
4195         int rc2;
4196
4197         /* n_ids limit is arbitrary */
4198         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4199                 return -EINVAL;
4200
4201         /*
4202          * if the user buffer has more space than the lnet_interfaces_max
4203          * then only fill it up to lnet_interfaces_max
4204          */
4205         if (n_ids > lnet_interfaces_max)
4206                 n_ids = lnet_interfaces_max;
4207
4208         if (id.pid == LNET_PID_ANY)
4209                 id.pid = LNET_PID_LUSTRE;
4210
4211         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4212         if (!pbuf)
4213                 return -ENOMEM;
4214
4215         /* initialize md content */
4216         md.start     = &pbuf->pb_info;
4217         md.length    = LNET_PING_INFO_SIZE(n_ids);
4218         md.threshold = 2; /* GET/REPLY */
4219         md.max_size  = 0;
4220         md.options   = LNET_MD_TRUNCATE;
4221         md.user_ptr  = &pd;
4222         md.handler   = lnet_ping_event_handler;
4223
4224         init_completion(&pd.completion);
4225
4226         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
4227         if (rc != 0) {
4228                 CERROR("Can't bind MD: %d\n", rc);
4229                 goto fail_ping_buffer_decref;
4230         }
4231
4232         rc = LNetGet(LNET_NID_ANY, pd.mdh, id,
4233                      LNET_RESERVED_PORTAL,
4234                      LNET_PROTO_PING_MATCHBITS, 0, false);
4235
4236         if (rc != 0) {
4237                 /* Don't CERROR; this could be deliberate! */
4238                 rc2 = LNetMDUnlink(pd.mdh);
4239                 LASSERT(rc2 == 0);
4240
4241                 /* NB must wait for the UNLINK event below... */
4242         }
4243
4244         if (wait_for_completion_timeout(&pd.completion, timeout) == 0) {
4245                 /* Ensure completion in finite time... */
4246                 LNetMDUnlink(pd.mdh);
4247                 wait_for_completion(&pd.completion);
4248         }
4249         if (!pd.replied) {
4250                 rc = -EIO;
4251                 goto fail_ping_buffer_decref;
4252         }
4253
4254         nob = pd.rc;
4255         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4256
4257         rc = -EPROTO;           /* if I can't parse... */
4258
4259         if (nob < 8) {
4260                 CERROR("%s: ping info too short %d\n",
4261                        libcfs_id2str(id), nob);
4262                 goto fail_ping_buffer_decref;
4263         }
4264
4265         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4266                 lnet_swap_pinginfo(pbuf);
4267         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4268                 CERROR("%s: Unexpected magic %08x\n",
4269                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4270                 goto fail_ping_buffer_decref;
4271         }
4272
4273         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4274                 CERROR("%s: ping w/o NI status: 0x%x\n",
4275                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4276                 goto fail_ping_buffer_decref;
4277         }
4278
4279         if (nob < LNET_PING_INFO_SIZE(0)) {
4280                 CERROR("%s: Short reply %d(%d min)\n",
4281                        libcfs_id2str(id),
4282                        nob, (int)LNET_PING_INFO_SIZE(0));
4283                 goto fail_ping_buffer_decref;
4284         }
4285
4286         if (pbuf->pb_info.pi_nnis < n_ids)
4287                 n_ids = pbuf->pb_info.pi_nnis;
4288
4289         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4290                 CERROR("%s: Short reply %d(%d expected)\n",
4291                        libcfs_id2str(id),
4292                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4293                 goto fail_ping_buffer_decref;
4294         }
4295
4296         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4297
4298         memset(&tmpid, 0, sizeof(tmpid));
4299         for (i = 0; i < n_ids; i++) {
4300                 tmpid.pid = pbuf->pb_info.pi_pid;
4301                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4302                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4303                         goto fail_ping_buffer_decref;
4304         }
4305         rc = pbuf->pb_info.pi_nnis;
4306
4307  fail_ping_buffer_decref:
4308         lnet_ping_buffer_decref(pbuf);
4309         return rc;
4310 }
4311
4312 static int
4313 lnet_discover(struct lnet_process_id id, __u32 force,
4314               struct lnet_process_id __user *ids, int n_ids)
4315 {
4316         struct lnet_peer_ni *lpni;
4317         struct lnet_peer_ni *p;
4318         struct lnet_peer *lp;
4319         struct lnet_process_id *buf;
4320         int cpt;
4321         int i;
4322         int rc;
4323
4324         if (n_ids <= 0 ||
4325             id.nid == LNET_NID_ANY)
4326                 return -EINVAL;
4327
4328         if (id.pid == LNET_PID_ANY)
4329                 id.pid = LNET_PID_LUSTRE;
4330
4331         /*
4332          * If the user buffer has more space than the lnet_interfaces_max,
4333          * then only fill it up to lnet_interfaces_max.
4334          */
4335         if (n_ids > lnet_interfaces_max)
4336                 n_ids = lnet_interfaces_max;
4337
4338         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
4339         if (!buf)
4340                 return -ENOMEM;
4341
4342         cpt = lnet_net_lock_current();
4343         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4344         if (IS_ERR(lpni)) {
4345                 rc = PTR_ERR(lpni);
4346                 goto out;
4347         }
4348
4349         /*
4350          * Clearing the NIDS_UPTODATE flag ensures the peer will
4351          * be discovered, provided discovery has not been disabled.
4352          */
4353         lp = lpni->lpni_peer_net->lpn_peer;
4354         spin_lock(&lp->lp_lock);
4355         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4356         /* If the force flag is set, force a PING and PUSH as well. */
4357         if (force)
4358                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4359         spin_unlock(&lp->lp_lock);
4360         rc = lnet_discover_peer_locked(lpni, cpt, true);
4361         if (rc)
4362                 goto out_decref;
4363
4364         i = 0;
4365         p = NULL;
4366         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4367                 buf[i].pid = id.pid;
4368                 buf[i].nid = p->lpni_nid;
4369                 if (++i >= n_ids)
4370                         break;
4371         }
4372         rc = i;
4373
4374 out_decref:
4375         lnet_peer_ni_decref_locked(lpni);
4376 out:
4377         lnet_net_unlock(cpt);
4378
4379         if (rc >= 0)
4380                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
4381                         rc = -EFAULT;
4382         CFS_FREE_PTR_ARRAY(buf, n_ids);
4383
4384         return rc;
4385 }
4386
4387 /**
4388  * Retrieve peer discovery status.
4389  *
4390  * \retval 1 if lnet_peer_discovery_disabled is 0
4391  * \retval 0 if lnet_peer_discovery_disabled is 1
4392  */
4393 int
4394 LNetGetPeerDiscoveryStatus(void)
4395 {
4396         return !lnet_peer_discovery_disabled;
4397 }
4398 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);