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