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