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