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