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