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