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