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