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