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