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