Whamcloud - gitweb
1b3aa1a436fbaa9a76c6a3501b59983817dd83aa
[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         lnet_ni_unlock(ni);
1953         lnet_ni_unlink_locked(ni);
1954         lnet_incr_dlc_seq();
1955         lnet_net_unlock(LNET_LOCK_EX);
1956
1957         /* clear messages for this NI on the lazy portal */
1958         for (i = 0; i < the_lnet.ln_nportals; i++)
1959                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
1960
1961         lnet_net_lock(LNET_LOCK_EX);
1962         lnet_clear_zombies_nis_locked(net);
1963         lnet_net_unlock(LNET_LOCK_EX);
1964 }
1965
1966 static void
1967 lnet_shutdown_lndnet(struct lnet_net *net)
1968 {
1969         struct lnet_ni *ni;
1970
1971         lnet_net_lock(LNET_LOCK_EX);
1972
1973         net->net_state = LNET_NET_STATE_DELETING;
1974
1975         list_del_init(&net->net_list);
1976
1977         while (!list_empty(&net->net_ni_list)) {
1978                 ni = list_entry(net->net_ni_list.next,
1979                                 struct lnet_ni, ni_netlist);
1980                 lnet_net_unlock(LNET_LOCK_EX);
1981                 lnet_shutdown_lndni(ni);
1982                 lnet_net_lock(LNET_LOCK_EX);
1983         }
1984
1985         lnet_net_unlock(LNET_LOCK_EX);
1986
1987         /* Do peer table cleanup for this net */
1988         lnet_peer_tables_cleanup(net);
1989
1990         lnet_net_lock(LNET_LOCK_EX);
1991         /*
1992          * decrement ref count on lnd only when the entire network goes
1993          * away
1994          */
1995         net->net_lnd->lnd_refcount--;
1996
1997         lnet_net_unlock(LNET_LOCK_EX);
1998
1999         lnet_net_free(net);
2000 }
2001
2002 static void
2003 lnet_shutdown_lndnets(void)
2004 {
2005         struct lnet_net *net;
2006         struct list_head resend;
2007         struct lnet_msg *msg, *tmp;
2008
2009         INIT_LIST_HEAD(&resend);
2010
2011         /* NB called holding the global mutex */
2012
2013         /* All quiet on the API front */
2014         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2015         LASSERT(the_lnet.ln_refcount == 0);
2016
2017         lnet_net_lock(LNET_LOCK_EX);
2018         the_lnet.ln_state = LNET_STATE_STOPPING;
2019
2020         while (!list_empty(&the_lnet.ln_nets)) {
2021                 /*
2022                  * move the nets to the zombie list to avoid them being
2023                  * picked up for new work. LONET is also included in the
2024                  * Nets that will be moved to the zombie list
2025                  */
2026                 net = list_entry(the_lnet.ln_nets.next,
2027                                  struct lnet_net, net_list);
2028                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
2029         }
2030
2031         /* Drop the cached loopback Net. */
2032         if (the_lnet.ln_loni != NULL) {
2033                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2034                 the_lnet.ln_loni = NULL;
2035         }
2036         lnet_net_unlock(LNET_LOCK_EX);
2037
2038         /* iterate through the net zombie list and delete each net */
2039         while (!list_empty(&the_lnet.ln_net_zombie)) {
2040                 net = list_entry(the_lnet.ln_net_zombie.next,
2041                                  struct lnet_net, net_list);
2042                 lnet_shutdown_lndnet(net);
2043         }
2044
2045         spin_lock(&the_lnet.ln_msg_resend_lock);
2046         list_splice(&the_lnet.ln_msg_resend, &resend);
2047         spin_unlock(&the_lnet.ln_msg_resend_lock);
2048
2049         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2050                 list_del_init(&msg->msg_list);
2051                 msg->msg_no_resend = true;
2052                 lnet_finalize(msg, -ECANCELED);
2053         }
2054
2055         lnet_net_lock(LNET_LOCK_EX);
2056         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2057         lnet_net_unlock(LNET_LOCK_EX);
2058 }
2059
2060 static int
2061 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2062 {
2063         int                     rc = -EINVAL;
2064         struct lnet_tx_queue    *tq;
2065         int                     i;
2066         struct lnet_net         *net = ni->ni_net;
2067
2068         mutex_lock(&the_lnet.ln_lnd_mutex);
2069
2070         if (tun) {
2071                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2072                 ni->ni_lnd_tunables_set = true;
2073         }
2074
2075         rc = (net->net_lnd->lnd_startup)(ni);
2076
2077         mutex_unlock(&the_lnet.ln_lnd_mutex);
2078
2079         if (rc != 0) {
2080                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2081                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2082                 lnet_net_lock(LNET_LOCK_EX);
2083                 net->net_lnd->lnd_refcount--;
2084                 lnet_net_unlock(LNET_LOCK_EX);
2085                 goto failed0;
2086         }
2087
2088         lnet_ni_lock(ni);
2089         ni->ni_state = LNET_NI_STATE_ACTIVE;
2090         lnet_ni_unlock(ni);
2091
2092         /* We keep a reference on the loopback net through the loopback NI */
2093         if (net->net_lnd->lnd_type == LOLND) {
2094                 lnet_ni_addref(ni);
2095                 LASSERT(the_lnet.ln_loni == NULL);
2096                 the_lnet.ln_loni = ni;
2097                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2098                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2099                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2100                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2101                 return 0;
2102         }
2103
2104         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2105             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2106                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2107                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2108                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2109                                         "" : "per-peer ");
2110                 /* shutdown the NI since if we get here then it must've already
2111                  * been started
2112                  */
2113                 lnet_shutdown_lndni(ni);
2114                 return -EINVAL;
2115         }
2116
2117         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2118                 tq->tq_credits_min =
2119                 tq->tq_credits_max =
2120                 tq->tq_credits = lnet_ni_tq_credits(ni);
2121         }
2122
2123         atomic_set(&ni->ni_tx_credits,
2124                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2125         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2126
2127         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2128                 libcfs_nid2str(ni->ni_nid),
2129                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2130                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2131                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2132                 ni->ni_net->net_tunables.lct_peer_timeout);
2133
2134         return 0;
2135 failed0:
2136         lnet_ni_free(ni);
2137         return rc;
2138 }
2139
2140 static int
2141 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2142 {
2143         struct lnet_ni *ni;
2144         struct lnet_net *net_l = NULL;
2145         struct list_head        local_ni_list;
2146         int                     rc;
2147         int                     ni_count = 0;
2148         __u32                   lnd_type;
2149         struct lnet_lnd *lnd;
2150         int                     peer_timeout =
2151                 net->net_tunables.lct_peer_timeout;
2152         int                     maxtxcredits =
2153                 net->net_tunables.lct_max_tx_credits;
2154         int                     peerrtrcredits =
2155                 net->net_tunables.lct_peer_rtr_credits;
2156
2157         INIT_LIST_HEAD(&local_ni_list);
2158
2159         /*
2160          * make sure that this net is unique. If it isn't then
2161          * we are adding interfaces to an already existing network, and
2162          * 'net' is just a convenient way to pass in the list.
2163          * if it is unique we need to find the LND and load it if
2164          * necessary.
2165          */
2166         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2167                 lnd_type = LNET_NETTYP(net->net_id);
2168
2169                 mutex_lock(&the_lnet.ln_lnd_mutex);
2170                 lnd = lnet_find_lnd_by_type(lnd_type);
2171
2172                 if (lnd == NULL) {
2173                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2174                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2175                         mutex_lock(&the_lnet.ln_lnd_mutex);
2176
2177                         lnd = lnet_find_lnd_by_type(lnd_type);
2178                         if (lnd == NULL) {
2179                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2180                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2181                                 libcfs_lnd2str(lnd_type),
2182                                 libcfs_lnd2modname(lnd_type), rc);
2183 #ifndef HAVE_MODULE_LOADING_SUPPORT
2184                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2185                                                 "compiled with kernel module "
2186                                                 "loading support.");
2187 #endif
2188                                 rc = -EINVAL;
2189                                 goto failed0;
2190                         }
2191                 }
2192
2193                 lnet_net_lock(LNET_LOCK_EX);
2194                 lnd->lnd_refcount++;
2195                 lnet_net_unlock(LNET_LOCK_EX);
2196
2197                 net->net_lnd = lnd;
2198
2199                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2200
2201                 net_l = net;
2202         }
2203
2204         /*
2205          * net_l: if the network being added is unique then net_l
2206          *        will point to that network
2207          *        if the network being added is not unique then
2208          *        net_l points to the existing network.
2209          *
2210          * When we enter the loop below, we'll pick NIs off he
2211          * network beign added and start them up, then add them to
2212          * a local ni list. Once we've successfully started all
2213          * the NIs then we join the local NI list (of started up
2214          * networks) with the net_l->net_ni_list, which should
2215          * point to the correct network to add the new ni list to
2216          *
2217          * If any of the new NIs fail to start up, then we want to
2218          * iterate through the local ni list, which should include
2219          * any NIs which were successfully started up, and shut
2220          * them down.
2221          *
2222          * After than we want to delete the network being added,
2223          * to avoid a memory leak.
2224          */
2225
2226         /*
2227          * When a network uses TCP bonding then all its interfaces
2228          * must be specified when the network is first defined: the
2229          * TCP bonding code doesn't allow for interfaces to be added
2230          * or removed.
2231          */
2232         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2233             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2234                 rc = -EINVAL;
2235                 goto failed0;
2236         }
2237
2238         while (!list_empty(&net->net_ni_added)) {
2239                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2240                                 ni_netlist);
2241                 list_del_init(&ni->ni_netlist);
2242
2243                 /* make sure that the the NI we're about to start
2244                  * up is actually unique. if it's not fail. */
2245                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2246                                         ni->ni_interfaces[0])) {
2247                         rc = -EINVAL;
2248                         goto failed1;
2249                 }
2250
2251                 /* adjust the pointer the parent network, just in case it
2252                  * the net is a duplicate */
2253                 ni->ni_net = net_l;
2254
2255                 rc = lnet_startup_lndni(ni, tun);
2256
2257                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
2258                         ni->ni_net->net_lnd->lnd_query != NULL);
2259
2260                 if (rc < 0)
2261                         goto failed1;
2262
2263                 lnet_ni_addref(ni);
2264                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2265
2266                 ni_count++;
2267         }
2268
2269         lnet_net_lock(LNET_LOCK_EX);
2270         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2271         lnet_incr_dlc_seq();
2272         lnet_net_unlock(LNET_LOCK_EX);
2273
2274         /* if the network is not unique then we don't want to keep
2275          * it around after we're done. Free it. Otherwise add that
2276          * net to the global the_lnet.ln_nets */
2277         if (net_l != net && net_l != NULL) {
2278                 /*
2279                  * TODO - note. currently the tunables can not be updated
2280                  * once added
2281                  */
2282                 lnet_net_free(net);
2283         } else {
2284                 net->net_state = LNET_NET_STATE_ACTIVE;
2285                 /*
2286                  * restore tunables after it has been overwitten by the
2287                  * lnd
2288                  */
2289                 if (peer_timeout != -1)
2290                         net->net_tunables.lct_peer_timeout = peer_timeout;
2291                 if (maxtxcredits != -1)
2292                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2293                 if (peerrtrcredits != -1)
2294                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2295
2296                 lnet_net_lock(LNET_LOCK_EX);
2297                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2298                 lnet_net_unlock(LNET_LOCK_EX);
2299         }
2300
2301         return ni_count;
2302
2303 failed1:
2304         /*
2305          * shutdown the new NIs that are being started up
2306          * free the NET being started
2307          */
2308         while (!list_empty(&local_ni_list)) {
2309                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2310                                 ni_netlist);
2311
2312                 lnet_shutdown_lndni(ni);
2313         }
2314
2315 failed0:
2316         lnet_net_free(net);
2317
2318         return rc;
2319 }
2320
2321 static int
2322 lnet_startup_lndnets(struct list_head *netlist)
2323 {
2324         struct lnet_net         *net;
2325         int                     rc;
2326         int                     ni_count = 0;
2327
2328         /*
2329          * Change to running state before bringing up the LNDs. This
2330          * allows lnet_shutdown_lndnets() to assert that we've passed
2331          * through here.
2332          */
2333         lnet_net_lock(LNET_LOCK_EX);
2334         the_lnet.ln_state = LNET_STATE_RUNNING;
2335         lnet_net_unlock(LNET_LOCK_EX);
2336
2337         while (!list_empty(netlist)) {
2338                 net = list_entry(netlist->next, struct lnet_net, net_list);
2339                 list_del_init(&net->net_list);
2340
2341                 rc = lnet_startup_lndnet(net, NULL);
2342
2343                 if (rc < 0)
2344                         goto failed;
2345
2346                 ni_count += rc;
2347         }
2348
2349         return ni_count;
2350 failed:
2351         lnet_shutdown_lndnets();
2352
2353         return rc;
2354 }
2355
2356 /**
2357  * Initialize LNet library.
2358  *
2359  * Automatically called at module loading time. Caller has to call
2360  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2361  * latter returned 0. It must be called exactly once.
2362  *
2363  * \retval 0 on success
2364  * \retval -ve on failures.
2365  */
2366 int lnet_lib_init(void)
2367 {
2368         int rc;
2369
2370         lnet_assert_wire_constants();
2371
2372         /* refer to global cfs_cpt_table for now */
2373         the_lnet.ln_cpt_table   = cfs_cpt_table;
2374         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2375
2376         LASSERT(the_lnet.ln_cpt_number > 0);
2377         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2378                 /* we are under risk of consuming all lh_cookie */
2379                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2380                        "please change setting of CPT-table and retry\n",
2381                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2382                 return -E2BIG;
2383         }
2384
2385         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2386                 the_lnet.ln_cpt_bits++;
2387
2388         rc = lnet_create_locks();
2389         if (rc != 0) {
2390                 CERROR("Can't create LNet global locks: %d\n", rc);
2391                 return rc;
2392         }
2393
2394         the_lnet.ln_refcount = 0;
2395         LNetInvalidateEQHandle(&the_lnet.ln_rc_eqh);
2396         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2397         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2398         INIT_LIST_HEAD(&the_lnet.ln_rcd_zombie);
2399         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2400         INIT_LIST_HEAD(&the_lnet.ln_rcd_deathrow);
2401
2402         /* The hash table size is the number of bits it takes to express the set
2403          * ln_num_routes, minus 1 (better to under estimate than over so we
2404          * don't waste memory). */
2405         if (rnet_htable_size <= 0)
2406                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2407         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2408                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2409         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2410                                            order_base_2(rnet_htable_size) - 1);
2411
2412         /* All LNDs apart from the LOLND are in separate modules.  They
2413          * register themselves when their module loads, and unregister
2414          * themselves when their module is unloaded. */
2415         lnet_register_lnd(&the_lolnd);
2416         return 0;
2417 }
2418
2419 /**
2420  * Finalize LNet library.
2421  *
2422  * \pre lnet_lib_init() called with success.
2423  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2424  */
2425 void lnet_lib_exit(void)
2426 {
2427         LASSERT(the_lnet.ln_refcount == 0);
2428
2429         while (!list_empty(&the_lnet.ln_lnds))
2430                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2431                                                struct lnet_lnd, lnd_list));
2432         lnet_destroy_locks();
2433 }
2434
2435 /**
2436  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2437  *
2438  * Users must call this function at least once before any other functions.
2439  * For each successful call there must be a corresponding call to
2440  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2441  * ignored.
2442  *
2443  * The PID used by LNet may be different from the one requested.
2444  * See LNetGetId().
2445  *
2446  * \param requested_pid PID requested by the caller.
2447  *
2448  * \return >= 0 on success, and < 0 error code on failures.
2449  */
2450 int
2451 LNetNIInit(lnet_pid_t requested_pid)
2452 {
2453         int                     im_a_router = 0;
2454         int                     rc;
2455         int                     ni_count;
2456         struct lnet_ping_buffer *pbuf;
2457         struct lnet_handle_md   ping_mdh;
2458         struct list_head        net_head;
2459         struct lnet_net         *net;
2460
2461         INIT_LIST_HEAD(&net_head);
2462
2463         mutex_lock(&the_lnet.ln_api_mutex);
2464
2465         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2466
2467         if (the_lnet.ln_refcount > 0) {
2468                 rc = the_lnet.ln_refcount++;
2469                 mutex_unlock(&the_lnet.ln_api_mutex);
2470                 return rc;
2471         }
2472
2473         rc = lnet_prepare(requested_pid);
2474         if (rc != 0) {
2475                 mutex_unlock(&the_lnet.ln_api_mutex);
2476                 return rc;
2477         }
2478
2479         /* create a network for Loopback network */
2480         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2481         if (net == NULL) {
2482                 rc = -ENOMEM;
2483                 goto err_empty_list;
2484         }
2485
2486         /* Add in the loopback NI */
2487         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2488                 rc = -ENOMEM;
2489                 goto err_empty_list;
2490         }
2491
2492         /* If LNet is being initialized via DLC it is possible
2493          * that the user requests not to load module parameters (ones which
2494          * are supported by DLC) on initialization.  Therefore, make sure not
2495          * to load networks, routes and forwarding from module parameters
2496          * in this case.  On cleanup in case of failure only clean up
2497          * routes if it has been loaded */
2498         if (!the_lnet.ln_nis_from_mod_params) {
2499                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2500                                          use_tcp_bonding);
2501                 if (rc < 0)
2502                         goto err_empty_list;
2503         }
2504
2505         ni_count = lnet_startup_lndnets(&net_head);
2506         if (ni_count < 0) {
2507                 rc = ni_count;
2508                 goto err_empty_list;
2509         }
2510
2511         if (!the_lnet.ln_nis_from_mod_params) {
2512                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2513                 if (rc != 0)
2514                         goto err_shutdown_lndnis;
2515
2516                 rc = lnet_check_routes();
2517                 if (rc != 0)
2518                         goto err_destroy_routes;
2519
2520                 rc = lnet_rtrpools_alloc(im_a_router);
2521                 if (rc != 0)
2522                         goto err_destroy_routes;
2523         }
2524
2525         rc = lnet_acceptor_start();
2526         if (rc != 0)
2527                 goto err_destroy_routes;
2528
2529         the_lnet.ln_refcount = 1;
2530         /* Now I may use my own API functions... */
2531
2532         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2533         if (rc != 0)
2534                 goto err_acceptor_stop;
2535
2536         lnet_ping_target_update(pbuf, ping_mdh);
2537
2538         rc = lnet_monitor_thr_start();
2539         if (rc != 0)
2540                 goto err_stop_ping;
2541
2542         rc = lnet_push_target_init();
2543         if (rc != 0)
2544                 goto err_stop_monitor_thr;
2545
2546         rc = lnet_peer_discovery_start();
2547         if (rc != 0)
2548                 goto err_destroy_push_target;
2549
2550         lnet_fault_init();
2551         lnet_router_debugfs_init();
2552
2553         mutex_unlock(&the_lnet.ln_api_mutex);
2554
2555         return 0;
2556
2557 err_destroy_push_target:
2558         lnet_push_target_fini();
2559 err_stop_monitor_thr:
2560         lnet_monitor_thr_stop();
2561 err_stop_ping:
2562         lnet_ping_target_fini();
2563 err_acceptor_stop:
2564         the_lnet.ln_refcount = 0;
2565         lnet_acceptor_stop();
2566 err_destroy_routes:
2567         if (!the_lnet.ln_nis_from_mod_params)
2568                 lnet_destroy_routes();
2569 err_shutdown_lndnis:
2570         lnet_shutdown_lndnets();
2571 err_empty_list:
2572         lnet_unprepare();
2573         LASSERT(rc < 0);
2574         mutex_unlock(&the_lnet.ln_api_mutex);
2575         while (!list_empty(&net_head)) {
2576                 struct lnet_net *net;
2577
2578                 net = list_entry(net_head.next, struct lnet_net, net_list);
2579                 list_del_init(&net->net_list);
2580                 lnet_net_free(net);
2581         }
2582         return rc;
2583 }
2584 EXPORT_SYMBOL(LNetNIInit);
2585
2586 /**
2587  * Stop LNet interfaces, routing, and forwarding.
2588  *
2589  * Users must call this function once for each successful call to LNetNIInit().
2590  * Once the LNetNIFini() operation has been started, the results of pending
2591  * API operations are undefined.
2592  *
2593  * \return always 0 for current implementation.
2594  */
2595 int
2596 LNetNIFini()
2597 {
2598         mutex_lock(&the_lnet.ln_api_mutex);
2599
2600         LASSERT(the_lnet.ln_refcount > 0);
2601
2602         if (the_lnet.ln_refcount != 1) {
2603                 the_lnet.ln_refcount--;
2604         } else {
2605                 LASSERT(!the_lnet.ln_niinit_self);
2606
2607                 lnet_fault_fini();
2608
2609                 lnet_router_debugfs_init();
2610                 lnet_peer_discovery_stop();
2611                 lnet_push_target_fini();
2612                 lnet_monitor_thr_stop();
2613                 lnet_ping_target_fini();
2614
2615                 /* Teardown fns that use my own API functions BEFORE here */
2616                 the_lnet.ln_refcount = 0;
2617
2618                 lnet_acceptor_stop();
2619                 lnet_destroy_routes();
2620                 lnet_shutdown_lndnets();
2621                 lnet_unprepare();
2622         }
2623
2624         mutex_unlock(&the_lnet.ln_api_mutex);
2625         return 0;
2626 }
2627 EXPORT_SYMBOL(LNetNIFini);
2628
2629 /**
2630  * Grabs the ni data from the ni structure and fills the out
2631  * parameters
2632  *
2633  * \param[in] ni network        interface structure
2634  * \param[out] cfg_ni           NI config information
2635  * \param[out] tun              network and LND tunables
2636  */
2637 static void
2638 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2639                    struct lnet_ioctl_config_lnd_tunables *tun,
2640                    struct lnet_ioctl_element_stats *stats,
2641                    __u32 tun_size)
2642 {
2643         size_t min_size = 0;
2644         int i;
2645
2646         if (!ni || !cfg_ni || !tun)
2647                 return;
2648
2649         if (ni->ni_interfaces[0] != NULL) {
2650                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2651                         if (ni->ni_interfaces[i] != NULL) {
2652                                 strncpy(cfg_ni->lic_ni_intf[i],
2653                                         ni->ni_interfaces[i],
2654                                         sizeof(cfg_ni->lic_ni_intf[i]));
2655                         }
2656                 }
2657         }
2658
2659         cfg_ni->lic_nid = ni->ni_nid;
2660         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2661                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2662         else
2663                 cfg_ni->lic_status = ni->ni_status->ns_status;
2664         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2665         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2666
2667         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2668
2669         if (stats) {
2670                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2671                                                        LNET_STATS_TYPE_SEND);
2672                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2673                                                        LNET_STATS_TYPE_RECV);
2674                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2675                                                        LNET_STATS_TYPE_DROP);
2676         }
2677
2678         /*
2679          * tun->lt_tun will always be present, but in order to be
2680          * backwards compatible, we need to deal with the cases when
2681          * tun->lt_tun is smaller than what the kernel has, because it
2682          * comes from an older version of a userspace program, then we'll
2683          * need to copy as much information as we have available space.
2684          */
2685         min_size = tun_size - sizeof(tun->lt_cmn);
2686         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2687
2688         /* copy over the cpts */
2689         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2690             ni->ni_cpts == NULL)  {
2691                 for (i = 0; i < ni->ni_ncpts; i++)
2692                         cfg_ni->lic_cpts[i] = i;
2693         } else {
2694                 for (i = 0;
2695                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2696                      i < LNET_MAX_SHOW_NUM_CPT;
2697                      i++)
2698                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2699         }
2700         cfg_ni->lic_ncpts = ni->ni_ncpts;
2701 }
2702
2703 /**
2704  * NOTE: This is a legacy function left in the code to be backwards
2705  * compatible with older userspace programs. It should eventually be
2706  * removed.
2707  *
2708  * Grabs the ni data from the ni structure and fills the out
2709  * parameters
2710  *
2711  * \param[in] ni network        interface structure
2712  * \param[out] config           config information
2713  */
2714 static void
2715 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2716                          struct lnet_ioctl_config_data *config)
2717 {
2718         struct lnet_ioctl_net_config *net_config;
2719         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2720         size_t min_size, tunable_size = 0;
2721         int i;
2722
2723         if (!ni || !config)
2724                 return;
2725
2726         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2727         if (!net_config)
2728                 return;
2729
2730         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2731                      ARRAY_SIZE(net_config->ni_interfaces));
2732
2733         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2734                 if (!ni->ni_interfaces[i])
2735                         break;
2736
2737                 strncpy(net_config->ni_interfaces[i],
2738                         ni->ni_interfaces[i],
2739                         sizeof(net_config->ni_interfaces[i]));
2740         }
2741
2742         config->cfg_nid = ni->ni_nid;
2743         config->cfg_config_u.cfg_net.net_peer_timeout =
2744                 ni->ni_net->net_tunables.lct_peer_timeout;
2745         config->cfg_config_u.cfg_net.net_max_tx_credits =
2746                 ni->ni_net->net_tunables.lct_max_tx_credits;
2747         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2748                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2749         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2750                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2751
2752         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2753                 net_config->ni_status = LNET_NI_STATUS_UP;
2754         else
2755                 net_config->ni_status = ni->ni_status->ns_status;
2756
2757         if (ni->ni_cpts) {
2758                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2759
2760                 for (i = 0; i < num_cpts; i++)
2761                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2762
2763                 config->cfg_ncpts = num_cpts;
2764         }
2765
2766         /*
2767          * See if user land tools sent in a newer and larger version
2768          * of struct lnet_tunables than what the kernel uses.
2769          */
2770         min_size = sizeof(*config) + sizeof(*net_config);
2771
2772         if (config->cfg_hdr.ioc_len > min_size)
2773                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2774
2775         /* Don't copy too much data to user space */
2776         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2777         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2778
2779         if (lnd_cfg && min_size) {
2780                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2781                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2782
2783                 /* Tell user land that kernel side has less data */
2784                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2785                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2786                         config->cfg_hdr.ioc_len -= min_size;
2787                 }
2788         }
2789 }
2790
2791 struct lnet_ni *
2792 lnet_get_ni_idx_locked(int idx)
2793 {
2794         struct lnet_ni          *ni;
2795         struct lnet_net         *net;
2796
2797         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2798                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2799                         if (idx-- == 0)
2800                                 return ni;
2801                 }
2802         }
2803
2804         return NULL;
2805 }
2806
2807 struct lnet_ni *
2808 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2809 {
2810         struct lnet_ni          *ni;
2811         struct lnet_net         *net = mynet;
2812
2813         /*
2814          * It is possible that the net has been cleaned out while there is
2815          * a message being sent. This function accessed the net without
2816          * checking if the list is empty
2817          */
2818         if (prev == NULL) {
2819                 if (net == NULL)
2820                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2821                                         net_list);
2822                 if (list_empty(&net->net_ni_list))
2823                         return NULL;
2824                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2825                                 ni_netlist);
2826
2827                 return ni;
2828         }
2829
2830         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2831                 /* if you reached the end of the ni list and the net is
2832                  * specified, then there are no more nis in that net */
2833                 if (net != NULL)
2834                         return NULL;
2835
2836                 /* we reached the end of this net ni list. move to the
2837                  * next net */
2838                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2839                         /* no more nets and no more NIs. */
2840                         return NULL;
2841
2842                 /* get the next net */
2843                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2844                                  net_list);
2845                 if (list_empty(&net->net_ni_list))
2846                         return NULL;
2847                 /* get the ni on it */
2848                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2849                                 ni_netlist);
2850
2851                 return ni;
2852         }
2853
2854         if (list_empty(&prev->ni_netlist))
2855                 return NULL;
2856
2857         /* there are more nis left */
2858         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
2859
2860         return ni;
2861 }
2862
2863 int
2864 lnet_get_net_config(struct lnet_ioctl_config_data *config)
2865 {
2866         struct lnet_ni *ni;
2867         int cpt;
2868         int rc = -ENOENT;
2869         int idx = config->cfg_count;
2870
2871         cpt = lnet_net_lock_current();
2872
2873         ni = lnet_get_ni_idx_locked(idx);
2874
2875         if (ni != NULL) {
2876                 rc = 0;
2877                 lnet_ni_lock(ni);
2878                 lnet_fill_ni_info_legacy(ni, config);
2879                 lnet_ni_unlock(ni);
2880         }
2881
2882         lnet_net_unlock(cpt);
2883         return rc;
2884 }
2885
2886 int
2887 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
2888                    struct lnet_ioctl_config_lnd_tunables *tun,
2889                    struct lnet_ioctl_element_stats *stats,
2890                    __u32 tun_size)
2891 {
2892         struct lnet_ni          *ni;
2893         int                     cpt;
2894         int                     rc = -ENOENT;
2895
2896         if (!cfg_ni || !tun || !stats)
2897                 return -EINVAL;
2898
2899         cpt = lnet_net_lock_current();
2900
2901         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
2902
2903         if (ni) {
2904                 rc = 0;
2905                 lnet_ni_lock(ni);
2906                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
2907                 lnet_ni_unlock(ni);
2908         }
2909
2910         lnet_net_unlock(cpt);
2911         return rc;
2912 }
2913
2914 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
2915 {
2916         struct lnet_ni *ni;
2917         int cpt;
2918         int rc = -ENOENT;
2919
2920         if (!msg_stats)
2921                 return -EINVAL;
2922
2923         cpt = lnet_net_lock_current();
2924
2925         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
2926
2927         if (ni) {
2928                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
2929                 rc = 0;
2930         }
2931
2932         lnet_net_unlock(cpt);
2933
2934         return rc;
2935 }
2936
2937 static int lnet_add_net_common(struct lnet_net *net,
2938                                struct lnet_ioctl_config_lnd_tunables *tun)
2939 {
2940         __u32                   net_id;
2941         struct lnet_ping_buffer *pbuf;
2942         struct lnet_handle_md   ping_mdh;
2943         int                     rc;
2944         struct lnet_remotenet *rnet;
2945         int                     net_ni_count;
2946         int                     num_acceptor_nets;
2947
2948         lnet_net_lock(LNET_LOCK_EX);
2949         rnet = lnet_find_rnet_locked(net->net_id);
2950         lnet_net_unlock(LNET_LOCK_EX);
2951         /*
2952          * make sure that the net added doesn't invalidate the current
2953          * configuration LNet is keeping
2954          */
2955         if (rnet) {
2956                 CERROR("Adding net %s will invalidate routing configuration\n",
2957                        libcfs_net2str(net->net_id));
2958                 lnet_net_free(net);
2959                 return -EUSERS;
2960         }
2961
2962         /*
2963          * make sure you calculate the correct number of slots in the ping
2964          * buffer. Since the ping info is a flattened list of all the NIs,
2965          * we should allocate enough slots to accomodate the number of NIs
2966          * which will be added.
2967          *
2968          * since ni hasn't been configured yet, use
2969          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
2970          */
2971         net_ni_count = lnet_get_net_ni_count_pre(net);
2972
2973         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
2974                                     net_ni_count + lnet_get_ni_count(),
2975                                     false);
2976         if (rc < 0) {
2977                 lnet_net_free(net);
2978                 return rc;
2979         }
2980
2981         if (tun)
2982                 memcpy(&net->net_tunables,
2983                        &tun->lt_cmn, sizeof(net->net_tunables));
2984         else
2985                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
2986
2987         /*
2988          * before starting this network get a count of the current TCP
2989          * networks which require the acceptor thread running. If that
2990          * count is == 0 before we start up this network, then we'd want to
2991          * start up the acceptor thread after starting up this network
2992          */
2993         num_acceptor_nets = lnet_count_acceptor_nets();
2994
2995         net_id = net->net_id;
2996
2997         rc = lnet_startup_lndnet(net,
2998                                  (tun) ? &tun->lt_tun : NULL);
2999         if (rc < 0)
3000                 goto failed;
3001
3002         lnet_net_lock(LNET_LOCK_EX);
3003         net = lnet_get_net_locked(net_id);
3004         lnet_net_unlock(LNET_LOCK_EX);
3005
3006         LASSERT(net);
3007
3008         /*
3009          * Start the acceptor thread if this is the first network
3010          * being added that requires the thread.
3011          */
3012         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
3013                 rc = lnet_acceptor_start();
3014                 if (rc < 0) {
3015                         /* shutdown the net that we just started */
3016                         CERROR("Failed to start up acceptor thread\n");
3017                         lnet_shutdown_lndnet(net);
3018                         goto failed;
3019                 }
3020         }
3021
3022         lnet_net_lock(LNET_LOCK_EX);
3023         lnet_peer_net_added(net);
3024         lnet_net_unlock(LNET_LOCK_EX);
3025
3026         lnet_ping_target_update(pbuf, ping_mdh);
3027
3028         return 0;
3029
3030 failed:
3031         lnet_ping_md_unlink(pbuf, &ping_mdh);
3032         lnet_ping_buffer_decref(pbuf);
3033         return rc;
3034 }
3035
3036 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3037                                       struct lnet_ioctl_config_lnd_tunables *tun)
3038 {
3039         struct lnet_net *net;
3040         char *nets;
3041         int rc;
3042         struct list_head net_head;
3043
3044         INIT_LIST_HEAD(&net_head);
3045
3046         rc = lnet_parse_ip2nets(&nets, ip2nets);
3047         if (rc < 0)
3048                 return rc;
3049
3050         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3051         if (rc < 0)
3052                 return rc;
3053
3054         mutex_lock(&the_lnet.ln_api_mutex);
3055         while (!list_empty(&net_head)) {
3056                 net = list_entry(net_head.next, struct lnet_net, net_list);
3057                 list_del_init(&net->net_list);
3058                 rc = lnet_add_net_common(net, tun);
3059                 if (rc < 0)
3060                         goto out;
3061         }
3062
3063 out:
3064         mutex_unlock(&the_lnet.ln_api_mutex);
3065
3066         while (!list_empty(&net_head)) {
3067                 net = list_entry(net_head.next, struct lnet_net, net_list);
3068                 list_del_init(&net->net_list);
3069                 lnet_net_free(net);
3070         }
3071         return rc;
3072 }
3073
3074 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3075 {
3076         struct lnet_net *net;
3077         struct lnet_ni *ni;
3078         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3079         int rc, i;
3080         __u32 net_id, lnd_type;
3081
3082         /* get the tunables if they are available */
3083         if (conf->lic_cfg_hdr.ioc_len >=
3084             sizeof(*conf) + sizeof(*tun))
3085                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3086                         conf->lic_bulk;
3087
3088         /* handle legacy ip2nets from DLC */
3089         if (conf->lic_legacy_ip2nets[0] != '\0')
3090                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3091                                                   tun);
3092
3093         net_id = LNET_NIDNET(conf->lic_nid);
3094         lnd_type = LNET_NETTYP(net_id);
3095
3096         if (!libcfs_isknown_lnd(lnd_type)) {
3097                 CERROR("No valid net and lnd information provided\n");
3098                 return -EINVAL;
3099         }
3100
3101         net = lnet_net_alloc(net_id, NULL);
3102         if (!net)
3103                 return -ENOMEM;
3104
3105         for (i = 0; i < conf->lic_ncpts; i++) {
3106                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3107                         return -EINVAL;
3108         }
3109
3110         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3111                                        conf->lic_ni_intf[0]);
3112         if (!ni)
3113                 return -ENOMEM;
3114
3115         mutex_lock(&the_lnet.ln_api_mutex);
3116
3117         rc = lnet_add_net_common(net, tun);
3118
3119         mutex_unlock(&the_lnet.ln_api_mutex);
3120
3121         return rc;
3122 }
3123
3124 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3125 {
3126         struct lnet_net  *net;
3127         struct lnet_ni *ni;
3128         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3129         struct lnet_ping_buffer *pbuf;
3130         struct lnet_handle_md  ping_mdh;
3131         int               rc;
3132         int               net_count;
3133         __u32             addr;
3134
3135         /* don't allow userspace to shutdown the LOLND */
3136         if (LNET_NETTYP(net_id) == LOLND)
3137                 return -EINVAL;
3138
3139         mutex_lock(&the_lnet.ln_api_mutex);
3140
3141         lnet_net_lock(0);
3142
3143         net = lnet_get_net_locked(net_id);
3144         if (!net) {
3145                 CERROR("net %s not found\n",
3146                        libcfs_net2str(net_id));
3147                 rc = -ENOENT;
3148                 goto unlock_net;
3149         }
3150
3151         addr = LNET_NIDADDR(conf->lic_nid);
3152         if (addr == 0) {
3153                 /* remove the entire net */
3154                 net_count = lnet_get_net_ni_count_locked(net);
3155
3156                 lnet_net_unlock(0);
3157
3158                 /* create and link a new ping info, before removing the old one */
3159                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3160                                         lnet_get_ni_count() - net_count,
3161                                         false);
3162                 if (rc != 0)
3163                         goto unlock_api_mutex;
3164
3165                 lnet_shutdown_lndnet(net);
3166
3167                 if (lnet_count_acceptor_nets() == 0)
3168                         lnet_acceptor_stop();
3169
3170                 lnet_ping_target_update(pbuf, ping_mdh);
3171
3172                 goto unlock_api_mutex;
3173         }
3174
3175         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3176         if (!ni) {
3177                 CERROR("nid %s not found\n",
3178                        libcfs_nid2str(conf->lic_nid));
3179                 rc = -ENOENT;
3180                 goto unlock_net;
3181         }
3182
3183         net_count = lnet_get_net_ni_count_locked(net);
3184
3185         lnet_net_unlock(0);
3186
3187         /* create and link a new ping info, before removing the old one */
3188         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3189                                   lnet_get_ni_count() - 1, false);
3190         if (rc != 0)
3191                 goto unlock_api_mutex;
3192
3193         lnet_shutdown_lndni(ni);
3194
3195         if (lnet_count_acceptor_nets() == 0)
3196                 lnet_acceptor_stop();
3197
3198         lnet_ping_target_update(pbuf, ping_mdh);
3199
3200         /* check if the net is empty and remove it if it is */
3201         if (net_count == 1)
3202                 lnet_shutdown_lndnet(net);
3203
3204         goto unlock_api_mutex;
3205
3206 unlock_net:
3207         lnet_net_unlock(0);
3208 unlock_api_mutex:
3209         mutex_unlock(&the_lnet.ln_api_mutex);
3210
3211         return rc;
3212 }
3213
3214 /*
3215  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3216  * They are only expected to be called for unique networks.
3217  * That can be as a result of older DLC library
3218  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3219  */
3220 int
3221 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3222 {
3223         struct lnet_net         *net;
3224         struct list_head        net_head;
3225         int                     rc;
3226         struct lnet_ioctl_config_lnd_tunables tun;
3227         char *nets = conf->cfg_config_u.cfg_net.net_intf;
3228
3229         INIT_LIST_HEAD(&net_head);
3230
3231         /* Create a net/ni structures for the network string */
3232         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3233         if (rc <= 0)
3234                 return rc == 0 ? -EINVAL : rc;
3235
3236         mutex_lock(&the_lnet.ln_api_mutex);
3237
3238         if (rc > 1) {
3239                 rc = -EINVAL; /* only add one network per call */
3240                 goto out_unlock_clean;
3241         }
3242
3243         net = list_entry(net_head.next, struct lnet_net, net_list);
3244         list_del_init(&net->net_list);
3245
3246         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3247
3248         memset(&tun, 0, sizeof(tun));
3249
3250         tun.lt_cmn.lct_peer_timeout =
3251           conf->cfg_config_u.cfg_net.net_peer_timeout;
3252         tun.lt_cmn.lct_peer_tx_credits =
3253           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3254         tun.lt_cmn.lct_peer_rtr_credits =
3255           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3256         tun.lt_cmn.lct_max_tx_credits =
3257           conf->cfg_config_u.cfg_net.net_max_tx_credits;
3258
3259         rc = lnet_add_net_common(net, &tun);
3260
3261 out_unlock_clean:
3262         mutex_unlock(&the_lnet.ln_api_mutex);
3263         while (!list_empty(&net_head)) {
3264                 /* net_head list is empty in success case */
3265                 net = list_entry(net_head.next, struct lnet_net, net_list);
3266                 list_del_init(&net->net_list);
3267                 lnet_net_free(net);
3268         }
3269         return rc;
3270 }
3271
3272 int
3273 lnet_dyn_del_net(__u32 net_id)
3274 {
3275         struct lnet_net  *net;
3276         struct lnet_ping_buffer *pbuf;
3277         struct lnet_handle_md ping_mdh;
3278         int               rc;
3279         int               net_ni_count;
3280
3281         /* don't allow userspace to shutdown the LOLND */
3282         if (LNET_NETTYP(net_id) == LOLND)
3283                 return -EINVAL;
3284
3285         mutex_lock(&the_lnet.ln_api_mutex);
3286
3287         lnet_net_lock(0);
3288
3289         net = lnet_get_net_locked(net_id);
3290         if (net == NULL) {
3291                 lnet_net_unlock(0);
3292                 rc = -EINVAL;
3293                 goto out;
3294         }
3295
3296         net_ni_count = lnet_get_net_ni_count_locked(net);
3297
3298         lnet_net_unlock(0);
3299
3300         /* create and link a new ping info, before removing the old one */
3301         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3302                                     lnet_get_ni_count() - net_ni_count, false);
3303         if (rc != 0)
3304                 goto out;
3305
3306         lnet_shutdown_lndnet(net);
3307
3308         if (lnet_count_acceptor_nets() == 0)
3309                 lnet_acceptor_stop();
3310
3311         lnet_ping_target_update(pbuf, ping_mdh);
3312
3313 out:
3314         mutex_unlock(&the_lnet.ln_api_mutex);
3315
3316         return rc;
3317 }
3318
3319 void lnet_incr_dlc_seq(void)
3320 {
3321         atomic_inc(&lnet_dlc_seq_no);
3322 }
3323
3324 __u32 lnet_get_dlc_seq_locked(void)
3325 {
3326         return atomic_read(&lnet_dlc_seq_no);
3327 }
3328
3329 static void
3330 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3331 {
3332         struct lnet_net *net;
3333         struct lnet_ni *ni;
3334
3335         lnet_net_lock(LNET_LOCK_EX);
3336         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3337                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3338                         if (ni->ni_nid == nid || all) {
3339                                 atomic_set(&ni->ni_healthv, value);
3340                                 if (list_empty(&ni->ni_recovery) &&
3341                                     value < LNET_MAX_HEALTH_VALUE) {
3342                                         CERROR("manually adding local NI %s to recovery\n",
3343                                                libcfs_nid2str(ni->ni_nid));
3344                                         list_add_tail(&ni->ni_recovery,
3345                                                       &the_lnet.ln_mt_localNIRecovq);
3346                                         lnet_ni_addref_locked(ni, 0);
3347                                 }
3348                                 if (!all) {
3349                                         lnet_net_unlock(LNET_LOCK_EX);
3350                                         return;
3351                                 }
3352                         }
3353                 }
3354         }
3355         lnet_net_unlock(LNET_LOCK_EX);
3356 }
3357
3358 static int
3359 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3360 {
3361         int cpt, rc = 0;
3362         struct lnet_ni *ni;
3363         lnet_nid_t nid = stats->hlni_nid;
3364
3365         cpt = lnet_net_lock_current();
3366         ni = lnet_nid2ni_locked(nid, cpt);
3367
3368         if (!ni) {
3369                 rc = -ENOENT;
3370                 goto unlock;
3371         }
3372
3373         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3374         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3375         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3376         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3377         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3378         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3379         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3380
3381 unlock:
3382         lnet_net_unlock(cpt);
3383
3384         return rc;
3385 }
3386
3387 static int
3388 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3389 {
3390         struct lnet_ni *ni;
3391         int i = 0;
3392
3393         lnet_net_lock(LNET_LOCK_EX);
3394         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3395                 list->rlst_nid_array[i] = ni->ni_nid;
3396                 i++;
3397                 if (i >= LNET_MAX_SHOW_NUM_NID)
3398                         break;
3399         }
3400         lnet_net_unlock(LNET_LOCK_EX);
3401         list->rlst_num_nids = i;
3402
3403         return 0;
3404 }
3405
3406 static int
3407 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3408 {
3409         struct lnet_peer_ni *lpni;
3410         int i = 0;
3411
3412         lnet_net_lock(LNET_LOCK_EX);
3413         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3414                 list->rlst_nid_array[i] = lpni->lpni_nid;
3415                 i++;
3416                 if (i >= LNET_MAX_SHOW_NUM_NID)
3417                         break;
3418         }
3419         lnet_net_unlock(LNET_LOCK_EX);
3420         list->rlst_num_nids = i;
3421
3422         return 0;
3423 }
3424
3425 /**
3426  * LNet ioctl handler.
3427  *
3428  */
3429 int
3430 LNetCtl(unsigned int cmd, void *arg)
3431 {
3432         struct libcfs_ioctl_data *data = arg;
3433         struct lnet_ioctl_config_data *config;
3434         struct lnet_process_id    id = {0};
3435         struct lnet_ni           *ni;
3436         int                       rc;
3437
3438         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3439                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3440
3441         switch (cmd) {
3442         case IOC_LIBCFS_GET_NI:
3443                 rc = LNetGetId(data->ioc_count, &id);
3444                 data->ioc_nid = id.nid;
3445                 return rc;
3446
3447         case IOC_LIBCFS_FAIL_NID:
3448                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3449
3450         case IOC_LIBCFS_ADD_ROUTE:
3451                 config = arg;
3452
3453                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3454                         return -EINVAL;
3455
3456                 mutex_lock(&the_lnet.ln_api_mutex);
3457                 rc = lnet_add_route(config->cfg_net,
3458                                     config->cfg_config_u.cfg_route.rtr_hop,
3459                                     config->cfg_nid,
3460                                     config->cfg_config_u.cfg_route.
3461                                         rtr_priority);
3462                 if (rc == 0) {
3463                         rc = lnet_check_routes();
3464                         if (rc != 0)
3465                                 lnet_del_route(config->cfg_net,
3466                                                config->cfg_nid);
3467                 }
3468                 mutex_unlock(&the_lnet.ln_api_mutex);
3469                 return rc;
3470
3471         case IOC_LIBCFS_DEL_ROUTE:
3472                 config = arg;
3473
3474                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3475                         return -EINVAL;
3476
3477                 mutex_lock(&the_lnet.ln_api_mutex);
3478                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3479                 mutex_unlock(&the_lnet.ln_api_mutex);
3480                 return rc;
3481
3482         case IOC_LIBCFS_GET_ROUTE:
3483                 config = arg;
3484
3485                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3486                         return -EINVAL;
3487
3488                 mutex_lock(&the_lnet.ln_api_mutex);
3489                 rc = lnet_get_route(config->cfg_count,
3490                                     &config->cfg_net,
3491                                     &config->cfg_config_u.cfg_route.rtr_hop,
3492                                     &config->cfg_nid,
3493                                     &config->cfg_config_u.cfg_route.rtr_flags,
3494                                     &config->cfg_config_u.cfg_route.
3495                                         rtr_priority);
3496                 mutex_unlock(&the_lnet.ln_api_mutex);
3497                 return rc;
3498
3499         case IOC_LIBCFS_GET_LOCAL_NI: {
3500                 struct lnet_ioctl_config_ni *cfg_ni;
3501                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3502                 struct lnet_ioctl_element_stats *stats;
3503                 __u32 tun_size;
3504
3505                 cfg_ni = arg;
3506
3507                 /* get the tunables if they are available */
3508                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3509                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3510                         return -EINVAL;
3511
3512                 stats = (struct lnet_ioctl_element_stats *)
3513                         cfg_ni->lic_bulk;
3514                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3515                                 (cfg_ni->lic_bulk + sizeof(*stats));
3516
3517                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3518                         sizeof(*stats);
3519
3520                 mutex_lock(&the_lnet.ln_api_mutex);
3521                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3522                 mutex_unlock(&the_lnet.ln_api_mutex);
3523                 return rc;
3524         }
3525
3526         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3527                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3528
3529                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3530                         return -EINVAL;
3531
3532                 mutex_lock(&the_lnet.ln_api_mutex);
3533                 rc = lnet_get_ni_stats(msg_stats);
3534                 mutex_unlock(&the_lnet.ln_api_mutex);
3535
3536                 return rc;
3537         }
3538
3539         case IOC_LIBCFS_GET_NET: {
3540                 size_t total = sizeof(*config) +
3541                                sizeof(struct lnet_ioctl_net_config);
3542                 config = arg;
3543
3544                 if (config->cfg_hdr.ioc_len < total)
3545                         return -EINVAL;
3546
3547                 mutex_lock(&the_lnet.ln_api_mutex);
3548                 rc = lnet_get_net_config(config);
3549                 mutex_unlock(&the_lnet.ln_api_mutex);
3550                 return rc;
3551         }
3552
3553         case IOC_LIBCFS_GET_LNET_STATS:
3554         {
3555                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3556
3557                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3558                         return -EINVAL;
3559
3560                 mutex_lock(&the_lnet.ln_api_mutex);
3561                 lnet_counters_get(&lnet_stats->st_cntrs);
3562                 mutex_unlock(&the_lnet.ln_api_mutex);
3563                 return 0;
3564         }
3565
3566         case IOC_LIBCFS_CONFIG_RTR:
3567                 config = arg;
3568
3569                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3570                         return -EINVAL;
3571
3572                 mutex_lock(&the_lnet.ln_api_mutex);
3573                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3574                         rc = lnet_rtrpools_enable();
3575                         mutex_unlock(&the_lnet.ln_api_mutex);
3576                         return rc;
3577                 }
3578                 lnet_rtrpools_disable();
3579                 mutex_unlock(&the_lnet.ln_api_mutex);
3580                 return 0;
3581
3582         case IOC_LIBCFS_ADD_BUF:
3583                 config = arg;
3584
3585                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3586                         return -EINVAL;
3587
3588                 mutex_lock(&the_lnet.ln_api_mutex);
3589                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3590                                                 buf_tiny,
3591                                           config->cfg_config_u.cfg_buffers.
3592                                                 buf_small,
3593                                           config->cfg_config_u.cfg_buffers.
3594                                                 buf_large);
3595                 mutex_unlock(&the_lnet.ln_api_mutex);
3596                 return rc;
3597
3598         case IOC_LIBCFS_SET_NUMA_RANGE: {
3599                 struct lnet_ioctl_set_value *numa;
3600                 numa = arg;
3601                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3602                         return -EINVAL;
3603                 lnet_net_lock(LNET_LOCK_EX);
3604                 lnet_numa_range = numa->sv_value;
3605                 lnet_net_unlock(LNET_LOCK_EX);
3606                 return 0;
3607         }
3608
3609         case IOC_LIBCFS_GET_NUMA_RANGE: {
3610                 struct lnet_ioctl_set_value *numa;
3611                 numa = arg;
3612                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3613                         return -EINVAL;
3614                 numa->sv_value = lnet_numa_range;
3615                 return 0;
3616         }
3617
3618         case IOC_LIBCFS_GET_BUF: {
3619                 struct lnet_ioctl_pool_cfg *pool_cfg;
3620                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3621
3622                 config = arg;
3623
3624                 if (config->cfg_hdr.ioc_len < total)
3625                         return -EINVAL;
3626
3627                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3628
3629                 mutex_lock(&the_lnet.ln_api_mutex);
3630                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3631                 mutex_unlock(&the_lnet.ln_api_mutex);
3632                 return rc;
3633         }
3634
3635         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3636                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3637
3638                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3639                         return -EINVAL;
3640
3641                 mutex_lock(&the_lnet.ln_api_mutex);
3642                 rc = lnet_get_local_ni_hstats(stats);
3643                 mutex_unlock(&the_lnet.ln_api_mutex);
3644
3645                 return rc;
3646         }
3647
3648         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3649                 struct lnet_ioctl_recovery_list *list = arg;
3650                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3651                         return -EINVAL;
3652
3653                 mutex_lock(&the_lnet.ln_api_mutex);
3654                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3655                         rc = lnet_get_local_ni_recovery_list(list);
3656                 else
3657                         rc = lnet_get_peer_ni_recovery_list(list);
3658                 mutex_unlock(&the_lnet.ln_api_mutex);
3659                 return rc;
3660         }
3661
3662         case IOC_LIBCFS_ADD_PEER_NI: {
3663                 struct lnet_ioctl_peer_cfg *cfg = arg;
3664
3665                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3666                         return -EINVAL;
3667
3668                 mutex_lock(&the_lnet.ln_api_mutex);
3669                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3670                                       cfg->prcfg_cfg_nid,
3671                                       cfg->prcfg_mr);
3672                 mutex_unlock(&the_lnet.ln_api_mutex);
3673                 return rc;
3674         }
3675
3676         case IOC_LIBCFS_DEL_PEER_NI: {
3677                 struct lnet_ioctl_peer_cfg *cfg = arg;
3678
3679                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3680                         return -EINVAL;
3681
3682                 mutex_lock(&the_lnet.ln_api_mutex);
3683                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3684                                       cfg->prcfg_cfg_nid);
3685                 mutex_unlock(&the_lnet.ln_api_mutex);
3686                 return rc;
3687         }
3688
3689         case IOC_LIBCFS_GET_PEER_INFO: {
3690                 struct lnet_ioctl_peer *peer_info = arg;
3691
3692                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3693                         return -EINVAL;
3694
3695                 mutex_lock(&the_lnet.ln_api_mutex);
3696                 rc = lnet_get_peer_ni_info(
3697                    peer_info->pr_count,
3698                    &peer_info->pr_nid,
3699                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3700                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3701                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3702                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3703                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3704                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3705                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3706                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3707                 mutex_unlock(&the_lnet.ln_api_mutex);
3708                 return rc;
3709         }
3710
3711         case IOC_LIBCFS_GET_PEER_NI: {
3712                 struct lnet_ioctl_peer_cfg *cfg = arg;
3713
3714                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3715                         return -EINVAL;
3716
3717                 mutex_lock(&the_lnet.ln_api_mutex);
3718                 rc = lnet_get_peer_info(cfg,
3719                                         (void __user *)cfg->prcfg_bulk);
3720                 mutex_unlock(&the_lnet.ln_api_mutex);
3721                 return rc;
3722         }
3723
3724         case IOC_LIBCFS_GET_PEER_LIST: {
3725                 struct lnet_ioctl_peer_cfg *cfg = arg;
3726
3727                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3728                         return -EINVAL;
3729
3730                 mutex_lock(&the_lnet.ln_api_mutex);
3731                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3732                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3733                 mutex_unlock(&the_lnet.ln_api_mutex);
3734                 return rc;
3735         }
3736
3737         case IOC_LIBCFS_SET_HEALHV: {
3738                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3739                 int value;
3740                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3741                         return -EINVAL;
3742                 if (cfg->rh_value < 0 ||
3743                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3744                         value = LNET_MAX_HEALTH_VALUE;
3745                 else
3746                         value = cfg->rh_value;
3747                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3748                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3749                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3750                 mutex_lock(&the_lnet.ln_api_mutex);
3751                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3752                         lnet_ni_set_healthv(cfg->rh_nid, value,
3753                                              cfg->rh_all);
3754                 else
3755                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3756                                                   cfg->rh_all);
3757                 mutex_unlock(&the_lnet.ln_api_mutex);
3758                 return 0;
3759         }
3760
3761         case IOC_LIBCFS_NOTIFY_ROUTER: {
3762                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3763
3764                 /* The deadline passed in by the user should be some time in
3765                  * seconds in the future since the UNIX epoch. We have to map
3766                  * that deadline to the wall clock.
3767                  */
3768                 deadline += ktime_get_seconds();
3769                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags,
3770                                    deadline);
3771         }
3772
3773         case IOC_LIBCFS_LNET_DIST:
3774                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3775                 if (rc < 0 && rc != -EHOSTUNREACH)
3776                         return rc;
3777
3778                 data->ioc_u32[0] = rc;
3779                 return 0;
3780
3781         case IOC_LIBCFS_TESTPROTOCOMPAT:
3782                 lnet_net_lock(LNET_LOCK_EX);
3783                 the_lnet.ln_testprotocompat = data->ioc_flags;
3784                 lnet_net_unlock(LNET_LOCK_EX);
3785                 return 0;
3786
3787         case IOC_LIBCFS_LNET_FAULT:
3788                 return lnet_fault_ctl(data->ioc_flags, data);
3789
3790         case IOC_LIBCFS_PING: {
3791                 signed long timeout;
3792
3793                 id.nid = data->ioc_nid;
3794                 id.pid = data->ioc_u32[0];
3795
3796                 /* If timeout is negative then set default of 3 minutes */
3797                 if (((s32)data->ioc_u32[1] <= 0) ||
3798                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3799                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3800                 else
3801                         timeout = msecs_to_jiffies(data->ioc_u32[1]);
3802
3803                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3804                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3805
3806                 if (rc < 0)
3807                         return rc;
3808
3809                 data->ioc_count = rc;
3810                 return 0;
3811         }
3812
3813         case IOC_LIBCFS_PING_PEER: {
3814                 struct lnet_ioctl_ping_data *ping = arg;
3815                 struct lnet_peer *lp;
3816                 signed long timeout;
3817
3818                 /* If timeout is negative then set default of 3 minutes */
3819                 if (((s32)ping->op_param) <= 0 ||
3820                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3821                         timeout = msecs_to_jiffies(DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC);
3822                 else
3823                         timeout = msecs_to_jiffies(ping->op_param);
3824
3825                 rc = lnet_ping(ping->ping_id, timeout,
3826                                ping->ping_buf,
3827                                ping->ping_count);
3828                 if (rc < 0)
3829                         return rc;
3830
3831                 mutex_lock(&the_lnet.ln_api_mutex);
3832                 lp = lnet_find_peer(ping->ping_id.nid);
3833                 if (lp) {
3834                         ping->ping_id.nid = lp->lp_primary_nid;
3835                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3836                         lnet_peer_decref_locked(lp);
3837                 }
3838                 mutex_unlock(&the_lnet.ln_api_mutex);
3839
3840                 ping->ping_count = rc;
3841                 return 0;
3842         }
3843
3844         case IOC_LIBCFS_DISCOVER: {
3845                 struct lnet_ioctl_ping_data *discover = arg;
3846                 struct lnet_peer *lp;
3847
3848                 rc = lnet_discover(discover->ping_id, discover->op_param,
3849                                    discover->ping_buf,
3850                                    discover->ping_count);
3851                 if (rc < 0)
3852                         return rc;
3853
3854                 mutex_lock(&the_lnet.ln_api_mutex);
3855                 lp = lnet_find_peer(discover->ping_id.nid);
3856                 if (lp) {
3857                         discover->ping_id.nid = lp->lp_primary_nid;
3858                         discover->mr_info = lnet_peer_is_multi_rail(lp);
3859                         lnet_peer_decref_locked(lp);
3860                 }
3861                 mutex_unlock(&the_lnet.ln_api_mutex);
3862
3863                 discover->ping_count = rc;
3864                 return 0;
3865         }
3866
3867         default:
3868                 ni = lnet_net2ni_addref(data->ioc_net);
3869                 if (ni == NULL)
3870                         return -EINVAL;
3871
3872                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
3873                         rc = -EINVAL;
3874                 else
3875                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
3876
3877                 lnet_ni_decref(ni);
3878                 return rc;
3879         }
3880         /* not reached */
3881 }
3882 EXPORT_SYMBOL(LNetCtl);
3883
3884 void LNetDebugPeer(struct lnet_process_id id)
3885 {
3886         lnet_debug_peer(id.nid);
3887 }
3888 EXPORT_SYMBOL(LNetDebugPeer);
3889
3890 /**
3891  * Determine if the specified peer \a nid is on the local node.
3892  *
3893  * \param nid   peer nid to check
3894  *
3895  * \retval true         If peer NID is on the local node.
3896  * \retval false        If peer NID is not on the local node.
3897  */
3898 bool LNetIsPeerLocal(lnet_nid_t nid)
3899 {
3900         struct lnet_net *net;
3901         struct lnet_ni *ni;
3902         int cpt;
3903
3904         cpt = lnet_net_lock_current();
3905         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3906                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3907                         if (ni->ni_nid == nid) {
3908                                 lnet_net_unlock(cpt);
3909                                 return true;
3910                         }
3911                 }
3912         }
3913         lnet_net_unlock(cpt);
3914
3915         return false;
3916 }
3917 EXPORT_SYMBOL(LNetIsPeerLocal);
3918
3919 /**
3920  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
3921  * Note that all interfaces share a same PID, as requested by LNetNIInit().
3922  *
3923  * \param index Index of the interface to look up.
3924  * \param id On successful return, this location will hold the
3925  * struct lnet_process_id ID of the interface.
3926  *
3927  * \retval 0 If an interface exists at \a index.
3928  * \retval -ENOENT If no interface has been found.
3929  */
3930 int
3931 LNetGetId(unsigned int index, struct lnet_process_id *id)
3932 {
3933         struct lnet_ni   *ni;
3934         struct lnet_net  *net;
3935         int               cpt;
3936         int               rc = -ENOENT;
3937
3938         LASSERT(the_lnet.ln_refcount > 0);
3939
3940         cpt = lnet_net_lock_current();
3941
3942         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3943                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3944                         if (index-- != 0)
3945                                 continue;
3946
3947                         id->nid = ni->ni_nid;
3948                         id->pid = the_lnet.ln_pid;
3949                         rc = 0;
3950                         break;
3951                 }
3952         }
3953
3954         lnet_net_unlock(cpt);
3955         return rc;
3956 }
3957 EXPORT_SYMBOL(LNetGetId);
3958
3959 static int lnet_ping(struct lnet_process_id id, signed long timeout,
3960                      struct lnet_process_id __user *ids, int n_ids)
3961 {
3962         struct lnet_handle_eq eqh;
3963         struct lnet_handle_md mdh;
3964         struct lnet_event event;
3965         struct lnet_md md = { NULL };
3966         int which;
3967         int unlinked = 0;
3968         int replied = 0;
3969         const signed long a_long_time = msecs_to_jiffies(60 * MSEC_PER_SEC);
3970         struct lnet_ping_buffer *pbuf;
3971         struct lnet_process_id tmpid;
3972         int i;
3973         int nob;
3974         int rc;
3975         int rc2;
3976         sigset_t blocked;
3977
3978         /* n_ids limit is arbitrary */
3979         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
3980                 return -EINVAL;
3981
3982         /*
3983          * if the user buffer has more space than the lnet_interfaces_max
3984          * then only fill it up to lnet_interfaces_max
3985          */
3986         if (n_ids > lnet_interfaces_max)
3987                 n_ids = lnet_interfaces_max;
3988
3989         if (id.pid == LNET_PID_ANY)
3990                 id.pid = LNET_PID_LUSTRE;
3991
3992         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
3993         if (!pbuf)
3994                 return -ENOMEM;
3995
3996         /* NB 2 events max (including any unlink event) */
3997         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
3998         if (rc != 0) {
3999                 CERROR("Can't allocate EQ: %d\n", rc);
4000                 goto fail_ping_buffer_decref;
4001         }
4002
4003         /* initialize md content */
4004         md.start     = &pbuf->pb_info;
4005         md.length    = LNET_PING_INFO_SIZE(n_ids);
4006         md.threshold = 2; /* GET/REPLY */
4007         md.max_size  = 0;
4008         md.options   = LNET_MD_TRUNCATE;
4009         md.user_ptr  = NULL;
4010         md.eq_handle = eqh;
4011
4012         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
4013         if (rc != 0) {
4014                 CERROR("Can't bind MD: %d\n", rc);
4015                 goto fail_free_eq;
4016         }
4017
4018         rc = LNetGet(LNET_NID_ANY, mdh, id,
4019                      LNET_RESERVED_PORTAL,
4020                      LNET_PROTO_PING_MATCHBITS, 0, false);
4021
4022         if (rc != 0) {
4023                 /* Don't CERROR; this could be deliberate! */
4024                 rc2 = LNetMDUnlink(mdh);
4025                 LASSERT(rc2 == 0);
4026
4027                 /* NB must wait for the UNLINK event below... */
4028                 unlinked = 1;
4029                 timeout = a_long_time;
4030         }
4031
4032         do {
4033                 /* MUST block for unlink to complete */
4034                 if (unlinked)
4035                         blocked = cfs_block_allsigs();
4036
4037                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
4038
4039                 if (unlinked)
4040                         cfs_restore_sigs(blocked);
4041
4042                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
4043                        (rc2 <= 0) ? -1 : event.type,
4044                        (rc2 <= 0) ? -1 : event.status,
4045                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
4046
4047                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
4048
4049                 if (rc2 <= 0 || event.status != 0) {
4050                         /* timeout or error */
4051                         if (!replied && rc == 0)
4052                                 rc = (rc2 < 0) ? rc2 :
4053                                      (rc2 == 0) ? -ETIMEDOUT :
4054                                      event.status;
4055
4056                         if (!unlinked) {
4057                                 /* Ensure completion in finite time... */
4058                                 LNetMDUnlink(mdh);
4059                                 /* No assertion (racing with network) */
4060                                 unlinked = 1;
4061                                 timeout = a_long_time;
4062                         } else if (rc2 == 0) {
4063                                 /* timed out waiting for unlink */
4064                                 CWARN("ping %s: late network completion\n",
4065                                       libcfs_id2str(id));
4066                         }
4067                 } else if (event.type == LNET_EVENT_REPLY) {
4068                         replied = 1;
4069                         rc = event.mlength;
4070                 }
4071         } while (rc2 <= 0 || !event.unlinked);
4072
4073         if (!replied) {
4074                 if (rc >= 0)
4075                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
4076                               libcfs_id2str(id));
4077                 rc = -EIO;
4078                 goto fail_free_eq;
4079         }
4080
4081         nob = rc;
4082         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4083
4084         rc = -EPROTO;           /* if I can't parse... */
4085
4086         if (nob < 8) {
4087                 CERROR("%s: ping info too short %d\n",
4088                        libcfs_id2str(id), nob);
4089                 goto fail_free_eq;
4090         }
4091
4092         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4093                 lnet_swap_pinginfo(pbuf);
4094         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4095                 CERROR("%s: Unexpected magic %08x\n",
4096                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4097                 goto fail_free_eq;
4098         }
4099
4100         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4101                 CERROR("%s: ping w/o NI status: 0x%x\n",
4102                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4103                 goto fail_free_eq;
4104         }
4105
4106         if (nob < LNET_PING_INFO_SIZE(0)) {
4107                 CERROR("%s: Short reply %d(%d min)\n",
4108                        libcfs_id2str(id),
4109                        nob, (int)LNET_PING_INFO_SIZE(0));
4110                 goto fail_free_eq;
4111         }
4112
4113         if (pbuf->pb_info.pi_nnis < n_ids)
4114                 n_ids = pbuf->pb_info.pi_nnis;
4115
4116         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4117                 CERROR("%s: Short reply %d(%d expected)\n",
4118                        libcfs_id2str(id),
4119                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4120                 goto fail_free_eq;
4121         }
4122
4123         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4124
4125         memset(&tmpid, 0, sizeof(tmpid));
4126         for (i = 0; i < n_ids; i++) {
4127                 tmpid.pid = pbuf->pb_info.pi_pid;
4128                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4129                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4130                         goto fail_free_eq;
4131         }
4132         rc = pbuf->pb_info.pi_nnis;
4133
4134  fail_free_eq:
4135         rc2 = LNetEQFree(eqh);
4136         if (rc2 != 0)
4137                 CERROR("rc2 %d\n", rc2);
4138         LASSERT(rc2 == 0);
4139
4140  fail_ping_buffer_decref:
4141         lnet_ping_buffer_decref(pbuf);
4142         return rc;
4143 }
4144
4145 static int
4146 lnet_discover(struct lnet_process_id id, __u32 force,
4147               struct lnet_process_id __user *ids, int n_ids)
4148 {
4149         struct lnet_peer_ni *lpni;
4150         struct lnet_peer_ni *p;
4151         struct lnet_peer *lp;
4152         struct lnet_process_id *buf;
4153         int cpt;
4154         int i;
4155         int rc;
4156         int max_intf = lnet_interfaces_max;
4157         size_t buf_size;
4158
4159         if (n_ids <= 0 ||
4160             id.nid == LNET_NID_ANY)
4161                 return -EINVAL;
4162
4163         if (id.pid == LNET_PID_ANY)
4164                 id.pid = LNET_PID_LUSTRE;
4165
4166         /*
4167          * if the user buffer has more space than the max_intf
4168          * then only fill it up to max_intf
4169          */
4170         if (n_ids > max_intf)
4171                 n_ids = max_intf;
4172
4173         buf_size = n_ids * sizeof(*buf);
4174
4175         LIBCFS_ALLOC(buf, buf_size);
4176         if (!buf)
4177                 return -ENOMEM;
4178
4179         cpt = lnet_net_lock_current();
4180         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4181         if (IS_ERR(lpni)) {
4182                 rc = PTR_ERR(lpni);
4183                 goto out;
4184         }
4185
4186         /*
4187          * Clearing the NIDS_UPTODATE flag ensures the peer will
4188          * be discovered, provided discovery has not been disabled.
4189          */
4190         lp = lpni->lpni_peer_net->lpn_peer;
4191         spin_lock(&lp->lp_lock);
4192         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4193         /* If the force flag is set, force a PING and PUSH as well. */
4194         if (force)
4195                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4196         spin_unlock(&lp->lp_lock);
4197         rc = lnet_discover_peer_locked(lpni, cpt, true);
4198         if (rc)
4199                 goto out_decref;
4200
4201         /* Peer may have changed. */
4202         lp = lpni->lpni_peer_net->lpn_peer;
4203         if (lp->lp_nnis < n_ids)
4204                 n_ids = lp->lp_nnis;
4205
4206         i = 0;
4207         p = NULL;
4208         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4209                 buf[i].pid = id.pid;
4210                 buf[i].nid = p->lpni_nid;
4211                 if (++i >= n_ids)
4212                         break;
4213         }
4214
4215         lnet_net_unlock(cpt);
4216
4217         rc = -EFAULT;
4218         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
4219                 goto out_relock;
4220         rc = n_ids;
4221 out_relock:
4222         lnet_net_lock(cpt);
4223 out_decref:
4224         lnet_peer_ni_decref_locked(lpni);
4225 out:
4226         lnet_net_unlock(cpt);
4227
4228         LIBCFS_FREE(buf, buf_size);
4229
4230         return rc;
4231 }
4232
4233 /**
4234  * Retrieve peer discovery status.
4235  *
4236  * \retval 1 if lnet_peer_discovery_disabled is 0
4237  * \retval 0 if lnet_peer_discovery_disabled is 1
4238  */
4239 int
4240 LNetGetPeerDiscoveryStatus(void)
4241 {
4242         return !lnet_peer_discovery_disabled;
4243 }
4244 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);