Whamcloud - gitweb
LU-14750 lnet: use ni fatal error when calculating net health
[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, ni_fatal;
3181
3182         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3183                 healthv = atomic_read(&ni->ni_healthv);
3184                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3185                 if (!ni_fatal && healthv > best_healthv)
3186                         best_healthv = healthv;
3187         }
3188
3189         return best_healthv;
3190 }
3191
3192 struct lnet_ni *
3193 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3194 {
3195         struct lnet_ni          *ni;
3196         struct lnet_net         *net = mynet;
3197
3198         /*
3199          * It is possible that the net has been cleaned out while there is
3200          * a message being sent. This function accessed the net without
3201          * checking if the list is empty
3202          */
3203         if (prev == NULL) {
3204                 if (net == NULL)
3205                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3206                                         net_list);
3207                 if (list_empty(&net->net_ni_list))
3208                         return NULL;
3209                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3210                                 ni_netlist);
3211
3212                 return ni;
3213         }
3214
3215         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3216                 /* if you reached the end of the ni list and the net is
3217                  * specified, then there are no more nis in that net */
3218                 if (net != NULL)
3219                         return NULL;
3220
3221                 /* we reached the end of this net ni list. move to the
3222                  * next net */
3223                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3224                         /* no more nets and no more NIs. */
3225                         return NULL;
3226
3227                 /* get the next net */
3228                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3229                                  net_list);
3230                 if (list_empty(&net->net_ni_list))
3231                         return NULL;
3232                 /* get the ni on it */
3233                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3234                                 ni_netlist);
3235
3236                 return ni;
3237         }
3238
3239         if (list_empty(&prev->ni_netlist))
3240                 return NULL;
3241
3242         /* there are more nis left */
3243         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3244
3245         return ni;
3246 }
3247
3248 int
3249 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3250 {
3251         struct lnet_ni *ni;
3252         int cpt;
3253         int rc = -ENOENT;
3254         int idx = config->cfg_count;
3255
3256         cpt = lnet_net_lock_current();
3257
3258         ni = lnet_get_ni_idx_locked(idx);
3259
3260         if (ni != NULL) {
3261                 rc = 0;
3262                 lnet_ni_lock(ni);
3263                 lnet_fill_ni_info_legacy(ni, config);
3264                 lnet_ni_unlock(ni);
3265         }
3266
3267         lnet_net_unlock(cpt);
3268         return rc;
3269 }
3270
3271 int
3272 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3273                    struct lnet_ioctl_config_lnd_tunables *tun,
3274                    struct lnet_ioctl_element_stats *stats,
3275                    __u32 tun_size)
3276 {
3277         struct lnet_ni          *ni;
3278         int                     cpt;
3279         int                     rc = -ENOENT;
3280
3281         if (!cfg_ni || !tun || !stats)
3282                 return -EINVAL;
3283
3284         cpt = lnet_net_lock_current();
3285
3286         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3287
3288         if (ni) {
3289                 rc = 0;
3290                 lnet_ni_lock(ni);
3291                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3292                 lnet_ni_unlock(ni);
3293         }
3294
3295         lnet_net_unlock(cpt);
3296         return rc;
3297 }
3298
3299 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3300 {
3301         struct lnet_ni *ni;
3302         int cpt;
3303         int rc = -ENOENT;
3304
3305         if (!msg_stats)
3306                 return -EINVAL;
3307
3308         cpt = lnet_net_lock_current();
3309
3310         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3311
3312         if (ni) {
3313                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3314                 rc = 0;
3315         }
3316
3317         lnet_net_unlock(cpt);
3318
3319         return rc;
3320 }
3321
3322 static int lnet_add_net_common(struct lnet_net *net,
3323                                struct lnet_ioctl_config_lnd_tunables *tun)
3324 {
3325         struct lnet_handle_md ping_mdh;
3326         struct lnet_ping_buffer *pbuf;
3327         struct lnet_remotenet *rnet;
3328         struct lnet_ni *ni;
3329         int net_ni_count;
3330         __u32 net_id;
3331         int rc;
3332
3333         lnet_net_lock(LNET_LOCK_EX);
3334         rnet = lnet_find_rnet_locked(net->net_id);
3335         lnet_net_unlock(LNET_LOCK_EX);
3336         /*
3337          * make sure that the net added doesn't invalidate the current
3338          * configuration LNet is keeping
3339          */
3340         if (rnet) {
3341                 CERROR("Adding net %s will invalidate routing configuration\n",
3342                        libcfs_net2str(net->net_id));
3343                 lnet_net_free(net);
3344                 return -EUSERS;
3345         }
3346
3347         /*
3348          * make sure you calculate the correct number of slots in the ping
3349          * buffer. Since the ping info is a flattened list of all the NIs,
3350          * we should allocate enough slots to accomodate the number of NIs
3351          * which will be added.
3352          *
3353          * since ni hasn't been configured yet, use
3354          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3355          */
3356         net_ni_count = lnet_get_net_ni_count_pre(net);
3357
3358         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3359                                     net_ni_count + lnet_get_ni_count(),
3360                                     false);
3361         if (rc < 0) {
3362                 lnet_net_free(net);
3363                 return rc;
3364         }
3365
3366         if (tun)
3367                 memcpy(&net->net_tunables,
3368                        &tun->lt_cmn, sizeof(net->net_tunables));
3369         else
3370                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3371
3372         net_id = net->net_id;
3373
3374         rc = lnet_startup_lndnet(net,
3375                                  (tun) ? &tun->lt_tun : NULL);
3376         if (rc < 0)
3377                 goto failed;
3378
3379         lnet_net_lock(LNET_LOCK_EX);
3380         net = lnet_get_net_locked(net_id);
3381         LASSERT(net);
3382
3383         /* apply the UDSPs */
3384         rc = lnet_udsp_apply_policies_on_net(net);
3385         if (rc)
3386                 CERROR("Failed to apply UDSPs on local net %s\n",
3387                        libcfs_net2str(net->net_id));
3388
3389         /* At this point we lost track of which NI was just added, so we
3390          * just re-apply the policies on all of the NIs on this net
3391          */
3392         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3393                 rc = lnet_udsp_apply_policies_on_ni(ni);
3394                 if (rc)
3395                         CERROR("Failed to apply UDSPs on ni %s\n",
3396                                libcfs_nid2str(ni->ni_nid));
3397         }
3398         lnet_net_unlock(LNET_LOCK_EX);
3399
3400         /*
3401          * Start the acceptor thread if this is the first network
3402          * being added that requires the thread.
3403          */
3404         if (net->net_lnd->lnd_accept) {
3405                 rc = lnet_acceptor_start();
3406                 if (rc < 0) {
3407                         /* shutdown the net that we just started */
3408                         CERROR("Failed to start up acceptor thread\n");
3409                         lnet_shutdown_lndnet(net);
3410                         goto failed;
3411                 }
3412         }
3413
3414         lnet_net_lock(LNET_LOCK_EX);
3415         lnet_peer_net_added(net);
3416         lnet_net_unlock(LNET_LOCK_EX);
3417
3418         lnet_ping_target_update(pbuf, ping_mdh);
3419
3420         return 0;
3421
3422 failed:
3423         lnet_ping_md_unlink(pbuf, &ping_mdh);
3424         lnet_ping_buffer_decref(pbuf);
3425         return rc;
3426 }
3427
3428 static void
3429 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3430 {
3431         if (tun) {
3432                 if (!tun->lt_cmn.lct_peer_timeout)
3433                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3434                 if (!tun->lt_cmn.lct_peer_tx_credits)
3435                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3436                 if (!tun->lt_cmn.lct_max_tx_credits)
3437                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3438         }
3439 }
3440
3441 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3442                                       struct lnet_ioctl_config_lnd_tunables *tun)
3443 {
3444         struct lnet_net *net;
3445         const char *nets;
3446         int rc;
3447         LIST_HEAD(net_head);
3448
3449         rc = lnet_parse_ip2nets(&nets, ip2nets);
3450         if (rc < 0)
3451                 return rc;
3452
3453         rc = lnet_parse_networks(&net_head, nets);
3454         if (rc < 0)
3455                 return rc;
3456
3457         lnet_set_tune_defaults(tun);
3458
3459         mutex_lock(&the_lnet.ln_api_mutex);
3460         while (!list_empty(&net_head)) {
3461                 net = list_entry(net_head.next, struct lnet_net, net_list);
3462                 list_del_init(&net->net_list);
3463                 rc = lnet_add_net_common(net, tun);
3464                 if (rc < 0)
3465                         goto out;
3466         }
3467
3468 out:
3469         mutex_unlock(&the_lnet.ln_api_mutex);
3470
3471         while (!list_empty(&net_head)) {
3472                 net = list_entry(net_head.next, struct lnet_net, net_list);
3473                 list_del_init(&net->net_list);
3474                 lnet_net_free(net);
3475         }
3476         return rc;
3477 }
3478
3479 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3480 {
3481         struct lnet_net *net;
3482         struct lnet_ni *ni;
3483         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3484         int rc, i;
3485         __u32 net_id, lnd_type;
3486
3487         /* get the tunables if they are available */
3488         if (conf->lic_cfg_hdr.ioc_len >=
3489             sizeof(*conf) + sizeof(*tun))
3490                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3491                         conf->lic_bulk;
3492
3493         /* handle legacy ip2nets from DLC */
3494         if (conf->lic_legacy_ip2nets[0] != '\0')
3495                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3496                                                   tun);
3497
3498         net_id = LNET_NIDNET(conf->lic_nid);
3499         lnd_type = LNET_NETTYP(net_id);
3500
3501         if (!libcfs_isknown_lnd(lnd_type)) {
3502                 CERROR("No valid net and lnd information provided\n");
3503                 return -EINVAL;
3504         }
3505
3506         net = lnet_net_alloc(net_id, NULL);
3507         if (!net)
3508                 return -ENOMEM;
3509
3510         for (i = 0; i < conf->lic_ncpts; i++) {
3511                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3512                         return -EINVAL;
3513         }
3514
3515         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3516                                        conf->lic_ni_intf);
3517         if (!ni)
3518                 return -ENOMEM;
3519
3520         lnet_set_tune_defaults(tun);
3521
3522         mutex_lock(&the_lnet.ln_api_mutex);
3523
3524         rc = lnet_add_net_common(net, tun);
3525
3526         mutex_unlock(&the_lnet.ln_api_mutex);
3527
3528         return rc;
3529 }
3530
3531 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3532 {
3533         struct lnet_net  *net;
3534         struct lnet_ni *ni;
3535         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3536         struct lnet_ping_buffer *pbuf;
3537         struct lnet_handle_md  ping_mdh;
3538         int               rc;
3539         int               net_count;
3540         __u32             addr;
3541
3542         /* don't allow userspace to shutdown the LOLND */
3543         if (LNET_NETTYP(net_id) == LOLND)
3544                 return -EINVAL;
3545
3546         mutex_lock(&the_lnet.ln_api_mutex);
3547
3548         lnet_net_lock(0);
3549
3550         net = lnet_get_net_locked(net_id);
3551         if (!net) {
3552                 CERROR("net %s not found\n",
3553                        libcfs_net2str(net_id));
3554                 rc = -ENOENT;
3555                 goto unlock_net;
3556         }
3557
3558         addr = LNET_NIDADDR(conf->lic_nid);
3559         if (addr == 0) {
3560                 /* remove the entire net */
3561                 net_count = lnet_get_net_ni_count_locked(net);
3562
3563                 lnet_net_unlock(0);
3564
3565                 /* create and link a new ping info, before removing the old one */
3566                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3567                                         lnet_get_ni_count() - net_count,
3568                                         false);
3569                 if (rc != 0)
3570                         goto unlock_api_mutex;
3571
3572                 lnet_shutdown_lndnet(net);
3573
3574                 lnet_acceptor_stop();
3575
3576                 lnet_ping_target_update(pbuf, ping_mdh);
3577
3578                 goto unlock_api_mutex;
3579         }
3580
3581         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3582         if (!ni) {
3583                 CERROR("nid %s not found\n",
3584                        libcfs_nid2str(conf->lic_nid));
3585                 rc = -ENOENT;
3586                 goto unlock_net;
3587         }
3588
3589         net_count = lnet_get_net_ni_count_locked(net);
3590
3591         lnet_net_unlock(0);
3592
3593         /* create and link a new ping info, before removing the old one */
3594         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3595                                   lnet_get_ni_count() - 1, false);
3596         if (rc != 0)
3597                 goto unlock_api_mutex;
3598
3599         lnet_shutdown_lndni(ni);
3600
3601         lnet_acceptor_stop();
3602
3603         lnet_ping_target_update(pbuf, ping_mdh);
3604
3605         /* check if the net is empty and remove it if it is */
3606         if (net_count == 1)
3607                 lnet_shutdown_lndnet(net);
3608
3609         goto unlock_api_mutex;
3610
3611 unlock_net:
3612         lnet_net_unlock(0);
3613 unlock_api_mutex:
3614         mutex_unlock(&the_lnet.ln_api_mutex);
3615
3616         return rc;
3617 }
3618
3619 /*
3620  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3621  * They are only expected to be called for unique networks.
3622  * That can be as a result of older DLC library
3623  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3624  */
3625 int
3626 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3627 {
3628         struct lnet_net *net;
3629         LIST_HEAD(net_head);
3630         int rc;
3631         struct lnet_ioctl_config_lnd_tunables tun;
3632         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3633
3634         /* Create a net/ni structures for the network string */
3635         rc = lnet_parse_networks(&net_head, nets);
3636         if (rc <= 0)
3637                 return rc == 0 ? -EINVAL : rc;
3638
3639         mutex_lock(&the_lnet.ln_api_mutex);
3640
3641         if (rc > 1) {
3642                 rc = -EINVAL; /* only add one network per call */
3643                 goto out_unlock_clean;
3644         }
3645
3646         net = list_entry(net_head.next, struct lnet_net, net_list);
3647         list_del_init(&net->net_list);
3648
3649         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3650
3651         memset(&tun, 0, sizeof(tun));
3652
3653         tun.lt_cmn.lct_peer_timeout =
3654           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3655                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3656         tun.lt_cmn.lct_peer_tx_credits =
3657           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3658                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3659         tun.lt_cmn.lct_peer_rtr_credits =
3660           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3661         tun.lt_cmn.lct_max_tx_credits =
3662           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3663                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3664
3665         rc = lnet_add_net_common(net, &tun);
3666
3667 out_unlock_clean:
3668         mutex_unlock(&the_lnet.ln_api_mutex);
3669         while (!list_empty(&net_head)) {
3670                 /* net_head list is empty in success case */
3671                 net = list_entry(net_head.next, struct lnet_net, net_list);
3672                 list_del_init(&net->net_list);
3673                 lnet_net_free(net);
3674         }
3675         return rc;
3676 }
3677
3678 int
3679 lnet_dyn_del_net(__u32 net_id)
3680 {
3681         struct lnet_net  *net;
3682         struct lnet_ping_buffer *pbuf;
3683         struct lnet_handle_md ping_mdh;
3684         int               rc;
3685         int               net_ni_count;
3686
3687         /* don't allow userspace to shutdown the LOLND */
3688         if (LNET_NETTYP(net_id) == LOLND)
3689                 return -EINVAL;
3690
3691         mutex_lock(&the_lnet.ln_api_mutex);
3692
3693         lnet_net_lock(0);
3694
3695         net = lnet_get_net_locked(net_id);
3696         if (net == NULL) {
3697                 lnet_net_unlock(0);
3698                 rc = -EINVAL;
3699                 goto out;
3700         }
3701
3702         net_ni_count = lnet_get_net_ni_count_locked(net);
3703
3704         lnet_net_unlock(0);
3705
3706         /* create and link a new ping info, before removing the old one */
3707         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3708                                     lnet_get_ni_count() - net_ni_count, false);
3709         if (rc != 0)
3710                 goto out;
3711
3712         lnet_shutdown_lndnet(net);
3713
3714         lnet_acceptor_stop();
3715
3716         lnet_ping_target_update(pbuf, ping_mdh);
3717
3718 out:
3719         mutex_unlock(&the_lnet.ln_api_mutex);
3720
3721         return rc;
3722 }
3723
3724 void lnet_incr_dlc_seq(void)
3725 {
3726         atomic_inc(&lnet_dlc_seq_no);
3727 }
3728
3729 __u32 lnet_get_dlc_seq_locked(void)
3730 {
3731         return atomic_read(&lnet_dlc_seq_no);
3732 }
3733
3734 static void
3735 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3736 {
3737         struct lnet_net *net;
3738         struct lnet_ni *ni;
3739
3740         lnet_net_lock(LNET_LOCK_EX);
3741         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3742                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3743                         if (ni->ni_nid == nid || all) {
3744                                 atomic_set(&ni->ni_healthv, value);
3745                                 if (list_empty(&ni->ni_recovery) &&
3746                                     value < LNET_MAX_HEALTH_VALUE) {
3747                                         CERROR("manually adding local NI %s to recovery\n",
3748                                                libcfs_nid2str(ni->ni_nid));
3749                                         list_add_tail(&ni->ni_recovery,
3750                                                       &the_lnet.ln_mt_localNIRecovq);
3751                                         lnet_ni_addref_locked(ni, 0);
3752                                 }
3753                                 if (!all) {
3754                                         lnet_net_unlock(LNET_LOCK_EX);
3755                                         return;
3756                                 }
3757                         }
3758                 }
3759         }
3760         lnet_net_unlock(LNET_LOCK_EX);
3761 }
3762
3763 static int
3764 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3765 {
3766         int cpt, rc = 0;
3767         struct lnet_ni *ni;
3768         lnet_nid_t nid = stats->hlni_nid;
3769
3770         cpt = lnet_net_lock_current();
3771         ni = lnet_nid2ni_locked(nid, cpt);
3772
3773         if (!ni) {
3774                 rc = -ENOENT;
3775                 goto unlock;
3776         }
3777
3778         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3779         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3780         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3781         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3782         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3783         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3784         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3785         stats->hlni_ping_count = ni->ni_ping_count;
3786         stats->hlni_next_ping = ni->ni_next_ping;
3787
3788 unlock:
3789         lnet_net_unlock(cpt);
3790
3791         return rc;
3792 }
3793
3794 static int
3795 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3796 {
3797         struct lnet_ni *ni;
3798         int i = 0;
3799
3800         lnet_net_lock(LNET_LOCK_EX);
3801         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3802                 list->rlst_nid_array[i] = ni->ni_nid;
3803                 i++;
3804                 if (i >= LNET_MAX_SHOW_NUM_NID)
3805                         break;
3806         }
3807         lnet_net_unlock(LNET_LOCK_EX);
3808         list->rlst_num_nids = i;
3809
3810         return 0;
3811 }
3812
3813 static int
3814 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3815 {
3816         struct lnet_peer_ni *lpni;
3817         int i = 0;
3818
3819         lnet_net_lock(LNET_LOCK_EX);
3820         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3821                 list->rlst_nid_array[i] = lpni->lpni_nid;
3822                 i++;
3823                 if (i >= LNET_MAX_SHOW_NUM_NID)
3824                         break;
3825         }
3826         lnet_net_unlock(LNET_LOCK_EX);
3827         list->rlst_num_nids = i;
3828
3829         return 0;
3830 }
3831
3832 /**
3833  * LNet ioctl handler.
3834  *
3835  */
3836 int
3837 LNetCtl(unsigned int cmd, void *arg)
3838 {
3839         struct libcfs_ioctl_data *data = arg;
3840         struct lnet_ioctl_config_data *config;
3841         struct lnet_process_id    id = {0};
3842         struct lnet_ni           *ni;
3843         int                       rc;
3844
3845         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3846                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3847
3848         switch (cmd) {
3849         case IOC_LIBCFS_GET_NI:
3850                 rc = LNetGetId(data->ioc_count, &id);
3851                 data->ioc_nid = id.nid;
3852                 return rc;
3853
3854         case IOC_LIBCFS_FAIL_NID:
3855                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3856
3857         case IOC_LIBCFS_ADD_ROUTE: {
3858                 /* default router sensitivity to 1 */
3859                 unsigned int sensitivity = 1;
3860                 config = arg;
3861
3862                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3863                         return -EINVAL;
3864
3865                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
3866                         sensitivity =
3867                           config->cfg_config_u.cfg_route.rtr_sensitivity;
3868                 }
3869
3870                 mutex_lock(&the_lnet.ln_api_mutex);
3871                 rc = lnet_add_route(config->cfg_net,
3872                                     config->cfg_config_u.cfg_route.rtr_hop,
3873                                     config->cfg_nid,
3874                                     config->cfg_config_u.cfg_route.
3875                                         rtr_priority, sensitivity);
3876                 mutex_unlock(&the_lnet.ln_api_mutex);
3877                 return rc;
3878         }
3879
3880         case IOC_LIBCFS_DEL_ROUTE:
3881                 config = arg;
3882
3883                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3884                         return -EINVAL;
3885
3886                 mutex_lock(&the_lnet.ln_api_mutex);
3887                 rc = lnet_del_route(config->cfg_net, config->cfg_nid);
3888                 mutex_unlock(&the_lnet.ln_api_mutex);
3889                 return rc;
3890
3891         case IOC_LIBCFS_GET_ROUTE:
3892                 config = arg;
3893
3894                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3895                         return -EINVAL;
3896
3897                 mutex_lock(&the_lnet.ln_api_mutex);
3898                 rc = lnet_get_route(config->cfg_count,
3899                                     &config->cfg_net,
3900                                     &config->cfg_config_u.cfg_route.rtr_hop,
3901                                     &config->cfg_nid,
3902                                     &config->cfg_config_u.cfg_route.rtr_flags,
3903                                     &config->cfg_config_u.cfg_route.
3904                                         rtr_priority,
3905                                     &config->cfg_config_u.cfg_route.
3906                                         rtr_sensitivity);
3907                 mutex_unlock(&the_lnet.ln_api_mutex);
3908                 return rc;
3909
3910         case IOC_LIBCFS_GET_LOCAL_NI: {
3911                 struct lnet_ioctl_config_ni *cfg_ni;
3912                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3913                 struct lnet_ioctl_element_stats *stats;
3914                 __u32 tun_size;
3915
3916                 cfg_ni = arg;
3917
3918                 /* get the tunables if they are available */
3919                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3920                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3921                         return -EINVAL;
3922
3923                 stats = (struct lnet_ioctl_element_stats *)
3924                         cfg_ni->lic_bulk;
3925                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3926                                 (cfg_ni->lic_bulk + sizeof(*stats));
3927
3928                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
3929                         sizeof(*stats);
3930
3931                 mutex_lock(&the_lnet.ln_api_mutex);
3932                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
3933                 mutex_unlock(&the_lnet.ln_api_mutex);
3934                 return rc;
3935         }
3936
3937         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
3938                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
3939
3940                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
3941                         return -EINVAL;
3942
3943                 mutex_lock(&the_lnet.ln_api_mutex);
3944                 rc = lnet_get_ni_stats(msg_stats);
3945                 mutex_unlock(&the_lnet.ln_api_mutex);
3946
3947                 return rc;
3948         }
3949
3950         case IOC_LIBCFS_GET_NET: {
3951                 size_t total = sizeof(*config) +
3952                                sizeof(struct lnet_ioctl_net_config);
3953                 config = arg;
3954
3955                 if (config->cfg_hdr.ioc_len < total)
3956                         return -EINVAL;
3957
3958                 mutex_lock(&the_lnet.ln_api_mutex);
3959                 rc = lnet_get_net_config(config);
3960                 mutex_unlock(&the_lnet.ln_api_mutex);
3961                 return rc;
3962         }
3963
3964         case IOC_LIBCFS_GET_LNET_STATS:
3965         {
3966                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
3967
3968                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
3969                         return -EINVAL;
3970
3971                 mutex_lock(&the_lnet.ln_api_mutex);
3972                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
3973                 mutex_unlock(&the_lnet.ln_api_mutex);
3974                 return rc;
3975         }
3976
3977         case IOC_LIBCFS_CONFIG_RTR:
3978                 config = arg;
3979
3980                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3981                         return -EINVAL;
3982
3983                 mutex_lock(&the_lnet.ln_api_mutex);
3984                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
3985                         rc = lnet_rtrpools_enable();
3986                         mutex_unlock(&the_lnet.ln_api_mutex);
3987                         return rc;
3988                 }
3989                 lnet_rtrpools_disable();
3990                 mutex_unlock(&the_lnet.ln_api_mutex);
3991                 return 0;
3992
3993         case IOC_LIBCFS_ADD_BUF:
3994                 config = arg;
3995
3996                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3997                         return -EINVAL;
3998
3999                 mutex_lock(&the_lnet.ln_api_mutex);
4000                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4001                                                 buf_tiny,
4002                                           config->cfg_config_u.cfg_buffers.
4003                                                 buf_small,
4004                                           config->cfg_config_u.cfg_buffers.
4005                                                 buf_large);
4006                 mutex_unlock(&the_lnet.ln_api_mutex);
4007                 return rc;
4008
4009         case IOC_LIBCFS_SET_NUMA_RANGE: {
4010                 struct lnet_ioctl_set_value *numa;
4011                 numa = arg;
4012                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4013                         return -EINVAL;
4014                 lnet_net_lock(LNET_LOCK_EX);
4015                 lnet_numa_range = numa->sv_value;
4016                 lnet_net_unlock(LNET_LOCK_EX);
4017                 return 0;
4018         }
4019
4020         case IOC_LIBCFS_GET_NUMA_RANGE: {
4021                 struct lnet_ioctl_set_value *numa;
4022                 numa = arg;
4023                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4024                         return -EINVAL;
4025                 numa->sv_value = lnet_numa_range;
4026                 return 0;
4027         }
4028
4029         case IOC_LIBCFS_GET_BUF: {
4030                 struct lnet_ioctl_pool_cfg *pool_cfg;
4031                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4032
4033                 config = arg;
4034
4035                 if (config->cfg_hdr.ioc_len < total)
4036                         return -EINVAL;
4037
4038                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4039
4040                 mutex_lock(&the_lnet.ln_api_mutex);
4041                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4042                 mutex_unlock(&the_lnet.ln_api_mutex);
4043                 return rc;
4044         }
4045
4046         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4047                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4048
4049                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4050                         return -EINVAL;
4051
4052                 mutex_lock(&the_lnet.ln_api_mutex);
4053                 rc = lnet_get_local_ni_hstats(stats);
4054                 mutex_unlock(&the_lnet.ln_api_mutex);
4055
4056                 return rc;
4057         }
4058
4059         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4060                 struct lnet_ioctl_recovery_list *list = arg;
4061                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4062                         return -EINVAL;
4063
4064                 mutex_lock(&the_lnet.ln_api_mutex);
4065                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4066                         rc = lnet_get_local_ni_recovery_list(list);
4067                 else
4068                         rc = lnet_get_peer_ni_recovery_list(list);
4069                 mutex_unlock(&the_lnet.ln_api_mutex);
4070                 return rc;
4071         }
4072
4073         case IOC_LIBCFS_ADD_PEER_NI: {
4074                 struct lnet_ioctl_peer_cfg *cfg = arg;
4075
4076                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4077                         return -EINVAL;
4078
4079                 mutex_lock(&the_lnet.ln_api_mutex);
4080                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
4081                                       cfg->prcfg_cfg_nid,
4082                                       cfg->prcfg_mr);
4083                 mutex_unlock(&the_lnet.ln_api_mutex);
4084                 return rc;
4085         }
4086
4087         case IOC_LIBCFS_DEL_PEER_NI: {
4088                 struct lnet_ioctl_peer_cfg *cfg = arg;
4089
4090                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4091                         return -EINVAL;
4092
4093                 mutex_lock(&the_lnet.ln_api_mutex);
4094                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
4095                                       cfg->prcfg_cfg_nid);
4096                 mutex_unlock(&the_lnet.ln_api_mutex);
4097                 return rc;
4098         }
4099
4100         case IOC_LIBCFS_GET_PEER_INFO: {
4101                 struct lnet_ioctl_peer *peer_info = arg;
4102
4103                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4104                         return -EINVAL;
4105
4106                 mutex_lock(&the_lnet.ln_api_mutex);
4107                 rc = lnet_get_peer_ni_info(
4108                    peer_info->pr_count,
4109                    &peer_info->pr_nid,
4110                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4111                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4112                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4113                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4114                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4115                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4116                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4117                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4118                 mutex_unlock(&the_lnet.ln_api_mutex);
4119                 return rc;
4120         }
4121
4122         case IOC_LIBCFS_GET_PEER_NI: {
4123                 struct lnet_ioctl_peer_cfg *cfg = arg;
4124
4125                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4126                         return -EINVAL;
4127
4128                 mutex_lock(&the_lnet.ln_api_mutex);
4129                 rc = lnet_get_peer_info(cfg,
4130                                         (void __user *)cfg->prcfg_bulk);
4131                 mutex_unlock(&the_lnet.ln_api_mutex);
4132                 return rc;
4133         }
4134
4135         case IOC_LIBCFS_GET_PEER_LIST: {
4136                 struct lnet_ioctl_peer_cfg *cfg = arg;
4137
4138                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4139                         return -EINVAL;
4140
4141                 mutex_lock(&the_lnet.ln_api_mutex);
4142                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4143                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4144                 mutex_unlock(&the_lnet.ln_api_mutex);
4145                 return rc;
4146         }
4147
4148         case IOC_LIBCFS_SET_HEALHV: {
4149                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4150                 int value;
4151                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4152                         return -EINVAL;
4153                 if (cfg->rh_value < 0 ||
4154                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4155                         value = LNET_MAX_HEALTH_VALUE;
4156                 else
4157                         value = cfg->rh_value;
4158                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4159                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4160                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4161                 mutex_lock(&the_lnet.ln_api_mutex);
4162                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
4163                         lnet_ni_set_healthv(cfg->rh_nid, value,
4164                                              cfg->rh_all);
4165                 else
4166                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
4167                                                   cfg->rh_all);
4168                 mutex_unlock(&the_lnet.ln_api_mutex);
4169                 return 0;
4170         }
4171
4172         case IOC_LIBCFS_NOTIFY_ROUTER: {
4173                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
4174
4175                 /* The deadline passed in by the user should be some time in
4176                  * seconds in the future since the UNIX epoch. We have to map
4177                  * that deadline to the wall clock.
4178                  */
4179                 deadline += ktime_get_seconds();
4180                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags, false,
4181                                    deadline);
4182         }
4183
4184         case IOC_LIBCFS_LNET_DIST:
4185                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
4186                 if (rc < 0 && rc != -EHOSTUNREACH)
4187                         return rc;
4188
4189                 data->ioc_u32[0] = rc;
4190                 return 0;
4191
4192         case IOC_LIBCFS_TESTPROTOCOMPAT:
4193                 the_lnet.ln_testprotocompat = data->ioc_flags;
4194                 return 0;
4195
4196         case IOC_LIBCFS_LNET_FAULT:
4197                 return lnet_fault_ctl(data->ioc_flags, data);
4198
4199         case IOC_LIBCFS_PING: {
4200                 signed long timeout;
4201
4202                 id.nid = data->ioc_nid;
4203                 id.pid = data->ioc_u32[0];
4204
4205                 /* If timeout is negative then set default of 3 minutes */
4206                 if (((s32)data->ioc_u32[1] <= 0) ||
4207                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4208                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4209                 else
4210                         timeout = nsecs_to_jiffies(data->ioc_u32[1] * NSEC_PER_MSEC);
4211
4212                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
4213                                data->ioc_plen1 / sizeof(struct lnet_process_id));
4214
4215                 if (rc < 0)
4216                         return rc;
4217
4218                 data->ioc_count = rc;
4219                 return 0;
4220         }
4221
4222         case IOC_LIBCFS_PING_PEER: {
4223                 struct lnet_ioctl_ping_data *ping = arg;
4224                 struct lnet_peer *lp;
4225                 signed long timeout;
4226
4227                 /* If timeout is negative then set default of 3 minutes */
4228                 if (((s32)ping->op_param) <= 0 ||
4229                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4230                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4231                 else
4232                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4233
4234                 rc = lnet_ping(ping->ping_id, timeout,
4235                                ping->ping_buf,
4236                                ping->ping_count);
4237                 if (rc < 0)
4238                         return rc;
4239
4240                 mutex_lock(&the_lnet.ln_api_mutex);
4241                 lp = lnet_find_peer(ping->ping_id.nid);
4242                 if (lp) {
4243                         ping->ping_id.nid = lp->lp_primary_nid;
4244                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4245                         lnet_peer_decref_locked(lp);
4246                 }
4247                 mutex_unlock(&the_lnet.ln_api_mutex);
4248
4249                 ping->ping_count = rc;
4250                 return 0;
4251         }
4252
4253         case IOC_LIBCFS_DISCOVER: {
4254                 struct lnet_ioctl_ping_data *discover = arg;
4255                 struct lnet_peer *lp;
4256
4257                 rc = lnet_discover(discover->ping_id, discover->op_param,
4258                                    discover->ping_buf,
4259                                    discover->ping_count);
4260                 if (rc < 0)
4261                         return rc;
4262
4263                 mutex_lock(&the_lnet.ln_api_mutex);
4264                 lp = lnet_find_peer(discover->ping_id.nid);
4265                 if (lp) {
4266                         discover->ping_id.nid = lp->lp_primary_nid;
4267                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4268                         lnet_peer_decref_locked(lp);
4269                 }
4270                 mutex_unlock(&the_lnet.ln_api_mutex);
4271
4272                 discover->ping_count = rc;
4273                 return 0;
4274         }
4275
4276         case IOC_LIBCFS_ADD_UDSP: {
4277                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4278                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4279
4280                 mutex_lock(&the_lnet.ln_api_mutex);
4281                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4282                 if (!rc) {
4283                         rc = lnet_udsp_apply_policies(NULL, false);
4284                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4285                         rc = 0;
4286                 }
4287                 mutex_unlock(&the_lnet.ln_api_mutex);
4288
4289                 return rc;
4290         }
4291
4292         case IOC_LIBCFS_DEL_UDSP: {
4293                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4294                 int idx = ioc_udsp->iou_idx;
4295
4296                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4297                         return -EINVAL;
4298
4299                 mutex_lock(&the_lnet.ln_api_mutex);
4300                 rc = lnet_udsp_del_policy(idx);
4301                 if (!rc) {
4302                         rc = lnet_udsp_apply_policies(NULL, false);
4303                         CDEBUG(D_NET, "policy re-application returned %d\n",
4304                                rc);
4305                         rc = 0;
4306                 }
4307                 mutex_unlock(&the_lnet.ln_api_mutex);
4308
4309                 return rc;
4310         }
4311
4312         case IOC_LIBCFS_GET_UDSP_SIZE: {
4313                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4314                 struct lnet_udsp *udsp;
4315
4316                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4317                         return -EINVAL;
4318
4319                 rc = 0;
4320
4321                 mutex_lock(&the_lnet.ln_api_mutex);
4322                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4323                 if (!udsp) {
4324                         rc = -ENOENT;
4325                 } else {
4326                         /* coming in iou_idx will hold the idx of the udsp
4327                          * to get the size of. going out the iou_idx will
4328                          * hold the size of the UDSP found at the passed
4329                          * in index.
4330                          */
4331                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4332                         if (ioc_udsp->iou_idx < 0)
4333                                 rc = -EINVAL;
4334                 }
4335                 mutex_unlock(&the_lnet.ln_api_mutex);
4336
4337                 return rc;
4338         }
4339
4340         case IOC_LIBCFS_GET_UDSP: {
4341                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4342                 struct lnet_udsp *udsp;
4343
4344                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4345                         return -EINVAL;
4346
4347                 rc = 0;
4348
4349                 mutex_lock(&the_lnet.ln_api_mutex);
4350                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4351                 if (!udsp)
4352                         rc = -ENOENT;
4353                 else
4354                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4355                 mutex_unlock(&the_lnet.ln_api_mutex);
4356
4357                 return rc;
4358         }
4359
4360         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4361                 struct lnet_ioctl_construct_udsp_info *info = arg;
4362
4363                 if (info->cud_hdr.ioc_len < sizeof(*info))
4364                         return -EINVAL;
4365
4366                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4367                        libcfs_nid2str(info->cud_nid));
4368
4369                 mutex_lock(&the_lnet.ln_api_mutex);
4370                 lnet_udsp_get_construct_info(info);
4371                 mutex_unlock(&the_lnet.ln_api_mutex);
4372
4373                 return 0;
4374         }
4375
4376         default:
4377                 ni = lnet_net2ni_addref(data->ioc_net);
4378                 if (ni == NULL)
4379                         return -EINVAL;
4380
4381                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4382                         rc = -EINVAL;
4383                 else
4384                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4385
4386                 lnet_ni_decref(ni);
4387                 return rc;
4388         }
4389         /* not reached */
4390 }
4391 EXPORT_SYMBOL(LNetCtl);
4392
4393 void LNetDebugPeer(struct lnet_process_id id)
4394 {
4395         lnet_debug_peer(id.nid);
4396 }
4397 EXPORT_SYMBOL(LNetDebugPeer);
4398
4399 /**
4400  * Determine if the specified peer \a nid is on the local node.
4401  *
4402  * \param nid   peer nid to check
4403  *
4404  * \retval true         If peer NID is on the local node.
4405  * \retval false        If peer NID is not on the local node.
4406  */
4407 bool LNetIsPeerLocal(lnet_nid_t nid)
4408 {
4409         struct lnet_net *net;
4410         struct lnet_ni *ni;
4411         int cpt;
4412
4413         cpt = lnet_net_lock_current();
4414         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4415                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4416                         if (ni->ni_nid == nid) {
4417                                 lnet_net_unlock(cpt);
4418                                 return true;
4419                         }
4420                 }
4421         }
4422         lnet_net_unlock(cpt);
4423
4424         return false;
4425 }
4426 EXPORT_SYMBOL(LNetIsPeerLocal);
4427
4428 /**
4429  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
4430  * Note that all interfaces share a same PID, as requested by LNetNIInit().
4431  *
4432  * \param index Index of the interface to look up.
4433  * \param id On successful return, this location will hold the
4434  * struct lnet_process_id ID of the interface.
4435  *
4436  * \retval 0 If an interface exists at \a index.
4437  * \retval -ENOENT If no interface has been found.
4438  */
4439 int
4440 LNetGetId(unsigned int index, struct lnet_process_id *id)
4441 {
4442         struct lnet_ni   *ni;
4443         struct lnet_net  *net;
4444         int               cpt;
4445         int               rc = -ENOENT;
4446
4447         LASSERT(the_lnet.ln_refcount > 0);
4448
4449         cpt = lnet_net_lock_current();
4450
4451         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4452                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4453                         if (index-- != 0)
4454                                 continue;
4455
4456                         id->nid = ni->ni_nid;
4457                         id->pid = the_lnet.ln_pid;
4458                         rc = 0;
4459                         break;
4460                 }
4461         }
4462
4463         lnet_net_unlock(cpt);
4464         return rc;
4465 }
4466 EXPORT_SYMBOL(LNetGetId);
4467
4468 struct ping_data {
4469         int rc;
4470         int replied;
4471         struct lnet_handle_md mdh;
4472         struct completion completion;
4473 };
4474
4475 static void
4476 lnet_ping_event_handler(struct lnet_event *event)
4477 {
4478         struct ping_data *pd = event->md_user_ptr;
4479
4480         CDEBUG(D_NET, "ping event (%d %d)%s\n",
4481                event->type, event->status,
4482                event->unlinked ? " unlinked" : "");
4483
4484         if (event->status) {
4485                 if (!pd->rc)
4486                         pd->rc = event->status;
4487         } else if (event->type == LNET_EVENT_REPLY) {
4488                 pd->replied = 1;
4489                 pd->rc = event->mlength;
4490         }
4491         if (event->unlinked)
4492                 complete(&pd->completion);
4493 }
4494
4495 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4496                      struct lnet_process_id __user *ids, int n_ids)
4497 {
4498         struct lnet_md md = { NULL };
4499         struct ping_data pd = { 0 };
4500         struct lnet_ping_buffer *pbuf;
4501         struct lnet_process_id tmpid;
4502         int i;
4503         int nob;
4504         int rc;
4505         int rc2;
4506
4507         /* n_ids limit is arbitrary */
4508         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4509                 return -EINVAL;
4510
4511         /*
4512          * if the user buffer has more space than the lnet_interfaces_max
4513          * then only fill it up to lnet_interfaces_max
4514          */
4515         if (n_ids > lnet_interfaces_max)
4516                 n_ids = lnet_interfaces_max;
4517
4518         if (id.pid == LNET_PID_ANY)
4519                 id.pid = LNET_PID_LUSTRE;
4520
4521         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4522         if (!pbuf)
4523                 return -ENOMEM;
4524
4525         /* initialize md content */
4526         md.start     = &pbuf->pb_info;
4527         md.length    = LNET_PING_INFO_SIZE(n_ids);
4528         md.threshold = 2; /* GET/REPLY */
4529         md.max_size  = 0;
4530         md.options   = LNET_MD_TRUNCATE;
4531         md.user_ptr  = &pd;
4532         md.handler   = lnet_ping_event_handler;
4533
4534         init_completion(&pd.completion);
4535
4536         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
4537         if (rc != 0) {
4538                 CERROR("Can't bind MD: %d\n", rc);
4539                 goto fail_ping_buffer_decref;
4540         }
4541
4542         rc = LNetGet(LNET_NID_ANY, pd.mdh, id,
4543                      LNET_RESERVED_PORTAL,
4544                      LNET_PROTO_PING_MATCHBITS, 0, false);
4545
4546         if (rc != 0) {
4547                 /* Don't CERROR; this could be deliberate! */
4548                 rc2 = LNetMDUnlink(pd.mdh);
4549                 LASSERT(rc2 == 0);
4550
4551                 /* NB must wait for the UNLINK event below... */
4552         }
4553
4554         if (wait_for_completion_timeout(&pd.completion, timeout) == 0) {
4555                 /* Ensure completion in finite time... */
4556                 LNetMDUnlink(pd.mdh);
4557                 wait_for_completion(&pd.completion);
4558         }
4559         if (!pd.replied) {
4560                 rc = -EIO;
4561                 goto fail_ping_buffer_decref;
4562         }
4563
4564         nob = pd.rc;
4565         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4566
4567         rc = -EPROTO;           /* if I can't parse... */
4568
4569         if (nob < 8) {
4570                 CERROR("%s: ping info too short %d\n",
4571                        libcfs_id2str(id), nob);
4572                 goto fail_ping_buffer_decref;
4573         }
4574
4575         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4576                 lnet_swap_pinginfo(pbuf);
4577         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4578                 CERROR("%s: Unexpected magic %08x\n",
4579                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4580                 goto fail_ping_buffer_decref;
4581         }
4582
4583         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4584                 CERROR("%s: ping w/o NI status: 0x%x\n",
4585                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4586                 goto fail_ping_buffer_decref;
4587         }
4588
4589         if (nob < LNET_PING_INFO_SIZE(0)) {
4590                 CERROR("%s: Short reply %d(%d min)\n",
4591                        libcfs_id2str(id),
4592                        nob, (int)LNET_PING_INFO_SIZE(0));
4593                 goto fail_ping_buffer_decref;
4594         }
4595
4596         if (pbuf->pb_info.pi_nnis < n_ids)
4597                 n_ids = pbuf->pb_info.pi_nnis;
4598
4599         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4600                 CERROR("%s: Short reply %d(%d expected)\n",
4601                        libcfs_id2str(id),
4602                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4603                 goto fail_ping_buffer_decref;
4604         }
4605
4606         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4607
4608         memset(&tmpid, 0, sizeof(tmpid));
4609         for (i = 0; i < n_ids; i++) {
4610                 tmpid.pid = pbuf->pb_info.pi_pid;
4611                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4612                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4613                         goto fail_ping_buffer_decref;
4614         }
4615         rc = pbuf->pb_info.pi_nnis;
4616
4617  fail_ping_buffer_decref:
4618         lnet_ping_buffer_decref(pbuf);
4619         return rc;
4620 }
4621
4622 static int
4623 lnet_discover(struct lnet_process_id id, __u32 force,
4624               struct lnet_process_id __user *ids, int n_ids)
4625 {
4626         struct lnet_peer_ni *lpni;
4627         struct lnet_peer_ni *p;
4628         struct lnet_peer *lp;
4629         struct lnet_process_id *buf;
4630         int cpt;
4631         int i;
4632         int rc;
4633
4634         if (n_ids <= 0 ||
4635             id.nid == LNET_NID_ANY)
4636                 return -EINVAL;
4637
4638         if (id.pid == LNET_PID_ANY)
4639                 id.pid = LNET_PID_LUSTRE;
4640
4641         /*
4642          * If the user buffer has more space than the lnet_interfaces_max,
4643          * then only fill it up to lnet_interfaces_max.
4644          */
4645         if (n_ids > lnet_interfaces_max)
4646                 n_ids = lnet_interfaces_max;
4647
4648         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
4649         if (!buf)
4650                 return -ENOMEM;
4651
4652         cpt = lnet_net_lock_current();
4653         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4654         if (IS_ERR(lpni)) {
4655                 rc = PTR_ERR(lpni);
4656                 goto out;
4657         }
4658
4659         /*
4660          * Clearing the NIDS_UPTODATE flag ensures the peer will
4661          * be discovered, provided discovery has not been disabled.
4662          */
4663         lp = lpni->lpni_peer_net->lpn_peer;
4664         spin_lock(&lp->lp_lock);
4665         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4666         /* If the force flag is set, force a PING and PUSH as well. */
4667         if (force)
4668                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4669         spin_unlock(&lp->lp_lock);
4670         rc = lnet_discover_peer_locked(lpni, cpt, true);
4671         if (rc)
4672                 goto out_decref;
4673
4674         /* The lpni (or lp) for this NID may have changed and our ref is
4675          * the only thing keeping the old one around. Release the ref
4676          * and lookup the lpni again
4677          */
4678         lnet_peer_ni_decref_locked(lpni);
4679         lpni = lnet_find_peer_ni_locked(id.nid);
4680         if (!lpni) {
4681                 rc = -ENOENT;
4682                 goto out;
4683         }
4684         lp = lpni->lpni_peer_net->lpn_peer;
4685
4686         i = 0;
4687         p = NULL;
4688         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4689                 buf[i].pid = id.pid;
4690                 buf[i].nid = p->lpni_nid;
4691                 if (++i >= n_ids)
4692                         break;
4693         }
4694         rc = i;
4695
4696 out_decref:
4697         lnet_peer_ni_decref_locked(lpni);
4698 out:
4699         lnet_net_unlock(cpt);
4700
4701         if (rc >= 0)
4702                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
4703                         rc = -EFAULT;
4704         CFS_FREE_PTR_ARRAY(buf, n_ids);
4705
4706         return rc;
4707 }
4708
4709 /**
4710  * Retrieve peer discovery status.
4711  *
4712  * \retval 1 if lnet_peer_discovery_disabled is 0
4713  * \retval 0 if lnet_peer_discovery_disabled is 1
4714  */
4715 int
4716 LNetGetPeerDiscoveryStatus(void)
4717 {
4718         return !lnet_peer_discovery_disabled;
4719 }
4720 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);