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