Whamcloud - gitweb
99ccfd776be56b33d156c1c7188a1be790914833
[fs/lustre-release.git] / lnet / lnet / api-ni.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  */
32
33 #define DEBUG_SUBSYSTEM S_LNET
34
35 #include <linux/ctype.h>
36 #include <linux/log2.h>
37 #include <linux/ktime.h>
38 #include <linux/moduleparam.h>
39 #include <linux/uaccess.h>
40
41 #include <lnet/lib-lnet.h>
42
43 #define D_LNI D_CONSOLE
44
45 /*
46  * initialize ln_api_mutex statically, since it needs to be used in
47  * discovery_set callback. That module parameter callback can be called
48  * before module init completes. The mutex needs to be ready for use then.
49  */
50 struct lnet the_lnet = {
51         .ln_api_mutex = __MUTEX_INITIALIZER(the_lnet.ln_api_mutex),
52 };              /* THE state of the network */
53 EXPORT_SYMBOL(the_lnet);
54
55 static char *ip2nets = "";
56 module_param(ip2nets, charp, 0444);
57 MODULE_PARM_DESC(ip2nets, "LNET network <- IP table");
58
59 static char *networks = "";
60 module_param(networks, charp, 0444);
61 MODULE_PARM_DESC(networks, "local networks");
62
63 static char *routes = "";
64 module_param(routes, charp, 0444);
65 MODULE_PARM_DESC(routes, "routes to non-local networks");
66
67 static int rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
68 module_param(rnet_htable_size, int, 0444);
69 MODULE_PARM_DESC(rnet_htable_size, "size of remote network hash table");
70
71 static int use_tcp_bonding = false;
72 module_param(use_tcp_bonding, int, 0444);
73 MODULE_PARM_DESC(use_tcp_bonding,
74                  "Set to 1 to use socklnd bonding. 0 to use Multi-Rail");
75
76 unsigned int lnet_numa_range = 0;
77 module_param(lnet_numa_range, uint, 0444);
78 MODULE_PARM_DESC(lnet_numa_range,
79                 "NUMA range to consider during Multi-Rail selection");
80
81 /*
82  * lnet_health_sensitivity determines by how much we decrement the health
83  * value on sending error. The value defaults to 100, which means health
84  * interface health is decremented by 100 points every failure.
85  */
86 unsigned int lnet_health_sensitivity = 100;
87 static int sensitivity_set(const char *val, cfs_kernel_param_arg_t *kp);
88 #ifdef HAVE_KERNEL_PARAM_OPS
89 static struct kernel_param_ops param_ops_health_sensitivity = {
90         .set = sensitivity_set,
91         .get = param_get_int,
92 };
93 #define param_check_health_sensitivity(name, p) \
94                 __param_check(name, p, int)
95 module_param(lnet_health_sensitivity, health_sensitivity, S_IRUGO|S_IWUSR);
96 #else
97 module_param_call(lnet_health_sensitivity, sensitivity_set, param_get_int,
98                   &lnet_health_sensitivity, S_IRUGO|S_IWUSR);
99 #endif
100 MODULE_PARM_DESC(lnet_health_sensitivity,
101                 "Value to decrement the health value by on error");
102
103 /*
104  * lnet_recovery_interval determines how often we should perform recovery
105  * on unhealthy interfaces.
106  */
107 unsigned int lnet_recovery_interval = 1;
108 static int recovery_interval_set(const char *val, cfs_kernel_param_arg_t *kp);
109 #ifdef HAVE_KERNEL_PARAM_OPS
110 static struct kernel_param_ops param_ops_recovery_interval = {
111         .set = recovery_interval_set,
112         .get = param_get_int,
113 };
114 #define param_check_recovery_interval(name, p) \
115                 __param_check(name, p, int)
116 module_param(lnet_recovery_interval, recovery_interval, S_IRUGO|S_IWUSR);
117 #else
118 module_param_call(lnet_recovery_interval, recovery_interval_set, param_get_int,
119                   &lnet_recovery_interval, S_IRUGO|S_IWUSR);
120 #endif
121 MODULE_PARM_DESC(lnet_recovery_interval,
122                 "Interval to recover unhealthy interfaces in seconds");
123
124 static int lnet_interfaces_max = LNET_INTERFACES_MAX_DEFAULT;
125 static int intf_max_set(const char *val, cfs_kernel_param_arg_t *kp);
126
127 static struct kernel_param_ops param_ops_interfaces_max = {
128         .set = intf_max_set,
129         .get = param_get_int,
130 };
131
132 #define param_check_interfaces_max(name, p) \
133                 __param_check(name, p, int)
134
135 #ifdef HAVE_KERNEL_PARAM_OPS
136 module_param(lnet_interfaces_max, interfaces_max, 0644);
137 #else
138 module_param_call(lnet_interfaces_max, intf_max_set, param_get_int,
139                   &param_ops_interfaces_max, 0644);
140 #endif
141 MODULE_PARM_DESC(lnet_interfaces_max,
142                 "Maximum number of interfaces in a node.");
143
144 unsigned lnet_peer_discovery_disabled = 0;
145 static int discovery_set(const char *val, cfs_kernel_param_arg_t *kp);
146
147 static struct kernel_param_ops param_ops_discovery_disabled = {
148         .set = discovery_set,
149         .get = param_get_int,
150 };
151
152 #define param_check_discovery_disabled(name, p) \
153                 __param_check(name, p, int)
154 #ifdef HAVE_KERNEL_PARAM_OPS
155 module_param(lnet_peer_discovery_disabled, discovery_disabled, 0644);
156 #else
157 module_param_call(lnet_peer_discovery_disabled, discovery_set, param_get_int,
158                   &param_ops_discovery_disabled, 0644);
159 #endif
160 MODULE_PARM_DESC(lnet_peer_discovery_disabled,
161                 "Set to 1 to disable peer discovery on this node.");
162
163 unsigned int lnet_drop_asym_route;
164 static int drop_asym_route_set(const char *val, cfs_kernel_param_arg_t *kp);
165
166 static struct kernel_param_ops param_ops_drop_asym_route = {
167         .set = drop_asym_route_set,
168         .get = param_get_int,
169 };
170
171 #define param_check_drop_asym_route(name, p)    \
172         __param_check(name, p, int)
173 #ifdef HAVE_KERNEL_PARAM_OPS
174 module_param(lnet_drop_asym_route, drop_asym_route, 0644);
175 #else
176 module_param_call(lnet_drop_asym_route, drop_asym_route_set, param_get_int,
177                   &param_ops_drop_asym_route, 0644);
178 #endif
179 MODULE_PARM_DESC(lnet_drop_asym_route,
180                  "Set to 1 to drop asymmetrical route messages.");
181
182 #define LNET_TRANSACTION_TIMEOUT_NO_HEALTH_DEFAULT 50
183 #define LNET_TRANSACTION_TIMEOUT_HEALTH_DEFAULT 10
184
185 unsigned lnet_transaction_timeout = LNET_TRANSACTION_TIMEOUT_HEALTH_DEFAULT;
186 static int transaction_to_set(const char *val, cfs_kernel_param_arg_t *kp);
187 #ifdef HAVE_KERNEL_PARAM_OPS
188 static struct kernel_param_ops param_ops_transaction_timeout = {
189         .set = transaction_to_set,
190         .get = param_get_int,
191 };
192
193 #define param_check_transaction_timeout(name, p) \
194                 __param_check(name, p, int)
195 module_param(lnet_transaction_timeout, transaction_timeout, S_IRUGO|S_IWUSR);
196 #else
197 module_param_call(lnet_transaction_timeout, transaction_to_set, param_get_int,
198                   &lnet_transaction_timeout, S_IRUGO|S_IWUSR);
199 #endif
200 MODULE_PARM_DESC(lnet_transaction_timeout,
201                 "Maximum number of seconds to wait for a peer response.");
202
203 #define LNET_RETRY_COUNT_HEALTH_DEFAULT 3
204 unsigned lnet_retry_count = LNET_RETRY_COUNT_HEALTH_DEFAULT;
205 static int retry_count_set(const char *val, cfs_kernel_param_arg_t *kp);
206 #ifdef HAVE_KERNEL_PARAM_OPS
207 static struct kernel_param_ops param_ops_retry_count = {
208         .set = retry_count_set,
209         .get = param_get_int,
210 };
211
212 #define param_check_retry_count(name, p) \
213                 __param_check(name, p, int)
214 module_param(lnet_retry_count, retry_count, S_IRUGO|S_IWUSR);
215 #else
216 module_param_call(lnet_retry_count, retry_count_set, param_get_int,
217                   &lnet_retry_count, S_IRUGO|S_IWUSR);
218 #endif
219 MODULE_PARM_DESC(lnet_retry_count,
220                  "Maximum number of times to retry transmitting a message");
221
222
223 unsigned lnet_lnd_timeout = LNET_LND_DEFAULT_TIMEOUT;
224
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 static int lnet_unprepare(void);
1103
1104 static int
1105 lnet_prepare(lnet_pid_t requested_pid)
1106 {
1107         /* Prepare to bring up the network */
1108         struct lnet_res_container **recs;
1109         int                       rc = 0;
1110
1111         if (requested_pid == LNET_PID_ANY) {
1112                 /* Don't instantiate LNET just for me */
1113                 return -ENETDOWN;
1114         }
1115
1116         LASSERT(the_lnet.ln_refcount == 0);
1117
1118         the_lnet.ln_routing = 0;
1119
1120         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1121         the_lnet.ln_pid = requested_pid;
1122
1123         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1124         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1125         INIT_LIST_HEAD(&the_lnet.ln_nets);
1126         INIT_LIST_HEAD(&the_lnet.ln_routers);
1127         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1128         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1129         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1130         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1131         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1132         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1133         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1134         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1135         LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
1136
1137         rc = lnet_descriptor_setup();
1138         if (rc != 0)
1139                 goto failed;
1140
1141         rc = lnet_create_remote_nets_table();
1142         if (rc != 0)
1143                 goto failed;
1144
1145         /*
1146          * NB the interface cookie in wire handles guards against delayed
1147          * replies and ACKs appearing valid after reboot.
1148          */
1149         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1150
1151         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1152                                                 sizeof(struct lnet_counters));
1153         if (the_lnet.ln_counters == NULL) {
1154                 CERROR("Failed to allocate counters for LNet\n");
1155                 rc = -ENOMEM;
1156                 goto failed;
1157         }
1158
1159         rc = lnet_peer_tables_create();
1160         if (rc != 0)
1161                 goto failed;
1162
1163         rc = lnet_msg_containers_create();
1164         if (rc != 0)
1165                 goto failed;
1166
1167         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1168                                       LNET_COOKIE_TYPE_EQ);
1169         if (rc != 0)
1170                 goto failed;
1171
1172         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
1173         if (recs == NULL) {
1174                 rc = -ENOMEM;
1175                 goto failed;
1176         }
1177
1178         the_lnet.ln_me_containers = recs;
1179
1180         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1181         if (recs == NULL) {
1182                 rc = -ENOMEM;
1183                 goto failed;
1184         }
1185
1186         the_lnet.ln_md_containers = recs;
1187
1188         rc = lnet_portals_create();
1189         if (rc != 0) {
1190                 CERROR("Failed to create portals for LNet: %d\n", rc);
1191                 goto failed;
1192         }
1193
1194         return 0;
1195
1196  failed:
1197         lnet_unprepare();
1198         return rc;
1199 }
1200
1201 static int
1202 lnet_unprepare (void)
1203 {
1204         int rc;
1205
1206         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1207          * have shut down already, so it is safe to unlink and free all
1208          * descriptors, even those that appear committed to a network op (eg MD
1209          * with non-zero pending count) */
1210
1211         lnet_fail_nid(LNET_NID_ANY, 0);
1212
1213         LASSERT(the_lnet.ln_refcount == 0);
1214         LASSERT(list_empty(&the_lnet.ln_test_peers));
1215         LASSERT(list_empty(&the_lnet.ln_nets));
1216
1217         if (!LNetEQHandleIsInvalid(the_lnet.ln_mt_eqh)) {
1218                 rc = LNetEQFree(the_lnet.ln_mt_eqh);
1219                 LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
1220                 LASSERT(rc == 0);
1221         }
1222
1223         lnet_portals_destroy();
1224
1225         if (the_lnet.ln_md_containers != NULL) {
1226                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1227                 the_lnet.ln_md_containers = NULL;
1228         }
1229
1230         if (the_lnet.ln_me_containers != NULL) {
1231                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
1232                 the_lnet.ln_me_containers = NULL;
1233         }
1234
1235         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1236
1237         lnet_msg_containers_destroy();
1238         lnet_peer_uninit();
1239         lnet_rtrpools_free(0);
1240
1241         if (the_lnet.ln_counters != NULL) {
1242                 cfs_percpt_free(the_lnet.ln_counters);
1243                 the_lnet.ln_counters = NULL;
1244         }
1245         lnet_destroy_remote_nets_table();
1246         lnet_descriptor_cleanup();
1247
1248         return 0;
1249 }
1250
1251 struct lnet_ni  *
1252 lnet_net2ni_locked(__u32 net_id, int cpt)
1253 {
1254         struct lnet_ni   *ni;
1255         struct lnet_net  *net;
1256
1257         LASSERT(cpt != LNET_LOCK_EX);
1258
1259         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1260                 if (net->net_id == net_id) {
1261                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1262                                         ni_netlist);
1263                         return ni;
1264                 }
1265         }
1266
1267         return NULL;
1268 }
1269
1270 struct lnet_ni *
1271 lnet_net2ni_addref(__u32 net)
1272 {
1273         struct lnet_ni *ni;
1274
1275         lnet_net_lock(0);
1276         ni = lnet_net2ni_locked(net, 0);
1277         if (ni)
1278                 lnet_ni_addref_locked(ni, 0);
1279         lnet_net_unlock(0);
1280
1281         return ni;
1282 }
1283 EXPORT_SYMBOL(lnet_net2ni_addref);
1284
1285 struct lnet_net *
1286 lnet_get_net_locked(__u32 net_id)
1287 {
1288         struct lnet_net  *net;
1289
1290         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1291                 if (net->net_id == net_id)
1292                         return net;
1293         }
1294
1295         return NULL;
1296 }
1297
1298 unsigned int
1299 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1300 {
1301         __u64           key = nid;
1302         unsigned int    val;
1303
1304         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1305
1306         if (number == 1)
1307                 return 0;
1308
1309         val = hash_long(key, LNET_CPT_BITS);
1310         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1311         if (val < number)
1312                 return val;
1313
1314         return (unsigned int)(key + val + (val >> 1)) % number;
1315 }
1316
1317 int
1318 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1319 {
1320         struct lnet_net *net;
1321
1322         /* must called with hold of lnet_net_lock */
1323         if (LNET_CPT_NUMBER == 1)
1324                 return 0; /* the only one */
1325
1326         /*
1327          * If NI is provided then use the CPT identified in the NI cpt
1328          * list if one exists. If one doesn't exist, then that NI is
1329          * associated with all CPTs and it follows that the net it belongs
1330          * to is implicitly associated with all CPTs, so just hash the nid
1331          * and return that.
1332          */
1333         if (ni != NULL) {
1334                 if (ni->ni_cpts != NULL)
1335                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1336                                                              ni->ni_ncpts)];
1337                 else
1338                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1339         }
1340
1341         /* no NI provided so look at the net */
1342         net = lnet_get_net_locked(LNET_NIDNET(nid));
1343
1344         if (net != NULL && net->net_cpts != NULL) {
1345                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1346         }
1347
1348         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1349 }
1350
1351 int
1352 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1353 {
1354         int     cpt;
1355         int     cpt2;
1356
1357         if (LNET_CPT_NUMBER == 1)
1358                 return 0; /* the only one */
1359
1360         cpt = lnet_net_lock_current();
1361
1362         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1363
1364         lnet_net_unlock(cpt);
1365
1366         return cpt2;
1367 }
1368 EXPORT_SYMBOL(lnet_cpt_of_nid);
1369
1370 int
1371 lnet_islocalnet(__u32 net_id)
1372 {
1373         struct lnet_net *net;
1374         int             cpt;
1375         bool            local;
1376
1377         cpt = lnet_net_lock_current();
1378
1379         net = lnet_get_net_locked(net_id);
1380
1381         local = net != NULL;
1382
1383         lnet_net_unlock(cpt);
1384
1385         return local;
1386 }
1387
1388 struct lnet_ni  *
1389 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1390 {
1391         struct lnet_net  *net;
1392         struct lnet_ni   *ni;
1393
1394         LASSERT(cpt != LNET_LOCK_EX);
1395
1396         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1397                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1398                         if (ni->ni_nid == nid)
1399                                 return ni;
1400                 }
1401         }
1402
1403         return NULL;
1404 }
1405
1406 struct lnet_ni *
1407 lnet_nid2ni_addref(lnet_nid_t nid)
1408 {
1409         struct lnet_ni *ni;
1410
1411         lnet_net_lock(0);
1412         ni = lnet_nid2ni_locked(nid, 0);
1413         if (ni)
1414                 lnet_ni_addref_locked(ni, 0);
1415         lnet_net_unlock(0);
1416
1417         return ni;
1418 }
1419 EXPORT_SYMBOL(lnet_nid2ni_addref);
1420
1421 int
1422 lnet_islocalnid(lnet_nid_t nid)
1423 {
1424         struct lnet_ni  *ni;
1425         int             cpt;
1426
1427         cpt = lnet_net_lock_current();
1428         ni = lnet_nid2ni_locked(nid, cpt);
1429         lnet_net_unlock(cpt);
1430
1431         return ni != NULL;
1432 }
1433
1434 int
1435 lnet_count_acceptor_nets(void)
1436 {
1437         /* Return the # of NIs that need the acceptor. */
1438         int              count = 0;
1439         struct lnet_net  *net;
1440         int              cpt;
1441
1442         cpt = lnet_net_lock_current();
1443         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1444                 /* all socklnd type networks should have the acceptor
1445                  * thread started */
1446                 if (net->net_lnd->lnd_accept != NULL)
1447                         count++;
1448         }
1449
1450         lnet_net_unlock(cpt);
1451
1452         return count;
1453 }
1454
1455 struct lnet_ping_buffer *
1456 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1457 {
1458         struct lnet_ping_buffer *pbuf;
1459
1460         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1461         if (pbuf) {
1462                 pbuf->pb_nnis = nnis;
1463                 atomic_set(&pbuf->pb_refcnt, 1);
1464         }
1465
1466         return pbuf;
1467 }
1468
1469 void
1470 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1471 {
1472         LASSERT(lnet_ping_buffer_numref(pbuf) == 0);
1473         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1474 }
1475
1476 static struct lnet_ping_buffer *
1477 lnet_ping_target_create(int nnis)
1478 {
1479         struct lnet_ping_buffer *pbuf;
1480
1481         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1482         if (pbuf == NULL) {
1483                 CERROR("Can't allocate ping source [%d]\n", nnis);
1484                 return NULL;
1485         }
1486
1487         pbuf->pb_info.pi_nnis = nnis;
1488         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1489         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1490         pbuf->pb_info.pi_features =
1491                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1492
1493         return pbuf;
1494 }
1495
1496 static inline int
1497 lnet_get_net_ni_count_locked(struct lnet_net *net)
1498 {
1499         struct lnet_ni  *ni;
1500         int             count = 0;
1501
1502         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1503                 count++;
1504
1505         return count;
1506 }
1507
1508 static inline int
1509 lnet_get_net_ni_count_pre(struct lnet_net *net)
1510 {
1511         struct lnet_ni  *ni;
1512         int             count = 0;
1513
1514         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1515                 count++;
1516
1517         return count;
1518 }
1519
1520 static inline int
1521 lnet_get_ni_count(void)
1522 {
1523         struct lnet_ni  *ni;
1524         struct lnet_net *net;
1525         int             count = 0;
1526
1527         lnet_net_lock(0);
1528
1529         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1530                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1531                         count++;
1532         }
1533
1534         lnet_net_unlock(0);
1535
1536         return count;
1537 }
1538
1539 int
1540 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1541 {
1542         if (!pinfo)
1543                 return -EINVAL;
1544         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1545                 return -EPROTO;
1546         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1547                 return -EPROTO;
1548         /* Loopback is guaranteed to be present */
1549         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1550                 return -ERANGE;
1551         if (LNET_NETTYP(LNET_NIDNET(LNET_PING_INFO_LONI(pinfo))) != LOLND)
1552                 return -EPROTO;
1553         return 0;
1554 }
1555
1556 static void
1557 lnet_ping_target_destroy(void)
1558 {
1559         struct lnet_net *net;
1560         struct lnet_ni  *ni;
1561
1562         lnet_net_lock(LNET_LOCK_EX);
1563
1564         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1565                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1566                         lnet_ni_lock(ni);
1567                         ni->ni_status = NULL;
1568                         lnet_ni_unlock(ni);
1569                 }
1570         }
1571
1572         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1573         the_lnet.ln_ping_target = NULL;
1574
1575         lnet_net_unlock(LNET_LOCK_EX);
1576 }
1577
1578 static void
1579 lnet_ping_target_event_handler(struct lnet_event *event)
1580 {
1581         struct lnet_ping_buffer *pbuf = event->md.user_ptr;
1582
1583         if (event->unlinked)
1584                 lnet_ping_buffer_decref(pbuf);
1585 }
1586
1587 static int
1588 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1589                        struct lnet_handle_md *ping_mdh,
1590                        int ni_count, bool set_eq)
1591 {
1592         struct lnet_process_id id = {
1593                 .nid = LNET_NID_ANY,
1594                 .pid = LNET_PID_ANY
1595         };
1596         struct lnet_handle_me me_handle;
1597         struct lnet_md md = { NULL };
1598         int rc, rc2;
1599
1600         if (set_eq) {
1601                 rc = LNetEQAlloc(0, lnet_ping_target_event_handler,
1602                                  &the_lnet.ln_ping_target_eq);
1603                 if (rc != 0) {
1604                         CERROR("Can't allocate ping buffer EQ: %d\n", rc);
1605                         return rc;
1606                 }
1607         }
1608
1609         *ppbuf = lnet_ping_target_create(ni_count);
1610         if (*ppbuf == NULL) {
1611                 rc = -ENOMEM;
1612                 goto fail_free_eq;
1613         }
1614
1615         /* Ping target ME/MD */
1616         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1617                           LNET_PROTO_PING_MATCHBITS, 0,
1618                           LNET_UNLINK, LNET_INS_AFTER,
1619                           &me_handle);
1620         if (rc != 0) {
1621                 CERROR("Can't create ping target ME: %d\n", rc);
1622                 goto fail_decref_ping_buffer;
1623         }
1624
1625         /* initialize md content */
1626         md.start     = &(*ppbuf)->pb_info;
1627         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1628         md.threshold = LNET_MD_THRESH_INF;
1629         md.max_size  = 0;
1630         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1631                        LNET_MD_MANAGE_REMOTE;
1632         md.eq_handle = the_lnet.ln_ping_target_eq;
1633         md.user_ptr  = *ppbuf;
1634
1635         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, ping_mdh);
1636         if (rc != 0) {
1637                 CERROR("Can't attach ping target MD: %d\n", rc);
1638                 goto fail_unlink_ping_me;
1639         }
1640         lnet_ping_buffer_addref(*ppbuf);
1641
1642         return 0;
1643
1644 fail_unlink_ping_me:
1645         rc2 = LNetMEUnlink(me_handle);
1646         LASSERT(rc2 == 0);
1647 fail_decref_ping_buffer:
1648         LASSERT(lnet_ping_buffer_numref(*ppbuf) == 1);
1649         lnet_ping_buffer_decref(*ppbuf);
1650         *ppbuf = NULL;
1651 fail_free_eq:
1652         if (set_eq) {
1653                 rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1654                 LASSERT(rc2 == 0);
1655         }
1656         return rc;
1657 }
1658
1659 static void
1660 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1661                     struct lnet_handle_md *ping_mdh)
1662 {
1663         sigset_t        blocked = cfs_block_allsigs();
1664
1665         LNetMDUnlink(*ping_mdh);
1666         LNetInvalidateMDHandle(ping_mdh);
1667
1668         /* NB the MD could be busy; this just starts the unlink */
1669         while (lnet_ping_buffer_numref(pbuf) > 1) {
1670                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1671                 set_current_state(TASK_UNINTERRUPTIBLE);
1672                 schedule_timeout(cfs_time_seconds(1));
1673         }
1674
1675         cfs_restore_sigs(blocked);
1676 }
1677
1678 static void
1679 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1680 {
1681         struct lnet_ni          *ni;
1682         struct lnet_net         *net;
1683         struct lnet_ni_status *ns;
1684         int                     i;
1685         int                     rc;
1686
1687         i = 0;
1688         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1689                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1690                         LASSERT(i < pbuf->pb_nnis);
1691
1692                         ns = &pbuf->pb_info.pi_ni[i];
1693
1694                         ns->ns_nid = ni->ni_nid;
1695
1696                         lnet_ni_lock(ni);
1697                         ns->ns_status = (ni->ni_status != NULL) ?
1698                                          ni->ni_status->ns_status :
1699                                                 LNET_NI_STATUS_UP;
1700                         ni->ni_status = ns;
1701                         lnet_ni_unlock(ni);
1702
1703                         i++;
1704                 }
1705         }
1706         /*
1707          * We (ab)use the ns_status of the loopback interface to
1708          * transmit the sequence number. The first interface listed
1709          * must be the loopback interface.
1710          */
1711         rc = lnet_ping_info_validate(&pbuf->pb_info);
1712         if (rc) {
1713                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1714                 LBUG();
1715         }
1716         LNET_PING_BUFFER_SEQNO(pbuf) =
1717                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1718 }
1719
1720 static void
1721 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1722                         struct lnet_handle_md ping_mdh)
1723 {
1724         struct lnet_ping_buffer *old_pbuf = NULL;
1725         struct lnet_handle_md old_ping_md;
1726
1727         /* switch the NIs to point to the new ping info created */
1728         lnet_net_lock(LNET_LOCK_EX);
1729
1730         if (!the_lnet.ln_routing)
1731                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1732         if (!lnet_peer_discovery_disabled)
1733                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1734
1735         /* Ensure only known feature bits have been set. */
1736         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1737         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1738
1739         lnet_ping_target_install_locked(pbuf);
1740
1741         if (the_lnet.ln_ping_target) {
1742                 old_pbuf = the_lnet.ln_ping_target;
1743                 old_ping_md = the_lnet.ln_ping_target_md;
1744         }
1745         the_lnet.ln_ping_target_md = ping_mdh;
1746         the_lnet.ln_ping_target = pbuf;
1747
1748         lnet_net_unlock(LNET_LOCK_EX);
1749
1750         if (old_pbuf) {
1751                 /* unlink and free the old ping info */
1752                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1753                 lnet_ping_buffer_decref(old_pbuf);
1754         }
1755
1756         lnet_push_update_to_peers(0);
1757 }
1758
1759 static void
1760 lnet_ping_target_fini(void)
1761 {
1762         int             rc;
1763
1764         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1765                             &the_lnet.ln_ping_target_md);
1766
1767         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1768         LASSERT(rc == 0);
1769
1770         lnet_ping_target_destroy();
1771 }
1772
1773 /* Resize the push target. */
1774 int lnet_push_target_resize(void)
1775 {
1776         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1777         struct lnet_md md = { NULL };
1778         struct lnet_handle_me meh;
1779         struct lnet_handle_md mdh;
1780         struct lnet_handle_md old_mdh;
1781         struct lnet_ping_buffer *pbuf;
1782         struct lnet_ping_buffer *old_pbuf;
1783         int nnis = the_lnet.ln_push_target_nnis;
1784         int rc;
1785
1786         if (nnis <= 0) {
1787                 rc = -EINVAL;
1788                 goto fail_return;
1789         }
1790 again:
1791         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1792         if (!pbuf) {
1793                 rc = -ENOMEM;
1794                 goto fail_return;
1795         }
1796
1797         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1798                           LNET_PROTO_PING_MATCHBITS, 0,
1799                           LNET_UNLINK, LNET_INS_AFTER,
1800                           &meh);
1801         if (rc) {
1802                 CERROR("Can't create push target ME: %d\n", rc);
1803                 goto fail_decref_pbuf;
1804         }
1805
1806         /* initialize md content */
1807         md.start     = &pbuf->pb_info;
1808         md.length    = LNET_PING_INFO_SIZE(nnis);
1809         md.threshold = LNET_MD_THRESH_INF;
1810         md.max_size  = 0;
1811         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE |
1812                        LNET_MD_MANAGE_REMOTE;
1813         md.user_ptr  = pbuf;
1814         md.eq_handle = the_lnet.ln_push_target_eq;
1815
1816         rc = LNetMDAttach(meh, md, LNET_RETAIN, &mdh);
1817         if (rc) {
1818                 CERROR("Can't attach push MD: %d\n", rc);
1819                 goto fail_unlink_meh;
1820         }
1821         lnet_ping_buffer_addref(pbuf);
1822
1823         lnet_net_lock(LNET_LOCK_EX);
1824         old_pbuf = the_lnet.ln_push_target;
1825         old_mdh = the_lnet.ln_push_target_md;
1826         the_lnet.ln_push_target = pbuf;
1827         the_lnet.ln_push_target_md = mdh;
1828         lnet_net_unlock(LNET_LOCK_EX);
1829
1830         if (old_pbuf) {
1831                 LNetMDUnlink(old_mdh);
1832                 lnet_ping_buffer_decref(old_pbuf);
1833         }
1834
1835         if (nnis < the_lnet.ln_push_target_nnis)
1836                 goto again;
1837
1838         CDEBUG(D_NET, "nnis %d success\n", nnis);
1839
1840         return 0;
1841
1842 fail_unlink_meh:
1843         LNetMEUnlink(meh);
1844 fail_decref_pbuf:
1845         lnet_ping_buffer_decref(pbuf);
1846 fail_return:
1847         CDEBUG(D_NET, "nnis %d error %d\n", nnis, rc);
1848         return rc;
1849 }
1850
1851 static void lnet_push_target_event_handler(struct lnet_event *ev)
1852 {
1853         struct lnet_ping_buffer *pbuf = ev->md.user_ptr;
1854
1855         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1856                 lnet_swap_pinginfo(pbuf);
1857
1858         lnet_peer_push_event(ev);
1859         if (ev->unlinked)
1860                 lnet_ping_buffer_decref(pbuf);
1861 }
1862
1863 /* Initialize the push target. */
1864 static int lnet_push_target_init(void)
1865 {
1866         int rc;
1867
1868         if (the_lnet.ln_push_target)
1869                 return -EALREADY;
1870
1871         rc = LNetEQAlloc(0, lnet_push_target_event_handler,
1872                          &the_lnet.ln_push_target_eq);
1873         if (rc) {
1874                 CERROR("Can't allocated push target EQ: %d\n", rc);
1875                 return rc;
1876         }
1877
1878         /* Start at the required minimum, we'll enlarge if required. */
1879         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
1880
1881         rc = lnet_push_target_resize();
1882
1883         if (rc) {
1884                 LNetEQFree(the_lnet.ln_push_target_eq);
1885                 LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1886         }
1887
1888         return rc;
1889 }
1890
1891 /* Clean up the push target. */
1892 static void lnet_push_target_fini(void)
1893 {
1894         if (!the_lnet.ln_push_target)
1895                 return;
1896
1897         /* Unlink and invalidate to prevent new references. */
1898         LNetMDUnlink(the_lnet.ln_push_target_md);
1899         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
1900
1901         /* Wait for the unlink to complete. */
1902         while (lnet_ping_buffer_numref(the_lnet.ln_push_target) > 1) {
1903                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1904                 set_current_state(TASK_UNINTERRUPTIBLE);
1905                 schedule_timeout(cfs_time_seconds(1));
1906         }
1907
1908         lnet_ping_buffer_decref(the_lnet.ln_push_target);
1909         the_lnet.ln_push_target = NULL;
1910         the_lnet.ln_push_target_nnis = 0;
1911
1912         LNetEQFree(the_lnet.ln_push_target_eq);
1913         LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1914 }
1915
1916 static int
1917 lnet_ni_tq_credits(struct lnet_ni *ni)
1918 {
1919         int     credits;
1920
1921         LASSERT(ni->ni_ncpts >= 1);
1922
1923         if (ni->ni_ncpts == 1)
1924                 return ni->ni_net->net_tunables.lct_max_tx_credits;
1925
1926         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
1927         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
1928         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
1929
1930         return credits;
1931 }
1932
1933 static void
1934 lnet_ni_unlink_locked(struct lnet_ni *ni)
1935 {
1936         /* move it to zombie list and nobody can find it anymore */
1937         LASSERT(!list_empty(&ni->ni_netlist));
1938         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
1939         lnet_ni_decref_locked(ni, 0);
1940 }
1941
1942 static void
1943 lnet_clear_zombies_nis_locked(struct lnet_net *net)
1944 {
1945         int             i;
1946         int             islo;
1947         struct lnet_ni  *ni;
1948         struct list_head *zombie_list = &net->net_ni_zombie;
1949
1950         /*
1951          * Now wait for the NIs I just nuked to show up on the zombie
1952          * list and shut them down in guaranteed thread context
1953          */
1954         i = 2;
1955         while (!list_empty(zombie_list)) {
1956                 int     *ref;
1957                 int     j;
1958
1959                 ni = list_entry(zombie_list->next,
1960                                 struct lnet_ni, ni_netlist);
1961                 list_del_init(&ni->ni_netlist);
1962                 /* the ni should be in deleting state. If it's not it's
1963                  * a bug */
1964                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
1965                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
1966                         if (*ref == 0)
1967                                 continue;
1968                         /* still busy, add it back to zombie list */
1969                         list_add(&ni->ni_netlist, zombie_list);
1970                         break;
1971                 }
1972
1973                 if (!list_empty(&ni->ni_netlist)) {
1974                         lnet_net_unlock(LNET_LOCK_EX);
1975                         ++i;
1976                         if ((i & (-i)) == i) {
1977                                 CDEBUG(D_WARNING,
1978                                        "Waiting for zombie LNI %s\n",
1979                                        libcfs_nid2str(ni->ni_nid));
1980                         }
1981                         set_current_state(TASK_UNINTERRUPTIBLE);
1982                         schedule_timeout(cfs_time_seconds(1));
1983                         lnet_net_lock(LNET_LOCK_EX);
1984                         continue;
1985                 }
1986
1987                 lnet_net_unlock(LNET_LOCK_EX);
1988
1989                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
1990
1991                 LASSERT(!in_interrupt());
1992                 (net->net_lnd->lnd_shutdown)(ni);
1993
1994                 if (!islo)
1995                         CDEBUG(D_LNI, "Removed LNI %s\n",
1996                               libcfs_nid2str(ni->ni_nid));
1997
1998                 lnet_ni_free(ni);
1999                 i = 2;
2000                 lnet_net_lock(LNET_LOCK_EX);
2001         }
2002 }
2003
2004 /* shutdown down the NI and release refcount */
2005 static void
2006 lnet_shutdown_lndni(struct lnet_ni *ni)
2007 {
2008         int i;
2009         struct lnet_net *net = ni->ni_net;
2010
2011         lnet_net_lock(LNET_LOCK_EX);
2012         lnet_ni_lock(ni);
2013         ni->ni_state = LNET_NI_STATE_DELETING;
2014         lnet_ni_unlock(ni);
2015         lnet_ni_unlink_locked(ni);
2016         lnet_incr_dlc_seq();
2017         lnet_net_unlock(LNET_LOCK_EX);
2018
2019         /* clear messages for this NI on the lazy portal */
2020         for (i = 0; i < the_lnet.ln_nportals; i++)
2021                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2022
2023         lnet_net_lock(LNET_LOCK_EX);
2024         lnet_clear_zombies_nis_locked(net);
2025         lnet_net_unlock(LNET_LOCK_EX);
2026 }
2027
2028 static void
2029 lnet_shutdown_lndnet(struct lnet_net *net)
2030 {
2031         struct lnet_ni *ni;
2032
2033         lnet_net_lock(LNET_LOCK_EX);
2034
2035         net->net_state = LNET_NET_STATE_DELETING;
2036
2037         list_del_init(&net->net_list);
2038
2039         while (!list_empty(&net->net_ni_list)) {
2040                 ni = list_entry(net->net_ni_list.next,
2041                                 struct lnet_ni, ni_netlist);
2042                 lnet_net_unlock(LNET_LOCK_EX);
2043                 lnet_shutdown_lndni(ni);
2044                 lnet_net_lock(LNET_LOCK_EX);
2045         }
2046
2047         lnet_net_unlock(LNET_LOCK_EX);
2048
2049         /* Do peer table cleanup for this net */
2050         lnet_peer_tables_cleanup(net);
2051
2052         lnet_net_lock(LNET_LOCK_EX);
2053         /*
2054          * decrement ref count on lnd only when the entire network goes
2055          * away
2056          */
2057         net->net_lnd->lnd_refcount--;
2058
2059         lnet_net_unlock(LNET_LOCK_EX);
2060
2061         lnet_net_free(net);
2062 }
2063
2064 static void
2065 lnet_shutdown_lndnets(void)
2066 {
2067         struct lnet_net *net;
2068         struct list_head resend;
2069         struct lnet_msg *msg, *tmp;
2070
2071         INIT_LIST_HEAD(&resend);
2072
2073         /* NB called holding the global mutex */
2074
2075         /* All quiet on the API front */
2076         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2077         LASSERT(the_lnet.ln_refcount == 0);
2078
2079         lnet_net_lock(LNET_LOCK_EX);
2080         the_lnet.ln_state = LNET_STATE_STOPPING;
2081
2082         while (!list_empty(&the_lnet.ln_nets)) {
2083                 /*
2084                  * move the nets to the zombie list to avoid them being
2085                  * picked up for new work. LONET is also included in the
2086                  * Nets that will be moved to the zombie list
2087                  */
2088                 net = list_entry(the_lnet.ln_nets.next,
2089                                  struct lnet_net, net_list);
2090                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
2091         }
2092
2093         /* Drop the cached loopback Net. */
2094         if (the_lnet.ln_loni != NULL) {
2095                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2096                 the_lnet.ln_loni = NULL;
2097         }
2098         lnet_net_unlock(LNET_LOCK_EX);
2099
2100         /* iterate through the net zombie list and delete each net */
2101         while (!list_empty(&the_lnet.ln_net_zombie)) {
2102                 net = list_entry(the_lnet.ln_net_zombie.next,
2103                                  struct lnet_net, net_list);
2104                 lnet_shutdown_lndnet(net);
2105         }
2106
2107         spin_lock(&the_lnet.ln_msg_resend_lock);
2108         list_splice(&the_lnet.ln_msg_resend, &resend);
2109         spin_unlock(&the_lnet.ln_msg_resend_lock);
2110
2111         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2112                 list_del_init(&msg->msg_list);
2113                 msg->msg_no_resend = true;
2114                 lnet_finalize(msg, -ECANCELED);
2115         }
2116
2117         lnet_net_lock(LNET_LOCK_EX);
2118         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2119         lnet_net_unlock(LNET_LOCK_EX);
2120 }
2121
2122 static int
2123 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2124 {
2125         int                     rc = -EINVAL;
2126         struct lnet_tx_queue    *tq;
2127         int                     i;
2128         struct lnet_net         *net = ni->ni_net;
2129
2130         mutex_lock(&the_lnet.ln_lnd_mutex);
2131
2132         if (tun) {
2133                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2134                 ni->ni_lnd_tunables_set = true;
2135         }
2136
2137         rc = (net->net_lnd->lnd_startup)(ni);
2138
2139         mutex_unlock(&the_lnet.ln_lnd_mutex);
2140
2141         if (rc != 0) {
2142                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2143                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2144                 lnet_net_lock(LNET_LOCK_EX);
2145                 net->net_lnd->lnd_refcount--;
2146                 lnet_net_unlock(LNET_LOCK_EX);
2147                 goto failed0;
2148         }
2149
2150         lnet_ni_lock(ni);
2151         ni->ni_state = LNET_NI_STATE_ACTIVE;
2152         lnet_ni_unlock(ni);
2153
2154         /* We keep a reference on the loopback net through the loopback NI */
2155         if (net->net_lnd->lnd_type == LOLND) {
2156                 lnet_ni_addref(ni);
2157                 LASSERT(the_lnet.ln_loni == NULL);
2158                 the_lnet.ln_loni = ni;
2159                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2160                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2161                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2162                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2163                 return 0;
2164         }
2165
2166         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2167             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2168                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2169                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2170                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2171                                         "" : "per-peer ");
2172                 /* shutdown the NI since if we get here then it must've already
2173                  * been started
2174                  */
2175                 lnet_shutdown_lndni(ni);
2176                 return -EINVAL;
2177         }
2178
2179         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2180                 tq->tq_credits_min =
2181                 tq->tq_credits_max =
2182                 tq->tq_credits = lnet_ni_tq_credits(ni);
2183         }
2184
2185         atomic_set(&ni->ni_tx_credits,
2186                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2187         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2188
2189         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2190                 libcfs_nid2str(ni->ni_nid),
2191                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2192                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2193                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2194                 ni->ni_net->net_tunables.lct_peer_timeout);
2195
2196         return 0;
2197 failed0:
2198         lnet_ni_free(ni);
2199         return rc;
2200 }
2201
2202 static int
2203 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2204 {
2205         struct lnet_ni *ni;
2206         struct lnet_net *net_l = NULL;
2207         struct list_head        local_ni_list;
2208         int                     rc;
2209         int                     ni_count = 0;
2210         __u32                   lnd_type;
2211         struct lnet_lnd *lnd;
2212         int                     peer_timeout =
2213                 net->net_tunables.lct_peer_timeout;
2214         int                     maxtxcredits =
2215                 net->net_tunables.lct_max_tx_credits;
2216         int                     peerrtrcredits =
2217                 net->net_tunables.lct_peer_rtr_credits;
2218
2219         INIT_LIST_HEAD(&local_ni_list);
2220
2221         /*
2222          * make sure that this net is unique. If it isn't then
2223          * we are adding interfaces to an already existing network, and
2224          * 'net' is just a convenient way to pass in the list.
2225          * if it is unique we need to find the LND and load it if
2226          * necessary.
2227          */
2228         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2229                 lnd_type = LNET_NETTYP(net->net_id);
2230
2231                 mutex_lock(&the_lnet.ln_lnd_mutex);
2232                 lnd = lnet_find_lnd_by_type(lnd_type);
2233
2234                 if (lnd == NULL) {
2235                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2236                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2237                         mutex_lock(&the_lnet.ln_lnd_mutex);
2238
2239                         lnd = lnet_find_lnd_by_type(lnd_type);
2240                         if (lnd == NULL) {
2241                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2242                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2243                                 libcfs_lnd2str(lnd_type),
2244                                 libcfs_lnd2modname(lnd_type), rc);
2245 #ifndef HAVE_MODULE_LOADING_SUPPORT
2246                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2247                                                 "compiled with kernel module "
2248                                                 "loading support.");
2249 #endif
2250                                 rc = -EINVAL;
2251                                 goto failed0;
2252                         }
2253                 }
2254
2255                 lnet_net_lock(LNET_LOCK_EX);
2256                 lnd->lnd_refcount++;
2257                 lnet_net_unlock(LNET_LOCK_EX);
2258
2259                 net->net_lnd = lnd;
2260
2261                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2262
2263                 net_l = net;
2264         }
2265
2266         /*
2267          * net_l: if the network being added is unique then net_l
2268          *        will point to that network
2269          *        if the network being added is not unique then
2270          *        net_l points to the existing network.
2271          *
2272          * When we enter the loop below, we'll pick NIs off he
2273          * network beign added and start them up, then add them to
2274          * a local ni list. Once we've successfully started all
2275          * the NIs then we join the local NI list (of started up
2276          * networks) with the net_l->net_ni_list, which should
2277          * point to the correct network to add the new ni list to
2278          *
2279          * If any of the new NIs fail to start up, then we want to
2280          * iterate through the local ni list, which should include
2281          * any NIs which were successfully started up, and shut
2282          * them down.
2283          *
2284          * After than we want to delete the network being added,
2285          * to avoid a memory leak.
2286          */
2287
2288         /*
2289          * When a network uses TCP bonding then all its interfaces
2290          * must be specified when the network is first defined: the
2291          * TCP bonding code doesn't allow for interfaces to be added
2292          * or removed.
2293          */
2294         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2295             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2296                 rc = -EINVAL;
2297                 goto failed0;
2298         }
2299
2300         while (!list_empty(&net->net_ni_added)) {
2301                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2302                                 ni_netlist);
2303                 list_del_init(&ni->ni_netlist);
2304
2305                 /* make sure that the the NI we're about to start
2306                  * up is actually unique. if it's not fail. */
2307                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2308                                         ni->ni_interfaces[0])) {
2309                         rc = -EINVAL;
2310                         goto failed1;
2311                 }
2312
2313                 /* adjust the pointer the parent network, just in case it
2314                  * the net is a duplicate */
2315                 ni->ni_net = net_l;
2316
2317                 rc = lnet_startup_lndni(ni, tun);
2318
2319                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
2320                         ni->ni_net->net_lnd->lnd_query != NULL);
2321
2322                 if (rc < 0)
2323                         goto failed1;
2324
2325                 lnet_ni_addref(ni);
2326                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2327
2328                 ni_count++;
2329         }
2330
2331         lnet_net_lock(LNET_LOCK_EX);
2332         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2333         lnet_incr_dlc_seq();
2334         lnet_net_unlock(LNET_LOCK_EX);
2335
2336         /* if the network is not unique then we don't want to keep
2337          * it around after we're done. Free it. Otherwise add that
2338          * net to the global the_lnet.ln_nets */
2339         if (net_l != net && net_l != NULL) {
2340                 /*
2341                  * TODO - note. currently the tunables can not be updated
2342                  * once added
2343                  */
2344                 lnet_net_free(net);
2345         } else {
2346                 net->net_state = LNET_NET_STATE_ACTIVE;
2347                 /*
2348                  * restore tunables after it has been overwitten by the
2349                  * lnd
2350                  */
2351                 if (peer_timeout != -1)
2352                         net->net_tunables.lct_peer_timeout = peer_timeout;
2353                 if (maxtxcredits != -1)
2354                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2355                 if (peerrtrcredits != -1)
2356                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2357
2358                 lnet_net_lock(LNET_LOCK_EX);
2359                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2360                 lnet_net_unlock(LNET_LOCK_EX);
2361         }
2362
2363         return ni_count;
2364
2365 failed1:
2366         /*
2367          * shutdown the new NIs that are being started up
2368          * free the NET being started
2369          */
2370         while (!list_empty(&local_ni_list)) {
2371                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2372                                 ni_netlist);
2373
2374                 lnet_shutdown_lndni(ni);
2375         }
2376
2377 failed0:
2378         lnet_net_free(net);
2379
2380         return rc;
2381 }
2382
2383 static int
2384 lnet_startup_lndnets(struct list_head *netlist)
2385 {
2386         struct lnet_net         *net;
2387         int                     rc;
2388         int                     ni_count = 0;
2389
2390         /*
2391          * Change to running state before bringing up the LNDs. This
2392          * allows lnet_shutdown_lndnets() to assert that we've passed
2393          * through here.
2394          */
2395         lnet_net_lock(LNET_LOCK_EX);
2396         the_lnet.ln_state = LNET_STATE_RUNNING;
2397         lnet_net_unlock(LNET_LOCK_EX);
2398
2399         while (!list_empty(netlist)) {
2400                 net = list_entry(netlist->next, struct lnet_net, net_list);
2401                 list_del_init(&net->net_list);
2402
2403                 rc = lnet_startup_lndnet(net, NULL);
2404
2405                 if (rc < 0)
2406                         goto failed;
2407
2408                 ni_count += rc;
2409         }
2410
2411         return ni_count;
2412 failed:
2413         lnet_shutdown_lndnets();
2414
2415         return rc;
2416 }
2417
2418 /**
2419  * Initialize LNet library.
2420  *
2421  * Automatically called at module loading time. Caller has to call
2422  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2423  * latter returned 0. It must be called exactly once.
2424  *
2425  * \retval 0 on success
2426  * \retval -ve on failures.
2427  */
2428 int lnet_lib_init(void)
2429 {
2430         int rc;
2431
2432         lnet_assert_wire_constants();
2433
2434         /* refer to global cfs_cpt_table for now */
2435         the_lnet.ln_cpt_table   = cfs_cpt_table;
2436         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2437
2438         LASSERT(the_lnet.ln_cpt_number > 0);
2439         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2440                 /* we are under risk of consuming all lh_cookie */
2441                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2442                        "please change setting of CPT-table and retry\n",
2443                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2444                 return -E2BIG;
2445         }
2446
2447         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2448                 the_lnet.ln_cpt_bits++;
2449
2450         rc = lnet_create_locks();
2451         if (rc != 0) {
2452                 CERROR("Can't create LNet global locks: %d\n", rc);
2453                 return rc;
2454         }
2455
2456         the_lnet.ln_refcount = 0;
2457         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2458         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2459         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2460         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2461         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2462         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2463
2464         /* The hash table size is the number of bits it takes to express the set
2465          * ln_num_routes, minus 1 (better to under estimate than over so we
2466          * don't waste memory). */
2467         if (rnet_htable_size <= 0)
2468                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2469         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2470                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2471         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2472                                            order_base_2(rnet_htable_size) - 1);
2473
2474         /* All LNDs apart from the LOLND are in separate modules.  They
2475          * register themselves when their module loads, and unregister
2476          * themselves when their module is unloaded. */
2477         lnet_register_lnd(&the_lolnd);
2478         return 0;
2479 }
2480
2481 /**
2482  * Finalize LNet library.
2483  *
2484  * \pre lnet_lib_init() called with success.
2485  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2486  */
2487 void lnet_lib_exit(void)
2488 {
2489         LASSERT(the_lnet.ln_refcount == 0);
2490
2491         while (!list_empty(&the_lnet.ln_lnds))
2492                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2493                                                struct lnet_lnd, lnd_list));
2494         lnet_destroy_locks();
2495 }
2496
2497 /**
2498  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2499  *
2500  * Users must call this function at least once before any other functions.
2501  * For each successful call there must be a corresponding call to
2502  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2503  * ignored.
2504  *
2505  * The PID used by LNet may be different from the one requested.
2506  * See LNetGetId().
2507  *
2508  * \param requested_pid PID requested by the caller.
2509  *
2510  * \return >= 0 on success, and < 0 error code on failures.
2511  */
2512 int
2513 LNetNIInit(lnet_pid_t requested_pid)
2514 {
2515         int                     im_a_router = 0;
2516         int                     rc;
2517         int                     ni_count;
2518         struct lnet_ping_buffer *pbuf;
2519         struct lnet_handle_md   ping_mdh;
2520         struct list_head        net_head;
2521         struct lnet_net         *net;
2522
2523         INIT_LIST_HEAD(&net_head);
2524
2525         mutex_lock(&the_lnet.ln_api_mutex);
2526
2527         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2528
2529         if (the_lnet.ln_refcount > 0) {
2530                 rc = the_lnet.ln_refcount++;
2531                 mutex_unlock(&the_lnet.ln_api_mutex);
2532                 return rc;
2533         }
2534
2535         rc = lnet_prepare(requested_pid);
2536         if (rc != 0) {
2537                 mutex_unlock(&the_lnet.ln_api_mutex);
2538                 return rc;
2539         }
2540
2541         /* create a network for Loopback network */
2542         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2543         if (net == NULL) {
2544                 rc = -ENOMEM;
2545                 goto err_empty_list;
2546         }
2547
2548         /* Add in the loopback NI */
2549         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2550                 rc = -ENOMEM;
2551                 goto err_empty_list;
2552         }
2553
2554         /* If LNet is being initialized via DLC it is possible
2555          * that the user requests not to load module parameters (ones which
2556          * are supported by DLC) on initialization.  Therefore, make sure not
2557          * to load networks, routes and forwarding from module parameters
2558          * in this case.  On cleanup in case of failure only clean up
2559          * routes if it has been loaded */
2560         if (!the_lnet.ln_nis_from_mod_params) {
2561                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2562                                          use_tcp_bonding);
2563                 if (rc < 0)
2564                         goto err_empty_list;
2565         }
2566
2567         ni_count = lnet_startup_lndnets(&net_head);
2568         if (ni_count < 0) {
2569                 rc = ni_count;
2570                 goto err_empty_list;
2571         }
2572
2573         if (!the_lnet.ln_nis_from_mod_params) {
2574                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2575                 if (rc != 0)
2576                         goto err_shutdown_lndnis;
2577
2578                 rc = lnet_rtrpools_alloc(im_a_router);
2579                 if (rc != 0)
2580                         goto err_destroy_routes;
2581         }
2582
2583         rc = lnet_acceptor_start();
2584         if (rc != 0)
2585                 goto err_destroy_routes;
2586
2587         the_lnet.ln_refcount = 1;
2588         /* Now I may use my own API functions... */
2589
2590         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2591         if (rc != 0)
2592                 goto err_acceptor_stop;
2593
2594         lnet_ping_target_update(pbuf, ping_mdh);
2595
2596         rc = LNetEQAlloc(0, lnet_mt_event_handler, &the_lnet.ln_mt_eqh);
2597         if (rc != 0) {
2598                 CERROR("Can't allocate monitor thread EQ: %d\n", rc);
2599                 goto err_stop_ping;
2600         }
2601
2602         rc = lnet_monitor_thr_start();
2603         if (rc != 0)
2604                 goto err_stop_ping;
2605
2606         rc = lnet_push_target_init();
2607         if (rc != 0)
2608                 goto err_stop_monitor_thr;
2609
2610         rc = lnet_peer_discovery_start();
2611         if (rc != 0)
2612                 goto err_destroy_push_target;
2613
2614         lnet_fault_init();
2615         lnet_router_debugfs_init();
2616
2617         mutex_unlock(&the_lnet.ln_api_mutex);
2618
2619         return 0;
2620
2621 err_destroy_push_target:
2622         lnet_push_target_fini();
2623 err_stop_monitor_thr:
2624         lnet_monitor_thr_stop();
2625 err_stop_ping:
2626         lnet_ping_target_fini();
2627 err_acceptor_stop:
2628         the_lnet.ln_refcount = 0;
2629         lnet_acceptor_stop();
2630 err_destroy_routes:
2631         if (!the_lnet.ln_nis_from_mod_params)
2632                 lnet_destroy_routes();
2633 err_shutdown_lndnis:
2634         lnet_shutdown_lndnets();
2635 err_empty_list:
2636         lnet_unprepare();
2637         LASSERT(rc < 0);
2638         mutex_unlock(&the_lnet.ln_api_mutex);
2639         while (!list_empty(&net_head)) {
2640                 struct lnet_net *net;
2641
2642                 net = list_entry(net_head.next, struct lnet_net, net_list);
2643                 list_del_init(&net->net_list);
2644                 lnet_net_free(net);
2645         }
2646         return rc;
2647 }
2648 EXPORT_SYMBOL(LNetNIInit);
2649
2650 /**
2651  * Stop LNet interfaces, routing, and forwarding.
2652  *
2653  * Users must call this function once for each successful call to LNetNIInit().
2654  * Once the LNetNIFini() operation has been started, the results of pending
2655  * API operations are undefined.
2656  *
2657  * \return always 0 for current implementation.
2658  */
2659 int
2660 LNetNIFini()
2661 {
2662         mutex_lock(&the_lnet.ln_api_mutex);
2663
2664         LASSERT(the_lnet.ln_refcount > 0);
2665
2666         if (the_lnet.ln_refcount != 1) {
2667                 the_lnet.ln_refcount--;
2668         } else {
2669                 LASSERT(!the_lnet.ln_niinit_self);
2670
2671                 lnet_fault_fini();
2672
2673                 lnet_router_debugfs_fini();
2674                 lnet_peer_discovery_stop();
2675                 lnet_push_target_fini();
2676                 lnet_monitor_thr_stop();
2677                 lnet_ping_target_fini();
2678
2679                 /* Teardown fns that use my own API functions BEFORE here */
2680                 the_lnet.ln_refcount = 0;
2681
2682                 lnet_acceptor_stop();
2683                 lnet_destroy_routes();
2684                 lnet_shutdown_lndnets();
2685                 lnet_unprepare();
2686         }
2687
2688         mutex_unlock(&the_lnet.ln_api_mutex);
2689         return 0;
2690 }
2691 EXPORT_SYMBOL(LNetNIFini);
2692
2693 /**
2694  * Grabs the ni data from the ni structure and fills the out
2695  * parameters
2696  *
2697  * \param[in] ni network        interface structure
2698  * \param[out] cfg_ni           NI config information
2699  * \param[out] tun              network and LND tunables
2700  */
2701 static void
2702 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2703                    struct lnet_ioctl_config_lnd_tunables *tun,
2704                    struct lnet_ioctl_element_stats *stats,
2705                    __u32 tun_size)
2706 {
2707         size_t min_size = 0;
2708         int i;
2709
2710         if (!ni || !cfg_ni || !tun)
2711                 return;
2712
2713         if (ni->ni_interfaces[0] != NULL) {
2714                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2715                         if (ni->ni_interfaces[i] != NULL) {
2716                                 strncpy(cfg_ni->lic_ni_intf[i],
2717                                         ni->ni_interfaces[i],
2718                                         sizeof(cfg_ni->lic_ni_intf[i]));
2719                         }
2720                 }
2721         }
2722
2723         cfg_ni->lic_nid = ni->ni_nid;
2724         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2725                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2726         else
2727                 cfg_ni->lic_status = ni->ni_status->ns_status;
2728         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2729         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2730
2731         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2732
2733         if (stats) {
2734                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2735                                                        LNET_STATS_TYPE_SEND);
2736                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2737                                                        LNET_STATS_TYPE_RECV);
2738                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2739                                                        LNET_STATS_TYPE_DROP);
2740         }
2741
2742         /*
2743          * tun->lt_tun will always be present, but in order to be
2744          * backwards compatible, we need to deal with the cases when
2745          * tun->lt_tun is smaller than what the kernel has, because it
2746          * comes from an older version of a userspace program, then we'll
2747          * need to copy as much information as we have available space.
2748          */
2749         min_size = tun_size - sizeof(tun->lt_cmn);
2750         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2751
2752         /* copy over the cpts */
2753         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2754             ni->ni_cpts == NULL)  {
2755                 for (i = 0; i < ni->ni_ncpts; i++)
2756                         cfg_ni->lic_cpts[i] = i;
2757         } else {
2758                 for (i = 0;
2759                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2760                      i < LNET_MAX_SHOW_NUM_CPT;
2761                      i++)
2762                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2763         }
2764         cfg_ni->lic_ncpts = ni->ni_ncpts;
2765 }
2766
2767 /**
2768  * NOTE: This is a legacy function left in the code to be backwards
2769  * compatible with older userspace programs. It should eventually be
2770  * removed.
2771  *
2772  * Grabs the ni data from the ni structure and fills the out
2773  * parameters
2774  *
2775  * \param[in] ni network        interface structure
2776  * \param[out] config           config information
2777  */
2778 static void
2779 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2780                          struct lnet_ioctl_config_data *config)
2781 {
2782         struct lnet_ioctl_net_config *net_config;
2783         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2784         size_t min_size, tunable_size = 0;
2785         int i;
2786
2787         if (!ni || !config)
2788                 return;
2789
2790         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2791         if (!net_config)
2792                 return;
2793
2794         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2795                      ARRAY_SIZE(net_config->ni_interfaces));
2796
2797         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2798                 if (!ni->ni_interfaces[i])
2799                         break;
2800
2801                 strncpy(net_config->ni_interfaces[i],
2802                         ni->ni_interfaces[i],
2803                         sizeof(net_config->ni_interfaces[i]));
2804         }
2805
2806         config->cfg_nid = ni->ni_nid;
2807         config->cfg_config_u.cfg_net.net_peer_timeout =
2808                 ni->ni_net->net_tunables.lct_peer_timeout;
2809         config->cfg_config_u.cfg_net.net_max_tx_credits =
2810                 ni->ni_net->net_tunables.lct_max_tx_credits;
2811         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2812                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2813         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2814                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2815
2816         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2817                 net_config->ni_status = LNET_NI_STATUS_UP;
2818         else
2819                 net_config->ni_status = ni->ni_status->ns_status;
2820
2821         if (ni->ni_cpts) {
2822                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2823
2824                 for (i = 0; i < num_cpts; i++)
2825                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2826
2827                 config->cfg_ncpts = num_cpts;
2828         }
2829
2830         /*
2831          * See if user land tools sent in a newer and larger version
2832          * of struct lnet_tunables than what the kernel uses.
2833          */
2834         min_size = sizeof(*config) + sizeof(*net_config);
2835
2836         if (config->cfg_hdr.ioc_len > min_size)
2837                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2838
2839         /* Don't copy too much data to user space */
2840         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2841         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2842
2843         if (lnd_cfg && min_size) {
2844                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2845                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2846
2847                 /* Tell user land that kernel side has less data */
2848                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2849                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2850                         config->cfg_hdr.ioc_len -= min_size;
2851                 }
2852         }
2853 }
2854
2855 struct lnet_ni *
2856 lnet_get_ni_idx_locked(int idx)
2857 {
2858         struct lnet_ni          *ni;
2859         struct lnet_net         *net;
2860
2861         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2862                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2863                         if (idx-- == 0)
2864                                 return ni;
2865                 }
2866         }
2867
2868         return NULL;
2869 }
2870
2871 struct lnet_ni *
2872 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2873 {
2874         struct lnet_ni          *ni;
2875         struct lnet_net         *net = mynet;
2876
2877         /*
2878          * It is possible that the net has been cleaned out while there is
2879          * a message being sent. This function accessed the net without
2880          * checking if the list is empty
2881          */
2882         if (prev == NULL) {
2883                 if (net == NULL)
2884                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2885                                         net_list);
2886                 if (list_empty(&net->net_ni_list))
2887                         return NULL;
2888                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2889                                 ni_netlist);
2890
2891                 return ni;
2892         }
2893
2894         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2895                 /* if you reached the end of the ni list and the net is
2896                  * specified, then there are no more nis in that net */
2897                 if (net != NULL)
2898                         return NULL;
2899
2900                 /* we reached the end of this net ni list. move to the
2901                  * next net */
2902                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2903                         /* no more nets and no more NIs. */
2904                         return NULL;
2905
2906                 /* get the next net */
2907                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2908                                  net_list);
2909                 if (list_empty(&net->net_ni_list))
2910                         return NULL;
2911                 /* get the ni on it */
2912                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2913                                 ni_netlist);
2914
2915                 return ni;
2916         }
2917
2918         if (list_empty(&prev->ni_netlist))
2919                 return NULL;
2920
2921         /* there are more nis left */
2922         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2923
2924         return ni;
2925 }
2926
2927 int
2928 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2929 {
2930         struct lnet_ni *ni;
2931         int cpt;
2932         int rc = -ENOENT;
2933         int idx = config->cfg_count;
2934
2935         cpt = lnet_net_lock_current();
2936
2937         ni = lnet_get_ni_idx_locked(idx);
2938
2939         if (ni != NULL) {
2940                 rc = 0;
2941                 lnet_ni_lock(ni);
2942                 lnet_fill_ni_info_legacy(ni, config);
2943                 lnet_ni_unlock(ni);
2944         }
2945
2946         lnet_net_unlock(cpt);
2947         return rc;
2948 }
2949
2950 int
2951 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2952                    struct lnet_ioctl_config_lnd_tunables *tun,
2953                    struct lnet_ioctl_element_stats *stats,
2954                    __u32 tun_size)
2955 {
2956         struct lnet_ni          *ni;
2957         int                     cpt;
2958         int                     rc = -ENOENT;
2959
2960         if (!cfg_ni || !tun || !stats)
2961                 return -EINVAL;
2962
2963         cpt = lnet_net_lock_current();
2964
2965         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2966
2967         if (ni) {
2968                 rc = 0;
2969                 lnet_ni_lock(ni);
2970                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2971                 lnet_ni_unlock(ni);
2972         }
2973
2974         lnet_net_unlock(cpt);
2975         return rc;
2976 }
2977
2978 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2979 {
2980         struct lnet_ni *ni;
2981         int cpt;
2982         int rc = -ENOENT;
2983
2984         if (!msg_stats)
2985                 return -EINVAL;
2986
2987         cpt = lnet_net_lock_current();
2988
2989         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2990
2991         if (ni) {
2992                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2993                 rc = 0;
2994         }
2995
2996         lnet_net_unlock(cpt);
2997
2998         return rc;
2999 }
3000
3001 static int lnet_add_net_common(struct lnet_net *net,
3002                                struct lnet_ioctl_config_lnd_tunables *tun)
3003 {
3004         __u32                   net_id;
3005         struct lnet_ping_buffer *pbuf;
3006         struct lnet_handle_md   ping_mdh;
3007         int                     rc;
3008         struct lnet_remotenet *rnet;
3009         int                     net_ni_count;
3010         int                     num_acceptor_nets;
3011
3012         lnet_net_lock(LNET_LOCK_EX);
3013         rnet = lnet_find_rnet_locked(net->net_id);
3014         lnet_net_unlock(LNET_LOCK_EX);
3015         /*
3016          * make sure that the net added doesn't invalidate the current
3017          * configuration LNet is keeping
3018          */
3019         if (rnet) {
3020                 CERROR("Adding net %s will invalidate routing configuration\n",
3021                        libcfs_net2str(net->net_id));
3022                 lnet_net_free(net);
3023                 return -EUSERS;
3024         }
3025
3026         /*
3027          * make sure you calculate the correct number of slots in the ping
3028          * buffer. Since the ping info is a flattened list of all the NIs,
3029          * we should allocate enough slots to accomodate the number of NIs
3030          * which will be added.
3031          *
3032          * since ni hasn't been configured yet, use
3033          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3034          */
3035         net_ni_count = lnet_get_net_ni_count_pre(net);
3036
3037         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3038                                     net_ni_count + lnet_get_ni_count(),
3039                                     false);
3040         if (rc < 0) {
3041                 lnet_net_free(net);
3042                 return rc;
3043         }
3044
3045         if (tun)
3046                 memcpy(&net->net_tunables,
3047                        &tun->lt_cmn, sizeof(net->net_tunables));
3048         else
3049                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3050
3051         /*
3052          * before starting this network get a count of the current TCP
3053          * networks which require the acceptor thread running. If that
3054          * count is == 0 before we start up this network, then we'd want to
3055          * start up the acceptor thread after starting up this network
3056          */
3057         num_acceptor_nets = lnet_count_acceptor_nets();
3058
3059         net_id = net->net_id;
3060
3061         rc = lnet_startup_lndnet(net,
3062                                  (tun) ? &tun->lt_tun : NULL);
3063         if (rc < 0)
3064                 goto failed;
3065
3066         lnet_net_lock(LNET_LOCK_EX);
3067         net = lnet_get_net_locked(net_id);
3068         lnet_net_unlock(LNET_LOCK_EX);
3069
3070         LASSERT(net);
3071
3072         /*
3073          * Start the acceptor thread if this is the first network
3074          * being added that requires the thread.
3075          */
3076         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
3077                 rc = lnet_acceptor_start();
3078                 if (rc < 0) {
3079                         /* shutdown the net that we just started */
3080                         CERROR("Failed to start up acceptor thread\n");
3081                         lnet_shutdown_lndnet(net);
3082                         goto failed;
3083                 }
3084         }
3085
3086         lnet_net_lock(LNET_LOCK_EX);
3087         lnet_peer_net_added(net);
3088         lnet_net_unlock(LNET_LOCK_EX);
3089
3090         lnet_ping_target_update(pbuf, ping_mdh);
3091
3092         return 0;
3093
3094 failed:
3095         lnet_ping_md_unlink(pbuf, &ping_mdh);
3096         lnet_ping_buffer_decref(pbuf);
3097         return rc;
3098 }
3099
3100 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3101                                       struct lnet_ioctl_config_lnd_tunables *tun)
3102 {
3103         struct lnet_net *net;
3104         char *nets;
3105         int rc;
3106         struct list_head net_head;
3107
3108         INIT_LIST_HEAD(&net_head);
3109
3110         rc = lnet_parse_ip2nets(&nets, ip2nets);
3111         if (rc < 0)
3112                 return rc;
3113
3114         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3115         if (rc < 0)
3116                 return rc;
3117
3118         mutex_lock(&the_lnet.ln_api_mutex);
3119         while (!list_empty(&net_head)) {
3120                 net = list_entry(net_head.next, struct lnet_net, net_list);
3121                 list_del_init(&net->net_list);
3122                 rc = lnet_add_net_common(net, tun);
3123                 if (rc < 0)
3124                         goto out;
3125         }
3126
3127 out:
3128         mutex_unlock(&the_lnet.ln_api_mutex);
3129
3130         while (!list_empty(&net_head)) {
3131                 net = list_entry(net_head.next, struct lnet_net, net_list);
3132                 list_del_init(&net->net_list);
3133                 lnet_net_free(net);
3134         }
3135         return rc;
3136 }
3137
3138 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3139 {
3140         struct lnet_net *net;
3141         struct lnet_ni *ni;
3142         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3143         int rc, i;
3144         __u32 net_id, lnd_type;
3145
3146         /* get the tunables if they are available */
3147         if (conf->lic_cfg_hdr.ioc_len >=
3148             sizeof(*conf) + sizeof(*tun))
3149                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3150                         conf->lic_bulk;
3151
3152         /* handle legacy ip2nets from DLC */
3153         if (conf->lic_legacy_ip2nets[0] != '\0')
3154                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3155                                                   tun);
3156
3157         net_id = LNET_NIDNET(conf->lic_nid);
3158         lnd_type = LNET_NETTYP(net_id);
3159
3160         if (!libcfs_isknown_lnd(lnd_type)) {
3161                 CERROR("No valid net and lnd information provided\n");
3162                 return -EINVAL;
3163         }
3164
3165         net = lnet_net_alloc(net_id, NULL);
3166         if (!net)
3167                 return -ENOMEM;
3168
3169         for (i = 0; i < conf->lic_ncpts; i++) {
3170                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3171                         return -EINVAL;
3172         }
3173
3174         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3175                                        conf->lic_ni_intf[0]);
3176         if (!ni)
3177                 return -ENOMEM;
3178
3179         mutex_lock(&the_lnet.ln_api_mutex);
3180
3181         rc = lnet_add_net_common(net, tun);
3182
3183         mutex_unlock(&the_lnet.ln_api_mutex);
3184
3185         return rc;
3186 }
3187
3188 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3189 {
3190         struct lnet_net  *net;
3191         struct lnet_ni *ni;
3192         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3193         struct lnet_ping_buffer *pbuf;
3194         struct lnet_handle_md  ping_mdh;
3195         int               rc;
3196         int               net_count;
3197         __u32             addr;
3198
3199         /* don't allow userspace to shutdown the LOLND */
3200         if (LNET_NETTYP(net_id) == LOLND)
3201                 return -EINVAL;
3202
3203         mutex_lock(&the_lnet.ln_api_mutex);
3204
3205         lnet_net_lock(0);
3206
3207         net = lnet_get_net_locked(net_id);
3208         if (!net) {
3209                 CERROR("net %s not found\n",
3210                        libcfs_net2str(net_id));
3211                 rc = -ENOENT;
3212                 goto unlock_net;
3213         }
3214
3215         addr = LNET_NIDADDR(conf->lic_nid);
3216         if (addr == 0) {
3217                 /* remove the entire net */
3218                 net_count = lnet_get_net_ni_count_locked(net);
3219
3220                 lnet_net_unlock(0);
3221
3222                 /* create and link a new ping info, before removing the old one */
3223                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3224                                         lnet_get_ni_count() - net_count,
3225                                         false);
3226                 if (rc != 0)
3227                         goto unlock_api_mutex;
3228
3229                 lnet_shutdown_lndnet(net);
3230
3231                 if (lnet_count_acceptor_nets() == 0)
3232                         lnet_acceptor_stop();
3233
3234                 lnet_ping_target_update(pbuf, ping_mdh);
3235
3236                 goto unlock_api_mutex;
3237         }
3238
3239         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3240         if (!ni) {
3241                 CERROR("nid %s not found\n",
3242                        libcfs_nid2str(conf->lic_nid));
3243                 rc = -ENOENT;
3244                 goto unlock_net;
3245         }
3246
3247         net_count = lnet_get_net_ni_count_locked(net);
3248
3249         lnet_net_unlock(0);
3250
3251         /* create and link a new ping info, before removing the old one */
3252         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3253                                   lnet_get_ni_count() - 1, false);
3254         if (rc != 0)
3255                 goto unlock_api_mutex;
3256
3257         lnet_shutdown_lndni(ni);
3258
3259         if (lnet_count_acceptor_nets() == 0)
3260                 lnet_acceptor_stop();
3261
3262         lnet_ping_target_update(pbuf, ping_mdh);
3263
3264         /* check if the net is empty and remove it if it is */
3265         if (net_count == 1)
3266                 lnet_shutdown_lndnet(net);
3267
3268         goto unlock_api_mutex;
3269
3270 unlock_net:
3271         lnet_net_unlock(0);
3272 unlock_api_mutex:
3273         mutex_unlock(&the_lnet.ln_api_mutex);
3274
3275         return rc;
3276 }
3277
3278 /*
3279  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3280  * They are only expected to be called for unique networks.
3281  * That can be as a result of older DLC library
3282  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3283  */
3284 int
3285 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3286 {
3287         struct lnet_net         *net;
3288         struct list_head        net_head;
3289         int                     rc;
3290         struct lnet_ioctl_config_lnd_tunables tun;
3291         char *nets = conf->cfg_config_u.cfg_net.net_intf;
3292
3293         INIT_LIST_HEAD(&net_head);
3294
3295         /* Create a net/ni structures for the network string */
3296         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3297         if (rc <= 0)
3298                 return rc == 0 ? -EINVAL : rc;
3299
3300         mutex_lock(&the_lnet.ln_api_mutex);
3301
3302         if (rc > 1) {
3303                 rc = -EINVAL; /* only add one network per call */
3304                 goto out_unlock_clean;
3305         }
3306
3307         net = list_entry(net_head.next, struct lnet_net, net_list);
3308         list_del_init(&net->net_list);
3309
3310         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3311
3312         memset(&tun, 0, sizeof(tun));
3313
3314         tun.lt_cmn.lct_peer_timeout =
3315           conf->cfg_config_u.cfg_net.net_peer_timeout;
3316         tun.lt_cmn.lct_peer_tx_credits =
3317           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3318         tun.lt_cmn.lct_peer_rtr_credits =
3319           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3320         tun.lt_cmn.lct_max_tx_credits =
3321           conf->cfg_config_u.cfg_net.net_max_tx_credits;
3322
3323         rc = lnet_add_net_common(net, &tun);
3324
3325 out_unlock_clean:
3326         mutex_unlock(&the_lnet.ln_api_mutex);
3327         while (!list_empty(&net_head)) {
3328                 /* net_head list is empty in success case */
3329                 net = list_entry(net_head.next, struct lnet_net, net_list);
3330                 list_del_init(&net->net_list);
3331                 lnet_net_free(net);
3332         }
3333         return rc;
3334 }
3335
3336 int
3337 lnet_dyn_del_net(__u32 net_id)
3338 {
3339         struct lnet_net  *net;
3340         struct lnet_ping_buffer *pbuf;
3341         struct lnet_handle_md ping_mdh;
3342         int               rc;
3343         int               net_ni_count;
3344
3345         /* don't allow userspace to shutdown the LOLND */
3346         if (LNET_NETTYP(net_id) == LOLND)
3347                 return -EINVAL;
3348
3349         mutex_lock(&the_lnet.ln_api_mutex);
3350
3351         lnet_net_lock(0);
3352
3353         net = lnet_get_net_locked(net_id);
3354         if (net == NULL) {
3355                 lnet_net_unlock(0);
3356                 rc = -EINVAL;
3357                 goto out;
3358         }
3359
3360         net_ni_count = lnet_get_net_ni_count_locked(net);
3361
3362         lnet_net_unlock(0);
3363
3364         /* create and link a new ping info, before removing the old one */
3365         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3366                                     lnet_get_ni_count() - net_ni_count, false);
3367         if (rc != 0)
3368                 goto out;
3369
3370         lnet_shutdown_lndnet(net);
3371
3372         if (lnet_count_acceptor_nets() == 0)
3373                 lnet_acceptor_stop();
3374
3375         lnet_ping_target_update(pbuf, ping_mdh);
3376
3377 out:
3378         mutex_unlock(&the_lnet.ln_api_mutex);
3379
3380         return rc;
3381 }
3382
3383 void lnet_incr_dlc_seq(void)
3384 {
3385         atomic_inc(&lnet_dlc_seq_no);
3386 }
3387
3388 __u32 lnet_get_dlc_seq_locked(void)
3389 {
3390         return atomic_read(&lnet_dlc_seq_no);
3391 }
3392
3393 static void
3394 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3395 {
3396         struct lnet_net *net;
3397         struct lnet_ni *ni;
3398
3399         lnet_net_lock(LNET_LOCK_EX);
3400         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3401                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3402                         if (ni->ni_nid == nid || all) {
3403                                 atomic_set(&ni->ni_healthv, value);
3404                                 if (list_empty(&ni->ni_recovery) &&
3405                                     value < LNET_MAX_HEALTH_VALUE) {
3406                                         CERROR("manually adding local NI %s to recovery\n",
3407                                                libcfs_nid2str(ni->ni_nid));
3408                                         list_add_tail(&ni->ni_recovery,
3409                                                       &the_lnet.ln_mt_localNIRecovq);
3410                                         lnet_ni_addref_locked(ni, 0);
3411                                 }
3412                                 if (!all) {
3413                                         lnet_net_unlock(LNET_LOCK_EX);
3414                                         return;
3415                                 }
3416                         }
3417                 }
3418         }
3419         lnet_net_unlock(LNET_LOCK_EX);
3420 }
3421
3422 static int
3423 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3424 {
3425         int cpt, rc = 0;
3426         struct lnet_ni *ni;
3427         lnet_nid_t nid = stats->hlni_nid;
3428
3429         cpt = lnet_net_lock_current();
3430         ni = lnet_nid2ni_locked(nid, cpt);
3431
3432         if (!ni) {
3433                 rc = -ENOENT;
3434                 goto unlock;
3435         }
3436
3437         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3438         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3439         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3440         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3441         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3442         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3443         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3444
3445 unlock:
3446         lnet_net_unlock(cpt);
3447
3448         return rc;
3449 }
3450
3451 static int
3452 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3453 {
3454         struct lnet_ni *ni;
3455         int i = 0;
3456
3457         lnet_net_lock(LNET_LOCK_EX);
3458         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3459                 list->rlst_nid_array[i] = ni->ni_nid;
3460                 i++;
3461                 if (i >= LNET_MAX_SHOW_NUM_NID)
3462                         break;
3463         }
3464         lnet_net_unlock(LNET_LOCK_EX);
3465         list->rlst_num_nids = i;
3466
3467         return 0;
3468 }
3469
3470 static int
3471 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3472 {
3473         struct lnet_peer_ni *lpni;
3474         int i = 0;
3475
3476         lnet_net_lock(LNET_LOCK_EX);
3477         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3478                 list->rlst_nid_array[i] = lpni->lpni_nid;
3479                 i++;
3480                 if (i >= LNET_MAX_SHOW_NUM_NID)
3481                         break;
3482         }
3483         lnet_net_unlock(LNET_LOCK_EX);
3484         list->rlst_num_nids = i;
3485
3486         return 0;
3487 }
3488
3489 /**
3490  * LNet ioctl handler.
3491  *
3492  */
3493 int
3494 LNetCtl(unsigned int cmd, void *arg)
3495 {
3496         struct libcfs_ioctl_data *data = arg;
3497         struct lnet_ioctl_config_data *config;
3498         struct lnet_process_id    id = {0};
3499         struct lnet_ni           *ni;
3500         int                       rc;
3501
3502         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3503                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3504
3505         switch (cmd) {
3506         case IOC_LIBCFS_GET_NI:
3507                 rc = LNetGetId(data->ioc_count, &id);
3508                 data->ioc_nid = id.nid;
3509                 return rc;
3510
3511         case IOC_LIBCFS_FAIL_NID:
3512                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3513
3514         case IOC_LIBCFS_ADD_ROUTE:
3515                 config = arg;
3516
3517                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3518                         return -EINVAL;
3519
3520                 mutex_lock(&the_lnet.ln_api_mutex);
3521                 rc = lnet_add_route(config->cfg_net,
3522                                     config->cfg_config_u.cfg_route.rtr_hop,
3523                                     config->cfg_nid,
3524                                     config->cfg_config_u.cfg_route.
3525                                         rtr_priority);
3526                 mutex_unlock(&the_lnet.ln_api_mutex);
3527                 return rc;
3528
3529         case IOC_LIBCFS_DEL_ROUTE:
3530                 config = arg;
3531
3532                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3533                         return -EINVAL;
3534
3535                 mutex_lock(&the_lnet.ln_api_mutex);
3536                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3537                 mutex_unlock(&the_lnet.ln_api_mutex);
3538                 return rc;
3539
3540         case IOC_LIBCFS_GET_ROUTE:
3541                 config = arg;
3542
3543                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3544                         return -EINVAL;
3545
3546                 mutex_lock(&the_lnet.ln_api_mutex);
3547                 rc = lnet_get_route(config->cfg_count,
3548                                     &config->cfg_net,
3549                                     &config->cfg_config_u.cfg_route.rtr_hop,
3550                                     &config->cfg_nid,
3551                                     &config->cfg_config_u.cfg_route.rtr_flags,
3552                                     &config->cfg_config_u.cfg_route.
3553                                         rtr_priority);
3554                 mutex_unlock(&the_lnet.ln_api_mutex);
3555                 return rc;
3556
3557         case IOC_LIBCFS_GET_LOCAL_NI: {
3558                 struct lnet_ioctl_config_ni *cfg_ni;
3559                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3560                 struct lnet_ioctl_element_stats *stats;
3561                 __u32 tun_size;
3562
3563                 cfg_ni = arg;
3564
3565                 /* get the tunables if they are available */
3566                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3567                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3568                         return -EINVAL;
3569
3570                 stats = (struct lnet_ioctl_element_stats *)
3571                         cfg_ni->lic_bulk;
3572                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3573                                 (cfg_ni->lic_bulk + sizeof(*stats));
3574
3575                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3576                         sizeof(*stats);
3577
3578                 mutex_lock(&the_lnet.ln_api_mutex);
3579                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3580                 mutex_unlock(&the_lnet.ln_api_mutex);
3581                 return rc;
3582         }
3583
3584         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3585                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3586
3587                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3588                         return -EINVAL;
3589
3590                 mutex_lock(&the_lnet.ln_api_mutex);
3591                 rc = lnet_get_ni_stats(msg_stats);
3592                 mutex_unlock(&the_lnet.ln_api_mutex);
3593
3594                 return rc;
3595         }
3596
3597         case IOC_LIBCFS_GET_NET: {
3598                 size_t total = sizeof(*config) +
3599                                sizeof(struct lnet_ioctl_net_config);
3600                 config = arg;
3601
3602                 if (config->cfg_hdr.ioc_len < total)
3603                         return -EINVAL;
3604
3605                 mutex_lock(&the_lnet.ln_api_mutex);
3606                 rc = lnet_get_net_config(config);
3607                 mutex_unlock(&the_lnet.ln_api_mutex);
3608                 return rc;
3609         }
3610
3611         case IOC_LIBCFS_GET_LNET_STATS:
3612         {
3613                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3614
3615                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3616                         return -EINVAL;
3617
3618                 mutex_lock(&the_lnet.ln_api_mutex);
3619                 lnet_counters_get(&lnet_stats->st_cntrs);
3620                 mutex_unlock(&the_lnet.ln_api_mutex);
3621                 return 0;
3622         }
3623
3624         case IOC_LIBCFS_CONFIG_RTR:
3625                 config = arg;
3626
3627                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3628                         return -EINVAL;
3629
3630                 mutex_lock(&the_lnet.ln_api_mutex);
3631                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3632                         rc = lnet_rtrpools_enable();
3633                         mutex_unlock(&the_lnet.ln_api_mutex);
3634                         return rc;
3635                 }
3636                 lnet_rtrpools_disable();
3637                 mutex_unlock(&the_lnet.ln_api_mutex);
3638                 return 0;
3639
3640         case IOC_LIBCFS_ADD_BUF:
3641                 config = arg;
3642
3643                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3644                         return -EINVAL;
3645
3646                 mutex_lock(&the_lnet.ln_api_mutex);
3647                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3648                                                 buf_tiny,
3649                                           config->cfg_config_u.cfg_buffers.
3650                                                 buf_small,
3651                                           config->cfg_config_u.cfg_buffers.
3652                                                 buf_large);
3653                 mutex_unlock(&the_lnet.ln_api_mutex);
3654                 return rc;
3655
3656         case IOC_LIBCFS_SET_NUMA_RANGE: {
3657                 struct lnet_ioctl_set_value *numa;
3658                 numa = arg;
3659                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3660                         return -EINVAL;
3661                 lnet_net_lock(LNET_LOCK_EX);
3662                 lnet_numa_range = numa->sv_value;
3663                 lnet_net_unlock(LNET_LOCK_EX);
3664                 return 0;
3665         }
3666
3667         case IOC_LIBCFS_GET_NUMA_RANGE: {
3668                 struct lnet_ioctl_set_value *numa;
3669                 numa = arg;
3670                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3671                         return -EINVAL;
3672                 numa->sv_value = lnet_numa_range;
3673                 return 0;
3674         }
3675
3676         case IOC_LIBCFS_GET_BUF: {
3677                 struct lnet_ioctl_pool_cfg *pool_cfg;
3678                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3679
3680                 config = arg;
3681
3682                 if (config->cfg_hdr.ioc_len < total)
3683                         return -EINVAL;
3684
3685                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3686
3687                 mutex_lock(&the_lnet.ln_api_mutex);
3688                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3689                 mutex_unlock(&the_lnet.ln_api_mutex);
3690                 return rc;
3691         }
3692
3693         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3694                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3695
3696                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3697                         return -EINVAL;
3698
3699                 mutex_lock(&the_lnet.ln_api_mutex);
3700                 rc = lnet_get_local_ni_hstats(stats);
3701                 mutex_unlock(&the_lnet.ln_api_mutex);
3702
3703                 return rc;
3704         }
3705
3706         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3707                 struct lnet_ioctl_recovery_list *list = arg;
3708                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3709                         return -EINVAL;
3710
3711                 mutex_lock(&the_lnet.ln_api_mutex);
3712                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3713                         rc = lnet_get_local_ni_recovery_list(list);
3714                 else
3715                         rc = lnet_get_peer_ni_recovery_list(list);
3716                 mutex_unlock(&the_lnet.ln_api_mutex);
3717                 return rc;
3718         }
3719
3720         case IOC_LIBCFS_ADD_PEER_NI: {
3721                 struct lnet_ioctl_peer_cfg *cfg = arg;
3722
3723                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3724                         return -EINVAL;
3725
3726                 mutex_lock(&the_lnet.ln_api_mutex);
3727                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3728                                       cfg->prcfg_cfg_nid,
3729                                       cfg->prcfg_mr);
3730                 mutex_unlock(&the_lnet.ln_api_mutex);
3731                 return rc;
3732         }
3733
3734         case IOC_LIBCFS_DEL_PEER_NI: {
3735                 struct lnet_ioctl_peer_cfg *cfg = arg;
3736
3737                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3738                         return -EINVAL;
3739
3740                 mutex_lock(&the_lnet.ln_api_mutex);
3741                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3742                                       cfg->prcfg_cfg_nid);
3743                 mutex_unlock(&the_lnet.ln_api_mutex);
3744                 return rc;
3745         }
3746
3747         case IOC_LIBCFS_GET_PEER_INFO: {
3748                 struct lnet_ioctl_peer *peer_info = arg;
3749
3750                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3751                         return -EINVAL;
3752
3753                 mutex_lock(&the_lnet.ln_api_mutex);
3754                 rc = lnet_get_peer_ni_info(
3755                    peer_info->pr_count,
3756                    &peer_info->pr_nid,
3757                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3758                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3759                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3760                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3761                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3762                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3763                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3764                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3765                 mutex_unlock(&the_lnet.ln_api_mutex);
3766                 return rc;
3767         }
3768
3769         case IOC_LIBCFS_GET_PEER_NI: {
3770                 struct lnet_ioctl_peer_cfg *cfg = arg;
3771
3772                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3773                         return -EINVAL;
3774
3775                 mutex_lock(&the_lnet.ln_api_mutex);
3776                 rc = lnet_get_peer_info(cfg,
3777                                         (void __user *)cfg->prcfg_bulk);
3778                 mutex_unlock(&the_lnet.ln_api_mutex);
3779                 return rc;
3780         }
3781
3782         case IOC_LIBCFS_GET_PEER_LIST: {
3783                 struct lnet_ioctl_peer_cfg *cfg = arg;
3784
3785                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3786                         return -EINVAL;
3787
3788                 mutex_lock(&the_lnet.ln_api_mutex);
3789                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3790                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3791                 mutex_unlock(&the_lnet.ln_api_mutex);
3792                 return rc;
3793         }
3794
3795         case IOC_LIBCFS_SET_HEALHV: {
3796                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3797                 int value;
3798                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3799                         return -EINVAL;
3800                 if (cfg->rh_value < 0 ||
3801                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3802                         value = LNET_MAX_HEALTH_VALUE;
3803                 else
3804                         value = cfg->rh_value;
3805                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3806                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3807                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3808                 mutex_lock(&the_lnet.ln_api_mutex);
3809                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3810                         lnet_ni_set_healthv(cfg->rh_nid, value,
3811                                              cfg->rh_all);
3812                 else
3813                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3814                                                   cfg->rh_all);
3815                 mutex_unlock(&the_lnet.ln_api_mutex);
3816                 return 0;
3817         }
3818
3819         case IOC_LIBCFS_NOTIFY_ROUTER: {
3820                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3821
3822                 /* The deadline passed in by the user should be some time in
3823                  * seconds in the future since the UNIX epoch. We have to map
3824                  * that deadline to the wall clock.
3825                  */
3826                 deadline += ktime_get_seconds();
3827                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
3828                                    deadline);
3829         }
3830
3831         case IOC_LIBCFS_LNET_DIST:
3832                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3833                 if (rc < 0 && rc != -EHOSTUNREACH)
3834                         return rc;
3835
3836                 data->ioc_u32[0] = rc;
3837                 return 0;
3838
3839         case IOC_LIBCFS_TESTPROTOCOMPAT:
3840                 lnet_net_lock(LNET_LOCK_EX);
3841                 the_lnet.ln_testprotocompat = data->ioc_flags;
3842                 lnet_net_unlock(LNET_LOCK_EX);
3843                 return 0;
3844
3845         case IOC_LIBCFS_LNET_FAULT:
3846                 return lnet_fault_ctl(data->ioc_flags, data);
3847
3848         case IOC_LIBCFS_PING: {
3849                 signed long timeout;
3850
3851                 id.nid = data->ioc_nid;
3852                 id.pid = data->ioc_u32[0];
3853
3854                 /* If timeout is negative then set default of 3 minutes */
3855                 if (((s32)data->ioc_u32[1] <= 0) ||
3856                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3857                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3858                 else
3859                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
3860
3861                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3862                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3863
3864                 if (rc < 0)
3865                         return rc;
3866
3867                 data->ioc_count = rc;
3868                 return 0;
3869         }
3870
3871         case IOC_LIBCFS_PING_PEER: {
3872                 struct lnet_ioctl_ping_data *ping = arg;
3873                 struct lnet_peer *lp;
3874                 signed long timeout;
3875
3876                 /* If timeout is negative then set default of 3 minutes */
3877                 if (((s32)ping->op_param) <= 0 ||
3878                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3879                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3880                 else
3881                         timeout = msecs_to_jiffies(ping->op_param);
3882
3883                 rc = lnet_ping(ping->ping_id, timeout,
3884                                ping->ping_buf,
3885                                ping->ping_count);
3886                 if (rc < 0)
3887                         return rc;
3888
3889                 mutex_lock(&the_lnet.ln_api_mutex);
3890                 lp = lnet_find_peer(ping->ping_id.nid);
3891                 if (lp) {
3892                         ping->ping_id.nid = lp->lp_primary_nid;
3893                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3894                         lnet_peer_decref_locked(lp);
3895                 }
3896                 mutex_unlock(&the_lnet.ln_api_mutex);
3897
3898                 ping->ping_count = rc;
3899                 return 0;
3900         }
3901
3902         case IOC_LIBCFS_DISCOVER: {
3903                 struct lnet_ioctl_ping_data *discover = arg;
3904                 struct lnet_peer *lp;
3905
3906                 rc = lnet_discover(discover->ping_id, discover->op_param,
3907                                    discover->ping_buf,
3908                                    discover->ping_count);
3909                 if (rc < 0)
3910                         return rc;
3911
3912                 mutex_lock(&the_lnet.ln_api_mutex);
3913                 lp = lnet_find_peer(discover->ping_id.nid);
3914                 if (lp) {
3915                         discover->ping_id.nid = lp->lp_primary_nid;
3916                         discover->mr_info = lnet_peer_is_multi_rail(lp);
3917                         lnet_peer_decref_locked(lp);
3918                 }
3919                 mutex_unlock(&the_lnet.ln_api_mutex);
3920
3921                 discover->ping_count = rc;
3922                 return 0;
3923         }
3924
3925         default:
3926                 ni = lnet_net2ni_addref(data->ioc_net);
3927                 if (ni == NULL)
3928                         return -EINVAL;
3929
3930                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
3931                         rc = -EINVAL;
3932                 else
3933                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
3934
3935                 lnet_ni_decref(ni);
3936                 return rc;
3937         }
3938         /* not reached */
3939 }
3940 EXPORT_SYMBOL(LNetCtl);
3941
3942 void LNetDebugPeer(struct lnet_process_id id)
3943 {
3944         lnet_debug_peer(id.nid);
3945 }
3946 EXPORT_SYMBOL(LNetDebugPeer);
3947
3948 /**
3949  * Determine if the specified peer \a nid is on the local node.
3950  *
3951  * \param nid   peer nid to check
3952  *
3953  * \retval true         If peer NID is on the local node.
3954  * \retval false        If peer NID is not on the local node.
3955  */
3956 bool LNetIsPeerLocal(lnet_nid_t nid)
3957 {
3958         struct lnet_net *net;
3959         struct lnet_ni *ni;
3960         int cpt;
3961
3962         cpt = lnet_net_lock_current();
3963         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3964                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3965                         if (ni->ni_nid == nid) {
3966                                 lnet_net_unlock(cpt);
3967                                 return true;
3968                         }
3969                 }
3970         }
3971         lnet_net_unlock(cpt);
3972
3973         return false;
3974 }
3975 EXPORT_SYMBOL(LNetIsPeerLocal);
3976
3977 /**
3978  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
3979  * Note that all interfaces share a same PID, as requested by LNetNIInit().
3980  *
3981  * \param index Index of the interface to look up.
3982  * \param id On successful return, this location will hold the
3983  * struct lnet_process_id ID of the interface.
3984  *
3985  * \retval 0 If an interface exists at \a index.
3986  * \retval -ENOENT If no interface has been found.
3987  */
3988 int
3989 LNetGetId(unsigned int index, struct lnet_process_id *id)
3990 {
3991         struct lnet_ni   *ni;
3992         struct lnet_net  *net;
3993         int               cpt;
3994         int               rc = -ENOENT;
3995
3996         LASSERT(the_lnet.ln_refcount > 0);
3997
3998         cpt = lnet_net_lock_current();
3999
4000         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4001                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4002                         if (index-- != 0)
4003                                 continue;
4004
4005                         id->nid = ni->ni_nid;
4006                         id->pid = the_lnet.ln_pid;
4007                         rc = 0;
4008                         break;
4009                 }
4010         }
4011
4012         lnet_net_unlock(cpt);
4013         return rc;
4014 }
4015 EXPORT_SYMBOL(LNetGetId);
4016
4017 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4018                      struct lnet_process_id __user *ids, int n_ids)
4019 {
4020         struct lnet_handle_eq eqh;
4021         struct lnet_handle_md mdh;
4022         struct lnet_event event;
4023         struct lnet_md md = { NULL };
4024         int which;
4025         int unlinked = 0;
4026         int replied = 0;
4027         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
4028         struct lnet_ping_buffer *pbuf;
4029         struct lnet_process_id tmpid;
4030         int i;
4031         int nob;
4032         int rc;
4033         int rc2;
4034         sigset_t blocked;
4035
4036         /* n_ids limit is arbitrary */
4037         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4038                 return -EINVAL;
4039
4040         /*
4041          * if the user buffer has more space than the lnet_interfaces_max
4042          * then only fill it up to lnet_interfaces_max
4043          */
4044         if (n_ids > lnet_interfaces_max)
4045                 n_ids = lnet_interfaces_max;
4046
4047         if (id.pid == LNET_PID_ANY)
4048                 id.pid = LNET_PID_LUSTRE;
4049
4050         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4051         if (!pbuf)
4052                 return -ENOMEM;
4053
4054         /* NB 2 events max (including any unlink event) */
4055         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
4056         if (rc != 0) {
4057                 CERROR("Can't allocate EQ: %d\n", rc);
4058                 goto fail_ping_buffer_decref;
4059         }
4060
4061         /* initialize md content */
4062         md.start     = &pbuf->pb_info;
4063         md.length    = LNET_PING_INFO_SIZE(n_ids);
4064         md.threshold = 2; /* GET/REPLY */
4065         md.max_size  = 0;
4066         md.options   = LNET_MD_TRUNCATE;
4067         md.user_ptr  = NULL;
4068         md.eq_handle = eqh;
4069
4070         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
4071         if (rc != 0) {
4072                 CERROR("Can't bind MD: %d\n", rc);
4073                 goto fail_free_eq;
4074         }
4075
4076         rc = LNetGet(LNET_NID_ANY, mdh, id,
4077                      LNET_RESERVED_PORTAL,
4078                      LNET_PROTO_PING_MATCHBITS, 0, false);
4079
4080         if (rc != 0) {
4081                 /* Don't CERROR; this could be deliberate! */
4082                 rc2 = LNetMDUnlink(mdh);
4083                 LASSERT(rc2 == 0);
4084
4085                 /* NB must wait for the UNLINK event below... */
4086                 unlinked = 1;
4087                 timeout = a_long_time;
4088         }
4089
4090         do {
4091                 /* MUST block for unlink to complete */
4092                 if (unlinked)
4093                         blocked = cfs_block_allsigs();
4094
4095                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
4096
4097                 if (unlinked)
4098                         cfs_restore_sigs(blocked);
4099
4100                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
4101                        (rc2 <= 0) ? -1 : event.type,
4102                        (rc2 <= 0) ? -1 : event.status,
4103                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
4104
4105                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
4106
4107                 if (rc2 <= 0 || event.status != 0) {
4108                         /* timeout or error */
4109                         if (!replied && rc == 0)
4110                                 rc = (rc2 < 0) ? rc2 :
4111                                      (rc2 == 0) ? -ETIMEDOUT :
4112                                      event.status;
4113
4114                         if (!unlinked) {
4115                                 /* Ensure completion in finite time... */
4116                                 LNetMDUnlink(mdh);
4117                                 /* No assertion (racing with network) */
4118                                 unlinked = 1;
4119                                 timeout = a_long_time;
4120                         } else if (rc2 == 0) {
4121                                 /* timed out waiting for unlink */
4122                                 CWARN("ping %s: late network completion\n",
4123                                       libcfs_id2str(id));
4124                         }
4125                 } else if (event.type == LNET_EVENT_REPLY) {
4126                         replied = 1;
4127                         rc = event.mlength;
4128                 }
4129         } while (rc2 <= 0 || !event.unlinked);
4130
4131         if (!replied) {
4132                 if (rc >= 0)
4133                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
4134                               libcfs_id2str(id));
4135                 rc = -EIO;
4136                 goto fail_free_eq;
4137         }
4138
4139         nob = rc;
4140         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4141
4142         rc = -EPROTO;           /* if I can't parse... */
4143
4144         if (nob < 8) {
4145                 CERROR("%s: ping info too short %d\n",
4146                        libcfs_id2str(id), nob);
4147                 goto fail_free_eq;
4148         }
4149
4150         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4151                 lnet_swap_pinginfo(pbuf);
4152         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4153                 CERROR("%s: Unexpected magic %08x\n",
4154                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4155                 goto fail_free_eq;
4156         }
4157
4158         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4159                 CERROR("%s: ping w/o NI status: 0x%x\n",
4160                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4161                 goto fail_free_eq;
4162         }
4163
4164         if (nob < LNET_PING_INFO_SIZE(0)) {
4165                 CERROR("%s: Short reply %d(%d min)\n",
4166                        libcfs_id2str(id),
4167                        nob, (int)LNET_PING_INFO_SIZE(0));
4168                 goto fail_free_eq;
4169         }
4170
4171         if (pbuf->pb_info.pi_nnis < n_ids)
4172                 n_ids = pbuf->pb_info.pi_nnis;
4173
4174         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4175                 CERROR("%s: Short reply %d(%d expected)\n",
4176                        libcfs_id2str(id),
4177                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4178                 goto fail_free_eq;
4179         }
4180
4181         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4182
4183         memset(&tmpid, 0, sizeof(tmpid));
4184         for (i = 0; i < n_ids; i++) {
4185                 tmpid.pid = pbuf->pb_info.pi_pid;
4186                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4187                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4188                         goto fail_free_eq;
4189         }
4190         rc = pbuf->pb_info.pi_nnis;
4191
4192  fail_free_eq:
4193         rc2 = LNetEQFree(eqh);
4194         if (rc2 != 0)
4195                 CERROR("rc2 %d\n", rc2);
4196         LASSERT(rc2 == 0);
4197
4198  fail_ping_buffer_decref:
4199         lnet_ping_buffer_decref(pbuf);
4200         return rc;
4201 }
4202
4203 static int
4204 lnet_discover(struct lnet_process_id id, __u32 force,
4205               struct lnet_process_id __user *ids, int n_ids)
4206 {
4207         struct lnet_peer_ni *lpni;
4208         struct lnet_peer_ni *p;
4209         struct lnet_peer *lp;
4210         struct lnet_process_id *buf;
4211         int cpt;
4212         int i;
4213         int rc;
4214         int max_intf = lnet_interfaces_max;
4215         size_t buf_size;
4216
4217         if (n_ids <= 0 ||
4218             id.nid == LNET_NID_ANY)
4219                 return -EINVAL;
4220
4221         if (id.pid == LNET_PID_ANY)
4222                 id.pid = LNET_PID_LUSTRE;
4223
4224         /*
4225          * if the user buffer has more space than the max_intf
4226          * then only fill it up to max_intf
4227          */
4228         if (n_ids > max_intf)
4229                 n_ids = max_intf;
4230
4231         buf_size = n_ids * sizeof(*buf);
4232
4233         LIBCFS_ALLOC(buf, buf_size);
4234         if (!buf)
4235                 return -ENOMEM;
4236
4237         cpt = lnet_net_lock_current();
4238         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4239         if (IS_ERR(lpni)) {
4240                 rc = PTR_ERR(lpni);
4241                 goto out;
4242         }
4243
4244         /*
4245          * Clearing the NIDS_UPTODATE flag ensures the peer will
4246          * be discovered, provided discovery has not been disabled.
4247          */
4248         lp = lpni->lpni_peer_net->lpn_peer;
4249         spin_lock(&lp->lp_lock);
4250         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4251         /* If the force flag is set, force a PING and PUSH as well. */
4252         if (force)
4253                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4254         spin_unlock(&lp->lp_lock);
4255         rc = lnet_discover_peer_locked(lpni, cpt, true);
4256         if (rc)
4257                 goto out_decref;
4258
4259         /* Peer may have changed. */
4260         lp = lpni->lpni_peer_net->lpn_peer;
4261         if (lp->lp_nnis < n_ids)
4262                 n_ids = lp->lp_nnis;
4263
4264         i = 0;
4265         p = NULL;
4266         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4267                 buf[i].pid = id.pid;
4268                 buf[i].nid = p->lpni_nid;
4269                 if (++i >= n_ids)
4270                         break;
4271         }
4272
4273         lnet_net_unlock(cpt);
4274
4275         rc = -EFAULT;
4276         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
4277                 goto out_relock;
4278         rc = n_ids;
4279 out_relock:
4280         lnet_net_lock(cpt);
4281 out_decref:
4282         lnet_peer_ni_decref_locked(lpni);
4283 out:
4284         lnet_net_unlock(cpt);
4285
4286         LIBCFS_FREE(buf, buf_size);
4287
4288         return rc;
4289 }
4290
4291 /**
4292  * Retrieve peer discovery status.
4293  *
4294  * \retval 1 if lnet_peer_discovery_disabled is 0
4295  * \retval 0 if lnet_peer_discovery_disabled is 1
4296  */
4297 int
4298 LNetGetPeerDiscoveryStatus(void)
4299 {
4300         return !lnet_peer_discovery_disabled;
4301 }
4302 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);