Whamcloud - gitweb
e3aa9bf3faaa3b01bc149861123e05aaa00ebbfd
[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         lnd->lnd_refcount = 0;
832
833         CDEBUG(D_NET, "%s LND registered\n", libcfs_lnd2str(lnd->lnd_type));
834
835         mutex_unlock(&the_lnet.ln_lnd_mutex);
836 }
837 EXPORT_SYMBOL(lnet_register_lnd);
838
839 void
840 lnet_unregister_lnd(struct lnet_lnd *lnd)
841 {
842         mutex_lock(&the_lnet.ln_lnd_mutex);
843
844         LASSERT(lnet_find_lnd_by_type(lnd->lnd_type) == lnd);
845         LASSERT(lnd->lnd_refcount == 0);
846
847         list_del(&lnd->lnd_list);
848         CDEBUG(D_NET, "%s LND unregistered\n", libcfs_lnd2str(lnd->lnd_type));
849
850         mutex_unlock(&the_lnet.ln_lnd_mutex);
851 }
852 EXPORT_SYMBOL(lnet_unregister_lnd);
853
854 void
855 lnet_counters_get_common(struct lnet_counters_common *common)
856 {
857         struct lnet_counters *ctr;
858         int i;
859
860         memset(common, 0, sizeof(*common));
861
862         lnet_net_lock(LNET_LOCK_EX);
863
864         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
865                 common->lcc_msgs_max     += ctr->lct_common.lcc_msgs_max;
866                 common->lcc_msgs_alloc   += ctr->lct_common.lcc_msgs_alloc;
867                 common->lcc_errors       += ctr->lct_common.lcc_errors;
868                 common->lcc_send_count   += ctr->lct_common.lcc_send_count;
869                 common->lcc_recv_count   += ctr->lct_common.lcc_recv_count;
870                 common->lcc_route_count  += ctr->lct_common.lcc_route_count;
871                 common->lcc_drop_count   += ctr->lct_common.lcc_drop_count;
872                 common->lcc_send_length  += ctr->lct_common.lcc_send_length;
873                 common->lcc_recv_length  += ctr->lct_common.lcc_recv_length;
874                 common->lcc_route_length += ctr->lct_common.lcc_route_length;
875                 common->lcc_drop_length  += ctr->lct_common.lcc_drop_length;
876         }
877         lnet_net_unlock(LNET_LOCK_EX);
878 }
879 EXPORT_SYMBOL(lnet_counters_get_common);
880
881 void
882 lnet_counters_get(struct lnet_counters *counters)
883 {
884         struct lnet_counters *ctr;
885         struct lnet_counters_health *health = &counters->lct_health;
886         int             i;
887
888         memset(counters, 0, sizeof(*counters));
889
890         lnet_counters_get_common(&counters->lct_common);
891
892         lnet_net_lock(LNET_LOCK_EX);
893
894         cfs_percpt_for_each(ctr, i, the_lnet.ln_counters) {
895                 health->lch_rst_alloc    += ctr->lct_health.lch_rst_alloc;
896                 health->lch_resend_count += ctr->lct_health.lch_resend_count;
897                 health->lch_response_timeout_count +=
898                                 ctr->lct_health.lch_response_timeout_count;
899                 health->lch_local_interrupt_count +=
900                                 ctr->lct_health.lch_local_interrupt_count;
901                 health->lch_local_dropped_count +=
902                                 ctr->lct_health.lch_local_dropped_count;
903                 health->lch_local_aborted_count +=
904                                 ctr->lct_health.lch_local_aborted_count;
905                 health->lch_local_no_route_count +=
906                                 ctr->lct_health.lch_local_no_route_count;
907                 health->lch_local_timeout_count +=
908                                 ctr->lct_health.lch_local_timeout_count;
909                 health->lch_local_error_count +=
910                                 ctr->lct_health.lch_local_error_count;
911                 health->lch_remote_dropped_count +=
912                                 ctr->lct_health.lch_remote_dropped_count;
913                 health->lch_remote_error_count +=
914                                 ctr->lct_health.lch_remote_error_count;
915                 health->lch_remote_timeout_count +=
916                                 ctr->lct_health.lch_remote_timeout_count;
917                 health->lch_network_timeout_count +=
918                                 ctr->lct_health.lch_network_timeout_count;
919         }
920         lnet_net_unlock(LNET_LOCK_EX);
921 }
922 EXPORT_SYMBOL(lnet_counters_get);
923
924 void
925 lnet_counters_reset(void)
926 {
927         struct lnet_counters *counters;
928         int             i;
929
930         lnet_net_lock(LNET_LOCK_EX);
931
932         cfs_percpt_for_each(counters, i, the_lnet.ln_counters)
933                 memset(counters, 0, sizeof(struct lnet_counters));
934
935         lnet_net_unlock(LNET_LOCK_EX);
936 }
937
938 static char *
939 lnet_res_type2str(int type)
940 {
941         switch (type) {
942         default:
943                 LBUG();
944         case LNET_COOKIE_TYPE_MD:
945                 return "MD";
946         case LNET_COOKIE_TYPE_ME:
947                 return "ME";
948         case LNET_COOKIE_TYPE_EQ:
949                 return "EQ";
950         }
951 }
952
953 static void
954 lnet_res_container_cleanup(struct lnet_res_container *rec)
955 {
956         int     count = 0;
957
958         if (rec->rec_type == 0) /* not set yet, it's uninitialized */
959                 return;
960
961         while (!list_empty(&rec->rec_active)) {
962                 struct list_head *e = rec->rec_active.next;
963
964                 list_del_init(e);
965                 if (rec->rec_type == LNET_COOKIE_TYPE_EQ) {
966                         lnet_eq_free(list_entry(e, struct lnet_eq, eq_list));
967
968                 } else if (rec->rec_type == LNET_COOKIE_TYPE_MD) {
969                         lnet_md_free(list_entry(e, struct lnet_libmd, md_list));
970
971                 } else { /* NB: Active MEs should be attached on portals */
972                         LBUG();
973                 }
974                 count++;
975         }
976
977         if (count > 0) {
978                 /* Found alive MD/ME/EQ, user really should unlink/free
979                  * all of them before finalize LNet, but if someone didn't,
980                  * we have to recycle garbage for him */
981                 CERROR("%d active elements on exit of %s container\n",
982                        count, lnet_res_type2str(rec->rec_type));
983         }
984
985         if (rec->rec_lh_hash != NULL) {
986                 LIBCFS_FREE(rec->rec_lh_hash,
987                             LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
988                 rec->rec_lh_hash = NULL;
989         }
990
991         rec->rec_type = 0; /* mark it as finalized */
992 }
993
994 static int
995 lnet_res_container_setup(struct lnet_res_container *rec, int cpt, int type)
996 {
997         int     rc = 0;
998         int     i;
999
1000         LASSERT(rec->rec_type == 0);
1001
1002         rec->rec_type = type;
1003         INIT_LIST_HEAD(&rec->rec_active);
1004
1005         rec->rec_lh_cookie = (cpt << LNET_COOKIE_TYPE_BITS) | type;
1006
1007         /* Arbitrary choice of hash table size */
1008         LIBCFS_CPT_ALLOC(rec->rec_lh_hash, lnet_cpt_table(), cpt,
1009                          LNET_LH_HASH_SIZE * sizeof(rec->rec_lh_hash[0]));
1010         if (rec->rec_lh_hash == NULL) {
1011                 rc = -ENOMEM;
1012                 goto out;
1013         }
1014
1015         for (i = 0; i < LNET_LH_HASH_SIZE; i++)
1016                 INIT_LIST_HEAD(&rec->rec_lh_hash[i]);
1017
1018         return 0;
1019
1020 out:
1021         CERROR("Failed to setup %s resource container\n",
1022                lnet_res_type2str(type));
1023         lnet_res_container_cleanup(rec);
1024         return rc;
1025 }
1026
1027 static void
1028 lnet_res_containers_destroy(struct lnet_res_container **recs)
1029 {
1030         struct lnet_res_container       *rec;
1031         int                             i;
1032
1033         cfs_percpt_for_each(rec, i, recs)
1034                 lnet_res_container_cleanup(rec);
1035
1036         cfs_percpt_free(recs);
1037 }
1038
1039 static struct lnet_res_container **
1040 lnet_res_containers_create(int type)
1041 {
1042         struct lnet_res_container       **recs;
1043         struct lnet_res_container       *rec;
1044         int                             rc;
1045         int                             i;
1046
1047         recs = cfs_percpt_alloc(lnet_cpt_table(), sizeof(*rec));
1048         if (recs == NULL) {
1049                 CERROR("Failed to allocate %s resource containers\n",
1050                        lnet_res_type2str(type));
1051                 return NULL;
1052         }
1053
1054         cfs_percpt_for_each(rec, i, recs) {
1055                 rc = lnet_res_container_setup(rec, i, type);
1056                 if (rc != 0) {
1057                         lnet_res_containers_destroy(recs);
1058                         return NULL;
1059                 }
1060         }
1061
1062         return recs;
1063 }
1064
1065 struct lnet_libhandle *
1066 lnet_res_lh_lookup(struct lnet_res_container *rec, __u64 cookie)
1067 {
1068         /* ALWAYS called with lnet_res_lock held */
1069         struct list_head        *head;
1070         struct lnet_libhandle   *lh;
1071         unsigned int            hash;
1072
1073         if ((cookie & LNET_COOKIE_MASK) != rec->rec_type)
1074                 return NULL;
1075
1076         hash = cookie >> (LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS);
1077         head = &rec->rec_lh_hash[hash & LNET_LH_HASH_MASK];
1078
1079         list_for_each_entry(lh, head, lh_hash_chain) {
1080                 if (lh->lh_cookie == cookie)
1081                         return lh;
1082         }
1083
1084         return NULL;
1085 }
1086
1087 void
1088 lnet_res_lh_initialize(struct lnet_res_container *rec,
1089                        struct lnet_libhandle *lh)
1090 {
1091         /* ALWAYS called with lnet_res_lock held */
1092         unsigned int    ibits = LNET_COOKIE_TYPE_BITS + LNET_CPT_BITS;
1093         unsigned int    hash;
1094
1095         lh->lh_cookie = rec->rec_lh_cookie;
1096         rec->rec_lh_cookie += 1 << ibits;
1097
1098         hash = (lh->lh_cookie >> ibits) & LNET_LH_HASH_MASK;
1099
1100         list_add(&lh->lh_hash_chain, &rec->rec_lh_hash[hash]);
1101 }
1102
1103 struct list_head **
1104 lnet_create_array_of_queues(void)
1105 {
1106         struct list_head **qs;
1107         struct list_head *q;
1108         int i;
1109
1110         qs = cfs_percpt_alloc(lnet_cpt_table(),
1111                               sizeof(struct list_head));
1112         if (!qs) {
1113                 CERROR("Failed to allocate queues\n");
1114                 return NULL;
1115         }
1116
1117         cfs_percpt_for_each(q, i, qs)
1118                 INIT_LIST_HEAD(q);
1119
1120         return qs;
1121 }
1122
1123 static int lnet_unprepare(void);
1124
1125 static int
1126 lnet_prepare(lnet_pid_t requested_pid)
1127 {
1128         /* Prepare to bring up the network */
1129         struct lnet_res_container **recs;
1130         int                       rc = 0;
1131
1132         if (requested_pid == LNET_PID_ANY) {
1133                 /* Don't instantiate LNET just for me */
1134                 return -ENETDOWN;
1135         }
1136
1137         LASSERT(the_lnet.ln_refcount == 0);
1138
1139         the_lnet.ln_routing = 0;
1140
1141         LASSERT((requested_pid & LNET_PID_USERFLAG) == 0);
1142         the_lnet.ln_pid = requested_pid;
1143
1144         INIT_LIST_HEAD(&the_lnet.ln_test_peers);
1145         INIT_LIST_HEAD(&the_lnet.ln_remote_peer_ni_list);
1146         INIT_LIST_HEAD(&the_lnet.ln_nets);
1147         INIT_LIST_HEAD(&the_lnet.ln_routers);
1148         INIT_LIST_HEAD(&the_lnet.ln_drop_rules);
1149         INIT_LIST_HEAD(&the_lnet.ln_delay_rules);
1150         INIT_LIST_HEAD(&the_lnet.ln_dc_request);
1151         INIT_LIST_HEAD(&the_lnet.ln_dc_working);
1152         INIT_LIST_HEAD(&the_lnet.ln_dc_expired);
1153         INIT_LIST_HEAD(&the_lnet.ln_mt_localNIRecovq);
1154         INIT_LIST_HEAD(&the_lnet.ln_mt_peerNIRecovq);
1155         init_waitqueue_head(&the_lnet.ln_dc_waitq);
1156         LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
1157         init_completion(&the_lnet.ln_started);
1158
1159         rc = lnet_descriptor_setup();
1160         if (rc != 0)
1161                 goto failed;
1162
1163         rc = lnet_create_remote_nets_table();
1164         if (rc != 0)
1165                 goto failed;
1166
1167         /*
1168          * NB the interface cookie in wire handles guards against delayed
1169          * replies and ACKs appearing valid after reboot.
1170          */
1171         the_lnet.ln_interface_cookie = ktime_get_real_ns();
1172
1173         the_lnet.ln_counters = cfs_percpt_alloc(lnet_cpt_table(),
1174                                                 sizeof(struct lnet_counters));
1175         if (the_lnet.ln_counters == NULL) {
1176                 CERROR("Failed to allocate counters for LNet\n");
1177                 rc = -ENOMEM;
1178                 goto failed;
1179         }
1180
1181         rc = lnet_peer_tables_create();
1182         if (rc != 0)
1183                 goto failed;
1184
1185         rc = lnet_msg_containers_create();
1186         if (rc != 0)
1187                 goto failed;
1188
1189         rc = lnet_res_container_setup(&the_lnet.ln_eq_container, 0,
1190                                       LNET_COOKIE_TYPE_EQ);
1191         if (rc != 0)
1192                 goto failed;
1193
1194         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_ME);
1195         if (recs == NULL) {
1196                 rc = -ENOMEM;
1197                 goto failed;
1198         }
1199
1200         the_lnet.ln_me_containers = recs;
1201
1202         recs = lnet_res_containers_create(LNET_COOKIE_TYPE_MD);
1203         if (recs == NULL) {
1204                 rc = -ENOMEM;
1205                 goto failed;
1206         }
1207
1208         the_lnet.ln_md_containers = recs;
1209
1210         rc = lnet_portals_create();
1211         if (rc != 0) {
1212                 CERROR("Failed to create portals for LNet: %d\n", rc);
1213                 goto failed;
1214         }
1215
1216         the_lnet.ln_mt_zombie_rstqs = lnet_create_array_of_queues();
1217         if (!the_lnet.ln_mt_zombie_rstqs) {
1218                 rc = -ENOMEM;
1219                 goto failed;
1220         }
1221
1222         return 0;
1223
1224  failed:
1225         lnet_unprepare();
1226         return rc;
1227 }
1228
1229 static int
1230 lnet_unprepare (void)
1231 {
1232         int rc;
1233
1234         /* NB no LNET_LOCK since this is the last reference.  All LND instances
1235          * have shut down already, so it is safe to unlink and free all
1236          * descriptors, even those that appear committed to a network op (eg MD
1237          * with non-zero pending count) */
1238
1239         lnet_fail_nid(LNET_NID_ANY, 0);
1240
1241         LASSERT(the_lnet.ln_refcount == 0);
1242         LASSERT(list_empty(&the_lnet.ln_test_peers));
1243         LASSERT(list_empty(&the_lnet.ln_nets));
1244
1245         if (the_lnet.ln_mt_zombie_rstqs) {
1246                 lnet_clean_zombie_rstqs();
1247                 the_lnet.ln_mt_zombie_rstqs = NULL;
1248         }
1249
1250         if (!LNetEQHandleIsInvalid(the_lnet.ln_mt_eqh)) {
1251                 rc = LNetEQFree(the_lnet.ln_mt_eqh);
1252                 LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
1253                 LASSERT(rc == 0);
1254         }
1255
1256         lnet_portals_destroy();
1257
1258         if (the_lnet.ln_md_containers != NULL) {
1259                 lnet_res_containers_destroy(the_lnet.ln_md_containers);
1260                 the_lnet.ln_md_containers = NULL;
1261         }
1262
1263         if (the_lnet.ln_me_containers != NULL) {
1264                 lnet_res_containers_destroy(the_lnet.ln_me_containers);
1265                 the_lnet.ln_me_containers = NULL;
1266         }
1267
1268         lnet_res_container_cleanup(&the_lnet.ln_eq_container);
1269
1270         lnet_msg_containers_destroy();
1271         lnet_peer_uninit();
1272         lnet_rtrpools_free(0);
1273
1274         if (the_lnet.ln_counters != NULL) {
1275                 cfs_percpt_free(the_lnet.ln_counters);
1276                 the_lnet.ln_counters = NULL;
1277         }
1278         lnet_destroy_remote_nets_table();
1279         lnet_descriptor_cleanup();
1280
1281         return 0;
1282 }
1283
1284 struct lnet_ni  *
1285 lnet_net2ni_locked(__u32 net_id, int cpt)
1286 {
1287         struct lnet_ni   *ni;
1288         struct lnet_net  *net;
1289
1290         LASSERT(cpt != LNET_LOCK_EX);
1291
1292         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1293                 if (net->net_id == net_id) {
1294                         ni = list_entry(net->net_ni_list.next, struct lnet_ni,
1295                                         ni_netlist);
1296                         return ni;
1297                 }
1298         }
1299
1300         return NULL;
1301 }
1302
1303 struct lnet_ni *
1304 lnet_net2ni_addref(__u32 net)
1305 {
1306         struct lnet_ni *ni;
1307
1308         lnet_net_lock(0);
1309         ni = lnet_net2ni_locked(net, 0);
1310         if (ni)
1311                 lnet_ni_addref_locked(ni, 0);
1312         lnet_net_unlock(0);
1313
1314         return ni;
1315 }
1316 EXPORT_SYMBOL(lnet_net2ni_addref);
1317
1318 struct lnet_net *
1319 lnet_get_net_locked(__u32 net_id)
1320 {
1321         struct lnet_net  *net;
1322
1323         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1324                 if (net->net_id == net_id)
1325                         return net;
1326         }
1327
1328         return NULL;
1329 }
1330
1331 unsigned int
1332 lnet_nid_cpt_hash(lnet_nid_t nid, unsigned int number)
1333 {
1334         __u64           key = nid;
1335         unsigned int    val;
1336
1337         LASSERT(number >= 1 && number <= LNET_CPT_NUMBER);
1338
1339         if (number == 1)
1340                 return 0;
1341
1342         val = hash_long(key, LNET_CPT_BITS);
1343         /* NB: LNET_CP_NUMBER doesn't have to be PO2 */
1344         if (val < number)
1345                 return val;
1346
1347         return (unsigned int)(key + val + (val >> 1)) % number;
1348 }
1349
1350 int
1351 lnet_cpt_of_nid_locked(lnet_nid_t nid, struct lnet_ni *ni)
1352 {
1353         struct lnet_net *net;
1354
1355         /* must called with hold of lnet_net_lock */
1356         if (LNET_CPT_NUMBER == 1)
1357                 return 0; /* the only one */
1358
1359         /*
1360          * If NI is provided then use the CPT identified in the NI cpt
1361          * list if one exists. If one doesn't exist, then that NI is
1362          * associated with all CPTs and it follows that the net it belongs
1363          * to is implicitly associated with all CPTs, so just hash the nid
1364          * and return that.
1365          */
1366         if (ni != NULL) {
1367                 if (ni->ni_cpts != NULL)
1368                         return ni->ni_cpts[lnet_nid_cpt_hash(nid,
1369                                                              ni->ni_ncpts)];
1370                 else
1371                         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1372         }
1373
1374         /* no NI provided so look at the net */
1375         net = lnet_get_net_locked(LNET_NIDNET(nid));
1376
1377         if (net != NULL && net->net_cpts != NULL) {
1378                 return net->net_cpts[lnet_nid_cpt_hash(nid, net->net_ncpts)];
1379         }
1380
1381         return lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
1382 }
1383
1384 int
1385 lnet_cpt_of_nid(lnet_nid_t nid, struct lnet_ni *ni)
1386 {
1387         int     cpt;
1388         int     cpt2;
1389
1390         if (LNET_CPT_NUMBER == 1)
1391                 return 0; /* the only one */
1392
1393         cpt = lnet_net_lock_current();
1394
1395         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1396
1397         lnet_net_unlock(cpt);
1398
1399         return cpt2;
1400 }
1401 EXPORT_SYMBOL(lnet_cpt_of_nid);
1402
1403 int
1404 lnet_islocalnet_locked(__u32 net_id)
1405 {
1406         struct lnet_net *net;
1407         bool local;
1408
1409         net = lnet_get_net_locked(net_id);
1410
1411         local = net != NULL;
1412
1413         return local;
1414 }
1415
1416 int
1417 lnet_islocalnet(__u32 net_id)
1418 {
1419         int cpt;
1420         bool local;
1421
1422         cpt = lnet_net_lock_current();
1423
1424         local = lnet_islocalnet_locked(net_id);
1425
1426         lnet_net_unlock(cpt);
1427
1428         return local;
1429 }
1430
1431 struct lnet_ni  *
1432 lnet_nid2ni_locked(lnet_nid_t nid, int cpt)
1433 {
1434         struct lnet_net  *net;
1435         struct lnet_ni   *ni;
1436
1437         LASSERT(cpt != LNET_LOCK_EX);
1438
1439         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1440                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1441                         if (ni->ni_nid == nid)
1442                                 return ni;
1443                 }
1444         }
1445
1446         return NULL;
1447 }
1448
1449 struct lnet_ni *
1450 lnet_nid2ni_addref(lnet_nid_t nid)
1451 {
1452         struct lnet_ni *ni;
1453
1454         lnet_net_lock(0);
1455         ni = lnet_nid2ni_locked(nid, 0);
1456         if (ni)
1457                 lnet_ni_addref_locked(ni, 0);
1458         lnet_net_unlock(0);
1459
1460         return ni;
1461 }
1462 EXPORT_SYMBOL(lnet_nid2ni_addref);
1463
1464 int
1465 lnet_islocalnid(lnet_nid_t nid)
1466 {
1467         struct lnet_ni  *ni;
1468         int             cpt;
1469
1470         cpt = lnet_net_lock_current();
1471         ni = lnet_nid2ni_locked(nid, cpt);
1472         lnet_net_unlock(cpt);
1473
1474         return ni != NULL;
1475 }
1476
1477 int
1478 lnet_count_acceptor_nets(void)
1479 {
1480         /* Return the # of NIs that need the acceptor. */
1481         int              count = 0;
1482         struct lnet_net  *net;
1483         int              cpt;
1484
1485         cpt = lnet_net_lock_current();
1486         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1487                 /* all socklnd type networks should have the acceptor
1488                  * thread started */
1489                 if (net->net_lnd->lnd_accept != NULL)
1490                         count++;
1491         }
1492
1493         lnet_net_unlock(cpt);
1494
1495         return count;
1496 }
1497
1498 struct lnet_ping_buffer *
1499 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1500 {
1501         struct lnet_ping_buffer *pbuf;
1502
1503         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1504         if (pbuf) {
1505                 pbuf->pb_nnis = nnis;
1506                 atomic_set(&pbuf->pb_refcnt, 1);
1507         }
1508
1509         return pbuf;
1510 }
1511
1512 void
1513 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1514 {
1515         LASSERT(lnet_ping_buffer_numref(pbuf) == 0);
1516         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1517 }
1518
1519 static struct lnet_ping_buffer *
1520 lnet_ping_target_create(int nnis)
1521 {
1522         struct lnet_ping_buffer *pbuf;
1523
1524         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1525         if (pbuf == NULL) {
1526                 CERROR("Can't allocate ping source [%d]\n", nnis);
1527                 return NULL;
1528         }
1529
1530         pbuf->pb_info.pi_nnis = nnis;
1531         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1532         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1533         pbuf->pb_info.pi_features =
1534                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1535
1536         return pbuf;
1537 }
1538
1539 static inline int
1540 lnet_get_net_ni_count_locked(struct lnet_net *net)
1541 {
1542         struct lnet_ni  *ni;
1543         int             count = 0;
1544
1545         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1546                 count++;
1547
1548         return count;
1549 }
1550
1551 static inline int
1552 lnet_get_net_ni_count_pre(struct lnet_net *net)
1553 {
1554         struct lnet_ni  *ni;
1555         int             count = 0;
1556
1557         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1558                 count++;
1559
1560         return count;
1561 }
1562
1563 static inline int
1564 lnet_get_ni_count(void)
1565 {
1566         struct lnet_ni  *ni;
1567         struct lnet_net *net;
1568         int             count = 0;
1569
1570         lnet_net_lock(0);
1571
1572         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1573                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1574                         count++;
1575         }
1576
1577         lnet_net_unlock(0);
1578
1579         return count;
1580 }
1581
1582 int
1583 lnet_get_net_count(void)
1584 {
1585         struct lnet_net *net;
1586         int count = 0;
1587
1588         lnet_net_lock(0);
1589
1590         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1591                 count++;
1592         }
1593
1594         lnet_net_unlock(0);
1595
1596         return count;
1597 }
1598
1599 void
1600 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1601 {
1602         struct lnet_ni_status *stat;
1603         int nnis;
1604         int i;
1605
1606         __swab32s(&pbuf->pb_info.pi_magic);
1607         __swab32s(&pbuf->pb_info.pi_features);
1608         __swab32s(&pbuf->pb_info.pi_pid);
1609         __swab32s(&pbuf->pb_info.pi_nnis);
1610         nnis = pbuf->pb_info.pi_nnis;
1611         if (nnis > pbuf->pb_nnis)
1612                 nnis = pbuf->pb_nnis;
1613         for (i = 0; i < nnis; i++) {
1614                 stat = &pbuf->pb_info.pi_ni[i];
1615                 __swab64s(&stat->ns_nid);
1616                 __swab32s(&stat->ns_status);
1617         }
1618 }
1619
1620 int
1621 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1622 {
1623         if (!pinfo)
1624                 return -EINVAL;
1625         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1626                 return -EPROTO;
1627         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1628                 return -EPROTO;
1629         /* Loopback is guaranteed to be present */
1630         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1631                 return -ERANGE;
1632         if (LNET_NETTYP(LNET_NIDNET(LNET_PING_INFO_LONI(pinfo))) != LOLND)
1633                 return -EPROTO;
1634         return 0;
1635 }
1636
1637 static void
1638 lnet_ping_target_destroy(void)
1639 {
1640         struct lnet_net *net;
1641         struct lnet_ni  *ni;
1642
1643         lnet_net_lock(LNET_LOCK_EX);
1644
1645         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1646                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1647                         lnet_ni_lock(ni);
1648                         ni->ni_status = NULL;
1649                         lnet_ni_unlock(ni);
1650                 }
1651         }
1652
1653         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1654         the_lnet.ln_ping_target = NULL;
1655
1656         lnet_net_unlock(LNET_LOCK_EX);
1657 }
1658
1659 static void
1660 lnet_ping_target_event_handler(struct lnet_event *event)
1661 {
1662         struct lnet_ping_buffer *pbuf = event->md.user_ptr;
1663
1664         if (event->unlinked)
1665                 lnet_ping_buffer_decref(pbuf);
1666 }
1667
1668 static int
1669 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1670                        struct lnet_handle_md *ping_mdh,
1671                        int ni_count, bool set_eq)
1672 {
1673         struct lnet_process_id id = {
1674                 .nid = LNET_NID_ANY,
1675                 .pid = LNET_PID_ANY
1676         };
1677         struct lnet_handle_me me_handle;
1678         struct lnet_md md = { NULL };
1679         int rc, rc2;
1680
1681         if (set_eq) {
1682                 rc = LNetEQAlloc(0, lnet_ping_target_event_handler,
1683                                  &the_lnet.ln_ping_target_eq);
1684                 if (rc != 0) {
1685                         CERROR("Can't allocate ping buffer EQ: %d\n", rc);
1686                         return rc;
1687                 }
1688         }
1689
1690         *ppbuf = lnet_ping_target_create(ni_count);
1691         if (*ppbuf == NULL) {
1692                 rc = -ENOMEM;
1693                 goto fail_free_eq;
1694         }
1695
1696         /* Ping target ME/MD */
1697         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1698                           LNET_PROTO_PING_MATCHBITS, 0,
1699                           LNET_UNLINK, LNET_INS_AFTER,
1700                           &me_handle);
1701         if (rc != 0) {
1702                 CERROR("Can't create ping target ME: %d\n", rc);
1703                 goto fail_decref_ping_buffer;
1704         }
1705
1706         /* initialize md content */
1707         md.start     = &(*ppbuf)->pb_info;
1708         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1709         md.threshold = LNET_MD_THRESH_INF;
1710         md.max_size  = 0;
1711         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1712                        LNET_MD_MANAGE_REMOTE;
1713         md.eq_handle = the_lnet.ln_ping_target_eq;
1714         md.user_ptr  = *ppbuf;
1715
1716         rc = LNetMDAttach(me_handle, md, LNET_RETAIN, ping_mdh);
1717         if (rc != 0) {
1718                 CERROR("Can't attach ping target MD: %d\n", rc);
1719                 goto fail_unlink_ping_me;
1720         }
1721         lnet_ping_buffer_addref(*ppbuf);
1722
1723         return 0;
1724
1725 fail_unlink_ping_me:
1726         rc2 = LNetMEUnlink(me_handle);
1727         LASSERT(rc2 == 0);
1728 fail_decref_ping_buffer:
1729         LASSERT(lnet_ping_buffer_numref(*ppbuf) == 1);
1730         lnet_ping_buffer_decref(*ppbuf);
1731         *ppbuf = NULL;
1732 fail_free_eq:
1733         if (set_eq) {
1734                 rc2 = LNetEQFree(the_lnet.ln_ping_target_eq);
1735                 LASSERT(rc2 == 0);
1736         }
1737         return rc;
1738 }
1739
1740 static void
1741 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1742                     struct lnet_handle_md *ping_mdh)
1743 {
1744         sigset_t        blocked = cfs_block_allsigs();
1745
1746         LNetMDUnlink(*ping_mdh);
1747         LNetInvalidateMDHandle(ping_mdh);
1748
1749         /* NB the MD could be busy; this just starts the unlink */
1750         while (lnet_ping_buffer_numref(pbuf) > 1) {
1751                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1752                 set_current_state(TASK_UNINTERRUPTIBLE);
1753                 schedule_timeout(cfs_time_seconds(1));
1754         }
1755
1756         cfs_restore_sigs(blocked);
1757 }
1758
1759 static void
1760 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1761 {
1762         struct lnet_ni          *ni;
1763         struct lnet_net         *net;
1764         struct lnet_ni_status *ns;
1765         int                     i;
1766         int                     rc;
1767
1768         i = 0;
1769         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1770                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1771                         LASSERT(i < pbuf->pb_nnis);
1772
1773                         ns = &pbuf->pb_info.pi_ni[i];
1774
1775                         ns->ns_nid = ni->ni_nid;
1776
1777                         lnet_ni_lock(ni);
1778                         ns->ns_status = (ni->ni_status != NULL) ?
1779                                          ni->ni_status->ns_status :
1780                                                 LNET_NI_STATUS_UP;
1781                         ni->ni_status = ns;
1782                         lnet_ni_unlock(ni);
1783
1784                         i++;
1785                 }
1786         }
1787         /*
1788          * We (ab)use the ns_status of the loopback interface to
1789          * transmit the sequence number. The first interface listed
1790          * must be the loopback interface.
1791          */
1792         rc = lnet_ping_info_validate(&pbuf->pb_info);
1793         if (rc) {
1794                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
1795                 LBUG();
1796         }
1797         LNET_PING_BUFFER_SEQNO(pbuf) =
1798                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
1799 }
1800
1801 static void
1802 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
1803                         struct lnet_handle_md ping_mdh)
1804 {
1805         struct lnet_ping_buffer *old_pbuf = NULL;
1806         struct lnet_handle_md old_ping_md;
1807
1808         /* switch the NIs to point to the new ping info created */
1809         lnet_net_lock(LNET_LOCK_EX);
1810
1811         if (!the_lnet.ln_routing)
1812                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
1813         if (!lnet_peer_discovery_disabled)
1814                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
1815
1816         /* Ensure only known feature bits have been set. */
1817         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
1818         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
1819
1820         lnet_ping_target_install_locked(pbuf);
1821
1822         if (the_lnet.ln_ping_target) {
1823                 old_pbuf = the_lnet.ln_ping_target;
1824                 old_ping_md = the_lnet.ln_ping_target_md;
1825         }
1826         the_lnet.ln_ping_target_md = ping_mdh;
1827         the_lnet.ln_ping_target = pbuf;
1828
1829         lnet_net_unlock(LNET_LOCK_EX);
1830
1831         if (old_pbuf) {
1832                 /* unlink and free the old ping info */
1833                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
1834                 lnet_ping_buffer_decref(old_pbuf);
1835         }
1836
1837         lnet_push_update_to_peers(0);
1838 }
1839
1840 static void
1841 lnet_ping_target_fini(void)
1842 {
1843         int             rc;
1844
1845         lnet_ping_md_unlink(the_lnet.ln_ping_target,
1846                             &the_lnet.ln_ping_target_md);
1847
1848         rc = LNetEQFree(the_lnet.ln_ping_target_eq);
1849         LASSERT(rc == 0);
1850
1851         lnet_ping_target_destroy();
1852 }
1853
1854 /* Resize the push target. */
1855 int lnet_push_target_resize(void)
1856 {
1857         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
1858         struct lnet_md md = { NULL };
1859         struct lnet_handle_me meh;
1860         struct lnet_handle_md mdh;
1861         struct lnet_handle_md old_mdh;
1862         struct lnet_ping_buffer *pbuf;
1863         struct lnet_ping_buffer *old_pbuf;
1864         int nnis = the_lnet.ln_push_target_nnis;
1865         int rc;
1866
1867         if (nnis <= 0) {
1868                 rc = -EINVAL;
1869                 goto fail_return;
1870         }
1871 again:
1872         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1873         if (!pbuf) {
1874                 rc = -ENOMEM;
1875                 goto fail_return;
1876         }
1877
1878         rc = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1879                           LNET_PROTO_PING_MATCHBITS, 0,
1880                           LNET_UNLINK, LNET_INS_AFTER,
1881                           &meh);
1882         if (rc) {
1883                 CERROR("Can't create push target ME: %d\n", rc);
1884                 goto fail_decref_pbuf;
1885         }
1886
1887         /* initialize md content */
1888         md.start     = &pbuf->pb_info;
1889         md.length    = LNET_PING_INFO_SIZE(nnis);
1890         md.threshold = LNET_MD_THRESH_INF;
1891         md.max_size  = 0;
1892         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE |
1893                        LNET_MD_MANAGE_REMOTE;
1894         md.user_ptr  = pbuf;
1895         md.eq_handle = the_lnet.ln_push_target_eq;
1896
1897         rc = LNetMDAttach(meh, md, LNET_RETAIN, &mdh);
1898         if (rc) {
1899                 CERROR("Can't attach push MD: %d\n", rc);
1900                 goto fail_unlink_meh;
1901         }
1902         lnet_ping_buffer_addref(pbuf);
1903
1904         lnet_net_lock(LNET_LOCK_EX);
1905         old_pbuf = the_lnet.ln_push_target;
1906         old_mdh = the_lnet.ln_push_target_md;
1907         the_lnet.ln_push_target = pbuf;
1908         the_lnet.ln_push_target_md = mdh;
1909         lnet_net_unlock(LNET_LOCK_EX);
1910
1911         if (old_pbuf) {
1912                 LNetMDUnlink(old_mdh);
1913                 lnet_ping_buffer_decref(old_pbuf);
1914         }
1915
1916         if (nnis < the_lnet.ln_push_target_nnis)
1917                 goto again;
1918
1919         CDEBUG(D_NET, "nnis %d success\n", nnis);
1920
1921         return 0;
1922
1923 fail_unlink_meh:
1924         LNetMEUnlink(meh);
1925 fail_decref_pbuf:
1926         lnet_ping_buffer_decref(pbuf);
1927 fail_return:
1928         CDEBUG(D_NET, "nnis %d error %d\n", nnis, rc);
1929         return rc;
1930 }
1931
1932 static void lnet_push_target_event_handler(struct lnet_event *ev)
1933 {
1934         struct lnet_ping_buffer *pbuf = ev->md.user_ptr;
1935
1936         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
1937                 lnet_swap_pinginfo(pbuf);
1938
1939         lnet_peer_push_event(ev);
1940         if (ev->unlinked)
1941                 lnet_ping_buffer_decref(pbuf);
1942 }
1943
1944 /* Initialize the push target. */
1945 static int lnet_push_target_init(void)
1946 {
1947         int rc;
1948
1949         if (the_lnet.ln_push_target)
1950                 return -EALREADY;
1951
1952         rc = LNetEQAlloc(0, lnet_push_target_event_handler,
1953                          &the_lnet.ln_push_target_eq);
1954         if (rc) {
1955                 CERROR("Can't allocated push target EQ: %d\n", rc);
1956                 return rc;
1957         }
1958
1959         /* Start at the required minimum, we'll enlarge if required. */
1960         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
1961
1962         rc = lnet_push_target_resize();
1963
1964         if (rc) {
1965                 LNetEQFree(the_lnet.ln_push_target_eq);
1966                 LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1967         }
1968
1969         return rc;
1970 }
1971
1972 /* Clean up the push target. */
1973 static void lnet_push_target_fini(void)
1974 {
1975         if (!the_lnet.ln_push_target)
1976                 return;
1977
1978         /* Unlink and invalidate to prevent new references. */
1979         LNetMDUnlink(the_lnet.ln_push_target_md);
1980         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
1981
1982         /* Wait for the unlink to complete. */
1983         while (lnet_ping_buffer_numref(the_lnet.ln_push_target) > 1) {
1984                 CDEBUG(D_NET, "Still waiting for ping data MD to unlink\n");
1985                 set_current_state(TASK_UNINTERRUPTIBLE);
1986                 schedule_timeout(cfs_time_seconds(1));
1987         }
1988
1989         lnet_ping_buffer_decref(the_lnet.ln_push_target);
1990         the_lnet.ln_push_target = NULL;
1991         the_lnet.ln_push_target_nnis = 0;
1992
1993         LNetEQFree(the_lnet.ln_push_target_eq);
1994         LNetInvalidateEQHandle(&the_lnet.ln_push_target_eq);
1995 }
1996
1997 static int
1998 lnet_ni_tq_credits(struct lnet_ni *ni)
1999 {
2000         int     credits;
2001
2002         LASSERT(ni->ni_ncpts >= 1);
2003
2004         if (ni->ni_ncpts == 1)
2005                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2006
2007         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2008         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2009         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2010
2011         return credits;
2012 }
2013
2014 static void
2015 lnet_ni_unlink_locked(struct lnet_ni *ni)
2016 {
2017         /* move it to zombie list and nobody can find it anymore */
2018         LASSERT(!list_empty(&ni->ni_netlist));
2019         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2020         lnet_ni_decref_locked(ni, 0);
2021 }
2022
2023 static void
2024 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2025 {
2026         int             i;
2027         int             islo;
2028         struct lnet_ni  *ni;
2029         struct list_head *zombie_list = &net->net_ni_zombie;
2030
2031         /*
2032          * Now wait for the NIs I just nuked to show up on the zombie
2033          * list and shut them down in guaranteed thread context
2034          */
2035         i = 2;
2036         while (!list_empty(zombie_list)) {
2037                 int     *ref;
2038                 int     j;
2039
2040                 ni = list_entry(zombie_list->next,
2041                                 struct lnet_ni, ni_netlist);
2042                 list_del_init(&ni->ni_netlist);
2043                 /* the ni should be in deleting state. If it's not it's
2044                  * a bug */
2045                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2046                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2047                         if (*ref == 0)
2048                                 continue;
2049                         /* still busy, add it back to zombie list */
2050                         list_add(&ni->ni_netlist, zombie_list);
2051                         break;
2052                 }
2053
2054                 if (!list_empty(&ni->ni_netlist)) {
2055                         lnet_net_unlock(LNET_LOCK_EX);
2056                         ++i;
2057                         if ((i & (-i)) == i) {
2058                                 CDEBUG(D_WARNING,
2059                                        "Waiting for zombie LNI %s\n",
2060                                        libcfs_nid2str(ni->ni_nid));
2061                         }
2062                         set_current_state(TASK_UNINTERRUPTIBLE);
2063                         schedule_timeout(cfs_time_seconds(1));
2064                         lnet_net_lock(LNET_LOCK_EX);
2065                         continue;
2066                 }
2067
2068                 lnet_net_unlock(LNET_LOCK_EX);
2069
2070                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2071
2072                 LASSERT(!in_interrupt());
2073                 (net->net_lnd->lnd_shutdown)(ni);
2074
2075                 if (!islo)
2076                         CDEBUG(D_LNI, "Removed LNI %s\n",
2077                               libcfs_nid2str(ni->ni_nid));
2078
2079                 lnet_ni_free(ni);
2080                 i = 2;
2081                 lnet_net_lock(LNET_LOCK_EX);
2082         }
2083 }
2084
2085 /* shutdown down the NI and release refcount */
2086 static void
2087 lnet_shutdown_lndni(struct lnet_ni *ni)
2088 {
2089         int i;
2090         struct lnet_net *net = ni->ni_net;
2091
2092         lnet_net_lock(LNET_LOCK_EX);
2093         lnet_ni_lock(ni);
2094         ni->ni_state = LNET_NI_STATE_DELETING;
2095         lnet_ni_unlock(ni);
2096         lnet_ni_unlink_locked(ni);
2097         lnet_incr_dlc_seq();
2098         lnet_net_unlock(LNET_LOCK_EX);
2099
2100         /* clear messages for this NI on the lazy portal */
2101         for (i = 0; i < the_lnet.ln_nportals; i++)
2102                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2103
2104         lnet_net_lock(LNET_LOCK_EX);
2105         lnet_clear_zombies_nis_locked(net);
2106         lnet_net_unlock(LNET_LOCK_EX);
2107 }
2108
2109 static void
2110 lnet_shutdown_lndnet(struct lnet_net *net)
2111 {
2112         struct lnet_ni *ni;
2113
2114         lnet_net_lock(LNET_LOCK_EX);
2115
2116         list_del_init(&net->net_list);
2117
2118         while (!list_empty(&net->net_ni_list)) {
2119                 ni = list_entry(net->net_ni_list.next,
2120                                 struct lnet_ni, ni_netlist);
2121                 lnet_net_unlock(LNET_LOCK_EX);
2122                 lnet_shutdown_lndni(ni);
2123                 lnet_net_lock(LNET_LOCK_EX);
2124         }
2125
2126         lnet_net_unlock(LNET_LOCK_EX);
2127
2128         /* Do peer table cleanup for this net */
2129         lnet_peer_tables_cleanup(net);
2130
2131         lnet_net_lock(LNET_LOCK_EX);
2132         /*
2133          * decrement ref count on lnd only when the entire network goes
2134          * away
2135          */
2136         net->net_lnd->lnd_refcount--;
2137
2138         lnet_net_unlock(LNET_LOCK_EX);
2139
2140         lnet_net_free(net);
2141 }
2142
2143 static void
2144 lnet_shutdown_lndnets(void)
2145 {
2146         struct lnet_net *net;
2147         struct list_head resend;
2148         struct lnet_msg *msg, *tmp;
2149
2150         INIT_LIST_HEAD(&resend);
2151
2152         /* NB called holding the global mutex */
2153
2154         /* All quiet on the API front */
2155         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2156         LASSERT(the_lnet.ln_refcount == 0);
2157
2158         lnet_net_lock(LNET_LOCK_EX);
2159         the_lnet.ln_state = LNET_STATE_STOPPING;
2160
2161         while (!list_empty(&the_lnet.ln_nets)) {
2162                 /*
2163                  * move the nets to the zombie list to avoid them being
2164                  * picked up for new work. LONET is also included in the
2165                  * Nets that will be moved to the zombie list
2166                  */
2167                 net = list_entry(the_lnet.ln_nets.next,
2168                                  struct lnet_net, net_list);
2169                 list_move(&net->net_list, &the_lnet.ln_net_zombie);
2170         }
2171
2172         /* Drop the cached loopback Net. */
2173         if (the_lnet.ln_loni != NULL) {
2174                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2175                 the_lnet.ln_loni = NULL;
2176         }
2177         lnet_net_unlock(LNET_LOCK_EX);
2178
2179         /* iterate through the net zombie list and delete each net */
2180         while (!list_empty(&the_lnet.ln_net_zombie)) {
2181                 net = list_entry(the_lnet.ln_net_zombie.next,
2182                                  struct lnet_net, net_list);
2183                 lnet_shutdown_lndnet(net);
2184         }
2185
2186         spin_lock(&the_lnet.ln_msg_resend_lock);
2187         list_splice(&the_lnet.ln_msg_resend, &resend);
2188         spin_unlock(&the_lnet.ln_msg_resend_lock);
2189
2190         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2191                 list_del_init(&msg->msg_list);
2192                 msg->msg_no_resend = true;
2193                 lnet_finalize(msg, -ECANCELED);
2194         }
2195
2196         lnet_net_lock(LNET_LOCK_EX);
2197         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2198         lnet_net_unlock(LNET_LOCK_EX);
2199 }
2200
2201 static int
2202 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2203 {
2204         int                     rc = -EINVAL;
2205         struct lnet_tx_queue    *tq;
2206         int                     i;
2207         struct lnet_net         *net = ni->ni_net;
2208
2209         mutex_lock(&the_lnet.ln_lnd_mutex);
2210
2211         if (tun) {
2212                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2213                 ni->ni_lnd_tunables_set = true;
2214         }
2215
2216         rc = (net->net_lnd->lnd_startup)(ni);
2217
2218         mutex_unlock(&the_lnet.ln_lnd_mutex);
2219
2220         if (rc != 0) {
2221                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2222                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2223                 lnet_net_lock(LNET_LOCK_EX);
2224                 net->net_lnd->lnd_refcount--;
2225                 lnet_net_unlock(LNET_LOCK_EX);
2226                 goto failed0;
2227         }
2228
2229         lnet_ni_lock(ni);
2230         ni->ni_state = LNET_NI_STATE_ACTIVE;
2231         lnet_ni_unlock(ni);
2232
2233         /* We keep a reference on the loopback net through the loopback NI */
2234         if (net->net_lnd->lnd_type == LOLND) {
2235                 lnet_ni_addref(ni);
2236                 LASSERT(the_lnet.ln_loni == NULL);
2237                 the_lnet.ln_loni = ni;
2238                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2239                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2240                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2241                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2242                 return 0;
2243         }
2244
2245         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2246             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2247                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2248                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2249                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2250                                         "" : "per-peer ");
2251                 /* shutdown the NI since if we get here then it must've already
2252                  * been started
2253                  */
2254                 lnet_shutdown_lndni(ni);
2255                 return -EINVAL;
2256         }
2257
2258         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2259                 tq->tq_credits_min =
2260                 tq->tq_credits_max =
2261                 tq->tq_credits = lnet_ni_tq_credits(ni);
2262         }
2263
2264         atomic_set(&ni->ni_tx_credits,
2265                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2266         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2267
2268         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2269                 libcfs_nid2str(ni->ni_nid),
2270                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2271                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2272                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2273                 ni->ni_net->net_tunables.lct_peer_timeout);
2274
2275         return 0;
2276 failed0:
2277         lnet_ni_free(ni);
2278         return rc;
2279 }
2280
2281 static int
2282 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2283 {
2284         struct lnet_ni *ni;
2285         struct lnet_net *net_l = NULL;
2286         struct list_head        local_ni_list;
2287         int                     rc;
2288         int                     ni_count = 0;
2289         __u32                   lnd_type;
2290         struct lnet_lnd *lnd;
2291         int                     peer_timeout =
2292                 net->net_tunables.lct_peer_timeout;
2293         int                     maxtxcredits =
2294                 net->net_tunables.lct_max_tx_credits;
2295         int                     peerrtrcredits =
2296                 net->net_tunables.lct_peer_rtr_credits;
2297
2298         INIT_LIST_HEAD(&local_ni_list);
2299
2300         /*
2301          * make sure that this net is unique. If it isn't then
2302          * we are adding interfaces to an already existing network, and
2303          * 'net' is just a convenient way to pass in the list.
2304          * if it is unique we need to find the LND and load it if
2305          * necessary.
2306          */
2307         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2308                 lnd_type = LNET_NETTYP(net->net_id);
2309
2310                 mutex_lock(&the_lnet.ln_lnd_mutex);
2311                 lnd = lnet_find_lnd_by_type(lnd_type);
2312
2313                 if (lnd == NULL) {
2314                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2315                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2316                         mutex_lock(&the_lnet.ln_lnd_mutex);
2317
2318                         lnd = lnet_find_lnd_by_type(lnd_type);
2319                         if (lnd == NULL) {
2320                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2321                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2322                                 libcfs_lnd2str(lnd_type),
2323                                 libcfs_lnd2modname(lnd_type), rc);
2324 #ifndef HAVE_MODULE_LOADING_SUPPORT
2325                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2326                                                 "compiled with kernel module "
2327                                                 "loading support.");
2328 #endif
2329                                 rc = -EINVAL;
2330                                 goto failed0;
2331                         }
2332                 }
2333
2334                 lnet_net_lock(LNET_LOCK_EX);
2335                 lnd->lnd_refcount++;
2336                 lnet_net_unlock(LNET_LOCK_EX);
2337
2338                 net->net_lnd = lnd;
2339
2340                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2341
2342                 net_l = net;
2343         }
2344
2345         /*
2346          * net_l: if the network being added is unique then net_l
2347          *        will point to that network
2348          *        if the network being added is not unique then
2349          *        net_l points to the existing network.
2350          *
2351          * When we enter the loop below, we'll pick NIs off he
2352          * network beign added and start them up, then add them to
2353          * a local ni list. Once we've successfully started all
2354          * the NIs then we join the local NI list (of started up
2355          * networks) with the net_l->net_ni_list, which should
2356          * point to the correct network to add the new ni list to
2357          *
2358          * If any of the new NIs fail to start up, then we want to
2359          * iterate through the local ni list, which should include
2360          * any NIs which were successfully started up, and shut
2361          * them down.
2362          *
2363          * After than we want to delete the network being added,
2364          * to avoid a memory leak.
2365          */
2366
2367         /*
2368          * When a network uses TCP bonding then all its interfaces
2369          * must be specified when the network is first defined: the
2370          * TCP bonding code doesn't allow for interfaces to be added
2371          * or removed.
2372          */
2373         if (net_l != net && net_l != NULL && use_tcp_bonding &&
2374             LNET_NETTYP(net_l->net_id) == SOCKLND) {
2375                 rc = -EINVAL;
2376                 goto failed0;
2377         }
2378
2379         while (!list_empty(&net->net_ni_added)) {
2380                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2381                                 ni_netlist);
2382                 list_del_init(&ni->ni_netlist);
2383
2384                 /* make sure that the the NI we're about to start
2385                  * up is actually unique. if it's not fail. */
2386                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2387                                         ni->ni_interfaces[0])) {
2388                         rc = -EEXIST;
2389                         goto failed1;
2390                 }
2391
2392                 /* adjust the pointer the parent network, just in case it
2393                  * the net is a duplicate */
2394                 ni->ni_net = net_l;
2395
2396                 rc = lnet_startup_lndni(ni, tun);
2397
2398                 LASSERT(ni->ni_net->net_tunables.lct_peer_timeout <= 0 ||
2399                         ni->ni_net->net_lnd->lnd_query != NULL);
2400
2401                 if (rc < 0)
2402                         goto failed1;
2403
2404                 lnet_ni_addref(ni);
2405                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2406
2407                 ni_count++;
2408         }
2409
2410         lnet_net_lock(LNET_LOCK_EX);
2411         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2412         lnet_incr_dlc_seq();
2413         lnet_net_unlock(LNET_LOCK_EX);
2414
2415         /* if the network is not unique then we don't want to keep
2416          * it around after we're done. Free it. Otherwise add that
2417          * net to the global the_lnet.ln_nets */
2418         if (net_l != net && net_l != NULL) {
2419                 /*
2420                  * TODO - note. currently the tunables can not be updated
2421                  * once added
2422                  */
2423                 lnet_net_free(net);
2424         } else {
2425                 /*
2426                  * restore tunables after it has been overwitten by the
2427                  * lnd
2428                  */
2429                 if (peer_timeout != -1)
2430                         net->net_tunables.lct_peer_timeout = peer_timeout;
2431                 if (maxtxcredits != -1)
2432                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2433                 if (peerrtrcredits != -1)
2434                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2435
2436                 lnet_net_lock(LNET_LOCK_EX);
2437                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2438                 lnet_net_unlock(LNET_LOCK_EX);
2439         }
2440
2441         /* update net count */
2442         lnet_current_net_count = lnet_get_net_count();
2443
2444         return ni_count;
2445
2446 failed1:
2447         /*
2448          * shutdown the new NIs that are being started up
2449          * free the NET being started
2450          */
2451         while (!list_empty(&local_ni_list)) {
2452                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2453                                 ni_netlist);
2454
2455                 lnet_shutdown_lndni(ni);
2456         }
2457
2458 failed0:
2459         lnet_net_free(net);
2460
2461         return rc;
2462 }
2463
2464 static int
2465 lnet_startup_lndnets(struct list_head *netlist)
2466 {
2467         struct lnet_net         *net;
2468         int                     rc;
2469         int                     ni_count = 0;
2470
2471         /*
2472          * Change to running state before bringing up the LNDs. This
2473          * allows lnet_shutdown_lndnets() to assert that we've passed
2474          * through here.
2475          */
2476         lnet_net_lock(LNET_LOCK_EX);
2477         the_lnet.ln_state = LNET_STATE_RUNNING;
2478         lnet_net_unlock(LNET_LOCK_EX);
2479
2480         while (!list_empty(netlist)) {
2481                 net = list_entry(netlist->next, struct lnet_net, net_list);
2482                 list_del_init(&net->net_list);
2483
2484                 rc = lnet_startup_lndnet(net, NULL);
2485
2486                 if (rc < 0)
2487                         goto failed;
2488
2489                 ni_count += rc;
2490         }
2491
2492         return ni_count;
2493 failed:
2494         lnet_shutdown_lndnets();
2495
2496         return rc;
2497 }
2498
2499 /**
2500  * Initialize LNet library.
2501  *
2502  * Automatically called at module loading time. Caller has to call
2503  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2504  * latter returned 0. It must be called exactly once.
2505  *
2506  * \retval 0 on success
2507  * \retval -ve on failures.
2508  */
2509 int lnet_lib_init(void)
2510 {
2511         int rc;
2512
2513         lnet_assert_wire_constants();
2514
2515         /* refer to global cfs_cpt_table for now */
2516         the_lnet.ln_cpt_table   = cfs_cpt_table;
2517         the_lnet.ln_cpt_number  = cfs_cpt_number(cfs_cpt_table);
2518
2519         LASSERT(the_lnet.ln_cpt_number > 0);
2520         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2521                 /* we are under risk of consuming all lh_cookie */
2522                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2523                        "please change setting of CPT-table and retry\n",
2524                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2525                 return -E2BIG;
2526         }
2527
2528         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2529                 the_lnet.ln_cpt_bits++;
2530
2531         rc = lnet_create_locks();
2532         if (rc != 0) {
2533                 CERROR("Can't create LNet global locks: %d\n", rc);
2534                 return rc;
2535         }
2536
2537         the_lnet.ln_refcount = 0;
2538         INIT_LIST_HEAD(&the_lnet.ln_lnds);
2539         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2540         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2541
2542         /* The hash table size is the number of bits it takes to express the set
2543          * ln_num_routes, minus 1 (better to under estimate than over so we
2544          * don't waste memory). */
2545         if (rnet_htable_size <= 0)
2546                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2547         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2548                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2549         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2550                                            order_base_2(rnet_htable_size) - 1);
2551
2552         /* All LNDs apart from the LOLND are in separate modules.  They
2553          * register themselves when their module loads, and unregister
2554          * themselves when their module is unloaded. */
2555         lnet_register_lnd(&the_lolnd);
2556         return 0;
2557 }
2558
2559 /**
2560  * Finalize LNet library.
2561  *
2562  * \pre lnet_lib_init() called with success.
2563  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2564  */
2565 void lnet_lib_exit(void)
2566 {
2567         LASSERT(the_lnet.ln_refcount == 0);
2568
2569         while (!list_empty(&the_lnet.ln_lnds))
2570                 lnet_unregister_lnd(list_entry(the_lnet.ln_lnds.next,
2571                                                struct lnet_lnd, lnd_list));
2572         lnet_destroy_locks();
2573 }
2574
2575 /**
2576  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2577  *
2578  * Users must call this function at least once before any other functions.
2579  * For each successful call there must be a corresponding call to
2580  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2581  * ignored.
2582  *
2583  * The PID used by LNet may be different from the one requested.
2584  * See LNetGetId().
2585  *
2586  * \param requested_pid PID requested by the caller.
2587  *
2588  * \return >= 0 on success, and < 0 error code on failures.
2589  */
2590 int
2591 LNetNIInit(lnet_pid_t requested_pid)
2592 {
2593         int                     im_a_router = 0;
2594         int                     rc;
2595         int                     ni_count;
2596         struct lnet_ping_buffer *pbuf;
2597         struct lnet_handle_md   ping_mdh;
2598         struct list_head        net_head;
2599         struct lnet_net         *net;
2600
2601         INIT_LIST_HEAD(&net_head);
2602
2603         mutex_lock(&the_lnet.ln_api_mutex);
2604
2605         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2606
2607         if (the_lnet.ln_refcount > 0) {
2608                 rc = the_lnet.ln_refcount++;
2609                 mutex_unlock(&the_lnet.ln_api_mutex);
2610                 return rc;
2611         }
2612
2613         rc = lnet_prepare(requested_pid);
2614         if (rc != 0) {
2615                 mutex_unlock(&the_lnet.ln_api_mutex);
2616                 return rc;
2617         }
2618
2619         /* create a network for Loopback network */
2620         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2621         if (net == NULL) {
2622                 rc = -ENOMEM;
2623                 goto err_empty_list;
2624         }
2625
2626         /* Add in the loopback NI */
2627         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2628                 rc = -ENOMEM;
2629                 goto err_empty_list;
2630         }
2631
2632         /* If LNet is being initialized via DLC it is possible
2633          * that the user requests not to load module parameters (ones which
2634          * are supported by DLC) on initialization.  Therefore, make sure not
2635          * to load networks, routes and forwarding from module parameters
2636          * in this case.  On cleanup in case of failure only clean up
2637          * routes if it has been loaded */
2638         if (!the_lnet.ln_nis_from_mod_params) {
2639                 rc = lnet_parse_networks(&net_head, lnet_get_networks(),
2640                                          use_tcp_bonding);
2641                 if (rc < 0)
2642                         goto err_empty_list;
2643         }
2644
2645         ni_count = lnet_startup_lndnets(&net_head);
2646         if (ni_count < 0) {
2647                 rc = ni_count;
2648                 goto err_empty_list;
2649         }
2650
2651         if (!the_lnet.ln_nis_from_mod_params) {
2652                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2653                 if (rc != 0)
2654                         goto err_shutdown_lndnis;
2655
2656                 rc = lnet_rtrpools_alloc(im_a_router);
2657                 if (rc != 0)
2658                         goto err_destroy_routes;
2659         }
2660
2661         rc = lnet_acceptor_start();
2662         if (rc != 0)
2663                 goto err_destroy_routes;
2664
2665         the_lnet.ln_refcount = 1;
2666         /* Now I may use my own API functions... */
2667
2668         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2669         if (rc != 0)
2670                 goto err_acceptor_stop;
2671
2672         lnet_ping_target_update(pbuf, ping_mdh);
2673
2674         rc = LNetEQAlloc(0, lnet_mt_event_handler, &the_lnet.ln_mt_eqh);
2675         if (rc != 0) {
2676                 CERROR("Can't allocate monitor thread EQ: %d\n", rc);
2677                 goto err_stop_ping;
2678         }
2679
2680         rc = lnet_push_target_init();
2681         if (rc != 0)
2682                 goto err_stop_ping;
2683
2684         rc = lnet_peer_discovery_start();
2685         if (rc != 0)
2686                 goto err_destroy_push_target;
2687
2688         rc = lnet_monitor_thr_start();
2689         if (rc != 0)
2690                 goto err_stop_discovery_thr;
2691
2692         lnet_fault_init();
2693         lnet_router_debugfs_init();
2694
2695         mutex_unlock(&the_lnet.ln_api_mutex);
2696
2697         complete_all(&the_lnet.ln_started);
2698
2699         /* wait for all routers to start */
2700         lnet_wait_router_start();
2701
2702         return 0;
2703
2704 err_stop_discovery_thr:
2705         lnet_peer_discovery_stop();
2706 err_destroy_push_target:
2707         lnet_push_target_fini();
2708 err_stop_ping:
2709         lnet_ping_target_fini();
2710 err_acceptor_stop:
2711         the_lnet.ln_refcount = 0;
2712         lnet_acceptor_stop();
2713 err_destroy_routes:
2714         if (!the_lnet.ln_nis_from_mod_params)
2715                 lnet_destroy_routes();
2716 err_shutdown_lndnis:
2717         lnet_shutdown_lndnets();
2718 err_empty_list:
2719         lnet_unprepare();
2720         LASSERT(rc < 0);
2721         mutex_unlock(&the_lnet.ln_api_mutex);
2722         while (!list_empty(&net_head)) {
2723                 struct lnet_net *net;
2724
2725                 net = list_entry(net_head.next, struct lnet_net, net_list);
2726                 list_del_init(&net->net_list);
2727                 lnet_net_free(net);
2728         }
2729         return rc;
2730 }
2731 EXPORT_SYMBOL(LNetNIInit);
2732
2733 /**
2734  * Stop LNet interfaces, routing, and forwarding.
2735  *
2736  * Users must call this function once for each successful call to LNetNIInit().
2737  * Once the LNetNIFini() operation has been started, the results of pending
2738  * API operations are undefined.
2739  *
2740  * \return always 0 for current implementation.
2741  */
2742 int
2743 LNetNIFini(void)
2744 {
2745         mutex_lock(&the_lnet.ln_api_mutex);
2746
2747         LASSERT(the_lnet.ln_refcount > 0);
2748
2749         if (the_lnet.ln_refcount != 1) {
2750                 the_lnet.ln_refcount--;
2751         } else {
2752                 LASSERT(!the_lnet.ln_niinit_self);
2753
2754                 lnet_fault_fini();
2755
2756                 lnet_router_debugfs_fini();
2757                 lnet_monitor_thr_stop();
2758                 lnet_peer_discovery_stop();
2759                 lnet_push_target_fini();
2760                 lnet_ping_target_fini();
2761
2762                 /* Teardown fns that use my own API functions BEFORE here */
2763                 the_lnet.ln_refcount = 0;
2764
2765                 lnet_acceptor_stop();
2766                 lnet_destroy_routes();
2767                 lnet_shutdown_lndnets();
2768                 lnet_unprepare();
2769         }
2770
2771         mutex_unlock(&the_lnet.ln_api_mutex);
2772         return 0;
2773 }
2774 EXPORT_SYMBOL(LNetNIFini);
2775
2776 /**
2777  * Grabs the ni data from the ni structure and fills the out
2778  * parameters
2779  *
2780  * \param[in] ni network        interface structure
2781  * \param[out] cfg_ni           NI config information
2782  * \param[out] tun              network and LND tunables
2783  */
2784 static void
2785 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
2786                    struct lnet_ioctl_config_lnd_tunables *tun,
2787                    struct lnet_ioctl_element_stats *stats,
2788                    __u32 tun_size)
2789 {
2790         size_t min_size = 0;
2791         int i;
2792
2793         if (!ni || !cfg_ni || !tun)
2794                 return;
2795
2796         if (ni->ni_interfaces[0] != NULL) {
2797                 for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2798                         if (ni->ni_interfaces[i] != NULL) {
2799                                 strncpy(cfg_ni->lic_ni_intf[i],
2800                                         ni->ni_interfaces[i],
2801                                         sizeof(cfg_ni->lic_ni_intf[i]));
2802                         }
2803                 }
2804         }
2805
2806         cfg_ni->lic_nid = ni->ni_nid;
2807         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2808                 cfg_ni->lic_status = LNET_NI_STATUS_UP;
2809         else
2810                 cfg_ni->lic_status = ni->ni_status->ns_status;
2811         cfg_ni->lic_tcp_bonding = use_tcp_bonding;
2812         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
2813
2814         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
2815
2816         if (stats) {
2817                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
2818                                                        LNET_STATS_TYPE_SEND);
2819                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
2820                                                        LNET_STATS_TYPE_RECV);
2821                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
2822                                                        LNET_STATS_TYPE_DROP);
2823         }
2824
2825         /*
2826          * tun->lt_tun will always be present, but in order to be
2827          * backwards compatible, we need to deal with the cases when
2828          * tun->lt_tun is smaller than what the kernel has, because it
2829          * comes from an older version of a userspace program, then we'll
2830          * need to copy as much information as we have available space.
2831          */
2832         min_size = tun_size - sizeof(tun->lt_cmn);
2833         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
2834
2835         /* copy over the cpts */
2836         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
2837             ni->ni_cpts == NULL)  {
2838                 for (i = 0; i < ni->ni_ncpts; i++)
2839                         cfg_ni->lic_cpts[i] = i;
2840         } else {
2841                 for (i = 0;
2842                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
2843                      i < LNET_MAX_SHOW_NUM_CPT;
2844                      i++)
2845                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
2846         }
2847         cfg_ni->lic_ncpts = ni->ni_ncpts;
2848 }
2849
2850 /**
2851  * NOTE: This is a legacy function left in the code to be backwards
2852  * compatible with older userspace programs. It should eventually be
2853  * removed.
2854  *
2855  * Grabs the ni data from the ni structure and fills the out
2856  * parameters
2857  *
2858  * \param[in] ni network        interface structure
2859  * \param[out] config           config information
2860  */
2861 static void
2862 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
2863                          struct lnet_ioctl_config_data *config)
2864 {
2865         struct lnet_ioctl_net_config *net_config;
2866         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
2867         size_t min_size, tunable_size = 0;
2868         int i;
2869
2870         if (!ni || !config)
2871                 return;
2872
2873         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
2874         if (!net_config)
2875                 return;
2876
2877         BUILD_BUG_ON(ARRAY_SIZE(ni->ni_interfaces) !=
2878                      ARRAY_SIZE(net_config->ni_interfaces));
2879
2880         for (i = 0; i < ARRAY_SIZE(ni->ni_interfaces); i++) {
2881                 if (!ni->ni_interfaces[i])
2882                         break;
2883
2884                 strncpy(net_config->ni_interfaces[i],
2885                         ni->ni_interfaces[i],
2886                         sizeof(net_config->ni_interfaces[i]));
2887         }
2888
2889         config->cfg_nid = ni->ni_nid;
2890         config->cfg_config_u.cfg_net.net_peer_timeout =
2891                 ni->ni_net->net_tunables.lct_peer_timeout;
2892         config->cfg_config_u.cfg_net.net_max_tx_credits =
2893                 ni->ni_net->net_tunables.lct_max_tx_credits;
2894         config->cfg_config_u.cfg_net.net_peer_tx_credits =
2895                 ni->ni_net->net_tunables.lct_peer_tx_credits;
2896         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
2897                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
2898
2899         if (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND)
2900                 net_config->ni_status = LNET_NI_STATUS_UP;
2901         else
2902                 net_config->ni_status = ni->ni_status->ns_status;
2903
2904         if (ni->ni_cpts) {
2905                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
2906
2907                 for (i = 0; i < num_cpts; i++)
2908                         net_config->ni_cpts[i] = ni->ni_cpts[i];
2909
2910                 config->cfg_ncpts = num_cpts;
2911         }
2912
2913         /*
2914          * See if user land tools sent in a newer and larger version
2915          * of struct lnet_tunables than what the kernel uses.
2916          */
2917         min_size = sizeof(*config) + sizeof(*net_config);
2918
2919         if (config->cfg_hdr.ioc_len > min_size)
2920                 tunable_size = config->cfg_hdr.ioc_len - min_size;
2921
2922         /* Don't copy too much data to user space */
2923         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
2924         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
2925
2926         if (lnd_cfg && min_size) {
2927                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
2928                 config->cfg_config_u.cfg_net.net_interface_count = 1;
2929
2930                 /* Tell user land that kernel side has less data */
2931                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
2932                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
2933                         config->cfg_hdr.ioc_len -= min_size;
2934                 }
2935         }
2936 }
2937
2938 struct lnet_ni *
2939 lnet_get_ni_idx_locked(int idx)
2940 {
2941         struct lnet_ni          *ni;
2942         struct lnet_net         *net;
2943
2944         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
2945                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
2946                         if (idx-- == 0)
2947                                 return ni;
2948                 }
2949         }
2950
2951         return NULL;
2952 }
2953
2954 struct lnet_ni *
2955 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
2956 {
2957         struct lnet_ni          *ni;
2958         struct lnet_net         *net = mynet;
2959
2960         /*
2961          * It is possible that the net has been cleaned out while there is
2962          * a message being sent. This function accessed the net without
2963          * checking if the list is empty
2964          */
2965         if (prev == NULL) {
2966                 if (net == NULL)
2967                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
2968                                         net_list);
2969                 if (list_empty(&net->net_ni_list))
2970                         return NULL;
2971                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2972                                 ni_netlist);
2973
2974                 return ni;
2975         }
2976
2977         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
2978                 /* if you reached the end of the ni list and the net is
2979                  * specified, then there are no more nis in that net */
2980                 if (net != NULL)
2981                         return NULL;
2982
2983                 /* we reached the end of this net ni list. move to the
2984                  * next net */
2985                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
2986                         /* no more nets and no more NIs. */
2987                         return NULL;
2988
2989                 /* get the next net */
2990                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
2991                                  net_list);
2992                 if (list_empty(&net->net_ni_list))
2993                         return NULL;
2994                 /* get the ni on it */
2995                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
2996                                 ni_netlist);
2997
2998                 return ni;
2999         }
3000
3001         if (list_empty(&prev->ni_netlist))
3002                 return NULL;
3003
3004         /* there are more nis left */
3005         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3006
3007         return ni;
3008 }
3009
3010 int
3011 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3012 {
3013         struct lnet_ni *ni;
3014         int cpt;
3015         int rc = -ENOENT;
3016         int idx = config->cfg_count;
3017
3018         cpt = lnet_net_lock_current();
3019
3020         ni = lnet_get_ni_idx_locked(idx);
3021
3022         if (ni != NULL) {
3023                 rc = 0;
3024                 lnet_ni_lock(ni);
3025                 lnet_fill_ni_info_legacy(ni, config);
3026                 lnet_ni_unlock(ni);
3027         }
3028
3029         lnet_net_unlock(cpt);
3030         return rc;
3031 }
3032
3033 int
3034 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3035                    struct lnet_ioctl_config_lnd_tunables *tun,
3036                    struct lnet_ioctl_element_stats *stats,
3037                    __u32 tun_size)
3038 {
3039         struct lnet_ni          *ni;
3040         int                     cpt;
3041         int                     rc = -ENOENT;
3042
3043         if (!cfg_ni || !tun || !stats)
3044                 return -EINVAL;
3045
3046         cpt = lnet_net_lock_current();
3047
3048         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3049
3050         if (ni) {
3051                 rc = 0;
3052                 lnet_ni_lock(ni);
3053                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3054                 lnet_ni_unlock(ni);
3055         }
3056
3057         lnet_net_unlock(cpt);
3058         return rc;
3059 }
3060
3061 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3062 {
3063         struct lnet_ni *ni;
3064         int cpt;
3065         int rc = -ENOENT;
3066
3067         if (!msg_stats)
3068                 return -EINVAL;
3069
3070         cpt = lnet_net_lock_current();
3071
3072         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3073
3074         if (ni) {
3075                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3076                 rc = 0;
3077         }
3078
3079         lnet_net_unlock(cpt);
3080
3081         return rc;
3082 }
3083
3084 static int lnet_add_net_common(struct lnet_net *net,
3085                                struct lnet_ioctl_config_lnd_tunables *tun)
3086 {
3087         __u32                   net_id;
3088         struct lnet_ping_buffer *pbuf;
3089         struct lnet_handle_md   ping_mdh;
3090         int                     rc;
3091         struct lnet_remotenet *rnet;
3092         int                     net_ni_count;
3093         int                     num_acceptor_nets;
3094
3095         lnet_net_lock(LNET_LOCK_EX);
3096         rnet = lnet_find_rnet_locked(net->net_id);
3097         lnet_net_unlock(LNET_LOCK_EX);
3098         /*
3099          * make sure that the net added doesn't invalidate the current
3100          * configuration LNet is keeping
3101          */
3102         if (rnet) {
3103                 CERROR("Adding net %s will invalidate routing configuration\n",
3104                        libcfs_net2str(net->net_id));
3105                 lnet_net_free(net);
3106                 return -EUSERS;
3107         }
3108
3109         /*
3110          * make sure you calculate the correct number of slots in the ping
3111          * buffer. Since the ping info is a flattened list of all the NIs,
3112          * we should allocate enough slots to accomodate the number of NIs
3113          * which will be added.
3114          *
3115          * since ni hasn't been configured yet, use
3116          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3117          */
3118         net_ni_count = lnet_get_net_ni_count_pre(net);
3119
3120         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3121                                     net_ni_count + lnet_get_ni_count(),
3122                                     false);
3123         if (rc < 0) {
3124                 lnet_net_free(net);
3125                 return rc;
3126         }
3127
3128         if (tun)
3129                 memcpy(&net->net_tunables,
3130                        &tun->lt_cmn, sizeof(net->net_tunables));
3131         else
3132                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3133
3134         /*
3135          * before starting this network get a count of the current TCP
3136          * networks which require the acceptor thread running. If that
3137          * count is == 0 before we start up this network, then we'd want to
3138          * start up the acceptor thread after starting up this network
3139          */
3140         num_acceptor_nets = lnet_count_acceptor_nets();
3141
3142         net_id = net->net_id;
3143
3144         rc = lnet_startup_lndnet(net,
3145                                  (tun) ? &tun->lt_tun : NULL);
3146         if (rc < 0)
3147                 goto failed;
3148
3149         lnet_net_lock(LNET_LOCK_EX);
3150         net = lnet_get_net_locked(net_id);
3151         lnet_net_unlock(LNET_LOCK_EX);
3152
3153         LASSERT(net);
3154
3155         /*
3156          * Start the acceptor thread if this is the first network
3157          * being added that requires the thread.
3158          */
3159         if (net->net_lnd->lnd_accept && num_acceptor_nets == 0) {
3160                 rc = lnet_acceptor_start();
3161                 if (rc < 0) {
3162                         /* shutdown the net that we just started */
3163                         CERROR("Failed to start up acceptor thread\n");
3164                         lnet_shutdown_lndnet(net);
3165                         goto failed;
3166                 }
3167         }
3168
3169         lnet_net_lock(LNET_LOCK_EX);
3170         lnet_peer_net_added(net);
3171         lnet_net_unlock(LNET_LOCK_EX);
3172
3173         lnet_ping_target_update(pbuf, ping_mdh);
3174
3175         return 0;
3176
3177 failed:
3178         lnet_ping_md_unlink(pbuf, &ping_mdh);
3179         lnet_ping_buffer_decref(pbuf);
3180         return rc;
3181 }
3182
3183 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3184                                       struct lnet_ioctl_config_lnd_tunables *tun)
3185 {
3186         struct lnet_net *net;
3187         char *nets;
3188         int rc;
3189         struct list_head net_head;
3190
3191         INIT_LIST_HEAD(&net_head);
3192
3193         rc = lnet_parse_ip2nets(&nets, ip2nets);
3194         if (rc < 0)
3195                 return rc;
3196
3197         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3198         if (rc < 0)
3199                 return rc;
3200
3201         mutex_lock(&the_lnet.ln_api_mutex);
3202         while (!list_empty(&net_head)) {
3203                 net = list_entry(net_head.next, struct lnet_net, net_list);
3204                 list_del_init(&net->net_list);
3205                 rc = lnet_add_net_common(net, tun);
3206                 if (rc < 0)
3207                         goto out;
3208         }
3209
3210 out:
3211         mutex_unlock(&the_lnet.ln_api_mutex);
3212
3213         while (!list_empty(&net_head)) {
3214                 net = list_entry(net_head.next, struct lnet_net, net_list);
3215                 list_del_init(&net->net_list);
3216                 lnet_net_free(net);
3217         }
3218         return rc;
3219 }
3220
3221 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3222 {
3223         struct lnet_net *net;
3224         struct lnet_ni *ni;
3225         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3226         int rc, i;
3227         __u32 net_id, lnd_type;
3228
3229         /* get the tunables if they are available */
3230         if (conf->lic_cfg_hdr.ioc_len >=
3231             sizeof(*conf) + sizeof(*tun))
3232                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3233                         conf->lic_bulk;
3234
3235         /* handle legacy ip2nets from DLC */
3236         if (conf->lic_legacy_ip2nets[0] != '\0')
3237                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3238                                                   tun);
3239
3240         net_id = LNET_NIDNET(conf->lic_nid);
3241         lnd_type = LNET_NETTYP(net_id);
3242
3243         if (!libcfs_isknown_lnd(lnd_type)) {
3244                 CERROR("No valid net and lnd information provided\n");
3245                 return -EINVAL;
3246         }
3247
3248         net = lnet_net_alloc(net_id, NULL);
3249         if (!net)
3250                 return -ENOMEM;
3251
3252         for (i = 0; i < conf->lic_ncpts; i++) {
3253                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3254                         return -EINVAL;
3255         }
3256
3257         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3258                                        conf->lic_ni_intf[0]);
3259         if (!ni)
3260                 return -ENOMEM;
3261
3262         mutex_lock(&the_lnet.ln_api_mutex);
3263
3264         rc = lnet_add_net_common(net, tun);
3265
3266         mutex_unlock(&the_lnet.ln_api_mutex);
3267
3268         return rc;
3269 }
3270
3271 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3272 {
3273         struct lnet_net  *net;
3274         struct lnet_ni *ni;
3275         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3276         struct lnet_ping_buffer *pbuf;
3277         struct lnet_handle_md  ping_mdh;
3278         int               rc;
3279         int               net_count;
3280         __u32             addr;
3281
3282         /* don't allow userspace to shutdown the LOLND */
3283         if (LNET_NETTYP(net_id) == LOLND)
3284                 return -EINVAL;
3285
3286         mutex_lock(&the_lnet.ln_api_mutex);
3287
3288         lnet_net_lock(0);
3289
3290         net = lnet_get_net_locked(net_id);
3291         if (!net) {
3292                 CERROR("net %s not found\n",
3293                        libcfs_net2str(net_id));
3294                 rc = -ENOENT;
3295                 goto unlock_net;
3296         }
3297
3298         addr = LNET_NIDADDR(conf->lic_nid);
3299         if (addr == 0) {
3300                 /* remove the entire net */
3301                 net_count = lnet_get_net_ni_count_locked(net);
3302
3303                 lnet_net_unlock(0);
3304
3305                 /* create and link a new ping info, before removing the old one */
3306                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3307                                         lnet_get_ni_count() - net_count,
3308                                         false);
3309                 if (rc != 0)
3310                         goto unlock_api_mutex;
3311
3312                 lnet_shutdown_lndnet(net);
3313
3314                 if (lnet_count_acceptor_nets() == 0)
3315                         lnet_acceptor_stop();
3316
3317                 lnet_ping_target_update(pbuf, ping_mdh);
3318
3319                 goto unlock_api_mutex;
3320         }
3321
3322         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3323         if (!ni) {
3324                 CERROR("nid %s not found\n",
3325                        libcfs_nid2str(conf->lic_nid));
3326                 rc = -ENOENT;
3327                 goto unlock_net;
3328         }
3329
3330         net_count = lnet_get_net_ni_count_locked(net);
3331
3332         lnet_net_unlock(0);
3333
3334         /* create and link a new ping info, before removing the old one */
3335         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3336                                   lnet_get_ni_count() - 1, false);
3337         if (rc != 0)
3338                 goto unlock_api_mutex;
3339
3340         lnet_shutdown_lndni(ni);
3341
3342         if (lnet_count_acceptor_nets() == 0)
3343                 lnet_acceptor_stop();
3344
3345         lnet_ping_target_update(pbuf, ping_mdh);
3346
3347         /* check if the net is empty and remove it if it is */
3348         if (net_count == 1)
3349                 lnet_shutdown_lndnet(net);
3350
3351         goto unlock_api_mutex;
3352
3353 unlock_net:
3354         lnet_net_unlock(0);
3355 unlock_api_mutex:
3356         mutex_unlock(&the_lnet.ln_api_mutex);
3357
3358         return rc;
3359 }
3360
3361 /*
3362  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3363  * They are only expected to be called for unique networks.
3364  * That can be as a result of older DLC library
3365  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3366  */
3367 int
3368 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3369 {
3370         struct lnet_net         *net;
3371         struct list_head        net_head;
3372         int                     rc;
3373         struct lnet_ioctl_config_lnd_tunables tun;
3374         char *nets = conf->cfg_config_u.cfg_net.net_intf;
3375
3376         INIT_LIST_HEAD(&net_head);
3377
3378         /* Create a net/ni structures for the network string */
3379         rc = lnet_parse_networks(&net_head, nets, use_tcp_bonding);
3380         if (rc <= 0)
3381                 return rc == 0 ? -EINVAL : rc;
3382
3383         mutex_lock(&the_lnet.ln_api_mutex);
3384
3385         if (rc > 1) {
3386                 rc = -EINVAL; /* only add one network per call */
3387                 goto out_unlock_clean;
3388         }
3389
3390         net = list_entry(net_head.next, struct lnet_net, net_list);
3391         list_del_init(&net->net_list);
3392
3393         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3394
3395         memset(&tun, 0, sizeof(tun));
3396
3397         tun.lt_cmn.lct_peer_timeout =
3398           conf->cfg_config_u.cfg_net.net_peer_timeout;
3399         tun.lt_cmn.lct_peer_tx_credits =
3400           conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3401         tun.lt_cmn.lct_peer_rtr_credits =
3402           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3403         tun.lt_cmn.lct_max_tx_credits =
3404           conf->cfg_config_u.cfg_net.net_max_tx_credits;
3405
3406         rc = lnet_add_net_common(net, &tun);
3407
3408 out_unlock_clean:
3409         mutex_unlock(&the_lnet.ln_api_mutex);
3410         while (!list_empty(&net_head)) {
3411                 /* net_head list is empty in success case */
3412                 net = list_entry(net_head.next, struct lnet_net, net_list);
3413                 list_del_init(&net->net_list);
3414                 lnet_net_free(net);
3415         }
3416         return rc;
3417 }
3418
3419 int
3420 lnet_dyn_del_net(__u32 net_id)
3421 {
3422         struct lnet_net  *net;
3423         struct lnet_ping_buffer *pbuf;
3424         struct lnet_handle_md ping_mdh;
3425         int               rc;
3426         int               net_ni_count;
3427
3428         /* don't allow userspace to shutdown the LOLND */
3429         if (LNET_NETTYP(net_id) == LOLND)
3430                 return -EINVAL;
3431
3432         mutex_lock(&the_lnet.ln_api_mutex);
3433
3434         lnet_net_lock(0);
3435
3436         net = lnet_get_net_locked(net_id);
3437         if (net == NULL) {
3438                 lnet_net_unlock(0);
3439                 rc = -EINVAL;
3440                 goto out;
3441         }
3442
3443         net_ni_count = lnet_get_net_ni_count_locked(net);
3444
3445         lnet_net_unlock(0);
3446
3447         /* create and link a new ping info, before removing the old one */
3448         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3449                                     lnet_get_ni_count() - net_ni_count, false);
3450         if (rc != 0)
3451                 goto out;
3452
3453         lnet_shutdown_lndnet(net);
3454
3455         if (lnet_count_acceptor_nets() == 0)
3456                 lnet_acceptor_stop();
3457
3458         lnet_ping_target_update(pbuf, ping_mdh);
3459
3460 out:
3461         mutex_unlock(&the_lnet.ln_api_mutex);
3462
3463         return rc;
3464 }
3465
3466 void lnet_incr_dlc_seq(void)
3467 {
3468         atomic_inc(&lnet_dlc_seq_no);
3469 }
3470
3471 __u32 lnet_get_dlc_seq_locked(void)
3472 {
3473         return atomic_read(&lnet_dlc_seq_no);
3474 }
3475
3476 static void
3477 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3478 {
3479         struct lnet_net *net;
3480         struct lnet_ni *ni;
3481
3482         lnet_net_lock(LNET_LOCK_EX);
3483         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3484                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3485                         if (ni->ni_nid == nid || all) {
3486                                 atomic_set(&ni->ni_healthv, value);
3487                                 if (list_empty(&ni->ni_recovery) &&
3488                                     value < LNET_MAX_HEALTH_VALUE) {
3489                                         CERROR("manually adding local NI %s to recovery\n",
3490                                                libcfs_nid2str(ni->ni_nid));
3491                                         list_add_tail(&ni->ni_recovery,
3492                                                       &the_lnet.ln_mt_localNIRecovq);
3493                                         lnet_ni_addref_locked(ni, 0);
3494                                 }
3495                                 if (!all) {
3496                                         lnet_net_unlock(LNET_LOCK_EX);
3497                                         return;
3498                                 }
3499                         }
3500                 }
3501         }
3502         lnet_net_unlock(LNET_LOCK_EX);
3503 }
3504
3505 static int
3506 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3507 {
3508         int cpt, rc = 0;
3509         struct lnet_ni *ni;
3510         lnet_nid_t nid = stats->hlni_nid;
3511
3512         cpt = lnet_net_lock_current();
3513         ni = lnet_nid2ni_locked(nid, cpt);
3514
3515         if (!ni) {
3516                 rc = -ENOENT;
3517                 goto unlock;
3518         }
3519
3520         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3521         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3522         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3523         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3524         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3525         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3526         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3527
3528 unlock:
3529         lnet_net_unlock(cpt);
3530
3531         return rc;
3532 }
3533
3534 static int
3535 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3536 {
3537         struct lnet_ni *ni;
3538         int i = 0;
3539
3540         lnet_net_lock(LNET_LOCK_EX);
3541         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3542                 list->rlst_nid_array[i] = ni->ni_nid;
3543                 i++;
3544                 if (i >= LNET_MAX_SHOW_NUM_NID)
3545                         break;
3546         }
3547         lnet_net_unlock(LNET_LOCK_EX);
3548         list->rlst_num_nids = i;
3549
3550         return 0;
3551 }
3552
3553 static int
3554 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3555 {
3556         struct lnet_peer_ni *lpni;
3557         int i = 0;
3558
3559         lnet_net_lock(LNET_LOCK_EX);
3560         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3561                 list->rlst_nid_array[i] = lpni->lpni_nid;
3562                 i++;
3563                 if (i >= LNET_MAX_SHOW_NUM_NID)
3564                         break;
3565         }
3566         lnet_net_unlock(LNET_LOCK_EX);
3567         list->rlst_num_nids = i;
3568
3569         return 0;
3570 }
3571
3572 /**
3573  * LNet ioctl handler.
3574  *
3575  */
3576 int
3577 LNetCtl(unsigned int cmd, void *arg)
3578 {
3579         struct libcfs_ioctl_data *data = arg;
3580         struct lnet_ioctl_config_data *config;
3581         struct lnet_process_id    id = {0};
3582         struct lnet_ni           *ni;
3583         int                       rc;
3584
3585         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3586                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3587
3588         switch (cmd) {
3589         case IOC_LIBCFS_GET_NI:
3590                 rc = LNetGetId(data->ioc_count, &id);
3591                 data->ioc_nid = id.nid;
3592                 return rc;
3593
3594         case IOC_LIBCFS_FAIL_NID:
3595                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3596
3597         case IOC_LIBCFS_ADD_ROUTE: {
3598                 /* default router sensitivity to 1 */
3599                 unsigned int sensitivity = 1;
3600                 config = arg;
3601
3602                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3603                         return -EINVAL;
3604
3605                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
3606                         sensitivity =
3607                           config->cfg_config_u.cfg_route.rtr_sensitivity;
3608                 }
3609
3610                 mutex_lock(&the_lnet.ln_api_mutex);
3611                 rc = lnet_add_route(config->cfg_net,
3612                                     config->cfg_config_u.cfg_route.rtr_hop,
3613                                     config->cfg_nid,
3614                                     config->cfg_config_u.cfg_route.
3615                                         rtr_priority, sensitivity);
3616                 mutex_unlock(&the_lnet.ln_api_mutex);
3617                 return rc;
3618         }
3619
3620         case IOC_LIBCFS_DEL_ROUTE:
3621                 config = arg;
3622
3623                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3624                         return -EINVAL;
3625
3626                 mutex_lock(&the_lnet.ln_api_mutex);
3627                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3628                 mutex_unlock(&the_lnet.ln_api_mutex);
3629                 return rc;
3630
3631         case IOC_LIBCFS_GET_ROUTE:
3632                 config = arg;
3633
3634                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3635                         return -EINVAL;
3636
3637                 mutex_lock(&the_lnet.ln_api_mutex);
3638                 rc = lnet_get_route(config->cfg_count,
3639                                     &config->cfg_net,
3640                                     &config->cfg_config_u.cfg_route.rtr_hop,
3641                                     &config->cfg_nid,
3642                                     &config->cfg_config_u.cfg_route.rtr_flags,
3643                                     &config->cfg_config_u.cfg_route.
3644                                         rtr_priority,
3645                                     &config->cfg_config_u.cfg_route.
3646                                         rtr_sensitivity);
3647                 mutex_unlock(&the_lnet.ln_api_mutex);
3648                 return rc;
3649
3650         case IOC_LIBCFS_GET_LOCAL_NI: {
3651                 struct lnet_ioctl_config_ni *cfg_ni;
3652                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3653                 struct lnet_ioctl_element_stats *stats;
3654                 __u32 tun_size;
3655
3656                 cfg_ni = arg;
3657
3658                 /* get the tunables if they are available */
3659                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3660                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3661                         return -EINVAL;
3662
3663                 stats = (struct lnet_ioctl_element_stats *)
3664                         cfg_ni->lic_bulk;
3665                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3666                                 (cfg_ni->lic_bulk + sizeof(*stats));
3667
3668                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3669                         sizeof(*stats);
3670
3671                 mutex_lock(&the_lnet.ln_api_mutex);
3672                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3673                 mutex_unlock(&the_lnet.ln_api_mutex);
3674                 return rc;
3675         }
3676
3677         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3678                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3679
3680                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3681                         return -EINVAL;
3682
3683                 mutex_lock(&the_lnet.ln_api_mutex);
3684                 rc = lnet_get_ni_stats(msg_stats);
3685                 mutex_unlock(&the_lnet.ln_api_mutex);
3686
3687                 return rc;
3688         }
3689
3690         case IOC_LIBCFS_GET_NET: {
3691                 size_t total = sizeof(*config) +
3692                                sizeof(struct lnet_ioctl_net_config);
3693                 config = arg;
3694
3695                 if (config->cfg_hdr.ioc_len < total)
3696                         return -EINVAL;
3697
3698                 mutex_lock(&the_lnet.ln_api_mutex);
3699                 rc = lnet_get_net_config(config);
3700                 mutex_unlock(&the_lnet.ln_api_mutex);
3701                 return rc;
3702         }
3703
3704         case IOC_LIBCFS_GET_LNET_STATS:
3705         {
3706                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3707
3708                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3709                         return -EINVAL;
3710
3711                 mutex_lock(&the_lnet.ln_api_mutex);
3712                 lnet_counters_get(&lnet_stats->st_cntrs);
3713                 mutex_unlock(&the_lnet.ln_api_mutex);
3714                 return 0;
3715         }
3716
3717         case IOC_LIBCFS_CONFIG_RTR:
3718                 config = arg;
3719
3720                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3721                         return -EINVAL;
3722
3723                 mutex_lock(&the_lnet.ln_api_mutex);
3724                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3725                         rc = lnet_rtrpools_enable();
3726                         mutex_unlock(&the_lnet.ln_api_mutex);
3727                         return rc;
3728                 }
3729                 lnet_rtrpools_disable();
3730                 mutex_unlock(&the_lnet.ln_api_mutex);
3731                 return 0;
3732
3733         case IOC_LIBCFS_ADD_BUF:
3734                 config = arg;
3735
3736                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3737                         return -EINVAL;
3738
3739                 mutex_lock(&the_lnet.ln_api_mutex);
3740                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
3741                                                 buf_tiny,
3742                                           config->cfg_config_u.cfg_buffers.
3743                                                 buf_small,
3744                                           config->cfg_config_u.cfg_buffers.
3745                                                 buf_large);
3746                 mutex_unlock(&the_lnet.ln_api_mutex);
3747                 return rc;
3748
3749         case IOC_LIBCFS_SET_NUMA_RANGE: {
3750                 struct lnet_ioctl_set_value *numa;
3751                 numa = arg;
3752                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3753                         return -EINVAL;
3754                 lnet_net_lock(LNET_LOCK_EX);
3755                 lnet_numa_range = numa->sv_value;
3756                 lnet_net_unlock(LNET_LOCK_EX);
3757                 return 0;
3758         }
3759
3760         case IOC_LIBCFS_GET_NUMA_RANGE: {
3761                 struct lnet_ioctl_set_value *numa;
3762                 numa = arg;
3763                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
3764                         return -EINVAL;
3765                 numa->sv_value = lnet_numa_range;
3766                 return 0;
3767         }
3768
3769         case IOC_LIBCFS_GET_BUF: {
3770                 struct lnet_ioctl_pool_cfg *pool_cfg;
3771                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
3772
3773                 config = arg;
3774
3775                 if (config->cfg_hdr.ioc_len < total)
3776                         return -EINVAL;
3777
3778                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
3779
3780                 mutex_lock(&the_lnet.ln_api_mutex);
3781                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
3782                 mutex_unlock(&the_lnet.ln_api_mutex);
3783                 return rc;
3784         }
3785
3786         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
3787                 struct lnet_ioctl_local_ni_hstats *stats = arg;
3788
3789                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
3790                         return -EINVAL;
3791
3792                 mutex_lock(&the_lnet.ln_api_mutex);
3793                 rc = lnet_get_local_ni_hstats(stats);
3794                 mutex_unlock(&the_lnet.ln_api_mutex);
3795
3796                 return rc;
3797         }
3798
3799         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
3800                 struct lnet_ioctl_recovery_list *list = arg;
3801                 if (list->rlst_hdr.ioc_len < sizeof(*list))
3802                         return -EINVAL;
3803
3804                 mutex_lock(&the_lnet.ln_api_mutex);
3805                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
3806                         rc = lnet_get_local_ni_recovery_list(list);
3807                 else
3808                         rc = lnet_get_peer_ni_recovery_list(list);
3809                 mutex_unlock(&the_lnet.ln_api_mutex);
3810                 return rc;
3811         }
3812
3813         case IOC_LIBCFS_ADD_PEER_NI: {
3814                 struct lnet_ioctl_peer_cfg *cfg = arg;
3815
3816                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3817                         return -EINVAL;
3818
3819                 mutex_lock(&the_lnet.ln_api_mutex);
3820                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
3821                                       cfg->prcfg_cfg_nid,
3822                                       cfg->prcfg_mr);
3823                 mutex_unlock(&the_lnet.ln_api_mutex);
3824                 return rc;
3825         }
3826
3827         case IOC_LIBCFS_DEL_PEER_NI: {
3828                 struct lnet_ioctl_peer_cfg *cfg = arg;
3829
3830                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3831                         return -EINVAL;
3832
3833                 mutex_lock(&the_lnet.ln_api_mutex);
3834                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
3835                                       cfg->prcfg_cfg_nid);
3836                 mutex_unlock(&the_lnet.ln_api_mutex);
3837                 return rc;
3838         }
3839
3840         case IOC_LIBCFS_GET_PEER_INFO: {
3841                 struct lnet_ioctl_peer *peer_info = arg;
3842
3843                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
3844                         return -EINVAL;
3845
3846                 mutex_lock(&the_lnet.ln_api_mutex);
3847                 rc = lnet_get_peer_ni_info(
3848                    peer_info->pr_count,
3849                    &peer_info->pr_nid,
3850                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
3851                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
3852                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
3853                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
3854                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
3855                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
3856                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
3857                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
3858                 mutex_unlock(&the_lnet.ln_api_mutex);
3859                 return rc;
3860         }
3861
3862         case IOC_LIBCFS_GET_PEER_NI: {
3863                 struct lnet_ioctl_peer_cfg *cfg = arg;
3864
3865                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3866                         return -EINVAL;
3867
3868                 mutex_lock(&the_lnet.ln_api_mutex);
3869                 rc = lnet_get_peer_info(cfg,
3870                                         (void __user *)cfg->prcfg_bulk);
3871                 mutex_unlock(&the_lnet.ln_api_mutex);
3872                 return rc;
3873         }
3874
3875         case IOC_LIBCFS_GET_PEER_LIST: {
3876                 struct lnet_ioctl_peer_cfg *cfg = arg;
3877
3878                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
3879                         return -EINVAL;
3880
3881                 mutex_lock(&the_lnet.ln_api_mutex);
3882                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
3883                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
3884                 mutex_unlock(&the_lnet.ln_api_mutex);
3885                 return rc;
3886         }
3887
3888         case IOC_LIBCFS_SET_HEALHV: {
3889                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
3890                 int value;
3891                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
3892                         return -EINVAL;
3893                 if (cfg->rh_value < 0 ||
3894                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
3895                         value = LNET_MAX_HEALTH_VALUE;
3896                 else
3897                         value = cfg->rh_value;
3898                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
3899                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
3900                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
3901                 mutex_lock(&the_lnet.ln_api_mutex);
3902                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
3903                         lnet_ni_set_healthv(cfg->rh_nid, value,
3904                                              cfg->rh_all);
3905                 else
3906                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
3907                                                   cfg->rh_all);
3908                 mutex_unlock(&the_lnet.ln_api_mutex);
3909                 return 0;
3910         }
3911
3912         case IOC_LIBCFS_NOTIFY_ROUTER: {
3913                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
3914
3915                 /* The deadline passed in by the user should be some time in
3916                  * seconds in the future since the UNIX epoch. We have to map
3917                  * that deadline to the wall clock.
3918                  */
3919                 deadline += ktime_get_seconds();
3920                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags, false,
3921                                    deadline);
3922         }
3923
3924         case IOC_LIBCFS_LNET_DIST:
3925                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
3926                 if (rc < 0 && rc != -EHOSTUNREACH)
3927                         return rc;
3928
3929                 data->ioc_u32[0] = rc;
3930                 return 0;
3931
3932         case IOC_LIBCFS_TESTPROTOCOMPAT:
3933                 lnet_net_lock(LNET_LOCK_EX);
3934                 the_lnet.ln_testprotocompat = data->ioc_flags;
3935                 lnet_net_unlock(LNET_LOCK_EX);
3936                 return 0;
3937
3938         case IOC_LIBCFS_LNET_FAULT:
3939                 return lnet_fault_ctl(data->ioc_flags, data);
3940
3941         case IOC_LIBCFS_PING: {
3942                 signed long timeout;
3943
3944                 id.nid = data->ioc_nid;
3945                 id.pid = data->ioc_u32[0];
3946
3947                 /* If timeout is negative then set default of 3 minutes */
3948                 if (((s32)data->ioc_u32[1] <= 0) ||
3949                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3950                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
3951                 else
3952                         timeout = nsecs_to_jiffies(data->ioc_u32[1] * NSEC_PER_MSEC);
3953
3954                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
3955                                data->ioc_plen1 / sizeof(struct lnet_process_id));
3956
3957                 if (rc < 0)
3958                         return rc;
3959
3960                 data->ioc_count = rc;
3961                 return 0;
3962         }
3963
3964         case IOC_LIBCFS_PING_PEER: {
3965                 struct lnet_ioctl_ping_data *ping = arg;
3966                 struct lnet_peer *lp;
3967                 signed long timeout;
3968
3969                 /* If timeout is negative then set default of 3 minutes */
3970                 if (((s32)ping->op_param) <= 0 ||
3971                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
3972                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
3973                 else
3974                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
3975
3976                 rc = lnet_ping(ping->ping_id, timeout,
3977                                ping->ping_buf,
3978                                ping->ping_count);
3979                 if (rc < 0)
3980                         return rc;
3981
3982                 mutex_lock(&the_lnet.ln_api_mutex);
3983                 lp = lnet_find_peer(ping->ping_id.nid);
3984                 if (lp) {
3985                         ping->ping_id.nid = lp->lp_primary_nid;
3986                         ping->mr_info = lnet_peer_is_multi_rail(lp);
3987                         lnet_peer_decref_locked(lp);
3988                 }
3989                 mutex_unlock(&the_lnet.ln_api_mutex);
3990
3991                 ping->ping_count = rc;
3992                 return 0;
3993         }
3994
3995         case IOC_LIBCFS_DISCOVER: {
3996                 struct lnet_ioctl_ping_data *discover = arg;
3997                 struct lnet_peer *lp;
3998
3999                 rc = lnet_discover(discover->ping_id, discover->op_param,
4000                                    discover->ping_buf,
4001                                    discover->ping_count);
4002                 if (rc < 0)
4003                         return rc;
4004
4005                 mutex_lock(&the_lnet.ln_api_mutex);
4006                 lp = lnet_find_peer(discover->ping_id.nid);
4007                 if (lp) {
4008                         discover->ping_id.nid = lp->lp_primary_nid;
4009                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4010                         lnet_peer_decref_locked(lp);
4011                 }
4012                 mutex_unlock(&the_lnet.ln_api_mutex);
4013
4014                 discover->ping_count = rc;
4015                 return 0;
4016         }
4017
4018         default:
4019                 ni = lnet_net2ni_addref(data->ioc_net);
4020                 if (ni == NULL)
4021                         return -EINVAL;
4022
4023                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4024                         rc = -EINVAL;
4025                 else
4026                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4027
4028                 lnet_ni_decref(ni);
4029                 return rc;
4030         }
4031         /* not reached */
4032 }
4033 EXPORT_SYMBOL(LNetCtl);
4034
4035 void LNetDebugPeer(struct lnet_process_id id)
4036 {
4037         lnet_debug_peer(id.nid);
4038 }
4039 EXPORT_SYMBOL(LNetDebugPeer);
4040
4041 /**
4042  * Determine if the specified peer \a nid is on the local node.
4043  *
4044  * \param nid   peer nid to check
4045  *
4046  * \retval true         If peer NID is on the local node.
4047  * \retval false        If peer NID is not on the local node.
4048  */
4049 bool LNetIsPeerLocal(lnet_nid_t nid)
4050 {
4051         struct lnet_net *net;
4052         struct lnet_ni *ni;
4053         int cpt;
4054
4055         cpt = lnet_net_lock_current();
4056         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4057                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4058                         if (ni->ni_nid == nid) {
4059                                 lnet_net_unlock(cpt);
4060                                 return true;
4061                         }
4062                 }
4063         }
4064         lnet_net_unlock(cpt);
4065
4066         return false;
4067 }
4068 EXPORT_SYMBOL(LNetIsPeerLocal);
4069
4070 /**
4071  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
4072  * Note that all interfaces share a same PID, as requested by LNetNIInit().
4073  *
4074  * \param index Index of the interface to look up.
4075  * \param id On successful return, this location will hold the
4076  * struct lnet_process_id ID of the interface.
4077  *
4078  * \retval 0 If an interface exists at \a index.
4079  * \retval -ENOENT If no interface has been found.
4080  */
4081 int
4082 LNetGetId(unsigned int index, struct lnet_process_id *id)
4083 {
4084         struct lnet_ni   *ni;
4085         struct lnet_net  *net;
4086         int               cpt;
4087         int               rc = -ENOENT;
4088
4089         LASSERT(the_lnet.ln_refcount > 0);
4090
4091         cpt = lnet_net_lock_current();
4092
4093         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4094                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4095                         if (index-- != 0)
4096                                 continue;
4097
4098                         id->nid = ni->ni_nid;
4099                         id->pid = the_lnet.ln_pid;
4100                         rc = 0;
4101                         break;
4102                 }
4103         }
4104
4105         lnet_net_unlock(cpt);
4106         return rc;
4107 }
4108 EXPORT_SYMBOL(LNetGetId);
4109
4110 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4111                      struct lnet_process_id __user *ids, int n_ids)
4112 {
4113         struct lnet_handle_eq eqh;
4114         struct lnet_handle_md mdh;
4115         struct lnet_event event;
4116         struct lnet_md md = { NULL };
4117         int which;
4118         int unlinked = 0;
4119         int replied = 0;
4120         const signed long a_long_time = cfs_time_seconds(60);
4121         struct lnet_ping_buffer *pbuf;
4122         struct lnet_process_id tmpid;
4123         int i;
4124         int nob;
4125         int rc;
4126         int rc2;
4127         sigset_t blocked;
4128
4129         /* n_ids limit is arbitrary */
4130         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4131                 return -EINVAL;
4132
4133         /*
4134          * if the user buffer has more space than the lnet_interfaces_max
4135          * then only fill it up to lnet_interfaces_max
4136          */
4137         if (n_ids > lnet_interfaces_max)
4138                 n_ids = lnet_interfaces_max;
4139
4140         if (id.pid == LNET_PID_ANY)
4141                 id.pid = LNET_PID_LUSTRE;
4142
4143         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4144         if (!pbuf)
4145                 return -ENOMEM;
4146
4147         /* NB 2 events max (including any unlink event) */
4148         rc = LNetEQAlloc(2, LNET_EQ_HANDLER_NONE, &eqh);
4149         if (rc != 0) {
4150                 CERROR("Can't allocate EQ: %d\n", rc);
4151                 goto fail_ping_buffer_decref;
4152         }
4153
4154         /* initialize md content */
4155         md.start     = &pbuf->pb_info;
4156         md.length    = LNET_PING_INFO_SIZE(n_ids);
4157         md.threshold = 2; /* GET/REPLY */
4158         md.max_size  = 0;
4159         md.options   = LNET_MD_TRUNCATE;
4160         md.user_ptr  = NULL;
4161         md.eq_handle = eqh;
4162
4163         rc = LNetMDBind(md, LNET_UNLINK, &mdh);
4164         if (rc != 0) {
4165                 CERROR("Can't bind MD: %d\n", rc);
4166                 goto fail_free_eq;
4167         }
4168
4169         rc = LNetGet(LNET_NID_ANY, mdh, id,
4170                      LNET_RESERVED_PORTAL,
4171                      LNET_PROTO_PING_MATCHBITS, 0, false);
4172
4173         if (rc != 0) {
4174                 /* Don't CERROR; this could be deliberate! */
4175                 rc2 = LNetMDUnlink(mdh);
4176                 LASSERT(rc2 == 0);
4177
4178                 /* NB must wait for the UNLINK event below... */
4179                 unlinked = 1;
4180                 timeout = a_long_time;
4181         }
4182
4183         do {
4184                 /* MUST block for unlink to complete */
4185                 if (unlinked)
4186                         blocked = cfs_block_allsigs();
4187
4188                 rc2 = LNetEQPoll(&eqh, 1, timeout, &event, &which);
4189
4190                 if (unlinked)
4191                         cfs_restore_sigs(blocked);
4192
4193                 CDEBUG(D_NET, "poll %d(%d %d)%s\n", rc2,
4194                        (rc2 <= 0) ? -1 : event.type,
4195                        (rc2 <= 0) ? -1 : event.status,
4196                        (rc2 > 0 && event.unlinked) ? " unlinked" : "");
4197
4198                 LASSERT(rc2 != -EOVERFLOW);     /* can't miss anything */
4199
4200                 if (rc2 <= 0 || event.status != 0) {
4201                         /* timeout or error */
4202                         if (!replied && rc == 0)
4203                                 rc = (rc2 < 0) ? rc2 :
4204                                      (rc2 == 0) ? -ETIMEDOUT :
4205                                      event.status;
4206
4207                         if (!unlinked) {
4208                                 /* Ensure completion in finite time... */
4209                                 LNetMDUnlink(mdh);
4210                                 /* No assertion (racing with network) */
4211                                 unlinked = 1;
4212                                 timeout = a_long_time;
4213                         } else if (rc2 == 0) {
4214                                 /* timed out waiting for unlink */
4215                                 CWARN("ping %s: late network completion\n",
4216                                       libcfs_id2str(id));
4217                         }
4218                 } else if (event.type == LNET_EVENT_REPLY) {
4219                         replied = 1;
4220                         rc = event.mlength;
4221                 }
4222         } while (rc2 <= 0 || !event.unlinked);
4223
4224         if (!replied) {
4225                 if (rc >= 0)
4226                         CWARN("%s: Unexpected rc >= 0 but no reply!\n",
4227                               libcfs_id2str(id));
4228                 rc = -EIO;
4229                 goto fail_free_eq;
4230         }
4231
4232         nob = rc;
4233         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4234
4235         rc = -EPROTO;           /* if I can't parse... */
4236
4237         if (nob < 8) {
4238                 CERROR("%s: ping info too short %d\n",
4239                        libcfs_id2str(id), nob);
4240                 goto fail_free_eq;
4241         }
4242
4243         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4244                 lnet_swap_pinginfo(pbuf);
4245         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4246                 CERROR("%s: Unexpected magic %08x\n",
4247                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4248                 goto fail_free_eq;
4249         }
4250
4251         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4252                 CERROR("%s: ping w/o NI status: 0x%x\n",
4253                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4254                 goto fail_free_eq;
4255         }
4256
4257         if (nob < LNET_PING_INFO_SIZE(0)) {
4258                 CERROR("%s: Short reply %d(%d min)\n",
4259                        libcfs_id2str(id),
4260                        nob, (int)LNET_PING_INFO_SIZE(0));
4261                 goto fail_free_eq;
4262         }
4263
4264         if (pbuf->pb_info.pi_nnis < n_ids)
4265                 n_ids = pbuf->pb_info.pi_nnis;
4266
4267         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4268                 CERROR("%s: Short reply %d(%d expected)\n",
4269                        libcfs_id2str(id),
4270                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4271                 goto fail_free_eq;
4272         }
4273
4274         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4275
4276         memset(&tmpid, 0, sizeof(tmpid));
4277         for (i = 0; i < n_ids; i++) {
4278                 tmpid.pid = pbuf->pb_info.pi_pid;
4279                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4280                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4281                         goto fail_free_eq;
4282         }
4283         rc = pbuf->pb_info.pi_nnis;
4284
4285  fail_free_eq:
4286         rc2 = LNetEQFree(eqh);
4287         if (rc2 != 0)
4288                 CERROR("rc2 %d\n", rc2);
4289         LASSERT(rc2 == 0);
4290
4291  fail_ping_buffer_decref:
4292         lnet_ping_buffer_decref(pbuf);
4293         return rc;
4294 }
4295
4296 static int
4297 lnet_discover(struct lnet_process_id id, __u32 force,
4298               struct lnet_process_id __user *ids, int n_ids)
4299 {
4300         struct lnet_peer_ni *lpni;
4301         struct lnet_peer_ni *p;
4302         struct lnet_peer *lp;
4303         struct lnet_process_id *buf;
4304         int cpt;
4305         int i;
4306         int rc;
4307         int max_intf = lnet_interfaces_max;
4308         size_t buf_size;
4309
4310         if (n_ids <= 0 ||
4311             id.nid == LNET_NID_ANY)
4312                 return -EINVAL;
4313
4314         if (id.pid == LNET_PID_ANY)
4315                 id.pid = LNET_PID_LUSTRE;
4316
4317         /*
4318          * if the user buffer has more space than the max_intf
4319          * then only fill it up to max_intf
4320          */
4321         if (n_ids > max_intf)
4322                 n_ids = max_intf;
4323
4324         buf_size = n_ids * sizeof(*buf);
4325
4326         LIBCFS_ALLOC(buf, buf_size);
4327         if (!buf)
4328                 return -ENOMEM;
4329
4330         cpt = lnet_net_lock_current();
4331         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4332         if (IS_ERR(lpni)) {
4333                 rc = PTR_ERR(lpni);
4334                 goto out;
4335         }
4336
4337         /*
4338          * Clearing the NIDS_UPTODATE flag ensures the peer will
4339          * be discovered, provided discovery has not been disabled.
4340          */
4341         lp = lpni->lpni_peer_net->lpn_peer;
4342         spin_lock(&lp->lp_lock);
4343         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4344         /* If the force flag is set, force a PING and PUSH as well. */
4345         if (force)
4346                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4347         spin_unlock(&lp->lp_lock);
4348         rc = lnet_discover_peer_locked(lpni, cpt, true);
4349         if (rc)
4350                 goto out_decref;
4351
4352         /* Peer may have changed. */
4353         lp = lpni->lpni_peer_net->lpn_peer;
4354         if (lp->lp_nnis < n_ids)
4355                 n_ids = lp->lp_nnis;
4356
4357         i = 0;
4358         p = NULL;
4359         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4360                 buf[i].pid = id.pid;
4361                 buf[i].nid = p->lpni_nid;
4362                 if (++i >= n_ids)
4363                         break;
4364         }
4365
4366         lnet_net_unlock(cpt);
4367
4368         rc = -EFAULT;
4369         if (copy_to_user(ids, buf, n_ids * sizeof(*buf)))
4370                 goto out_relock;
4371         rc = n_ids;
4372 out_relock:
4373         lnet_net_lock(cpt);
4374 out_decref:
4375         lnet_peer_ni_decref_locked(lpni);
4376 out:
4377         lnet_net_unlock(cpt);
4378
4379         LIBCFS_FREE(buf, buf_size);
4380
4381         return rc;
4382 }
4383
4384 /**
4385  * Retrieve peer discovery status.
4386  *
4387  * \retval 1 if lnet_peer_discovery_disabled is 0
4388  * \retval 0 if lnet_peer_discovery_disabled is 1
4389  */
4390 int
4391 LNetGetPeerDiscoveryStatus(void)
4392 {
4393         return !lnet_peer_discovery_disabled;
4394 }
4395 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);