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