Whamcloud - gitweb
LU-9121 lnet: select best peer and local net
[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_LIST_HEAD(&the_lnet.ln_udsp_list);
1232         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1233         the_lnet.ln_mt_handler = NULL;
1234         init_completion(&the_lnet.ln_started);
1235
1236         rc = lnet_slab_setup();
1237         if (rc != 0)
1238                 goto failed;
1239
1240         rc = lnet_create_remote_nets_table();
1241         if (rc != 0)
1242                 goto failed;
1243
1244         /*
1245          * NB the interface cookie in wire handles guards against delayed
1246          * replies and ACKs appearing valid after reboot.
1247          */
1248         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1249
1250         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1251                                                 sizeof(struct lnet_counters));
1252         if (the_lnet.ln_counters == NULL) {
1253                 CERROR("Failed to allocate counters for LNet\n");
1254                 rc = -ENOMEM;
1255                 goto failed;
1256         }
1257
1258         rc = lnet_peer_tables_create();
1259         if (rc != 0)
1260                 goto failed;
1261
1262         rc = lnet_msg_containers_create();
1263         if (rc != 0)
1264                 goto failed;
1265
1266         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1267                                       LNET_COOKIE_TYPE_EQ);
1268         if (rc != 0)
1269                 goto failed;
1270
1271         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1272         if (recs == NULL) {
1273                 rc = -ENOMEM;
1274                 goto failed;
1275         }
1276
1277         the_lnet.ln_md_containers = recs;
1278
1279         rc = lnet_portals_create();
1280         if (rc != 0) {
1281                 CERROR("Failed to create portals for LNet: %d\n", rc);
1282                 goto failed;
1283         }
1284
1285         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1286         if (!the_lnet.ln_mt_zombie_rstqs) {
1287                 rc = -ENOMEM;
1288                 goto failed;
1289         }
1290
1291         return 0;
1292
1293  failed:
1294         lnet_unprepare();
1295         return rc;
1296 }
1297
1298 static int
1299 lnet_unprepare (void)
1300 {
1301         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1302          * have shut down already, so it is safe to unlink and free all
1303          * descriptors, even those that appear committed to a network op (eg MD
1304          * with non-zero pending count) */
1305
1306         lnet_fail_nid(LNET_NID_ANY, 0);
1307
1308         LASSERT(the_lnet.ln_refcount == 0);
1309         LASSERT(list_empty(&the_lnet.ln_test_peers));
1310         LASSERT(list_empty(&the_lnet.ln_nets));
1311
1312         if (the_lnet.ln_mt_zombie_rstqs) {
1313                 lnet_clean_zombie_rstqs();
1314                 the_lnet.ln_mt_zombie_rstqs = NULL;
1315         }
1316
1317         lnet_assert_handler_unused(the_lnet.ln_mt_handler);
1318         the_lnet.ln_mt_handler = NULL;
1319
1320         lnet_portals_destroy();
1321
1322         if (the_lnet.ln_md_containers != NULL) {
1323                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1324                 the_lnet.ln_md_containers = NULL;
1325         }
1326
1327         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1328
1329         lnet_msg_containers_destroy();
1330         lnet_peer_uninit();
1331         lnet_rtrpools_free(0);
1332
1333         if (the_lnet.ln_counters != NULL) {
1334                 cfs_percpt_free(the_lnet.ln_counters);
1335                 the_lnet.ln_counters = NULL;
1336         }
1337         lnet_destroy_remote_nets_table();
1338         lnet_slab_cleanup();
1339
1340         return 0;
1341 }
1342
1343 struct lnet_ni  *
1344 lnet_net2ni_locked(__u32 net_id, int cpt)
1345 {
1346         struct lnet_ni   *ni;
1347         struct lnet_net  *net;
1348
1349         LASSERT(cpt != LNET_LOCK_EX);
1350
1351         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1352                 if (net->net_id == net_id) {
1353                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1354                                         ni_netlist);
1355                         return ni;
1356                 }
1357         }
1358
1359         return NULL;
1360 }
1361
1362 struct lnet_ni *
1363 lnet_net2ni_addref(__u32 net)
1364 {
1365         struct lnet_ni *ni;
1366
1367         lnet_net_lock(0);
1368         ni = lnet_net2ni_locked(net, 0);
1369         if (ni)
1370                 lnet_ni_addref_locked(ni, 0);
1371         lnet_net_unlock(0);
1372
1373         return ni;
1374 }
1375 EXPORT_SYMBOL(lnet_net2ni_addref);
1376
1377 struct lnet_net *
1378 lnet_get_net_locked(__u32 net_id)
1379 {
1380         struct lnet_net  *net;
1381
1382         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1383                 if (net->net_id == net_id)
1384                         return net;
1385         }
1386
1387         return NULL;
1388 }
1389
1390 unsigned int
1391 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1392 {
1393         __u64           key = nid;
1394         unsigned int    val;
1395
1396         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1397
1398         if (number == 1)
1399                 return 0;
1400
1401         val = hash_long(key, LNET_CPT_BITS);
1402         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1403         if (val < number)
1404                 return val;
1405
1406         return (unsigned int)(key + val + (val >> 1)) % number;
1407 }
1408
1409 int
1410 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1411 {
1412         struct lnet_net *net;
1413
1414         /* must called with hold of lnet_net_lock */
1415         if (LNET_CPT_NUMBER == 1)
1416                 return 0; /* the only one */
1417
1418         /*
1419          * If NI is provided then use the CPT identified in the NI cpt
1420          * list if one exists. If one doesn't exist, then that NI is
1421          * associated with all CPTs and it follows that the net it belongs
1422          * to is implicitly associated with all CPTs, so just hash the nid
1423          * and return that.
1424          */
1425         if (ni != NULL) {
1426                 if (ni->ni_cpts != NULL)
1427                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1428                                                              ni->ni_ncpts)];
1429                 else
1430                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1431         }
1432
1433         /* no NI provided so look at the net */
1434         net = lnet_get_net_locked(LNET_NIDNET(nid));
1435
1436         if (net != NULL && net->net_cpts != NULL) {
1437                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1438         }
1439
1440         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1441 }
1442
1443 int
1444 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1445 {
1446         int     cpt;
1447         int     cpt2;
1448
1449         if (LNET_CPT_NUMBER == 1)
1450                 return 0; /* the only one */
1451
1452         cpt = lnet_net_lock_current();
1453
1454         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1455
1456         lnet_net_unlock(cpt);
1457
1458         return cpt2;
1459 }
1460 EXPORT_SYMBOL(lnet_cpt_of_nid);
1461
1462 int
1463 lnet_islocalnet_locked(__u32 net_id)
1464 {
1465         struct lnet_net *net;
1466         bool local;
1467
1468         net = lnet_get_net_locked(net_id);
1469
1470         local = net != NULL;
1471
1472         return local;
1473 }
1474
1475 int
1476 lnet_islocalnet(__u32 net_id)
1477 {
1478         int cpt;
1479         bool local;
1480
1481         cpt = lnet_net_lock_current();
1482
1483         local = lnet_islocalnet_locked(net_id);
1484
1485         lnet_net_unlock(cpt);
1486
1487         return local;
1488 }
1489
1490 struct lnet_ni  *
1491 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1492 {
1493         struct lnet_net  *net;
1494         struct lnet_ni   *ni;
1495
1496         LASSERT(cpt != LNET_LOCK_EX);
1497
1498         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1499                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1500                         if (ni->ni_nid == nid)
1501                                 return ni;
1502                 }
1503         }
1504
1505         return NULL;
1506 }
1507
1508 struct lnet_ni *
1509 lnet_nid2ni_addref(lnet_nid_t nid)
1510 {
1511         struct lnet_ni *ni;
1512
1513         lnet_net_lock(0);
1514         ni = lnet_nid2ni_locked(nid, 0);
1515         if (ni)
1516                 lnet_ni_addref_locked(ni, 0);
1517         lnet_net_unlock(0);
1518
1519         return ni;
1520 }
1521 EXPORT_SYMBOL(lnet_nid2ni_addref);
1522
1523 int
1524 lnet_islocalnid(lnet_nid_t nid)
1525 {
1526         struct lnet_ni  *ni;
1527         int             cpt;
1528
1529         cpt = lnet_net_lock_current();
1530         ni = lnet_nid2ni_locked(nid, cpt);
1531         lnet_net_unlock(cpt);
1532
1533         return ni != NULL;
1534 }
1535
1536 int
1537 lnet_count_acceptor_nets(void)
1538 {
1539         /* Return the # of NIs that need the acceptor. */
1540         int              count = 0;
1541         struct lnet_net  *net;
1542         int              cpt;
1543
1544         cpt = lnet_net_lock_current();
1545         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1546                 /* all socklnd type networks should have the acceptor
1547                  * thread started */
1548                 if (net->net_lnd->lnd_accept != NULL)
1549                         count++;
1550         }
1551
1552         lnet_net_unlock(cpt);
1553
1554         return count;
1555 }
1556
1557 struct lnet_ping_buffer *
1558 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1559 {
1560         struct lnet_ping_buffer *pbuf;
1561
1562         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1563         if (pbuf) {
1564                 pbuf->pb_nnis = nnis;
1565                 pbuf->pb_needs_post = false;
1566                 atomic_set(&pbuf->pb_refcnt, 1);
1567         }
1568
1569         return pbuf;
1570 }
1571
1572 void
1573 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1574 {
1575         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1576         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1577 }
1578
1579 static struct lnet_ping_buffer *
1580 lnet_ping_target_create(int nnis)
1581 {
1582         struct lnet_ping_buffer *pbuf;
1583
1584         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1585         if (pbuf == NULL) {
1586                 CERROR("Can't allocate ping source [%d]\n", nnis);
1587                 return NULL;
1588         }
1589
1590         pbuf->pb_info.pi_nnis = nnis;
1591         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1592         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1593         pbuf->pb_info.pi_features =
1594                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1595
1596         return pbuf;
1597 }
1598
1599 static inline int
1600 lnet_get_net_ni_count_locked(struct lnet_net *net)
1601 {
1602         struct lnet_ni  *ni;
1603         int             count = 0;
1604
1605         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1606                 count++;
1607
1608         return count;
1609 }
1610
1611 static inline int
1612 lnet_get_net_ni_count_pre(struct lnet_net *net)
1613 {
1614         struct lnet_ni  *ni;
1615         int             count = 0;
1616
1617         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1618                 count++;
1619
1620         return count;
1621 }
1622
1623 static inline int
1624 lnet_get_ni_count(void)
1625 {
1626         struct lnet_ni  *ni;
1627         struct lnet_net *net;
1628         int             count = 0;
1629
1630         lnet_net_lock(0);
1631
1632         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1633                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1634                         count++;
1635         }
1636
1637         lnet_net_unlock(0);
1638
1639         return count;
1640 }
1641
1642 int
1643 lnet_get_net_count(void)
1644 {
1645         struct lnet_net *net;
1646         int count = 0;
1647
1648         lnet_net_lock(0);
1649
1650         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1651                 count++;
1652         }
1653
1654         lnet_net_unlock(0);
1655
1656         return count;
1657 }
1658
1659 void
1660 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1661 {
1662         struct lnet_ni_status *stat;
1663         int nnis;
1664         int i;
1665
1666         __swab32s(&pbuf->pb_info.pi_magic);
1667         __swab32s(&pbuf->pb_info.pi_features);
1668         __swab32s(&pbuf->pb_info.pi_pid);
1669         __swab32s(&pbuf->pb_info.pi_nnis);
1670         nnis = pbuf->pb_info.pi_nnis;
1671         if (nnis > pbuf->pb_nnis)
1672                 nnis = pbuf->pb_nnis;
1673         for (i = 0; i < nnis; i++) {
1674                 stat = &pbuf->pb_info.pi_ni[i];
1675                 __swab64s(&stat->ns_nid);
1676                 __swab32s(&stat->ns_status);
1677         }
1678 }
1679
1680 int
1681 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1682 {
1683         if (!pinfo)
1684                 return -EINVAL;
1685         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1686                 return -EPROTO;
1687         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1688                 return -EPROTO;
1689         /* Loopback is guaranteed to be present */
1690         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1691                 return -ERANGE;
1692         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1693                 return -EPROTO;
1694         return 0;
1695 }
1696
1697 static void
1698 lnet_ping_target_destroy(void)
1699 {
1700         struct lnet_net *net;
1701         struct lnet_ni  *ni;
1702
1703         lnet_net_lock(LNET_LOCK_EX);
1704
1705         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1706                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1707                         lnet_ni_lock(ni);
1708                         ni->ni_status = NULL;
1709                         lnet_ni_unlock(ni);
1710                 }
1711         }
1712
1713         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1714         the_lnet.ln_ping_target = NULL;
1715
1716         lnet_net_unlock(LNET_LOCK_EX);
1717 }
1718
1719 static void
1720 lnet_ping_target_event_handler(struct lnet_event *event)
1721 {
1722         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1723
1724         if (event->unlinked)
1725                 lnet_ping_buffer_decref(pbuf);
1726 }
1727
1728 static int
1729 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1730                        struct lnet_handle_md *ping_mdh,
1731                        int ni_count, bool set_eq)
1732 {
1733         struct lnet_process_id id = {
1734                 .nid = LNET_NID_ANY,
1735                 .pid = LNET_PID_ANY
1736         };
1737         struct lnet_me *me;
1738         struct lnet_md md = { NULL };
1739         int rc;
1740
1741         if (set_eq)
1742                 the_lnet.ln_ping_target_handler =
1743                         lnet_ping_target_event_handler;
1744
1745         *ppbuf = lnet_ping_target_create(ni_count);
1746         if (*ppbuf == NULL) {
1747                 rc = -ENOMEM;
1748                 goto fail_free_eq;
1749         }
1750
1751         /* Ping target ME/MD */
1752         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1753                           LNET_PROTO_PING_MATCHBITS, 0,
1754                           LNET_UNLINK, LNET_INS_AFTER);
1755         if (IS_ERR(me)) {
1756                 rc = PTR_ERR(me);
1757                 CERROR("Can't create ping target ME: %d\n", rc);
1758                 goto fail_decref_ping_buffer;
1759         }
1760
1761         /* initialize md content */
1762         md.start     = &(*ppbuf)->pb_info;
1763         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1764         md.threshold = LNET_MD_THRESH_INF;
1765         md.max_size  = 0;
1766         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1767                        LNET_MD_MANAGE_REMOTE;
1768         md.handler   = the_lnet.ln_ping_target_handler;
1769         md.user_ptr  = *ppbuf;
1770
1771         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
1772         if (rc != 0) {
1773                 CERROR("Can't attach ping target MD: %d\n", rc);
1774                 goto fail_decref_ping_buffer;
1775         }
1776         lnet_ping_buffer_addref(*ppbuf);
1777
1778         return 0;
1779
1780 fail_decref_ping_buffer:
1781         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
1782         lnet_ping_buffer_decref(*ppbuf);
1783         *ppbuf = NULL;
1784 fail_free_eq:
1785         return rc;
1786 }
1787
1788 static void
1789 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1790                     struct lnet_handle_md *ping_mdh)
1791 {
1792         LNetMDUnlink(*ping_mdh);
1793         LNetInvalidateMDHandle(ping_mdh);
1794
1795         /* NB the MD could be busy; this just starts the unlink */
1796         wait_var_event_warning(&pbuf->pb_refcnt,
1797                                atomic_read(&pbuf->pb_refcnt) <= 1,
1798                                "Still waiting for ping data MD to unlink\n");
1799 }
1800
1801 static void
1802 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1803 {
1804         struct lnet_ni          *ni;
1805         struct lnet_net         *net;
1806         struct lnet_ni_status *ns;
1807         int                     i;
1808         int                     rc;
1809
1810         i = 0;
1811         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1812                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1813                         LASSERT(i < pbuf->pb_nnis);
1814
1815                         ns = &pbuf->pb_info.pi_ni[i];
1816
1817                         ns->ns_nid = ni->ni_nid;
1818
1819                         lnet_ni_lock(ni);
1820                         ns->ns_status = (ni->ni_status != NULL) ?
1821                                          ni->ni_status->ns_status :
1822                                                 LNET_NI_STATUS_UP;
1823                         ni->ni_status = ns;
1824                         lnet_ni_unlock(ni);
1825
1826                         i++;
1827                 }
1828         }
1829         /*
1830          * We (ab)use the ns_status of the loopback interface to
1831          * transmit the sequence number. The first interface listed
1832          * must be the loopback interface.
1833          */
1834         rc = lnet_ping_info_validate(&pbuf->pb_info);
1835         if (rc) {
1836                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1837                 LBUG();
1838         }
1839         LNET_PING_BUFFER_SEQNO(pbuf) =
1840                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1841 }
1842
1843 static void
1844 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1845                         struct lnet_handle_md ping_mdh)
1846 {
1847         struct lnet_ping_buffer *old_pbuf = NULL;
1848         struct lnet_handle_md old_ping_md;
1849
1850         /* switch the NIs to point to the new ping info created */
1851         lnet_net_lock(LNET_LOCK_EX);
1852
1853         if (!the_lnet.ln_routing)
1854                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1855         if (!lnet_peer_discovery_disabled)
1856                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1857
1858         /* Ensure only known feature bits have been set. */
1859         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1860         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1861
1862         lnet_ping_target_install_locked(pbuf);
1863
1864         if (the_lnet.ln_ping_target) {
1865                 old_pbuf = the_lnet.ln_ping_target;
1866                 old_ping_md = the_lnet.ln_ping_target_md;
1867         }
1868         the_lnet.ln_ping_target_md = ping_mdh;
1869         the_lnet.ln_ping_target = pbuf;
1870
1871         lnet_net_unlock(LNET_LOCK_EX);
1872
1873         if (old_pbuf) {
1874                 /* unlink and free the old ping info */
1875                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1876                 lnet_ping_buffer_decref(old_pbuf);
1877         }
1878
1879         lnet_push_update_to_peers(0);
1880 }
1881
1882 static void
1883 lnet_ping_target_fini(void)
1884 {
1885         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1886                             &the_lnet.ln_ping_target_md);
1887
1888         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
1889         lnet_ping_target_destroy();
1890 }
1891
1892 /* Resize the push target. */
1893 int lnet_push_target_resize(void)
1894 {
1895         struct lnet_handle_md mdh;
1896         struct lnet_handle_md old_mdh;
1897         struct lnet_ping_buffer *pbuf;
1898         struct lnet_ping_buffer *old_pbuf;
1899         int nnis;
1900         int rc;
1901
1902 again:
1903         nnis = the_lnet.ln_push_target_nnis;
1904         if (nnis <= 0) {
1905                 CDEBUG(D_NET, "Invalid nnis %d\n", nnis);
1906                 return -EINVAL;
1907         }
1908
1909         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
1910          * dropped when we need to resize again (see "old_pbuf" below) or when
1911          * LNet is shutdown (see lnet_push_target_fini())
1912          */
1913         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1914         if (!pbuf) {
1915                 CDEBUG(D_NET, "Can't allocate pbuf for nnis %d\n", nnis);
1916                 return -ENOMEM;
1917         }
1918
1919         rc = lnet_push_target_post(pbuf, &mdh);
1920         if (rc) {
1921                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
1922                 lnet_ping_buffer_decref(pbuf);
1923                 return rc;
1924         }
1925
1926         lnet_net_lock(LNET_LOCK_EX);
1927         old_pbuf = the_lnet.ln_push_target;
1928         old_mdh = the_lnet.ln_push_target_md;
1929         the_lnet.ln_push_target = pbuf;
1930         the_lnet.ln_push_target_md = mdh;
1931         lnet_net_unlock(LNET_LOCK_EX);
1932
1933         if (old_pbuf) {
1934                 LNetMDUnlink(old_mdh);
1935                 /* Drop ref set by lnet_ping_buffer_alloc() */
1936                 lnet_ping_buffer_decref(old_pbuf);
1937         }
1938
1939         /* Received another push or reply that requires a larger buffer */
1940         if (nnis < the_lnet.ln_push_target_nnis)
1941                 goto again;
1942
1943         CDEBUG(D_NET, "nnis %d success\n", nnis);
1944         return 0;
1945 }
1946
1947 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
1948                           struct lnet_handle_md *mdhp)
1949 {
1950         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1951         struct lnet_md md = { NULL };
1952         struct lnet_me *me;
1953         int rc;
1954
1955         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1956                           LNET_PROTO_PING_MATCHBITS, 0,
1957                           LNET_UNLINK, LNET_INS_AFTER);
1958         if (IS_ERR(me)) {
1959                 rc = PTR_ERR(me);
1960                 CERROR("Can't create push target ME: %d\n", rc);
1961                 return rc;
1962         }
1963
1964         pbuf->pb_needs_post = false;
1965
1966         /* This reference is dropped by lnet_push_target_event_handler() */
1967         lnet_ping_buffer_addref(pbuf);
1968
1969         /* initialize md content */
1970         md.start     = &pbuf->pb_info;
1971         md.length    = LNET_PING_INFO_SIZE(pbuf->pb_nnis);
1972         md.threshold = 1;
1973         md.max_size  = 0;
1974         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
1975         md.user_ptr  = pbuf;
1976         md.handler   = the_lnet.ln_push_target_handler;
1977
1978         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
1979         if (rc) {
1980                 CERROR("Can't attach push MD: %d\n", rc);
1981                 lnet_ping_buffer_decref(pbuf);
1982                 pbuf->pb_needs_post = true;
1983                 return rc;
1984         }
1985
1986         CDEBUG(D_NET, "posted push target %p\n", pbuf);
1987
1988         return 0;
1989 }
1990
1991 static void lnet_push_target_event_handler(struct lnet_event *ev)
1992 {
1993         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
1994
1995         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
1996                ev->unlinked);
1997
1998         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1999                 lnet_swap_pinginfo(pbuf);
2000
2001         if (ev->type == LNET_EVENT_UNLINK) {
2002                 /* Drop ref added by lnet_push_target_post() */
2003                 lnet_ping_buffer_decref(pbuf);
2004                 return;
2005         }
2006
2007         lnet_peer_push_event(ev);
2008         if (ev->unlinked)
2009                 /* Drop ref added by lnet_push_target_post */
2010                 lnet_ping_buffer_decref(pbuf);
2011 }
2012
2013 /* Initialize the push target. */
2014 static int lnet_push_target_init(void)
2015 {
2016         int rc;
2017
2018         if (the_lnet.ln_push_target)
2019                 return -EALREADY;
2020
2021         the_lnet.ln_push_target_handler =
2022                 lnet_push_target_event_handler;
2023
2024         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2025         LASSERT(rc == 0);
2026
2027         /* Start at the required minimum, we'll enlarge if required. */
2028         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
2029
2030         rc = lnet_push_target_resize();
2031
2032         if (rc) {
2033                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2034                 the_lnet.ln_push_target_handler = NULL;
2035         }
2036
2037         return rc;
2038 }
2039
2040 /* Clean up the push target. */
2041 static void lnet_push_target_fini(void)
2042 {
2043         if (!the_lnet.ln_push_target)
2044                 return;
2045
2046         /* Unlink and invalidate to prevent new references. */
2047         LNetMDUnlink(the_lnet.ln_push_target_md);
2048         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2049
2050         /* Wait for the unlink to complete. */
2051         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2052                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2053                                "Still waiting for ping data MD to unlink\n");
2054
2055         /* Drop ref set by lnet_ping_buffer_alloc() */
2056         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2057         the_lnet.ln_push_target = NULL;
2058         the_lnet.ln_push_target_nnis = 0;
2059
2060         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2061         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2062         the_lnet.ln_push_target_handler = NULL;
2063 }
2064
2065 static int
2066 lnet_ni_tq_credits(struct lnet_ni *ni)
2067 {
2068         int     credits;
2069
2070         LASSERT(ni->ni_ncpts >= 1);
2071
2072         if (ni->ni_ncpts == 1)
2073                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2074
2075         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2076         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2077         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2078
2079         return credits;
2080 }
2081
2082 static void
2083 lnet_ni_unlink_locked(struct lnet_ni *ni)
2084 {
2085         /* move it to zombie list and nobody can find it anymore */
2086         LASSERT(!list_empty(&ni->ni_netlist));
2087         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2088         lnet_ni_decref_locked(ni, 0);
2089 }
2090
2091 static void
2092 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2093 {
2094         int             i;
2095         int             islo;
2096         struct lnet_ni  *ni;
2097         struct list_head *zombie_list = &net->net_ni_zombie;
2098
2099         /*
2100          * Now wait for the NIs I just nuked to show up on the zombie
2101          * list and shut them down in guaranteed thread context
2102          */
2103         i = 2;
2104         while (!list_empty(zombie_list)) {
2105                 int     *ref;
2106                 int     j;
2107
2108                 ni = list_entry(zombie_list->next,
2109                                 struct lnet_ni, ni_netlist);
2110                 list_del_init(&ni->ni_netlist);
2111                 /* the ni should be in deleting state. If it's not it's
2112                  * a bug */
2113                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2114                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2115                         if (*ref == 0)
2116                                 continue;
2117                         /* still busy, add it back to zombie list */
2118                         list_add(&ni->ni_netlist, zombie_list);
2119                         break;
2120                 }
2121
2122                 if (!list_empty(&ni->ni_netlist)) {
2123                         /* Unlock mutex while waiting to allow other
2124                          * threads to read the LNet state and fall through
2125                          * to avoid deadlock
2126                          */
2127                         lnet_net_unlock(LNET_LOCK_EX);
2128                         mutex_unlock(&the_lnet.ln_api_mutex);
2129
2130                         ++i;
2131                         if ((i & (-i)) == i) {
2132                                 CDEBUG(D_WARNING,
2133                                        "Waiting for zombie LNI %s\n",
2134                                        libcfs_nid2str(ni->ni_nid));
2135                         }
2136                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2137
2138                         mutex_lock(&the_lnet.ln_api_mutex);
2139                         lnet_net_lock(LNET_LOCK_EX);
2140                         continue;
2141                 }
2142
2143                 lnet_net_unlock(LNET_LOCK_EX);
2144
2145                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2146
2147                 LASSERT(!in_interrupt());
2148                 /* Holding the mutex makes it safe for lnd_shutdown
2149                  * to call module_put(). Module unload cannot finish
2150                  * until lnet_unregister_lnd() completes, and that
2151                  * requires the mutex.
2152                  */
2153                 mutex_lock(&the_lnet.ln_lnd_mutex);
2154                 (net->net_lnd->lnd_shutdown)(ni);
2155                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2156
2157                 if (!islo)
2158                         CDEBUG(D_LNI, "Removed LNI %s\n",
2159                               libcfs_nid2str(ni->ni_nid));
2160
2161                 lnet_ni_free(ni);
2162                 i = 2;
2163                 lnet_net_lock(LNET_LOCK_EX);
2164         }
2165 }
2166
2167 /* shutdown down the NI and release refcount */
2168 static void
2169 lnet_shutdown_lndni(struct lnet_ni *ni)
2170 {
2171         int i;
2172         struct lnet_net *net = ni->ni_net;
2173
2174         lnet_net_lock(LNET_LOCK_EX);
2175         lnet_ni_lock(ni);
2176         ni->ni_state = LNET_NI_STATE_DELETING;
2177         lnet_ni_unlock(ni);
2178         lnet_ni_unlink_locked(ni);
2179         lnet_incr_dlc_seq();
2180         lnet_net_unlock(LNET_LOCK_EX);
2181
2182         /* clear messages for this NI on the lazy portal */
2183         for (i = 0; i < the_lnet.ln_nportals; i++)
2184                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2185
2186         lnet_net_lock(LNET_LOCK_EX);
2187         lnet_clear_zombies_nis_locked(net);
2188         lnet_net_unlock(LNET_LOCK_EX);
2189 }
2190
2191 static void
2192 lnet_shutdown_lndnet(struct lnet_net *net)
2193 {
2194         struct lnet_ni *ni;
2195
2196         lnet_net_lock(LNET_LOCK_EX);
2197
2198         list_del_init(&net->net_list);
2199
2200         while (!list_empty(&net->net_ni_list)) {
2201                 ni = list_entry(net->net_ni_list.next,
2202                                 struct lnet_ni, ni_netlist);
2203                 lnet_net_unlock(LNET_LOCK_EX);
2204                 lnet_shutdown_lndni(ni);
2205                 lnet_net_lock(LNET_LOCK_EX);
2206         }
2207
2208         lnet_net_unlock(LNET_LOCK_EX);
2209
2210         /* Do peer table cleanup for this net */
2211         lnet_peer_tables_cleanup(net);
2212
2213         lnet_net_free(net);
2214 }
2215
2216 static void
2217 lnet_shutdown_lndnets(void)
2218 {
2219         struct lnet_net *net;
2220         LIST_HEAD(resend);
2221         struct lnet_msg *msg, *tmp;
2222
2223         /* NB called holding the global mutex */
2224
2225         /* All quiet on the API front */
2226         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2227         LASSERT(the_lnet.ln_refcount == 0);
2228
2229         lnet_net_lock(LNET_LOCK_EX);
2230         the_lnet.ln_state = LNET_STATE_STOPPING;
2231
2232         /*
2233          * move the nets to the zombie list to avoid them being
2234          * picked up for new work. LONET is also included in the
2235          * Nets that will be moved to the zombie list
2236          */
2237         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2238
2239         /* Drop the cached loopback Net. */
2240         if (the_lnet.ln_loni != NULL) {
2241                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2242                 the_lnet.ln_loni = NULL;
2243         }
2244         lnet_net_unlock(LNET_LOCK_EX);
2245
2246         /* iterate through the net zombie list and delete each net */
2247         while (!list_empty(&the_lnet.ln_net_zombie)) {
2248                 net = list_entry(the_lnet.ln_net_zombie.next,
2249                                  struct lnet_net, net_list);
2250                 lnet_shutdown_lndnet(net);
2251         }
2252
2253         spin_lock(&the_lnet.ln_msg_resend_lock);
2254         list_splice(&the_lnet.ln_msg_resend, &resend);
2255         spin_unlock(&the_lnet.ln_msg_resend_lock);
2256
2257         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2258                 list_del_init(&msg->msg_list);
2259                 msg->msg_no_resend = true;
2260                 lnet_finalize(msg, -ECANCELED);
2261         }
2262
2263         lnet_net_lock(LNET_LOCK_EX);
2264         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2265         lnet_net_unlock(LNET_LOCK_EX);
2266 }
2267
2268 static int
2269 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2270 {
2271         int                     rc = -EINVAL;
2272         struct lnet_tx_queue    *tq;
2273         int                     i;
2274         struct lnet_net         *net = ni->ni_net;
2275
2276         mutex_lock(&the_lnet.ln_lnd_mutex);
2277
2278         if (tun) {
2279                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2280                 ni->ni_lnd_tunables_set = true;
2281         }
2282
2283         rc = (net->net_lnd->lnd_startup)(ni);
2284
2285         mutex_unlock(&the_lnet.ln_lnd_mutex);
2286
2287         if (rc != 0) {
2288                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2289                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2290                 goto failed0;
2291         }
2292
2293         lnet_ni_lock(ni);
2294         ni->ni_state = LNET_NI_STATE_ACTIVE;
2295         lnet_ni_unlock(ni);
2296
2297         /* We keep a reference on the loopback net through the loopback NI */
2298         if (net->net_lnd->lnd_type == LOLND) {
2299                 lnet_ni_addref(ni);
2300                 LASSERT(the_lnet.ln_loni == NULL);
2301                 the_lnet.ln_loni = ni;
2302                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2303                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2304                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2305                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2306                 return 0;
2307         }
2308
2309         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2310             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2311                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2312                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2313                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2314                                         "" : "per-peer ");
2315                 /* shutdown the NI since if we get here then it must've already
2316                  * been started
2317                  */
2318                 lnet_shutdown_lndni(ni);
2319                 return -EINVAL;
2320         }
2321
2322         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2323                 tq->tq_credits_min =
2324                 tq->tq_credits_max =
2325                 tq->tq_credits = lnet_ni_tq_credits(ni);
2326         }
2327
2328         atomic_set(&ni->ni_tx_credits,
2329                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2330         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2331
2332         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2333                 libcfs_nid2str(ni->ni_nid),
2334                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2335                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2336                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2337                 ni->ni_net->net_tunables.lct_peer_timeout);
2338
2339         return 0;
2340 failed0:
2341         lnet_ni_free(ni);
2342         return rc;
2343 }
2344
2345 static int
2346 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2347 {
2348         struct lnet_ni *ni;
2349         struct lnet_net *net_l = NULL;
2350         LIST_HEAD(local_ni_list);
2351         int rc;
2352         int ni_count = 0;
2353         __u32 lnd_type;
2354         const struct lnet_lnd  *lnd;
2355         int peer_timeout =
2356                 net->net_tunables.lct_peer_timeout;
2357         int maxtxcredits =
2358                 net->net_tunables.lct_max_tx_credits;
2359         int peerrtrcredits =
2360                 net->net_tunables.lct_peer_rtr_credits;
2361
2362         /*
2363          * make sure that this net is unique. If it isn't then
2364          * we are adding interfaces to an already existing network, and
2365          * 'net' is just a convenient way to pass in the list.
2366          * if it is unique we need to find the LND and load it if
2367          * necessary.
2368          */
2369         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2370                 lnd_type = LNET_NETTYP(net->net_id);
2371
2372                 mutex_lock(&the_lnet.ln_lnd_mutex);
2373                 lnd = lnet_find_lnd_by_type(lnd_type);
2374
2375                 if (lnd == NULL) {
2376                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2377                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2378                         mutex_lock(&the_lnet.ln_lnd_mutex);
2379
2380                         lnd = lnet_find_lnd_by_type(lnd_type);
2381                         if (lnd == NULL) {
2382                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2383                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2384                                 libcfs_lnd2str(lnd_type),
2385                                 libcfs_lnd2modname(lnd_type), rc);
2386 #ifndef HAVE_MODULE_LOADING_SUPPORT
2387                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2388                                                 "compiled with kernel module "
2389                                                 "loading support.");
2390 #endif
2391                                 rc = -EINVAL;
2392                                 goto failed0;
2393                         }
2394                 }
2395
2396                 net->net_lnd = lnd;
2397
2398                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2399
2400                 net_l = net;
2401         }
2402
2403         /*
2404          * net_l: if the network being added is unique then net_l
2405          *        will point to that network
2406          *        if the network being added is not unique then
2407          *        net_l points to the existing network.
2408          *
2409          * When we enter the loop below, we'll pick NIs off he
2410          * network beign added and start them up, then add them to
2411          * a local ni list. Once we've successfully started all
2412          * the NIs then we join the local NI list (of started up
2413          * networks) with the net_l->net_ni_list, which should
2414          * point to the correct network to add the new ni list to
2415          *
2416          * If any of the new NIs fail to start up, then we want to
2417          * iterate through the local ni list, which should include
2418          * any NIs which were successfully started up, and shut
2419          * them down.
2420          *
2421          * After than we want to delete the network being added,
2422          * to avoid a memory leak.
2423          */
2424
2425         /*
2426          * When a network uses TCP bonding then all its interfaces
2427          * must be specified when the network is first defined: the
2428          * TCP bonding code doesn't allow for interfaces to be added
2429          * or removed.
2430          */
2431         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2432             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2433                 rc = -EINVAL;
2434                 goto failed0;
2435         }
2436
2437         while (!list_empty(&net->net_ni_added)) {
2438                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2439                                 ni_netlist);
2440                 list_del_init(&ni->ni_netlist);
2441
2442                 /* make sure that the the NI we're about to start
2443                  * up is actually unique. if it's not fail. */
2444                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2445                                         ni->ni_interfaces[0])) {
2446                         rc = -EEXIST;
2447                         goto failed1;
2448                 }
2449
2450                 /* adjust the pointer the parent network, just in case it
2451                  * the net is a duplicate */
2452                 ni->ni_net = net_l;
2453
2454                 rc = lnet_startup_lndni(ni, tun);
2455
2456                 if (rc < 0)
2457                         goto failed1;
2458
2459                 lnet_ni_addref(ni);
2460                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2461
2462                 ni_count++;
2463         }
2464
2465         lnet_net_lock(LNET_LOCK_EX);
2466         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2467         lnet_incr_dlc_seq();
2468         lnet_net_unlock(LNET_LOCK_EX);
2469
2470         /* if the network is not unique then we don't want to keep
2471          * it around after we're done. Free it. Otherwise add that
2472          * net to the global the_lnet.ln_nets */
2473         if (net_l != net && net_l != NULL) {
2474                 /*
2475                  * TODO - note. currently the tunables can not be updated
2476                  * once added
2477                  */
2478                 lnet_net_free(net);
2479         } else {
2480                 /*
2481                  * restore tunables after it has been overwitten by the
2482                  * lnd
2483                  */
2484                 if (peer_timeout != -1)
2485                         net->net_tunables.lct_peer_timeout = peer_timeout;
2486                 if (maxtxcredits != -1)
2487                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2488                 if (peerrtrcredits != -1)
2489                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2490
2491                 lnet_net_lock(LNET_LOCK_EX);
2492                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2493                 lnet_net_unlock(LNET_LOCK_EX);
2494         }
2495
2496         /* update net count */
2497         lnet_current_net_count = lnet_get_net_count();
2498
2499         return ni_count;
2500
2501 failed1:
2502         /*
2503          * shutdown the new NIs that are being started up
2504          * free the NET being started
2505          */
2506         while (!list_empty(&local_ni_list)) {
2507                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2508                                 ni_netlist);
2509
2510                 lnet_shutdown_lndni(ni);
2511         }
2512
2513 failed0:
2514         lnet_net_free(net);
2515
2516         return rc;
2517 }
2518
2519 static int
2520 lnet_startup_lndnets(struct list_head *netlist)
2521 {
2522         struct lnet_net         *net;
2523         int                     rc;
2524         int                     ni_count = 0;
2525
2526         /*
2527          * Change to running state before bringing up the LNDs. This
2528          * allows lnet_shutdown_lndnets() to assert that we've passed
2529          * through here.
2530          */
2531         lnet_net_lock(LNET_LOCK_EX);
2532         the_lnet.ln_state = LNET_STATE_RUNNING;
2533         lnet_net_unlock(LNET_LOCK_EX);
2534
2535         while (!list_empty(netlist)) {
2536                 net = list_entry(netlist->next, struct lnet_net, net_list);
2537                 list_del_init(&net->net_list);
2538
2539                 rc = lnet_startup_lndnet(net, NULL);
2540
2541                 if (rc < 0)
2542                         goto failed;
2543
2544                 ni_count += rc;
2545         }
2546
2547         return ni_count;
2548 failed:
2549         lnet_shutdown_lndnets();
2550
2551         return rc;
2552 }
2553
2554 /**
2555  * Initialize LNet library.
2556  *
2557  * Automatically called at module loading time. Caller has to call
2558  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2559  * latter returned 0. It must be called exactly once.
2560  *
2561  * \retval 0 on success
2562  * \retval -ve on failures.
2563  */
2564 int lnet_lib_init(void)
2565 {
2566         int rc;
2567
2568         lnet_assert_wire_constants();
2569
2570         /* refer to global cfs_cpt_table for now */
2571         the_lnet.ln_cpt_table = cfs_cpt_tab;
2572         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2573
2574         LASSERT(the_lnet.ln_cpt_number > 0);
2575         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2576                 /* we are under risk of consuming all lh_cookie */
2577                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2578                        "please change setting of CPT-table and retry\n",
2579                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2580                 return -E2BIG;
2581         }
2582
2583         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2584                 the_lnet.ln_cpt_bits++;
2585
2586         rc = lnet_create_locks();
2587         if (rc != 0) {
2588                 CERROR("Can't create LNet global locks: %d\n", rc);
2589                 return rc;
2590         }
2591
2592         the_lnet.ln_refcount = 0;
2593         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2594         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2595
2596         /* The hash table size is the number of bits it takes to express the set
2597          * ln_num_routes, minus 1 (better to under estimate than over so we
2598          * don't waste memory). */
2599         if (rnet_htable_size <= 0)
2600                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2601         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2602                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2603         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2604                                            order_base_2(rnet_htable_size) - 1);
2605
2606         /* All LNDs apart from the LOLND are in separate modules.  They
2607          * register themselves when their module loads, and unregister
2608          * themselves when their module is unloaded. */
2609         lnet_register_lnd(&the_lolnd);
2610         return 0;
2611 }
2612
2613 /**
2614  * Finalize LNet library.
2615  *
2616  * \pre lnet_lib_init() called with success.
2617  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2618  *
2619  * As this happens at module-unload, all lnds must already be unloaded,
2620  * so they must already be unregistered.
2621  */
2622 void lnet_lib_exit(void)
2623 {
2624         int i;
2625
2626         LASSERT(the_lnet.ln_refcount == 0);
2627         lnet_unregister_lnd(&the_lolnd);
2628         for (i = 0; i < NUM_LNDS; i++)
2629                 LASSERT(!the_lnet.ln_lnds[i]);
2630         lnet_destroy_locks();
2631 }
2632
2633 /**
2634  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2635  *
2636  * Users must call this function at least once before any other functions.
2637  * For each successful call there must be a corresponding call to
2638  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2639  * ignored.
2640  *
2641  * The PID used by LNet may be different from the one requested.
2642  * See LNetGetId().
2643  *
2644  * \param requested_pid PID requested by the caller.
2645  *
2646  * \return >= 0 on success, and < 0 error code on failures.
2647  */
2648 int
2649 LNetNIInit(lnet_pid_t requested_pid)
2650 {
2651         int                     im_a_router = 0;
2652         int                     rc;
2653         int                     ni_count;
2654         struct lnet_ping_buffer *pbuf;
2655         struct lnet_handle_md   ping_mdh;
2656         LIST_HEAD(net_head);
2657         struct lnet_net         *net;
2658
2659         mutex_lock(&the_lnet.ln_api_mutex);
2660
2661         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2662
2663         if (the_lnet.ln_refcount > 0) {
2664                 rc = the_lnet.ln_refcount++;
2665                 mutex_unlock(&the_lnet.ln_api_mutex);
2666                 return rc;
2667         }
2668
2669         rc = lnet_prepare(requested_pid);
2670         if (rc != 0) {
2671                 mutex_unlock(&the_lnet.ln_api_mutex);
2672                 return rc;
2673         }
2674
2675         /* create a network for Loopback network */
2676         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2677         if (net == NULL) {
2678                 rc = -ENOMEM;
2679                 goto err_empty_list;
2680         }
2681
2682         /* Add in the loopback NI */
2683         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2684                 rc = -ENOMEM;
2685                 goto err_empty_list;
2686         }
2687
2688         if (use_tcp_bonding)
2689                 CWARN("'use_tcp_bonding' option has been deprecated. See LU-13641\n");
2690
2691         /* If LNet is being initialized via DLC it is possible
2692          * that the user requests not to load module parameters (ones which
2693          * are supported by DLC) on initialization.  Therefore, make sure not
2694          * to load networks, routes and forwarding from module parameters
2695          * in this case.  On cleanup in case of failure only clean up
2696          * routes if it has been loaded */
2697         if (!the_lnet.ln_nis_from_mod_params) {
2698                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2699                                          use_tcp_bonding);
2700                 if (rc < 0)
2701                         goto err_empty_list;
2702         }
2703
2704         ni_count = lnet_startup_lndnets(&net_head);
2705         if (ni_count < 0) {
2706                 rc = ni_count;
2707                 goto err_empty_list;
2708         }
2709
2710         if (!the_lnet.ln_nis_from_mod_params) {
2711                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2712                 if (rc != 0)
2713                         goto err_shutdown_lndnis;
2714
2715                 rc = lnet_rtrpools_alloc(im_a_router);
2716                 if (rc != 0)
2717                         goto err_destroy_routes;
2718         }
2719
2720         rc = lnet_acceptor_start();
2721         if (rc != 0)
2722                 goto err_destroy_routes;
2723
2724         the_lnet.ln_refcount = 1;
2725         /* Now I may use my own API functions... */
2726
2727         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2728         if (rc != 0)
2729                 goto err_acceptor_stop;
2730
2731         lnet_ping_target_update(pbuf, ping_mdh);
2732
2733         the_lnet.ln_mt_handler = lnet_mt_event_handler;
2734
2735         rc = lnet_push_target_init();
2736         if (rc != 0)
2737                 goto err_stop_ping;
2738
2739         rc = lnet_peer_discovery_start();
2740         if (rc != 0)
2741                 goto err_destroy_push_target;
2742
2743         rc = lnet_monitor_thr_start();
2744         if (rc != 0)
2745                 goto err_stop_discovery_thr;
2746
2747         lnet_fault_init();
2748         lnet_router_debugfs_init();
2749
2750         mutex_unlock(&the_lnet.ln_api_mutex);
2751
2752         complete_all(&the_lnet.ln_started);
2753
2754         /* wait for all routers to start */
2755         lnet_wait_router_start();
2756
2757         return 0;
2758
2759 err_stop_discovery_thr:
2760         lnet_peer_discovery_stop();
2761 err_destroy_push_target:
2762         lnet_push_target_fini();
2763 err_stop_ping:
2764         lnet_ping_target_fini();
2765 err_acceptor_stop:
2766         the_lnet.ln_refcount = 0;
2767         lnet_acceptor_stop();
2768 err_destroy_routes:
2769         if (!the_lnet.ln_nis_from_mod_params)
2770                 lnet_destroy_routes();
2771 err_shutdown_lndnis:
2772         lnet_shutdown_lndnets();
2773 err_empty_list:
2774         lnet_unprepare();
2775         LASSERT(rc < 0);
2776         mutex_unlock(&the_lnet.ln_api_mutex);
2777         while (!list_empty(&net_head)) {
2778                 struct lnet_net *net;
2779
2780                 net = list_entry(net_head.next, struct lnet_net, net_list);
2781                 list_del_init(&net->net_list);
2782                 lnet_net_free(net);
2783         }
2784         return rc;
2785 }
2786 EXPORT_SYMBOL(LNetNIInit);
2787
2788 /**
2789  * Stop LNet interfaces, routing, and forwarding.
2790  *
2791  * Users must call this function once for each successful call to LNetNIInit().
2792  * Once the LNetNIFini() operation has been started, the results of pending
2793  * API operations are undefined.
2794  *
2795  * \return always 0 for current implementation.
2796  */
2797 int
2798 LNetNIFini(void)
2799 {
2800         mutex_lock(&the_lnet.ln_api_mutex);
2801
2802         LASSERT(the_lnet.ln_refcount > 0);
2803
2804         if (the_lnet.ln_refcount != 1) {
2805                 the_lnet.ln_refcount--;
2806         } else {
2807                 LASSERT(!the_lnet.ln_niinit_self);
2808
2809                 lnet_fault_fini();
2810
2811                 lnet_router_debugfs_fini();
2812                 lnet_monitor_thr_stop();
2813                 lnet_peer_discovery_stop();
2814                 lnet_push_target_fini();
2815                 lnet_ping_target_fini();
2816
2817                 /* Teardown fns that use my own API functions BEFORE here */
2818                 the_lnet.ln_refcount = 0;
2819
2820                 lnet_acceptor_stop();
2821                 lnet_destroy_routes();
2822                 lnet_shutdown_lndnets();
2823                 lnet_unprepare();
2824         }
2825
2826         mutex_unlock(&the_lnet.ln_api_mutex);
2827         return 0;
2828 }
2829 EXPORT_SYMBOL(LNetNIFini);
2830
2831 /**
2832  * Grabs the ni data from the ni structure and fills the out
2833  * parameters
2834  *
2835  * \param[in] ni network        interface structure
2836  * \param[out] cfg_ni           NI config information
2837  * \param[out] tun              network and LND tunables
2838  */
2839 static void
2840 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2841                    struct lnet_ioctl_config_lnd_tunables *tun,
2842                    struct lnet_ioctl_element_stats *stats,
2843                    __u32 tun_size)
2844 {
2845         size_t min_size = 0;
2846         int i;
2847
2848         if (!ni || !cfg_ni || !tun)
2849                 return;
2850
2851         if (ni->ni_interfaces[0] != NULL) {
2852                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2853                         if (ni->ni_interfaces[i] != NULL) {
2854                                 strncpy(cfg_ni->lic_ni_intf[i],
2855                                         ni->ni_interfaces[i],
2856                                         sizeof(cfg_ni->lic_ni_intf[i]));
2857                         }
2858                 }
2859         }
2860
2861         cfg_ni->lic_nid = ni->ni_nid;
2862         if (ni->ni_nid == LNET_NID_LO_0)
2863                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2864         else
2865                 cfg_ni->lic_status = ni->ni_status->ns_status;
2866         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2867         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2868
2869         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2870
2871         if (stats) {
2872                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2873                                                        LNET_STATS_TYPE_SEND);
2874                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2875                                                        LNET_STATS_TYPE_RECV);
2876                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2877                                                        LNET_STATS_TYPE_DROP);
2878         }
2879
2880         /*
2881          * tun->lt_tun will always be present, but in order to be
2882          * backwards compatible, we need to deal with the cases when
2883          * tun->lt_tun is smaller than what the kernel has, because it
2884          * comes from an older version of a userspace program, then we'll
2885          * need to copy as much information as we have available space.
2886          */
2887         min_size = tun_size - sizeof(tun->lt_cmn);
2888         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2889
2890         /* copy over the cpts */
2891         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2892             ni->ni_cpts == NULL)  {
2893                 for (i = 0; i < ni->ni_ncpts; i++)
2894                         cfg_ni->lic_cpts[i] = i;
2895         } else {
2896                 for (i = 0;
2897                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2898                      i < LNET_MAX_SHOW_NUM_CPT;
2899                      i++)
2900                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2901         }
2902         cfg_ni->lic_ncpts = ni->ni_ncpts;
2903 }
2904
2905 /**
2906  * NOTE: This is a legacy function left in the code to be backwards
2907  * compatible with older userspace programs. It should eventually be
2908  * removed.
2909  *
2910  * Grabs the ni data from the ni structure and fills the out
2911  * parameters
2912  *
2913  * \param[in] ni network        interface structure
2914  * \param[out] config           config information
2915  */
2916 static void
2917 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2918                          struct lnet_ioctl_config_data *config)
2919 {
2920         struct lnet_ioctl_net_config *net_config;
2921         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2922         size_t min_size, tunable_size = 0;
2923         int i;
2924
2925         if (!ni || !config)
2926                 return;
2927
2928         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2929         if (!net_config)
2930                 return;
2931
2932         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2933                      ARRAY_SIZE(net_config->ni_interfaces));
2934
2935         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2936                 if (!ni->ni_interfaces[i])
2937                         break;
2938
2939                 strncpy(net_config->ni_interfaces[i],
2940                         ni->ni_interfaces[i],
2941                         sizeof(net_config->ni_interfaces[i]));
2942         }
2943
2944         config->cfg_nid = ni->ni_nid;
2945         config->cfg_config_u.cfg_net.net_peer_timeout =
2946                 ni->ni_net->net_tunables.lct_peer_timeout;
2947         config->cfg_config_u.cfg_net.net_max_tx_credits =
2948                 ni->ni_net->net_tunables.lct_max_tx_credits;
2949         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2950                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2951         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2952                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2953
2954         if (ni->ni_nid == LNET_NID_LO_0)
2955                 net_config->ni_status = LNET_NI_STATUS_UP;
2956         else
2957                 net_config->ni_status = ni->ni_status->ns_status;
2958
2959         if (ni->ni_cpts) {
2960                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2961
2962                 for (i = 0; i < num_cpts; i++)
2963                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2964
2965                 config->cfg_ncpts = num_cpts;
2966         }
2967
2968         /*
2969          * See if user land tools sent in a newer and larger version
2970          * of struct lnet_tunables than what the kernel uses.
2971          */
2972         min_size = sizeof(*config) + sizeof(*net_config);
2973
2974         if (config->cfg_hdr.ioc_len > min_size)
2975                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2976
2977         /* Don't copy too much data to user space */
2978         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2979         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2980
2981         if (lnd_cfg && min_size) {
2982                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2983                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2984
2985                 /* Tell user land that kernel side has less data */
2986                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2987                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2988                         config->cfg_hdr.ioc_len -= min_size;
2989                 }
2990         }
2991 }
2992
2993 struct lnet_ni *
2994 lnet_get_ni_idx_locked(int idx)
2995 {
2996         struct lnet_ni          *ni;
2997         struct lnet_net         *net;
2998
2999         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3000                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3001                         if (idx-- == 0)
3002                                 return ni;
3003                 }
3004         }
3005
3006         return NULL;
3007 }
3008
3009 int lnet_get_net_healthv_locked(struct lnet_net *net)
3010 {
3011         struct lnet_ni *ni;
3012         int best_healthv = 0;
3013         int healthv;
3014
3015         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3016                 healthv = atomic_read(&ni->ni_healthv);
3017                 if (healthv > best_healthv)
3018                         best_healthv = healthv;
3019         }
3020
3021         return best_healthv;
3022 }
3023
3024 struct lnet_ni *
3025 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3026 {
3027         struct lnet_ni          *ni;
3028         struct lnet_net         *net = mynet;
3029
3030         /*
3031          * It is possible that the net has been cleaned out while there is
3032          * a message being sent. This function accessed the net without
3033          * checking if the list is empty
3034          */
3035         if (prev == NULL) {
3036                 if (net == NULL)
3037                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3038                                         net_list);
3039                 if (list_empty(&net->net_ni_list))
3040                         return NULL;
3041                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3042                                 ni_netlist);
3043
3044                 return ni;
3045         }
3046
3047         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3048                 /* if you reached the end of the ni list and the net is
3049                  * specified, then there are no more nis in that net */
3050                 if (net != NULL)
3051                         return NULL;
3052
3053                 /* we reached the end of this net ni list. move to the
3054                  * next net */
3055                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3056                         /* no more nets and no more NIs. */
3057                         return NULL;
3058
3059                 /* get the next net */
3060                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3061                                  net_list);
3062                 if (list_empty(&net->net_ni_list))
3063                         return NULL;
3064                 /* get the ni on it */
3065                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3066                                 ni_netlist);
3067
3068                 return ni;
3069         }
3070
3071         if (list_empty(&prev->ni_netlist))
3072                 return NULL;
3073
3074         /* there are more nis left */
3075         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3076
3077         return ni;
3078 }
3079
3080 int
3081 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3082 {
3083         struct lnet_ni *ni;
3084         int cpt;
3085         int rc = -ENOENT;
3086         int idx = config->cfg_count;
3087
3088         cpt = lnet_net_lock_current();
3089
3090         ni = lnet_get_ni_idx_locked(idx);
3091
3092         if (ni != NULL) {
3093                 rc = 0;
3094                 lnet_ni_lock(ni);
3095                 lnet_fill_ni_info_legacy(ni, config);
3096                 lnet_ni_unlock(ni);
3097         }
3098
3099         lnet_net_unlock(cpt);
3100         return rc;
3101 }
3102
3103 int
3104 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3105                    struct lnet_ioctl_config_lnd_tunables *tun,
3106                    struct lnet_ioctl_element_stats *stats,
3107                    __u32 tun_size)
3108 {
3109         struct lnet_ni          *ni;
3110         int                     cpt;
3111         int                     rc = -ENOENT;
3112
3113         if (!cfg_ni || !tun || !stats)
3114                 return -EINVAL;
3115
3116         cpt = lnet_net_lock_current();
3117
3118         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3119
3120         if (ni) {
3121                 rc = 0;
3122                 lnet_ni_lock(ni);
3123                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3124                 lnet_ni_unlock(ni);
3125         }
3126
3127         lnet_net_unlock(cpt);
3128         return rc;
3129 }
3130
3131 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3132 {
3133         struct lnet_ni *ni;
3134         int cpt;
3135         int rc = -ENOENT;
3136
3137         if (!msg_stats)
3138                 return -EINVAL;
3139
3140         cpt = lnet_net_lock_current();
3141
3142         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3143
3144         if (ni) {
3145                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3146                 rc = 0;
3147         }
3148
3149         lnet_net_unlock(cpt);
3150
3151         return rc;
3152 }
3153
3154 static int lnet_add_net_common(struct lnet_net *net,
3155                                struct lnet_ioctl_config_lnd_tunables *tun)
3156 {
3157         __u32                   net_id;
3158         struct lnet_ping_buffer *pbuf;
3159         struct lnet_handle_md   ping_mdh;
3160         int                     rc;
3161         struct lnet_remotenet *rnet;
3162         int                     net_ni_count;
3163
3164         lnet_net_lock(LNET_LOCK_EX);
3165         rnet = lnet_find_rnet_locked(net->net_id);
3166         lnet_net_unlock(LNET_LOCK_EX);
3167         /*
3168          * make sure that the net added doesn't invalidate the current
3169          * configuration LNet is keeping
3170          */
3171         if (rnet) {
3172                 CERROR("Adding net %s will invalidate routing configuration\n",
3173                        libcfs_net2str(net->net_id));
3174                 lnet_net_free(net);
3175                 return -EUSERS;
3176         }
3177
3178         /*
3179          * make sure you calculate the correct number of slots in the ping
3180          * buffer. Since the ping info is a flattened list of all the NIs,
3181          * we should allocate enough slots to accomodate the number of NIs
3182          * which will be added.
3183          *
3184          * since ni hasn't been configured yet, use
3185          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3186          */
3187         net_ni_count = lnet_get_net_ni_count_pre(net);
3188
3189         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3190                                     net_ni_count + lnet_get_ni_count(),
3191                                     false);
3192         if (rc < 0) {
3193                 lnet_net_free(net);
3194                 return rc;
3195         }
3196
3197         if (tun)
3198                 memcpy(&net->net_tunables,
3199                        &tun->lt_cmn, sizeof(net->net_tunables));
3200         else
3201                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3202
3203         net_id = net->net_id;
3204
3205         rc = lnet_startup_lndnet(net,
3206                                  (tun) ? &tun->lt_tun : NULL);
3207         if (rc < 0)
3208                 goto failed;
3209
3210         lnet_net_lock(LNET_LOCK_EX);
3211         net = lnet_get_net_locked(net_id);
3212         lnet_net_unlock(LNET_LOCK_EX);
3213
3214         LASSERT(net);
3215
3216         /*
3217          * Start the acceptor thread if this is the first network
3218          * being added that requires the thread.
3219          */
3220         if (net->net_lnd->lnd_accept) {
3221                 rc = lnet_acceptor_start();
3222                 if (rc < 0) {
3223                         /* shutdown the net that we just started */
3224                         CERROR("Failed to start up acceptor thread\n");
3225                         lnet_shutdown_lndnet(net);
3226                         goto failed;
3227                 }
3228         }
3229
3230         lnet_net_lock(LNET_LOCK_EX);
3231         lnet_peer_net_added(net);
3232         lnet_net_unlock(LNET_LOCK_EX);
3233
3234         lnet_ping_target_update(pbuf, ping_mdh);
3235
3236         return 0;
3237
3238 failed:
3239         lnet_ping_md_unlink(pbuf, &ping_mdh);
3240         lnet_ping_buffer_decref(pbuf);
3241         return rc;
3242 }
3243
3244 static void
3245 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3246 {
3247         if (tun) {
3248                 if (!tun->lt_cmn.lct_peer_timeout)
3249                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3250                 if (!tun->lt_cmn.lct_peer_tx_credits)
3251                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3252                 if (!tun->lt_cmn.lct_max_tx_credits)
3253                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3254         }
3255 }
3256
3257 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3258                                       struct lnet_ioctl_config_lnd_tunables *tun)
3259 {
3260         struct lnet_net *net;
3261         const char *nets;
3262         int rc;
3263         LIST_HEAD(net_head);
3264
3265         rc = lnet_parse_ip2nets(&nets, ip2nets);
3266         if (rc < 0)
3267                 return rc;
3268
3269         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3270         if (rc < 0)
3271                 return rc;
3272
3273         lnet_set_tune_defaults(tun);
3274
3275         mutex_lock(&the_lnet.ln_api_mutex);
3276         while (!list_empty(&net_head)) {
3277                 net = list_entry(net_head.next, struct lnet_net, net_list);
3278                 list_del_init(&net->net_list);
3279                 rc = lnet_add_net_common(net, tun);
3280                 if (rc < 0)
3281                         goto out;
3282         }
3283
3284 out:
3285         mutex_unlock(&the_lnet.ln_api_mutex);
3286
3287         while (!list_empty(&net_head)) {
3288                 net = list_entry(net_head.next, struct lnet_net, net_list);
3289                 list_del_init(&net->net_list);
3290                 lnet_net_free(net);
3291         }
3292         return rc;
3293 }
3294
3295 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3296 {
3297         struct lnet_net *net;
3298         struct lnet_ni *ni;
3299         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3300         int rc, i;
3301         __u32 net_id, lnd_type;
3302
3303         /* get the tunables if they are available */
3304         if (conf->lic_cfg_hdr.ioc_len >=
3305             sizeof(*conf) + sizeof(*tun))
3306                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3307                         conf->lic_bulk;
3308
3309         /* handle legacy ip2nets from DLC */
3310         if (conf->lic_legacy_ip2nets[0] != '\0')
3311                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3312                                                   tun);
3313
3314         net_id = LNET_NIDNET(conf->lic_nid);
3315         lnd_type = LNET_NETTYP(net_id);
3316
3317         if (!libcfs_isknown_lnd(lnd_type)) {
3318                 CERROR("No valid net and lnd information provided\n");
3319                 return -EINVAL;
3320         }
3321
3322         net = lnet_net_alloc(net_id, NULL);
3323         if (!net)
3324                 return -ENOMEM;
3325
3326         for (i = 0; i < conf->lic_ncpts; i++) {
3327                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3328                         return -EINVAL;
3329         }
3330
3331         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3332                                        conf->lic_ni_intf[0]);
3333         if (!ni)
3334                 return -ENOMEM;
3335
3336         lnet_set_tune_defaults(tun);
3337
3338         mutex_lock(&the_lnet.ln_api_mutex);
3339
3340         rc = lnet_add_net_common(net, tun);
3341
3342         mutex_unlock(&the_lnet.ln_api_mutex);
3343
3344         return rc;
3345 }
3346
3347 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3348 {
3349         struct lnet_net  *net;
3350         struct lnet_ni *ni;
3351         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3352         struct lnet_ping_buffer *pbuf;
3353         struct lnet_handle_md  ping_mdh;
3354         int               rc;
3355         int               net_count;
3356         __u32             addr;
3357
3358         /* don't allow userspace to shutdown the LOLND */
3359         if (LNET_NETTYP(net_id) == LOLND)
3360                 return -EINVAL;
3361
3362         mutex_lock(&the_lnet.ln_api_mutex);
3363
3364         lnet_net_lock(0);
3365
3366         net = lnet_get_net_locked(net_id);
3367         if (!net) {
3368                 CERROR("net %s not found\n",
3369                        libcfs_net2str(net_id));
3370                 rc = -ENOENT;
3371                 goto unlock_net;
3372         }
3373
3374         addr = LNET_NIDADDR(conf->lic_nid);
3375         if (addr == 0) {
3376                 /* remove the entire net */
3377                 net_count = lnet_get_net_ni_count_locked(net);
3378
3379                 lnet_net_unlock(0);
3380
3381                 /* create and link a new ping info, before removing the old one */
3382                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3383                                         lnet_get_ni_count() - net_count,
3384                                         false);
3385                 if (rc != 0)
3386                         goto unlock_api_mutex;
3387
3388                 lnet_shutdown_lndnet(net);
3389
3390                 lnet_acceptor_stop();
3391
3392                 lnet_ping_target_update(pbuf, ping_mdh);
3393
3394                 goto unlock_api_mutex;
3395         }
3396
3397         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3398         if (!ni) {
3399                 CERROR("nid %s not found\n",
3400                        libcfs_nid2str(conf->lic_nid));
3401                 rc = -ENOENT;
3402                 goto unlock_net;
3403         }
3404
3405         net_count = lnet_get_net_ni_count_locked(net);
3406
3407         lnet_net_unlock(0);
3408
3409         /* create and link a new ping info, before removing the old one */
3410         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3411                                   lnet_get_ni_count() - 1, false);
3412         if (rc != 0)
3413                 goto unlock_api_mutex;
3414
3415         lnet_shutdown_lndni(ni);
3416
3417         lnet_acceptor_stop();
3418
3419         lnet_ping_target_update(pbuf, ping_mdh);
3420
3421         /* check if the net is empty and remove it if it is */
3422         if (net_count == 1)
3423                 lnet_shutdown_lndnet(net);
3424
3425         goto unlock_api_mutex;
3426
3427 unlock_net:
3428         lnet_net_unlock(0);
3429 unlock_api_mutex:
3430         mutex_unlock(&the_lnet.ln_api_mutex);
3431
3432         return rc;
3433 }
3434
3435 /*
3436  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3437  * They are only expected to be called for unique networks.
3438  * That can be as a result of older DLC library
3439  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3440  */
3441 int
3442 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3443 {
3444         struct lnet_net *net;
3445         LIST_HEAD(net_head);
3446         int rc;
3447         struct lnet_ioctl_config_lnd_tunables tun;
3448         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3449
3450         /* Create a net/ni structures for the network string */
3451         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3452         if (rc <= 0)
3453                 return rc == 0 ? -EINVAL : rc;
3454
3455         mutex_lock(&the_lnet.ln_api_mutex);
3456
3457         if (rc > 1) {
3458                 rc = -EINVAL; /* only add one network per call */
3459                 goto out_unlock_clean;
3460         }
3461
3462         net = list_entry(net_head.next, struct lnet_net, net_list);
3463         list_del_init(&net->net_list);
3464
3465         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3466
3467         memset(&tun, 0, sizeof(tun));
3468
3469         tun.lt_cmn.lct_peer_timeout =
3470           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3471                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3472         tun.lt_cmn.lct_peer_tx_credits =
3473           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3474                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3475         tun.lt_cmn.lct_peer_rtr_credits =
3476           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3477         tun.lt_cmn.lct_max_tx_credits =
3478           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3479                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3480
3481         rc = lnet_add_net_common(net, &tun);
3482
3483 out_unlock_clean:
3484         mutex_unlock(&the_lnet.ln_api_mutex);
3485         while (!list_empty(&net_head)) {
3486                 /* net_head list is empty in success case */
3487                 net = list_entry(net_head.next, struct lnet_net, net_list);
3488                 list_del_init(&net->net_list);
3489                 lnet_net_free(net);
3490         }
3491         return rc;
3492 }
3493
3494 int
3495 lnet_dyn_del_net(__u32 net_id)
3496 {
3497         struct lnet_net  *net;
3498         struct lnet_ping_buffer *pbuf;
3499         struct lnet_handle_md ping_mdh;
3500         int               rc;
3501         int               net_ni_count;
3502
3503         /* don't allow userspace to shutdown the LOLND */
3504         if (LNET_NETTYP(net_id) == LOLND)
3505                 return -EINVAL;
3506
3507         mutex_lock(&the_lnet.ln_api_mutex);
3508
3509         lnet_net_lock(0);
3510
3511         net = lnet_get_net_locked(net_id);
3512         if (net == NULL) {
3513                 lnet_net_unlock(0);
3514                 rc = -EINVAL;
3515                 goto out;
3516         }
3517
3518         net_ni_count = lnet_get_net_ni_count_locked(net);
3519
3520         lnet_net_unlock(0);
3521
3522         /* create and link a new ping info, before removing the old one */
3523         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,