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