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