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