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