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