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