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