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