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