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