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