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