Whamcloud - gitweb
99089176b6baf6ec6a9cad7e9a5f12be39f1f683
[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_nid2cpt(struct lnet_nid *nid, struct lnet_ni *ni)
1588 {
1589         int     cpt;
1590         int     cpt2;
1591
1592         if (LNET_CPT_NUMBER == 1)
1593                 return 0; /* the only one */
1594
1595         cpt = lnet_net_lock_current();
1596
1597         cpt2 = lnet_cpt_of_nid_locked(nid, ni);
1598
1599         lnet_net_unlock(cpt);
1600
1601         return cpt2;
1602 }
1603 EXPORT_SYMBOL(lnet_nid2cpt);
1604
1605 int
1606 lnet_cpt_of_nid(lnet_nid_t nid4, struct lnet_ni *ni)
1607 {
1608         struct lnet_nid nid;
1609
1610         if (LNET_CPT_NUMBER == 1)
1611                 return 0; /* the only one */
1612
1613         lnet_nid4_to_nid(nid4, &nid);
1614         return lnet_nid2cpt(&nid, ni);
1615 }
1616 EXPORT_SYMBOL(lnet_cpt_of_nid);
1617
1618 int
1619 lnet_islocalnet_locked(__u32 net_id)
1620 {
1621         struct lnet_net *net;
1622         bool local;
1623
1624         net = lnet_get_net_locked(net_id);
1625
1626         local = net != NULL;
1627
1628         return local;
1629 }
1630
1631 int
1632 lnet_islocalnet(__u32 net_id)
1633 {
1634         int cpt;
1635         bool local;
1636
1637         cpt = lnet_net_lock_current();
1638
1639         local = lnet_islocalnet_locked(net_id);
1640
1641         lnet_net_unlock(cpt);
1642
1643         return local;
1644 }
1645
1646 struct lnet_ni  *
1647 lnet_nid_to_ni_locked(struct lnet_nid *nid, int cpt)
1648 {
1649         struct lnet_net  *net;
1650         struct lnet_ni *ni;
1651
1652         LASSERT(cpt != LNET_LOCK_EX);
1653
1654         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1655                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1656                         if (nid_same(&ni->ni_nid, nid))
1657                                 return ni;
1658                 }
1659         }
1660
1661         return NULL;
1662 }
1663
1664 struct lnet_ni  *
1665 lnet_nid2ni_locked(lnet_nid_t nid4, int cpt)
1666 {
1667         struct lnet_nid nid;
1668
1669         lnet_nid4_to_nid(nid4, &nid);
1670         return lnet_nid_to_ni_locked(&nid, cpt);
1671 }
1672
1673 struct lnet_ni *
1674 lnet_nid2ni_addref(lnet_nid_t nid4)
1675 {
1676         struct lnet_ni *ni;
1677         struct lnet_nid nid;
1678
1679         lnet_nid4_to_nid(nid4, &nid);
1680
1681         lnet_net_lock(0);
1682         ni = lnet_nid_to_ni_locked(&nid, 0);
1683         if (ni)
1684                 lnet_ni_addref_locked(ni, 0);
1685         lnet_net_unlock(0);
1686
1687         return ni;
1688 }
1689 EXPORT_SYMBOL(lnet_nid2ni_addref);
1690
1691 struct lnet_ni *
1692 lnet_nid_to_ni_addref(struct lnet_nid *nid)
1693 {
1694         struct lnet_ni *ni;
1695
1696         lnet_net_lock(0);
1697         ni = lnet_nid_to_ni_locked(nid, 0);
1698         if (ni)
1699                 lnet_ni_addref_locked(ni, 0);
1700         lnet_net_unlock(0);
1701
1702         return ni;
1703 }
1704 EXPORT_SYMBOL(lnet_nid_to_ni_addref);
1705
1706 int
1707 lnet_islocalnid(lnet_nid_t nid)
1708 {
1709         struct lnet_ni  *ni;
1710         int             cpt;
1711
1712         cpt = lnet_net_lock_current();
1713         ni = lnet_nid2ni_locked(nid, cpt);
1714         lnet_net_unlock(cpt);
1715
1716         return ni != NULL;
1717 }
1718
1719 int
1720 lnet_count_acceptor_nets(void)
1721 {
1722         /* Return the # of NIs that need the acceptor. */
1723         int              count = 0;
1724         struct lnet_net  *net;
1725         int              cpt;
1726
1727         cpt = lnet_net_lock_current();
1728         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1729                 /* all socklnd type networks should have the acceptor
1730                  * thread started */
1731                 if (net->net_lnd->lnd_accept != NULL)
1732                         count++;
1733         }
1734
1735         lnet_net_unlock(cpt);
1736
1737         return count;
1738 }
1739
1740 struct lnet_ping_buffer *
1741 lnet_ping_buffer_alloc(int nnis, gfp_t gfp)
1742 {
1743         struct lnet_ping_buffer *pbuf;
1744
1745         LIBCFS_ALLOC_GFP(pbuf, LNET_PING_BUFFER_SIZE(nnis), gfp);
1746         if (pbuf) {
1747                 pbuf->pb_nnis = nnis;
1748                 pbuf->pb_needs_post = false;
1749                 atomic_set(&pbuf->pb_refcnt, 1);
1750         }
1751
1752         return pbuf;
1753 }
1754
1755 void
1756 lnet_ping_buffer_free(struct lnet_ping_buffer *pbuf)
1757 {
1758         LASSERT(atomic_read(&pbuf->pb_refcnt) == 0);
1759         LIBCFS_FREE(pbuf, LNET_PING_BUFFER_SIZE(pbuf->pb_nnis));
1760 }
1761
1762 static struct lnet_ping_buffer *
1763 lnet_ping_target_create(int nnis)
1764 {
1765         struct lnet_ping_buffer *pbuf;
1766
1767         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
1768         if (pbuf == NULL) {
1769                 CERROR("Can't allocate ping source [%d]\n", nnis);
1770                 return NULL;
1771         }
1772
1773         pbuf->pb_info.pi_nnis = nnis;
1774         pbuf->pb_info.pi_pid = the_lnet.ln_pid;
1775         pbuf->pb_info.pi_magic = LNET_PROTO_PING_MAGIC;
1776         pbuf->pb_info.pi_features =
1777                 LNET_PING_FEAT_NI_STATUS | LNET_PING_FEAT_MULTI_RAIL;
1778
1779         return pbuf;
1780 }
1781
1782 static inline int
1783 lnet_get_net_ni_count_locked(struct lnet_net *net)
1784 {
1785         struct lnet_ni  *ni;
1786         int             count = 0;
1787
1788         list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1789                 count++;
1790
1791         return count;
1792 }
1793
1794 static inline int
1795 lnet_get_net_ni_count_pre(struct lnet_net *net)
1796 {
1797         struct lnet_ni  *ni;
1798         int             count = 0;
1799
1800         list_for_each_entry(ni, &net->net_ni_added, ni_netlist)
1801                 count++;
1802
1803         return count;
1804 }
1805
1806 static inline int
1807 lnet_get_ni_count(void)
1808 {
1809         struct lnet_ni  *ni;
1810         struct lnet_net *net;
1811         int             count = 0;
1812
1813         lnet_net_lock(0);
1814
1815         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1816                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist)
1817                         count++;
1818         }
1819
1820         lnet_net_unlock(0);
1821
1822         return count;
1823 }
1824
1825 void
1826 lnet_swap_pinginfo(struct lnet_ping_buffer *pbuf)
1827 {
1828         struct lnet_ni_status *stat;
1829         int nnis;
1830         int i;
1831
1832         __swab32s(&pbuf->pb_info.pi_magic);
1833         __swab32s(&pbuf->pb_info.pi_features);
1834         __swab32s(&pbuf->pb_info.pi_pid);
1835         __swab32s(&pbuf->pb_info.pi_nnis);
1836         nnis = pbuf->pb_info.pi_nnis;
1837         if (nnis > pbuf->pb_nnis)
1838                 nnis = pbuf->pb_nnis;
1839         for (i = 0; i < nnis; i++) {
1840                 stat = &pbuf->pb_info.pi_ni[i];
1841                 __swab64s(&stat->ns_nid);
1842                 __swab32s(&stat->ns_status);
1843         }
1844 }
1845
1846 int
1847 lnet_ping_info_validate(struct lnet_ping_info *pinfo)
1848 {
1849         if (!pinfo)
1850                 return -EINVAL;
1851         if (pinfo->pi_magic != LNET_PROTO_PING_MAGIC)
1852                 return -EPROTO;
1853         if (!(pinfo->pi_features & LNET_PING_FEAT_NI_STATUS))
1854                 return -EPROTO;
1855         /* Loopback is guaranteed to be present */
1856         if (pinfo->pi_nnis < 1 || pinfo->pi_nnis > lnet_interfaces_max)
1857                 return -ERANGE;
1858         if (LNET_PING_INFO_LONI(pinfo) != LNET_NID_LO_0)
1859                 return -EPROTO;
1860         return 0;
1861 }
1862
1863 static void
1864 lnet_ping_target_destroy(void)
1865 {
1866         struct lnet_net *net;
1867         struct lnet_ni  *ni;
1868
1869         lnet_net_lock(LNET_LOCK_EX);
1870
1871         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1872                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1873                         lnet_ni_lock(ni);
1874                         ni->ni_status = NULL;
1875                         lnet_ni_unlock(ni);
1876                 }
1877         }
1878
1879         lnet_ping_buffer_decref(the_lnet.ln_ping_target);
1880         the_lnet.ln_ping_target = NULL;
1881
1882         lnet_net_unlock(LNET_LOCK_EX);
1883 }
1884
1885 static void
1886 lnet_ping_target_event_handler(struct lnet_event *event)
1887 {
1888         struct lnet_ping_buffer *pbuf = event->md_user_ptr;
1889
1890         if (event->unlinked)
1891                 lnet_ping_buffer_decref(pbuf);
1892 }
1893
1894 static int
1895 lnet_ping_target_setup(struct lnet_ping_buffer **ppbuf,
1896                        struct lnet_handle_md *ping_mdh,
1897                        int ni_count, bool set_eq)
1898 {
1899         struct lnet_process_id id = {
1900                 .nid = LNET_NID_ANY,
1901                 .pid = LNET_PID_ANY
1902         };
1903         struct lnet_me *me;
1904         struct lnet_md md = { NULL };
1905         int rc;
1906
1907         if (set_eq)
1908                 the_lnet.ln_ping_target_handler =
1909                         lnet_ping_target_event_handler;
1910
1911         *ppbuf = lnet_ping_target_create(ni_count);
1912         if (*ppbuf == NULL) {
1913                 rc = -ENOMEM;
1914                 goto fail_free_eq;
1915         }
1916
1917         /* Ping target ME/MD */
1918         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
1919                           LNET_PROTO_PING_MATCHBITS, 0,
1920                           LNET_UNLINK, LNET_INS_AFTER);
1921         if (IS_ERR(me)) {
1922                 rc = PTR_ERR(me);
1923                 CERROR("Can't create ping target ME: %d\n", rc);
1924                 goto fail_decref_ping_buffer;
1925         }
1926
1927         /* initialize md content */
1928         md.start     = &(*ppbuf)->pb_info;
1929         md.length    = LNET_PING_INFO_SIZE((*ppbuf)->pb_nnis);
1930         md.threshold = LNET_MD_THRESH_INF;
1931         md.max_size  = 0;
1932         md.options   = LNET_MD_OP_GET | LNET_MD_TRUNCATE |
1933                        LNET_MD_MANAGE_REMOTE;
1934         md.handler   = the_lnet.ln_ping_target_handler;
1935         md.user_ptr  = *ppbuf;
1936
1937         rc = LNetMDAttach(me, &md, LNET_RETAIN, ping_mdh);
1938         if (rc != 0) {
1939                 CERROR("Can't attach ping target MD: %d\n", rc);
1940                 goto fail_decref_ping_buffer;
1941         }
1942         lnet_ping_buffer_addref(*ppbuf);
1943
1944         return 0;
1945
1946 fail_decref_ping_buffer:
1947         LASSERT(atomic_read(&(*ppbuf)->pb_refcnt) == 1);
1948         lnet_ping_buffer_decref(*ppbuf);
1949         *ppbuf = NULL;
1950 fail_free_eq:
1951         return rc;
1952 }
1953
1954 static void
1955 lnet_ping_md_unlink(struct lnet_ping_buffer *pbuf,
1956                     struct lnet_handle_md *ping_mdh)
1957 {
1958         LNetMDUnlink(*ping_mdh);
1959         LNetInvalidateMDHandle(ping_mdh);
1960
1961         /* NB the MD could be busy; this just starts the unlink */
1962         wait_var_event_warning(&pbuf->pb_refcnt,
1963                                atomic_read(&pbuf->pb_refcnt) <= 1,
1964                                "Still waiting for ping data MD to unlink\n");
1965 }
1966
1967 static void
1968 lnet_ping_target_install_locked(struct lnet_ping_buffer *pbuf)
1969 {
1970         struct lnet_ni          *ni;
1971         struct lnet_net         *net;
1972         struct lnet_ni_status *ns;
1973         int                     i;
1974         int                     rc;
1975
1976         i = 0;
1977         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
1978                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
1979                         LASSERT(i < pbuf->pb_nnis);
1980
1981                         ns = &pbuf->pb_info.pi_ni[i];
1982
1983                         if (!nid_is_nid4(&ni->ni_nid))
1984                                 continue;
1985                         ns->ns_nid = lnet_nid_to_nid4(&ni->ni_nid);
1986
1987                         lnet_ni_lock(ni);
1988                         ns->ns_status = lnet_ni_get_status_locked(ni);
1989                         ni->ni_status = ns;
1990                         lnet_ni_unlock(ni);
1991
1992                         i++;
1993                 }
1994         }
1995         /*
1996          * We (ab)use the ns_status of the loopback interface to
1997          * transmit the sequence number. The first interface listed
1998          * must be the loopback interface.
1999          */
2000         rc = lnet_ping_info_validate(&pbuf->pb_info);
2001         if (rc) {
2002                 LCONSOLE_EMERG("Invalid ping target: %d\n", rc);
2003                 LBUG();
2004         }
2005         LNET_PING_BUFFER_SEQNO(pbuf) =
2006                 atomic_inc_return(&the_lnet.ln_ping_target_seqno);
2007 }
2008
2009 static void
2010 lnet_ping_target_update(struct lnet_ping_buffer *pbuf,
2011                         struct lnet_handle_md ping_mdh)
2012 {
2013         struct lnet_ping_buffer *old_pbuf = NULL;
2014         struct lnet_handle_md old_ping_md;
2015
2016         /* switch the NIs to point to the new ping info created */
2017         lnet_net_lock(LNET_LOCK_EX);
2018
2019         if (!the_lnet.ln_routing)
2020                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_RTE_DISABLED;
2021         if (!lnet_peer_discovery_disabled)
2022                 pbuf->pb_info.pi_features |= LNET_PING_FEAT_DISCOVERY;
2023
2024         /* Ensure only known feature bits have been set. */
2025         LASSERT(pbuf->pb_info.pi_features & LNET_PING_FEAT_BITS);
2026         LASSERT(!(pbuf->pb_info.pi_features & ~LNET_PING_FEAT_BITS));
2027
2028         lnet_ping_target_install_locked(pbuf);
2029
2030         if (the_lnet.ln_ping_target) {
2031                 old_pbuf = the_lnet.ln_ping_target;
2032                 old_ping_md = the_lnet.ln_ping_target_md;
2033         }
2034         the_lnet.ln_ping_target_md = ping_mdh;
2035         the_lnet.ln_ping_target = pbuf;
2036
2037         lnet_net_unlock(LNET_LOCK_EX);
2038
2039         if (old_pbuf) {
2040                 /* unlink and free the old ping info */
2041                 lnet_ping_md_unlink(old_pbuf, &old_ping_md);
2042                 lnet_ping_buffer_decref(old_pbuf);
2043         }
2044
2045         lnet_push_update_to_peers(0);
2046 }
2047
2048 static void
2049 lnet_ping_target_fini(void)
2050 {
2051         lnet_ping_md_unlink(the_lnet.ln_ping_target,
2052                             &the_lnet.ln_ping_target_md);
2053
2054         lnet_assert_handler_unused(the_lnet.ln_ping_target_handler);
2055         lnet_ping_target_destroy();
2056 }
2057
2058 /* Resize the push target. */
2059 int lnet_push_target_resize(void)
2060 {
2061         struct lnet_handle_md mdh;
2062         struct lnet_handle_md old_mdh;
2063         struct lnet_ping_buffer *pbuf;
2064         struct lnet_ping_buffer *old_pbuf;
2065         int nnis;
2066         int rc;
2067
2068 again:
2069         nnis = the_lnet.ln_push_target_nnis;
2070         if (nnis <= 0) {
2071                 CDEBUG(D_NET, "Invalid nnis %d\n", nnis);
2072                 return -EINVAL;
2073         }
2074
2075         /* NB: lnet_ping_buffer_alloc() sets pbuf refcount to 1. That ref is
2076          * dropped when we need to resize again (see "old_pbuf" below) or when
2077          * LNet is shutdown (see lnet_push_target_fini())
2078          */
2079         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
2080         if (!pbuf) {
2081                 CDEBUG(D_NET, "Can't allocate pbuf for nnis %d\n", nnis);
2082                 return -ENOMEM;
2083         }
2084
2085         rc = lnet_push_target_post(pbuf, &mdh);
2086         if (rc) {
2087                 CDEBUG(D_NET, "Failed to post push target: %d\n", rc);
2088                 lnet_ping_buffer_decref(pbuf);
2089                 return rc;
2090         }
2091
2092         lnet_net_lock(LNET_LOCK_EX);
2093         old_pbuf = the_lnet.ln_push_target;
2094         old_mdh = the_lnet.ln_push_target_md;
2095         the_lnet.ln_push_target = pbuf;
2096         the_lnet.ln_push_target_md = mdh;
2097         lnet_net_unlock(LNET_LOCK_EX);
2098
2099         if (old_pbuf) {
2100                 LNetMDUnlink(old_mdh);
2101                 /* Drop ref set by lnet_ping_buffer_alloc() */
2102                 lnet_ping_buffer_decref(old_pbuf);
2103         }
2104
2105         /* Received another push or reply that requires a larger buffer */
2106         if (nnis < the_lnet.ln_push_target_nnis)
2107                 goto again;
2108
2109         CDEBUG(D_NET, "nnis %d success\n", nnis);
2110         return 0;
2111 }
2112
2113 int lnet_push_target_post(struct lnet_ping_buffer *pbuf,
2114                           struct lnet_handle_md *mdhp)
2115 {
2116         struct lnet_process_id id = { LNET_NID_ANY, LNET_PID_ANY };
2117         struct lnet_md md = { NULL };
2118         struct lnet_me *me;
2119         int rc;
2120
2121         me = LNetMEAttach(LNET_RESERVED_PORTAL, id,
2122                           LNET_PROTO_PING_MATCHBITS, 0,
2123                           LNET_UNLINK, LNET_INS_AFTER);
2124         if (IS_ERR(me)) {
2125                 rc = PTR_ERR(me);
2126                 CERROR("Can't create push target ME: %d\n", rc);
2127                 return rc;
2128         }
2129
2130         pbuf->pb_needs_post = false;
2131
2132         /* This reference is dropped by lnet_push_target_event_handler() */
2133         lnet_ping_buffer_addref(pbuf);
2134
2135         /* initialize md content */
2136         md.start     = &pbuf->pb_info;
2137         md.length    = LNET_PING_INFO_SIZE(pbuf->pb_nnis);
2138         md.threshold = 1;
2139         md.max_size  = 0;
2140         md.options   = LNET_MD_OP_PUT | LNET_MD_TRUNCATE;
2141         md.user_ptr  = pbuf;
2142         md.handler   = the_lnet.ln_push_target_handler;
2143
2144         rc = LNetMDAttach(me, &md, LNET_UNLINK, mdhp);
2145         if (rc) {
2146                 CERROR("Can't attach push MD: %d\n", rc);
2147                 lnet_ping_buffer_decref(pbuf);
2148                 pbuf->pb_needs_post = true;
2149                 return rc;
2150         }
2151
2152         CDEBUG(D_NET, "posted push target %p\n", pbuf);
2153
2154         return 0;
2155 }
2156
2157 static void lnet_push_target_event_handler(struct lnet_event *ev)
2158 {
2159         struct lnet_ping_buffer *pbuf = ev->md_user_ptr;
2160
2161         CDEBUG(D_NET, "type %d status %d unlinked %d\n", ev->type, ev->status,
2162                ev->unlinked);
2163
2164         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2165                 lnet_swap_pinginfo(pbuf);
2166
2167         if (ev->type == LNET_EVENT_UNLINK) {
2168                 /* Drop ref added by lnet_push_target_post() */
2169                 lnet_ping_buffer_decref(pbuf);
2170                 return;
2171         }
2172
2173         lnet_peer_push_event(ev);
2174         if (ev->unlinked)
2175                 /* Drop ref added by lnet_push_target_post */
2176                 lnet_ping_buffer_decref(pbuf);
2177 }
2178
2179 /* Initialize the push target. */
2180 static int lnet_push_target_init(void)
2181 {
2182         int rc;
2183
2184         if (the_lnet.ln_push_target)
2185                 return -EALREADY;
2186
2187         the_lnet.ln_push_target_handler =
2188                 lnet_push_target_event_handler;
2189
2190         rc = LNetSetLazyPortal(LNET_RESERVED_PORTAL);
2191         LASSERT(rc == 0);
2192
2193         /* Start at the required minimum, we'll enlarge if required. */
2194         the_lnet.ln_push_target_nnis = LNET_INTERFACES_MIN;
2195
2196         rc = lnet_push_target_resize();
2197
2198         if (rc) {
2199                 LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2200                 the_lnet.ln_push_target_handler = NULL;
2201         }
2202
2203         return rc;
2204 }
2205
2206 /* Clean up the push target. */
2207 static void lnet_push_target_fini(void)
2208 {
2209         if (!the_lnet.ln_push_target)
2210                 return;
2211
2212         /* Unlink and invalidate to prevent new references. */
2213         LNetMDUnlink(the_lnet.ln_push_target_md);
2214         LNetInvalidateMDHandle(&the_lnet.ln_push_target_md);
2215
2216         /* Wait for the unlink to complete. */
2217         wait_var_event_warning(&the_lnet.ln_push_target->pb_refcnt,
2218                                atomic_read(&the_lnet.ln_push_target->pb_refcnt) <= 1,
2219                                "Still waiting for ping data MD to unlink\n");
2220
2221         /* Drop ref set by lnet_ping_buffer_alloc() */
2222         lnet_ping_buffer_decref(the_lnet.ln_push_target);
2223         the_lnet.ln_push_target = NULL;
2224         the_lnet.ln_push_target_nnis = 0;
2225
2226         LNetClearLazyPortal(LNET_RESERVED_PORTAL);
2227         lnet_assert_handler_unused(the_lnet.ln_push_target_handler);
2228         the_lnet.ln_push_target_handler = NULL;
2229 }
2230
2231 static int
2232 lnet_ni_tq_credits(struct lnet_ni *ni)
2233 {
2234         int     credits;
2235
2236         LASSERT(ni->ni_ncpts >= 1);
2237
2238         if (ni->ni_ncpts == 1)
2239                 return ni->ni_net->net_tunables.lct_max_tx_credits;
2240
2241         credits = ni->ni_net->net_tunables.lct_max_tx_credits / ni->ni_ncpts;
2242         credits = max(credits, 8 * ni->ni_net->net_tunables.lct_peer_tx_credits);
2243         credits = min(credits, ni->ni_net->net_tunables.lct_max_tx_credits);
2244
2245         return credits;
2246 }
2247
2248 static void
2249 lnet_ni_unlink_locked(struct lnet_ni *ni)
2250 {
2251         /* move it to zombie list and nobody can find it anymore */
2252         LASSERT(!list_empty(&ni->ni_netlist));
2253         list_move(&ni->ni_netlist, &ni->ni_net->net_ni_zombie);
2254         lnet_ni_decref_locked(ni, 0);
2255 }
2256
2257 static void
2258 lnet_clear_zombies_nis_locked(struct lnet_net *net)
2259 {
2260         int             i;
2261         int             islo;
2262         struct lnet_ni  *ni;
2263         struct list_head *zombie_list = &net->net_ni_zombie;
2264
2265         /*
2266          * Now wait for the NIs I just nuked to show up on the zombie
2267          * list and shut them down in guaranteed thread context
2268          */
2269         i = 2;
2270         while (!list_empty(zombie_list)) {
2271                 int     *ref;
2272                 int     j;
2273
2274                 ni = list_entry(zombie_list->next,
2275                                 struct lnet_ni, ni_netlist);
2276                 list_del_init(&ni->ni_netlist);
2277                 /* the ni should be in deleting state. If it's not it's
2278                  * a bug */
2279                 LASSERT(ni->ni_state == LNET_NI_STATE_DELETING);
2280                 cfs_percpt_for_each(ref, j, ni->ni_refs) {
2281                         if (*ref == 0)
2282                                 continue;
2283                         /* still busy, add it back to zombie list */
2284                         list_add(&ni->ni_netlist, zombie_list);
2285                         break;
2286                 }
2287
2288                 if (!list_empty(&ni->ni_netlist)) {
2289                         /* Unlock mutex while waiting to allow other
2290                          * threads to read the LNet state and fall through
2291                          * to avoid deadlock
2292                          */
2293                         lnet_net_unlock(LNET_LOCK_EX);
2294                         mutex_unlock(&the_lnet.ln_api_mutex);
2295
2296                         ++i;
2297                         if ((i & (-i)) == i) {
2298                                 CDEBUG(D_WARNING,
2299                                        "Waiting for zombie LNI %s\n",
2300                                        libcfs_nidstr(&ni->ni_nid));
2301                         }
2302                         schedule_timeout_uninterruptible(cfs_time_seconds(1));
2303
2304                         mutex_lock(&the_lnet.ln_api_mutex);
2305                         lnet_net_lock(LNET_LOCK_EX);
2306                         continue;
2307                 }
2308
2309                 lnet_net_unlock(LNET_LOCK_EX);
2310
2311                 islo = ni->ni_net->net_lnd->lnd_type == LOLND;
2312
2313                 LASSERT(!in_interrupt());
2314                 /* Holding the mutex makes it safe for lnd_shutdown
2315                  * to call module_put(). Module unload cannot finish
2316                  * until lnet_unregister_lnd() completes, and that
2317                  * requires the mutex.
2318                  */
2319                 mutex_lock(&the_lnet.ln_lnd_mutex);
2320                 (net->net_lnd->lnd_shutdown)(ni);
2321                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2322
2323                 if (!islo)
2324                         CDEBUG(D_LNI, "Removed LNI %s\n",
2325                               libcfs_nidstr(&ni->ni_nid));
2326
2327                 lnet_ni_free(ni);
2328                 i = 2;
2329                 lnet_net_lock(LNET_LOCK_EX);
2330         }
2331 }
2332
2333 /* shutdown down the NI and release refcount */
2334 static void
2335 lnet_shutdown_lndni(struct lnet_ni *ni)
2336 {
2337         int i;
2338         struct lnet_net *net = ni->ni_net;
2339
2340         lnet_net_lock(LNET_LOCK_EX);
2341         lnet_ni_lock(ni);
2342         ni->ni_state = LNET_NI_STATE_DELETING;
2343         lnet_ni_unlock(ni);
2344         lnet_ni_unlink_locked(ni);
2345         lnet_incr_dlc_seq();
2346         lnet_net_unlock(LNET_LOCK_EX);
2347
2348         /* clear messages for this NI on the lazy portal */
2349         for (i = 0; i < the_lnet.ln_nportals; i++)
2350                 lnet_clear_lazy_portal(ni, i, "Shutting down NI");
2351
2352         lnet_net_lock(LNET_LOCK_EX);
2353         lnet_clear_zombies_nis_locked(net);
2354         lnet_net_unlock(LNET_LOCK_EX);
2355 }
2356
2357 static void
2358 lnet_shutdown_lndnet(struct lnet_net *net)
2359 {
2360         struct lnet_ni *ni;
2361
2362         lnet_net_lock(LNET_LOCK_EX);
2363
2364         list_del_init(&net->net_list);
2365
2366         while (!list_empty(&net->net_ni_list)) {
2367                 ni = list_entry(net->net_ni_list.next,
2368                                 struct lnet_ni, ni_netlist);
2369                 lnet_net_unlock(LNET_LOCK_EX);
2370                 lnet_shutdown_lndni(ni);
2371                 lnet_net_lock(LNET_LOCK_EX);
2372         }
2373
2374         lnet_net_unlock(LNET_LOCK_EX);
2375
2376         /* Do peer table cleanup for this net */
2377         lnet_peer_tables_cleanup(net);
2378
2379         lnet_net_free(net);
2380 }
2381
2382 static void
2383 lnet_shutdown_lndnets(void)
2384 {
2385         struct lnet_net *net;
2386         LIST_HEAD(resend);
2387         struct lnet_msg *msg, *tmp;
2388
2389         /* NB called holding the global mutex */
2390
2391         /* All quiet on the API front */
2392         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
2393         LASSERT(the_lnet.ln_refcount == 0);
2394
2395         lnet_net_lock(LNET_LOCK_EX);
2396         the_lnet.ln_state = LNET_STATE_STOPPING;
2397
2398         /*
2399          * move the nets to the zombie list to avoid them being
2400          * picked up for new work. LONET is also included in the
2401          * Nets that will be moved to the zombie list
2402          */
2403         list_splice_init(&the_lnet.ln_nets, &the_lnet.ln_net_zombie);
2404
2405         /* Drop the cached loopback Net. */
2406         if (the_lnet.ln_loni != NULL) {
2407                 lnet_ni_decref_locked(the_lnet.ln_loni, 0);
2408                 the_lnet.ln_loni = NULL;
2409         }
2410         lnet_net_unlock(LNET_LOCK_EX);
2411
2412         /* iterate through the net zombie list and delete each net */
2413         while (!list_empty(&the_lnet.ln_net_zombie)) {
2414                 net = list_entry(the_lnet.ln_net_zombie.next,
2415                                  struct lnet_net, net_list);
2416                 lnet_shutdown_lndnet(net);
2417         }
2418
2419         spin_lock(&the_lnet.ln_msg_resend_lock);
2420         list_splice(&the_lnet.ln_msg_resend, &resend);
2421         spin_unlock(&the_lnet.ln_msg_resend_lock);
2422
2423         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
2424                 list_del_init(&msg->msg_list);
2425                 msg->msg_no_resend = true;
2426                 lnet_finalize(msg, -ECANCELED);
2427         }
2428
2429         lnet_net_lock(LNET_LOCK_EX);
2430         the_lnet.ln_state = LNET_STATE_SHUTDOWN;
2431         lnet_net_unlock(LNET_LOCK_EX);
2432 }
2433
2434 static int
2435 lnet_startup_lndni(struct lnet_ni *ni, struct lnet_lnd_tunables *tun)
2436 {
2437         int                     rc = -EINVAL;
2438         struct lnet_tx_queue    *tq;
2439         int                     i;
2440         struct lnet_net         *net = ni->ni_net;
2441
2442         mutex_lock(&the_lnet.ln_lnd_mutex);
2443
2444         if (tun) {
2445                 memcpy(&ni->ni_lnd_tunables, tun, sizeof(*tun));
2446                 ni->ni_lnd_tunables_set = true;
2447         }
2448
2449         rc = (net->net_lnd->lnd_startup)(ni);
2450
2451         mutex_unlock(&the_lnet.ln_lnd_mutex);
2452
2453         if (rc != 0) {
2454                 LCONSOLE_ERROR_MSG(0x105, "Error %d starting up LNI %s\n",
2455                                    rc, libcfs_lnd2str(net->net_lnd->lnd_type));
2456                 goto failed0;
2457         }
2458
2459         lnet_ni_lock(ni);
2460         ni->ni_state = LNET_NI_STATE_ACTIVE;
2461         lnet_ni_unlock(ni);
2462
2463         /* We keep a reference on the loopback net through the loopback NI */
2464         if (net->net_lnd->lnd_type == LOLND) {
2465                 lnet_ni_addref(ni);
2466                 LASSERT(the_lnet.ln_loni == NULL);
2467                 the_lnet.ln_loni = ni;
2468                 ni->ni_net->net_tunables.lct_peer_tx_credits = 0;
2469                 ni->ni_net->net_tunables.lct_peer_rtr_credits = 0;
2470                 ni->ni_net->net_tunables.lct_max_tx_credits = 0;
2471                 ni->ni_net->net_tunables.lct_peer_timeout = 0;
2472                 return 0;
2473         }
2474
2475         if (ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ||
2476             ni->ni_net->net_tunables.lct_max_tx_credits == 0) {
2477                 LCONSOLE_ERROR_MSG(0x107, "LNI %s has no %scredits\n",
2478                                    libcfs_lnd2str(net->net_lnd->lnd_type),
2479                                    ni->ni_net->net_tunables.lct_peer_tx_credits == 0 ?
2480                                         "" : "per-peer ");
2481                 /* shutdown the NI since if we get here then it must've already
2482                  * been started
2483                  */
2484                 lnet_shutdown_lndni(ni);
2485                 return -EINVAL;
2486         }
2487
2488         cfs_percpt_for_each(tq, i, ni->ni_tx_queues) {
2489                 tq->tq_credits_min =
2490                 tq->tq_credits_max =
2491                 tq->tq_credits = lnet_ni_tq_credits(ni);
2492         }
2493
2494         atomic_set(&ni->ni_tx_credits,
2495                    lnet_ni_tq_credits(ni) * ni->ni_ncpts);
2496         atomic_set(&ni->ni_healthv, LNET_MAX_HEALTH_VALUE);
2497
2498         CDEBUG(D_LNI, "Added LNI %s [%d/%d/%d/%d]\n",
2499                 libcfs_nidstr(&ni->ni_nid),
2500                 ni->ni_net->net_tunables.lct_peer_tx_credits,
2501                 lnet_ni_tq_credits(ni) * LNET_CPT_NUMBER,
2502                 ni->ni_net->net_tunables.lct_peer_rtr_credits,
2503                 ni->ni_net->net_tunables.lct_peer_timeout);
2504
2505         return 0;
2506 failed0:
2507         lnet_ni_free(ni);
2508         return rc;
2509 }
2510
2511 static int
2512 lnet_startup_lndnet(struct lnet_net *net, struct lnet_lnd_tunables *tun)
2513 {
2514         struct lnet_ni *ni;
2515         struct lnet_net *net_l = NULL;
2516         LIST_HEAD(local_ni_list);
2517         int rc;
2518         int ni_count = 0;
2519         __u32 lnd_type;
2520         const struct lnet_lnd  *lnd;
2521         int peer_timeout =
2522                 net->net_tunables.lct_peer_timeout;
2523         int maxtxcredits =
2524                 net->net_tunables.lct_max_tx_credits;
2525         int peerrtrcredits =
2526                 net->net_tunables.lct_peer_rtr_credits;
2527
2528         /*
2529          * make sure that this net is unique. If it isn't then
2530          * we are adding interfaces to an already existing network, and
2531          * 'net' is just a convenient way to pass in the list.
2532          * if it is unique we need to find the LND and load it if
2533          * necessary.
2534          */
2535         if (lnet_net_unique(net->net_id, &the_lnet.ln_nets, &net_l)) {
2536                 lnd_type = LNET_NETTYP(net->net_id);
2537
2538                 mutex_lock(&the_lnet.ln_lnd_mutex);
2539                 lnd = lnet_find_lnd_by_type(lnd_type);
2540
2541                 if (lnd == NULL) {
2542                         mutex_unlock(&the_lnet.ln_lnd_mutex);
2543                         rc = request_module("%s", libcfs_lnd2modname(lnd_type));
2544                         mutex_lock(&the_lnet.ln_lnd_mutex);
2545
2546                         lnd = lnet_find_lnd_by_type(lnd_type);
2547                         if (lnd == NULL) {
2548                                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2549                                 CERROR("Can't load LND %s, module %s, rc=%d\n",
2550                                 libcfs_lnd2str(lnd_type),
2551                                 libcfs_lnd2modname(lnd_type), rc);
2552 #ifndef HAVE_MODULE_LOADING_SUPPORT
2553                                 LCONSOLE_ERROR_MSG(0x104, "Your kernel must be "
2554                                                 "compiled with kernel module "
2555                                                 "loading support.");
2556 #endif
2557                                 rc = -EINVAL;
2558                                 goto failed0;
2559                         }
2560                 }
2561
2562                 net->net_lnd = lnd;
2563
2564                 mutex_unlock(&the_lnet.ln_lnd_mutex);
2565
2566                 net_l = net;
2567         }
2568
2569         /*
2570          * net_l: if the network being added is unique then net_l
2571          *        will point to that network
2572          *        if the network being added is not unique then
2573          *        net_l points to the existing network.
2574          *
2575          * When we enter the loop below, we'll pick NIs off he
2576          * network beign added and start them up, then add them to
2577          * a local ni list. Once we've successfully started all
2578          * the NIs then we join the local NI list (of started up
2579          * networks) with the net_l->net_ni_list, which should
2580          * point to the correct network to add the new ni list to
2581          *
2582          * If any of the new NIs fail to start up, then we want to
2583          * iterate through the local ni list, which should include
2584          * any NIs which were successfully started up, and shut
2585          * them down.
2586          *
2587          * After than we want to delete the network being added,
2588          * to avoid a memory leak.
2589          */
2590         while (!list_empty(&net->net_ni_added)) {
2591                 ni = list_entry(net->net_ni_added.next, struct lnet_ni,
2592                                 ni_netlist);
2593                 list_del_init(&ni->ni_netlist);
2594
2595                 /* make sure that the the NI we're about to start
2596                  * up is actually unique. if it's not fail. */
2597                 if (!lnet_ni_unique_net(&net_l->net_ni_list,
2598                                         ni->ni_interface)) {
2599                         rc = -EEXIST;
2600                         goto failed1;
2601                 }
2602
2603                 /* adjust the pointer the parent network, just in case it
2604                  * the net is a duplicate */
2605                 ni->ni_net = net_l;
2606
2607                 rc = lnet_startup_lndni(ni, tun);
2608
2609                 if (rc < 0)
2610                         goto failed1;
2611
2612                 lnet_ni_addref(ni);
2613                 list_add_tail(&ni->ni_netlist, &local_ni_list);
2614
2615                 ni_count++;
2616         }
2617
2618         lnet_net_lock(LNET_LOCK_EX);
2619         list_splice_tail(&local_ni_list, &net_l->net_ni_list);
2620         lnet_incr_dlc_seq();
2621         lnet_net_unlock(LNET_LOCK_EX);
2622
2623         /* if the network is not unique then we don't want to keep
2624          * it around after we're done. Free it. Otherwise add that
2625          * net to the global the_lnet.ln_nets */
2626         if (net_l != net && net_l != NULL) {
2627                 /*
2628                  * TODO - note. currently the tunables can not be updated
2629                  * once added
2630                  */
2631                 lnet_net_free(net);
2632         } else {
2633                 /*
2634                  * restore tunables after it has been overwitten by the
2635                  * lnd
2636                  */
2637                 if (peer_timeout != -1)
2638                         net->net_tunables.lct_peer_timeout = peer_timeout;
2639                 if (maxtxcredits != -1)
2640                         net->net_tunables.lct_max_tx_credits = maxtxcredits;
2641                 if (peerrtrcredits != -1)
2642                         net->net_tunables.lct_peer_rtr_credits = peerrtrcredits;
2643
2644                 lnet_net_lock(LNET_LOCK_EX);
2645                 list_add_tail(&net->net_list, &the_lnet.ln_nets);
2646                 lnet_net_unlock(LNET_LOCK_EX);
2647         }
2648
2649         return ni_count;
2650
2651 failed1:
2652         /*
2653          * shutdown the new NIs that are being started up
2654          * free the NET being started
2655          */
2656         while (!list_empty(&local_ni_list)) {
2657                 ni = list_entry(local_ni_list.next, struct lnet_ni,
2658                                 ni_netlist);
2659
2660                 lnet_shutdown_lndni(ni);
2661         }
2662
2663 failed0:
2664         lnet_net_free(net);
2665
2666         return rc;
2667 }
2668
2669 static int
2670 lnet_startup_lndnets(struct list_head *netlist)
2671 {
2672         struct lnet_net         *net;
2673         int                     rc;
2674         int                     ni_count = 0;
2675
2676         /*
2677          * Change to running state before bringing up the LNDs. This
2678          * allows lnet_shutdown_lndnets() to assert that we've passed
2679          * through here.
2680          */
2681         lnet_net_lock(LNET_LOCK_EX);
2682         the_lnet.ln_state = LNET_STATE_RUNNING;
2683         lnet_net_unlock(LNET_LOCK_EX);
2684
2685         while (!list_empty(netlist)) {
2686                 net = list_entry(netlist->next, struct lnet_net, net_list);
2687                 list_del_init(&net->net_list);
2688
2689                 rc = lnet_startup_lndnet(net, NULL);
2690
2691                 if (rc < 0)
2692                         goto failed;
2693
2694                 ni_count += rc;
2695         }
2696
2697         return ni_count;
2698 failed:
2699         lnet_shutdown_lndnets();
2700
2701         return rc;
2702 }
2703
2704 static int lnet_genl_parse_list(struct sk_buff *msg,
2705                                 const struct ln_key_list *data[], u16 idx)
2706 {
2707         const struct ln_key_list *list = data[idx];
2708         const struct ln_key_props *props;
2709         struct nlattr *node;
2710         u16 count;
2711
2712         if (!list)
2713                 return 0;
2714
2715         if (!list->lkl_maxattr)
2716                 return -ERANGE;
2717
2718         props = list->lkl_list;
2719         if (!props)
2720                 return -EINVAL;
2721
2722         node = nla_nest_start(msg, LN_SCALAR_ATTR_LIST);
2723         if (!node)
2724                 return -ENOBUFS;
2725
2726         for (count = 1; count <= list->lkl_maxattr; count++) {
2727                 struct nlattr *key = nla_nest_start(msg, count);
2728
2729                 if (count == 1)
2730                         nla_put_u16(msg, LN_SCALAR_ATTR_LIST_SIZE,
2731                                     list->lkl_maxattr);
2732
2733                 nla_put_u16(msg, LN_SCALAR_ATTR_INDEX, count);
2734                 if (props[count].lkp_values)
2735                         nla_put_string(msg, LN_SCALAR_ATTR_VALUE,
2736                                        props[count].lkp_values);
2737                 if (props[count].lkp_key_format)
2738                         nla_put_u16(msg, LN_SCALAR_ATTR_KEY_FORMAT,
2739                                     props[count].lkp_key_format);
2740                 nla_put_u16(msg, LN_SCALAR_ATTR_NLA_TYPE,
2741                             props[count].lkp_data_type);
2742                 if (props[count].lkp_data_type == NLA_NESTED) {
2743                         int rc;
2744
2745                         rc = lnet_genl_parse_list(msg, data, ++idx);
2746                         if (rc < 0)
2747                                 return rc;
2748                 }
2749
2750                 nla_nest_end(msg, key);
2751         }
2752
2753         nla_nest_end(msg, node);
2754         return 0;
2755 }
2756
2757 int lnet_genl_send_scalar_list(struct sk_buff *msg, u32 portid, u32 seq,
2758                                const struct genl_family *family, int flags,
2759                                u8 cmd, const struct ln_key_list *data[])
2760 {
2761         int rc = 0;
2762         void *hdr;
2763
2764         if (!data[0])
2765                 return -EINVAL;
2766
2767         hdr = genlmsg_put(msg, portid, seq, family, flags, cmd);
2768         if (!hdr)
2769                 GOTO(canceled, rc = -EMSGSIZE);
2770
2771         rc = lnet_genl_parse_list(msg, data, 0);
2772         if (rc < 0)
2773                 GOTO(canceled, rc);
2774
2775         genlmsg_end(msg, hdr);
2776 canceled:
2777         if (rc < 0)
2778                 genlmsg_cancel(msg, hdr);
2779         return rc;
2780 }
2781 EXPORT_SYMBOL(lnet_genl_send_scalar_list);
2782
2783 /**
2784  * Initialize LNet library.
2785  *
2786  * Automatically called at module loading time. Caller has to call
2787  * lnet_lib_exit() after a call to lnet_lib_init(), if and only if the
2788  * latter returned 0. It must be called exactly once.
2789  *
2790  * \retval 0 on success
2791  * \retval -ve on failures.
2792  */
2793 int lnet_lib_init(void)
2794 {
2795         int rc;
2796
2797         lnet_assert_wire_constants();
2798
2799         /* refer to global cfs_cpt_table for now */
2800         the_lnet.ln_cpt_table = cfs_cpt_tab;
2801         the_lnet.ln_cpt_number = cfs_cpt_number(cfs_cpt_tab);
2802
2803         LASSERT(the_lnet.ln_cpt_number > 0);
2804         if (the_lnet.ln_cpt_number > LNET_CPT_MAX) {
2805                 /* we are under risk of consuming all lh_cookie */
2806                 CERROR("Can't have %d CPTs for LNet (max allowed is %d), "
2807                        "please change setting of CPT-table and retry\n",
2808                        the_lnet.ln_cpt_number, LNET_CPT_MAX);
2809                 return -E2BIG;
2810         }
2811
2812         while ((1 << the_lnet.ln_cpt_bits) < the_lnet.ln_cpt_number)
2813                 the_lnet.ln_cpt_bits++;
2814
2815         rc = lnet_create_locks();
2816         if (rc != 0) {
2817                 CERROR("Can't create LNet global locks: %d\n", rc);
2818                 return rc;
2819         }
2820
2821         the_lnet.ln_refcount = 0;
2822         INIT_LIST_HEAD(&the_lnet.ln_net_zombie);
2823         INIT_LIST_HEAD(&the_lnet.ln_msg_resend);
2824
2825         /* The hash table size is the number of bits it takes to express the set
2826          * ln_num_routes, minus 1 (better to under estimate than over so we
2827          * don't waste memory). */
2828         if (rnet_htable_size <= 0)
2829                 rnet_htable_size = LNET_REMOTE_NETS_HASH_DEFAULT;
2830         else if (rnet_htable_size > LNET_REMOTE_NETS_HASH_MAX)
2831                 rnet_htable_size = LNET_REMOTE_NETS_HASH_MAX;
2832         the_lnet.ln_remote_nets_hbits = max_t(int, 1,
2833                                            order_base_2(rnet_htable_size) - 1);
2834
2835         /* All LNDs apart from the LOLND are in separate modules.  They
2836          * register themselves when their module loads, and unregister
2837          * themselves when their module is unloaded. */
2838         lnet_register_lnd(&the_lolnd);
2839         return 0;
2840 }
2841
2842 /**
2843  * Finalize LNet library.
2844  *
2845  * \pre lnet_lib_init() called with success.
2846  * \pre All LNet users called LNetNIFini() for matching LNetNIInit() calls.
2847  *
2848  * As this happens at module-unload, all lnds must already be unloaded,
2849  * so they must already be unregistered.
2850  */
2851 void lnet_lib_exit(void)
2852 {
2853         int i;
2854
2855         LASSERT(the_lnet.ln_refcount == 0);
2856         lnet_unregister_lnd(&the_lolnd);
2857         for (i = 0; i < NUM_LNDS; i++)
2858                 LASSERT(!the_lnet.ln_lnds[i]);
2859         lnet_destroy_locks();
2860 }
2861
2862 /**
2863  * Set LNet PID and start LNet interfaces, routing, and forwarding.
2864  *
2865  * Users must call this function at least once before any other functions.
2866  * For each successful call there must be a corresponding call to
2867  * LNetNIFini(). For subsequent calls to LNetNIInit(), \a requested_pid is
2868  * ignored.
2869  *
2870  * The PID used by LNet may be different from the one requested.
2871  * See LNetGetId().
2872  *
2873  * \param requested_pid PID requested by the caller.
2874  *
2875  * \return >= 0 on success, and < 0 error code on failures.
2876  */
2877 int
2878 LNetNIInit(lnet_pid_t requested_pid)
2879 {
2880         int                     im_a_router = 0;
2881         int                     rc;
2882         int                     ni_count;
2883         struct lnet_ping_buffer *pbuf;
2884         struct lnet_handle_md   ping_mdh;
2885         LIST_HEAD(net_head);
2886         struct lnet_net         *net;
2887
2888         mutex_lock(&the_lnet.ln_api_mutex);
2889
2890         CDEBUG(D_OTHER, "refs %d\n", the_lnet.ln_refcount);
2891
2892         if (the_lnet.ln_refcount > 0) {
2893                 rc = the_lnet.ln_refcount++;
2894                 mutex_unlock(&the_lnet.ln_api_mutex);
2895                 return rc;
2896         }
2897
2898         rc = lnet_prepare(requested_pid);
2899         if (rc != 0) {
2900                 mutex_unlock(&the_lnet.ln_api_mutex);
2901                 return rc;
2902         }
2903
2904         /* create a network for Loopback network */
2905         net = lnet_net_alloc(LNET_MKNET(LOLND, 0), &net_head);
2906         if (net == NULL) {
2907                 rc = -ENOMEM;
2908                 goto err_empty_list;
2909         }
2910
2911         /* Add in the loopback NI */
2912         if (lnet_ni_alloc(net, NULL, NULL) == NULL) {
2913                 rc = -ENOMEM;
2914                 goto err_empty_list;
2915         }
2916
2917         if (use_tcp_bonding)
2918                 CWARN("use_tcp_bonding has been removed. Use Multi-Rail and Dynamic Discovery instead, see LU-13641\n");
2919
2920         /* If LNet is being initialized via DLC it is possible
2921          * that the user requests not to load module parameters (ones which
2922          * are supported by DLC) on initialization.  Therefore, make sure not
2923          * to load networks, routes and forwarding from module parameters
2924          * in this case.  On cleanup in case of failure only clean up
2925          * routes if it has been loaded */
2926         if (!the_lnet.ln_nis_from_mod_params) {
2927                 rc = lnet_parse_networks(&net_head, lnet_get_networks());
2928                 if (rc < 0)
2929                         goto err_empty_list;
2930         }
2931
2932         ni_count = lnet_startup_lndnets(&net_head);
2933         if (ni_count < 0) {
2934                 rc = ni_count;
2935                 goto err_empty_list;
2936         }
2937
2938         if (!the_lnet.ln_nis_from_mod_params) {
2939                 rc = lnet_parse_routes(lnet_get_routes(), &im_a_router);
2940                 if (rc != 0)
2941                         goto err_shutdown_lndnis;
2942
2943                 rc = lnet_rtrpools_alloc(im_a_router);
2944                 if (rc != 0)
2945                         goto err_destroy_routes;
2946         }
2947
2948         rc = lnet_acceptor_start();
2949         if (rc != 0)
2950                 goto err_destroy_routes;
2951
2952         the_lnet.ln_refcount = 1;
2953         /* Now I may use my own API functions... */
2954
2955         rc = lnet_ping_target_setup(&pbuf, &ping_mdh, ni_count, true);
2956         if (rc != 0)
2957                 goto err_acceptor_stop;
2958
2959         lnet_ping_target_update(pbuf, ping_mdh);
2960
2961         the_lnet.ln_mt_handler = lnet_mt_event_handler;
2962
2963         rc = lnet_push_target_init();
2964         if (rc != 0)
2965                 goto err_stop_ping;
2966
2967         rc = lnet_peer_discovery_start();
2968         if (rc != 0)
2969                 goto err_destroy_push_target;
2970
2971         rc = lnet_monitor_thr_start();
2972         if (rc != 0)
2973                 goto err_stop_discovery_thr;
2974
2975         lnet_fault_init();
2976         lnet_router_debugfs_init();
2977
2978         mutex_unlock(&the_lnet.ln_api_mutex);
2979
2980         complete_all(&the_lnet.ln_started);
2981
2982         /* wait for all routers to start */
2983         lnet_wait_router_start();
2984
2985         return 0;
2986
2987 err_stop_discovery_thr:
2988         lnet_peer_discovery_stop();
2989 err_destroy_push_target:
2990         lnet_push_target_fini();
2991 err_stop_ping:
2992         lnet_ping_target_fini();
2993 err_acceptor_stop:
2994         the_lnet.ln_refcount = 0;
2995         lnet_acceptor_stop();
2996 err_destroy_routes:
2997         if (!the_lnet.ln_nis_from_mod_params)
2998                 lnet_destroy_routes();
2999 err_shutdown_lndnis:
3000         lnet_shutdown_lndnets();
3001 err_empty_list:
3002         lnet_unprepare();
3003         LASSERT(rc < 0);
3004         mutex_unlock(&the_lnet.ln_api_mutex);
3005         while (!list_empty(&net_head)) {
3006                 struct lnet_net *net;
3007
3008                 net = list_entry(net_head.next, struct lnet_net, net_list);
3009                 list_del_init(&net->net_list);
3010                 lnet_net_free(net);
3011         }
3012         return rc;
3013 }
3014 EXPORT_SYMBOL(LNetNIInit);
3015
3016 /**
3017  * Stop LNet interfaces, routing, and forwarding.
3018  *
3019  * Users must call this function once for each successful call to LNetNIInit().
3020  * Once the LNetNIFini() operation has been started, the results of pending
3021  * API operations are undefined.
3022  *
3023  * \return always 0 for current implementation.
3024  */
3025 int
3026 LNetNIFini(void)
3027 {
3028         mutex_lock(&the_lnet.ln_api_mutex);
3029
3030         LASSERT(the_lnet.ln_refcount > 0);
3031
3032         if (the_lnet.ln_refcount != 1) {
3033                 the_lnet.ln_refcount--;
3034         } else {
3035                 LASSERT(!the_lnet.ln_niinit_self);
3036
3037                 lnet_fault_fini();
3038
3039                 lnet_router_debugfs_fini();
3040                 lnet_monitor_thr_stop();
3041                 lnet_peer_discovery_stop();
3042                 lnet_push_target_fini();
3043                 lnet_ping_target_fini();
3044
3045                 /* Teardown fns that use my own API functions BEFORE here */
3046                 the_lnet.ln_refcount = 0;
3047
3048                 lnet_acceptor_stop();
3049                 lnet_destroy_routes();
3050                 lnet_shutdown_lndnets();
3051                 lnet_unprepare();
3052         }
3053
3054         mutex_unlock(&the_lnet.ln_api_mutex);
3055         return 0;
3056 }
3057 EXPORT_SYMBOL(LNetNIFini);
3058
3059 /**
3060  * Grabs the ni data from the ni structure and fills the out
3061  * parameters
3062  *
3063  * \param[in] ni network        interface structure
3064  * \param[out] cfg_ni           NI config information
3065  * \param[out] tun              network and LND tunables
3066  */
3067 static void
3068 lnet_fill_ni_info(struct lnet_ni *ni, struct lnet_ioctl_config_ni *cfg_ni,
3069                    struct lnet_ioctl_config_lnd_tunables *tun,
3070                    struct lnet_ioctl_element_stats *stats,
3071                    __u32 tun_size)
3072 {
3073         size_t min_size = 0;
3074         int i;
3075
3076         if (!ni || !cfg_ni || !tun || !nid_is_nid4(&ni->ni_nid))
3077                 return;
3078
3079         if (ni->ni_interface != NULL) {
3080                 strncpy(cfg_ni->lic_ni_intf,
3081                         ni->ni_interface,
3082                         sizeof(cfg_ni->lic_ni_intf));
3083         }
3084
3085         cfg_ni->lic_nid = lnet_nid_to_nid4(&ni->ni_nid);
3086         cfg_ni->lic_status = lnet_ni_get_status_locked(ni);
3087         cfg_ni->lic_dev_cpt = ni->ni_dev_cpt;
3088
3089         memcpy(&tun->lt_cmn, &ni->ni_net->net_tunables, sizeof(tun->lt_cmn));
3090
3091         if (stats) {
3092                 stats->iel_send_count = lnet_sum_stats(&ni->ni_stats,
3093                                                        LNET_STATS_TYPE_SEND);
3094                 stats->iel_recv_count = lnet_sum_stats(&ni->ni_stats,
3095                                                        LNET_STATS_TYPE_RECV);
3096                 stats->iel_drop_count = lnet_sum_stats(&ni->ni_stats,
3097                                                        LNET_STATS_TYPE_DROP);
3098         }
3099
3100         /*
3101          * tun->lt_tun will always be present, but in order to be
3102          * backwards compatible, we need to deal with the cases when
3103          * tun->lt_tun is smaller than what the kernel has, because it
3104          * comes from an older version of a userspace program, then we'll
3105          * need to copy as much information as we have available space.
3106          */
3107         min_size = tun_size - sizeof(tun->lt_cmn);
3108         memcpy(&tun->lt_tun, &ni->ni_lnd_tunables, min_size);
3109
3110         /* copy over the cpts */
3111         if (ni->ni_ncpts == LNET_CPT_NUMBER &&
3112             ni->ni_cpts == NULL)  {
3113                 for (i = 0; i < ni->ni_ncpts; i++)
3114                         cfg_ni->lic_cpts[i] = i;
3115         } else {
3116                 for (i = 0;
3117                      ni->ni_cpts != NULL && i < ni->ni_ncpts &&
3118                      i < LNET_MAX_SHOW_NUM_CPT;
3119                      i++)
3120                         cfg_ni->lic_cpts[i] = ni->ni_cpts[i];
3121         }
3122         cfg_ni->lic_ncpts = ni->ni_ncpts;
3123 }
3124
3125 /**
3126  * NOTE: This is a legacy function left in the code to be backwards
3127  * compatible with older userspace programs. It should eventually be
3128  * removed.
3129  *
3130  * Grabs the ni data from the ni structure and fills the out
3131  * parameters
3132  *
3133  * \param[in] ni network        interface structure
3134  * \param[out] config           config information
3135  */
3136 static void
3137 lnet_fill_ni_info_legacy(struct lnet_ni *ni,
3138                          struct lnet_ioctl_config_data *config)
3139 {
3140         struct lnet_ioctl_net_config *net_config;
3141         struct lnet_ioctl_config_lnd_tunables *lnd_cfg = NULL;
3142         size_t min_size, tunable_size = 0;
3143         int i;
3144
3145         if (!ni || !config || !nid_is_nid4(&ni->ni_nid))
3146                 return;
3147
3148         net_config = (struct lnet_ioctl_net_config *) config->cfg_bulk;
3149         if (!net_config)
3150                 return;
3151
3152         if (!ni->ni_interface)
3153                 return;
3154
3155         strncpy(net_config->ni_interface,
3156                 ni->ni_interface,
3157                 sizeof(net_config->ni_interface));
3158
3159         config->cfg_nid = lnet_nid_to_nid4(&ni->ni_nid);
3160         config->cfg_config_u.cfg_net.net_peer_timeout =
3161                 ni->ni_net->net_tunables.lct_peer_timeout;
3162         config->cfg_config_u.cfg_net.net_max_tx_credits =
3163                 ni->ni_net->net_tunables.lct_max_tx_credits;
3164         config->cfg_config_u.cfg_net.net_peer_tx_credits =
3165                 ni->ni_net->net_tunables.lct_peer_tx_credits;
3166         config->cfg_config_u.cfg_net.net_peer_rtr_credits =
3167                 ni->ni_net->net_tunables.lct_peer_rtr_credits;
3168
3169         net_config->ni_status = lnet_ni_get_status_locked(ni);
3170
3171         if (ni->ni_cpts) {
3172                 int num_cpts = min(ni->ni_ncpts, LNET_MAX_SHOW_NUM_CPT);
3173
3174                 for (i = 0; i < num_cpts; i++)
3175                         net_config->ni_cpts[i] = ni->ni_cpts[i];
3176
3177                 config->cfg_ncpts = num_cpts;
3178         }
3179
3180         /*
3181          * See if user land tools sent in a newer and larger version
3182          * of struct lnet_tunables than what the kernel uses.
3183          */
3184         min_size = sizeof(*config) + sizeof(*net_config);
3185
3186         if (config->cfg_hdr.ioc_len > min_size)
3187                 tunable_size = config->cfg_hdr.ioc_len - min_size;
3188
3189         /* Don't copy too much data to user space */
3190         min_size = min(tunable_size, sizeof(ni->ni_lnd_tunables));
3191         lnd_cfg = (struct lnet_ioctl_config_lnd_tunables *)net_config->cfg_bulk;
3192
3193         if (lnd_cfg && min_size) {
3194                 memcpy(&lnd_cfg->lt_tun, &ni->ni_lnd_tunables, min_size);
3195                 config->cfg_config_u.cfg_net.net_interface_count = 1;
3196
3197                 /* Tell user land that kernel side has less data */
3198                 if (tunable_size > sizeof(ni->ni_lnd_tunables)) {
3199                         min_size = tunable_size - sizeof(ni->ni_lnd_tunables);
3200                         config->cfg_hdr.ioc_len -= min_size;
3201                 }
3202         }
3203 }
3204
3205 struct lnet_ni *
3206 lnet_get_ni_idx_locked(int idx)
3207 {
3208         struct lnet_ni          *ni;
3209         struct lnet_net         *net;
3210
3211         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3212                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3213                         if (idx-- == 0)
3214                                 return ni;
3215                 }
3216         }
3217
3218         return NULL;
3219 }
3220
3221 int lnet_get_net_healthv_locked(struct lnet_net *net)
3222 {
3223         struct lnet_ni *ni;
3224         int best_healthv = 0;
3225         int healthv, ni_fatal;
3226
3227         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3228                 healthv = atomic_read(&ni->ni_healthv);
3229                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
3230                 if (!ni_fatal && healthv > best_healthv)
3231                         best_healthv = healthv;
3232         }
3233
3234         return best_healthv;
3235 }
3236
3237 struct lnet_ni *
3238 lnet_get_next_ni_locked(struct lnet_net *mynet, struct lnet_ni *prev)
3239 {
3240         struct lnet_ni          *ni;
3241         struct lnet_net         *net = mynet;
3242
3243         /*
3244          * It is possible that the net has been cleaned out while there is
3245          * a message being sent. This function accessed the net without
3246          * checking if the list is empty
3247          */
3248         if (prev == NULL) {
3249                 if (net == NULL)
3250                         net = list_entry(the_lnet.ln_nets.next, struct lnet_net,
3251                                         net_list);
3252                 if (list_empty(&net->net_ni_list))
3253                         return NULL;
3254                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3255                                 ni_netlist);
3256
3257                 return ni;
3258         }
3259
3260         if (prev->ni_netlist.next == &prev->ni_net->net_ni_list) {
3261                 /* if you reached the end of the ni list and the net is
3262                  * specified, then there are no more nis in that net */
3263                 if (net != NULL)
3264                         return NULL;
3265
3266                 /* we reached the end of this net ni list. move to the
3267                  * next net */
3268                 if (prev->ni_net->net_list.next == &the_lnet.ln_nets)
3269                         /* no more nets and no more NIs. */
3270                         return NULL;
3271
3272                 /* get the next net */
3273                 net = list_entry(prev->ni_net->net_list.next, struct lnet_net,
3274                                  net_list);
3275                 if (list_empty(&net->net_ni_list))
3276                         return NULL;
3277                 /* get the ni on it */
3278                 ni = list_entry(net->net_ni_list.next, struct lnet_ni,
3279                                 ni_netlist);
3280
3281                 return ni;
3282         }
3283
3284         if (list_empty(&prev->ni_netlist))
3285                 return NULL;
3286
3287         /* there are more nis left */
3288         ni = list_entry(prev->ni_netlist.next, struct lnet_ni, ni_netlist);
3289
3290         return ni;
3291 }
3292
3293 int
3294 lnet_get_net_config(struct lnet_ioctl_config_data *config)
3295 {
3296         struct lnet_ni *ni;
3297         int cpt;
3298         int rc = -ENOENT;
3299         int idx = config->cfg_count;
3300
3301         cpt = lnet_net_lock_current();
3302
3303         ni = lnet_get_ni_idx_locked(idx);
3304
3305         if (ni != NULL) {
3306                 rc = 0;
3307                 lnet_ni_lock(ni);
3308                 lnet_fill_ni_info_legacy(ni, config);
3309                 lnet_ni_unlock(ni);
3310         }
3311
3312         lnet_net_unlock(cpt);
3313         return rc;
3314 }
3315
3316 int
3317 lnet_get_ni_config(struct lnet_ioctl_config_ni *cfg_ni,
3318                    struct lnet_ioctl_config_lnd_tunables *tun,
3319                    struct lnet_ioctl_element_stats *stats,
3320                    __u32 tun_size)
3321 {
3322         struct lnet_ni          *ni;
3323         int                     cpt;
3324         int                     rc = -ENOENT;
3325
3326         if (!cfg_ni || !tun || !stats)
3327                 return -EINVAL;
3328
3329         cpt = lnet_net_lock_current();
3330
3331         ni = lnet_get_ni_idx_locked(cfg_ni->lic_idx);
3332
3333         if (ni) {
3334                 rc = 0;
3335                 lnet_ni_lock(ni);
3336                 lnet_fill_ni_info(ni, cfg_ni, tun, stats, tun_size);
3337                 lnet_ni_unlock(ni);
3338         }
3339
3340         lnet_net_unlock(cpt);
3341         return rc;
3342 }
3343
3344 int lnet_get_ni_stats(struct lnet_ioctl_element_msg_stats *msg_stats)
3345 {
3346         struct lnet_ni *ni;
3347         int cpt;
3348         int rc = -ENOENT;
3349
3350         if (!msg_stats)
3351                 return -EINVAL;
3352
3353         cpt = lnet_net_lock_current();
3354
3355         ni = lnet_get_ni_idx_locked(msg_stats->im_idx);
3356
3357         if (ni) {
3358                 lnet_usr_translate_stats(msg_stats, &ni->ni_stats);
3359                 rc = 0;
3360         }
3361
3362         lnet_net_unlock(cpt);
3363
3364         return rc;
3365 }
3366
3367 static int lnet_add_net_common(struct lnet_net *net,
3368                                struct lnet_ioctl_config_lnd_tunables *tun)
3369 {
3370         struct lnet_handle_md ping_mdh;
3371         struct lnet_ping_buffer *pbuf;
3372         struct lnet_remotenet *rnet;
3373         struct lnet_ni *ni;
3374         int net_ni_count;
3375         __u32 net_id;
3376         int rc;
3377
3378         lnet_net_lock(LNET_LOCK_EX);
3379         rnet = lnet_find_rnet_locked(net->net_id);
3380         lnet_net_unlock(LNET_LOCK_EX);
3381         /*
3382          * make sure that the net added doesn't invalidate the current
3383          * configuration LNet is keeping
3384          */
3385         if (rnet) {
3386                 CERROR("Adding net %s will invalidate routing configuration\n",
3387                        libcfs_net2str(net->net_id));
3388                 lnet_net_free(net);
3389                 return -EUSERS;
3390         }
3391
3392         /*
3393          * make sure you calculate the correct number of slots in the ping
3394          * buffer. Since the ping info is a flattened list of all the NIs,
3395          * we should allocate enough slots to accomodate the number of NIs
3396          * which will be added.
3397          *
3398          * since ni hasn't been configured yet, use
3399          * lnet_get_net_ni_count_pre() which checks the net_ni_added list
3400          */
3401         net_ni_count = lnet_get_net_ni_count_pre(net);
3402
3403         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3404                                     net_ni_count + lnet_get_ni_count(),
3405                                     false);
3406         if (rc < 0) {
3407                 lnet_net_free(net);
3408                 return rc;
3409         }
3410
3411         if (tun)
3412                 memcpy(&net->net_tunables,
3413                        &tun->lt_cmn, sizeof(net->net_tunables));
3414         else
3415                 memset(&net->net_tunables, -1, sizeof(net->net_tunables));
3416
3417         net_id = net->net_id;
3418
3419         rc = lnet_startup_lndnet(net,
3420                                  (tun) ? &tun->lt_tun : NULL);
3421         if (rc < 0)
3422                 goto failed;
3423
3424         lnet_net_lock(LNET_LOCK_EX);
3425         net = lnet_get_net_locked(net_id);
3426         LASSERT(net);
3427
3428         /* apply the UDSPs */
3429         rc = lnet_udsp_apply_policies_on_net(net);
3430         if (rc)
3431                 CERROR("Failed to apply UDSPs on local net %s\n",
3432                        libcfs_net2str(net->net_id));
3433
3434         /* At this point we lost track of which NI was just added, so we
3435          * just re-apply the policies on all of the NIs on this net
3436          */
3437         list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3438                 rc = lnet_udsp_apply_policies_on_ni(ni);
3439                 if (rc)
3440                         CERROR("Failed to apply UDSPs on ni %s\n",
3441                                libcfs_nidstr(&ni->ni_nid));
3442         }
3443         lnet_net_unlock(LNET_LOCK_EX);
3444
3445         /*
3446          * Start the acceptor thread if this is the first network
3447          * being added that requires the thread.
3448          */
3449         if (net->net_lnd->lnd_accept) {
3450                 rc = lnet_acceptor_start();
3451                 if (rc < 0) {
3452                         /* shutdown the net that we just started */
3453                         CERROR("Failed to start up acceptor thread\n");
3454                         lnet_shutdown_lndnet(net);
3455                         goto failed;
3456                 }
3457         }
3458
3459         lnet_net_lock(LNET_LOCK_EX);
3460         lnet_peer_net_added(net);
3461         lnet_net_unlock(LNET_LOCK_EX);
3462
3463         lnet_ping_target_update(pbuf, ping_mdh);
3464
3465         return 0;
3466
3467 failed:
3468         lnet_ping_md_unlink(pbuf, &ping_mdh);
3469         lnet_ping_buffer_decref(pbuf);
3470         return rc;
3471 }
3472
3473 static void
3474 lnet_set_tune_defaults(struct lnet_ioctl_config_lnd_tunables *tun)
3475 {
3476         if (tun) {
3477                 if (!tun->lt_cmn.lct_peer_timeout)
3478                         tun->lt_cmn.lct_peer_timeout = DEFAULT_PEER_TIMEOUT;
3479                 if (!tun->lt_cmn.lct_peer_tx_credits)
3480                         tun->lt_cmn.lct_peer_tx_credits = DEFAULT_PEER_CREDITS;
3481                 if (!tun->lt_cmn.lct_max_tx_credits)
3482                         tun->lt_cmn.lct_max_tx_credits = DEFAULT_CREDITS;
3483         }
3484 }
3485
3486 static int lnet_handle_legacy_ip2nets(char *ip2nets,
3487                                       struct lnet_ioctl_config_lnd_tunables *tun)
3488 {
3489         struct lnet_net *net;
3490         const char *nets;
3491         int rc;
3492         LIST_HEAD(net_head);
3493
3494         rc = lnet_parse_ip2nets(&nets, ip2nets);
3495         if (rc < 0)
3496                 return rc;
3497
3498         rc = lnet_parse_networks(&net_head, nets);
3499         if (rc < 0)
3500                 return rc;
3501
3502         lnet_set_tune_defaults(tun);
3503
3504         mutex_lock(&the_lnet.ln_api_mutex);
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                 rc = lnet_add_net_common(net, tun);
3509                 if (rc < 0)
3510                         goto out;
3511         }
3512
3513 out:
3514         mutex_unlock(&the_lnet.ln_api_mutex);
3515
3516         while (!list_empty(&net_head)) {
3517                 net = list_entry(net_head.next, struct lnet_net, net_list);
3518                 list_del_init(&net->net_list);
3519                 lnet_net_free(net);
3520         }
3521         return rc;
3522 }
3523
3524 int lnet_dyn_add_ni(struct lnet_ioctl_config_ni *conf)
3525 {
3526         struct lnet_net *net;
3527         struct lnet_ni *ni;
3528         struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3529         int rc, i;
3530         __u32 net_id, lnd_type;
3531
3532         /* get the tunables if they are available */
3533         if (conf->lic_cfg_hdr.ioc_len >=
3534             sizeof(*conf) + sizeof(*tun))
3535                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3536                         conf->lic_bulk;
3537
3538         /* handle legacy ip2nets from DLC */
3539         if (conf->lic_legacy_ip2nets[0] != '\0')
3540                 return lnet_handle_legacy_ip2nets(conf->lic_legacy_ip2nets,
3541                                                   tun);
3542
3543         net_id = LNET_NIDNET(conf->lic_nid);
3544         lnd_type = LNET_NETTYP(net_id);
3545
3546         if (!libcfs_isknown_lnd(lnd_type)) {
3547                 CERROR("No valid net and lnd information provided\n");
3548                 return -EINVAL;
3549         }
3550
3551         net = lnet_net_alloc(net_id, NULL);
3552         if (!net)
3553                 return -ENOMEM;
3554
3555         for (i = 0; i < conf->lic_ncpts; i++) {
3556                 if (conf->lic_cpts[i] >= LNET_CPT_NUMBER)
3557                         return -EINVAL;
3558         }
3559
3560         ni = lnet_ni_alloc_w_cpt_array(net, conf->lic_cpts, conf->lic_ncpts,
3561                                        conf->lic_ni_intf);
3562         if (!ni)
3563                 return -ENOMEM;
3564
3565         lnet_set_tune_defaults(tun);
3566
3567         mutex_lock(&the_lnet.ln_api_mutex);
3568
3569         rc = lnet_add_net_common(net, tun);
3570
3571         mutex_unlock(&the_lnet.ln_api_mutex);
3572
3573         return rc;
3574 }
3575
3576 int lnet_dyn_del_ni(struct lnet_ioctl_config_ni *conf)
3577 {
3578         struct lnet_net  *net;
3579         struct lnet_ni *ni;
3580         __u32 net_id = LNET_NIDNET(conf->lic_nid);
3581         struct lnet_ping_buffer *pbuf;
3582         struct lnet_handle_md  ping_mdh;
3583         int               rc;
3584         int               net_count;
3585         __u32             addr;
3586
3587         /* don't allow userspace to shutdown the LOLND */
3588         if (LNET_NETTYP(net_id) == LOLND)
3589                 return -EINVAL;
3590
3591         mutex_lock(&the_lnet.ln_api_mutex);
3592
3593         lnet_net_lock(0);
3594
3595         net = lnet_get_net_locked(net_id);
3596         if (!net) {
3597                 CERROR("net %s not found\n",
3598                        libcfs_net2str(net_id));
3599                 rc = -ENOENT;
3600                 goto unlock_net;
3601         }
3602
3603         addr = LNET_NIDADDR(conf->lic_nid);
3604         if (addr == 0) {
3605                 /* remove the entire net */
3606                 net_count = lnet_get_net_ni_count_locked(net);
3607
3608                 lnet_net_unlock(0);
3609
3610                 /* create and link a new ping info, before removing the old one */
3611                 rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3612                                         lnet_get_ni_count() - net_count,
3613                                         false);
3614                 if (rc != 0)
3615                         goto unlock_api_mutex;
3616
3617                 lnet_shutdown_lndnet(net);
3618
3619                 lnet_acceptor_stop();
3620
3621                 lnet_ping_target_update(pbuf, ping_mdh);
3622
3623                 goto unlock_api_mutex;
3624         }
3625
3626         ni = lnet_nid2ni_locked(conf->lic_nid, 0);
3627         if (!ni) {
3628                 CERROR("nid %s not found\n",
3629                        libcfs_nid2str(conf->lic_nid));
3630                 rc = -ENOENT;
3631                 goto unlock_net;
3632         }
3633
3634         net_count = lnet_get_net_ni_count_locked(net);
3635
3636         lnet_net_unlock(0);
3637
3638         /* create and link a new ping info, before removing the old one */
3639         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3640                                   lnet_get_ni_count() - 1, false);
3641         if (rc != 0)
3642                 goto unlock_api_mutex;
3643
3644         lnet_shutdown_lndni(ni);
3645
3646         lnet_acceptor_stop();
3647
3648         lnet_ping_target_update(pbuf, ping_mdh);
3649
3650         /* check if the net is empty and remove it if it is */
3651         if (net_count == 1)
3652                 lnet_shutdown_lndnet(net);
3653
3654         goto unlock_api_mutex;
3655
3656 unlock_net:
3657         lnet_net_unlock(0);
3658 unlock_api_mutex:
3659         mutex_unlock(&the_lnet.ln_api_mutex);
3660
3661         return rc;
3662 }
3663
3664 /*
3665  * lnet_dyn_add_net and lnet_dyn_del_net are now deprecated.
3666  * They are only expected to be called for unique networks.
3667  * That can be as a result of older DLC library
3668  * calls. Multi-Rail DLC and beyond no longer uses these APIs.
3669  */
3670 int
3671 lnet_dyn_add_net(struct lnet_ioctl_config_data *conf)
3672 {
3673         struct lnet_net *net;
3674         LIST_HEAD(net_head);
3675         int rc;
3676         struct lnet_ioctl_config_lnd_tunables tun;
3677         const char *nets = conf->cfg_config_u.cfg_net.net_intf;
3678
3679         /* Create a net/ni structures for the network string */
3680         rc = lnet_parse_networks(&net_head, nets);
3681         if (rc <= 0)
3682                 return rc == 0 ? -EINVAL : rc;
3683
3684         mutex_lock(&the_lnet.ln_api_mutex);
3685
3686         if (rc > 1) {
3687                 rc = -EINVAL; /* only add one network per call */
3688                 goto out_unlock_clean;
3689         }
3690
3691         net = list_entry(net_head.next, struct lnet_net, net_list);
3692         list_del_init(&net->net_list);
3693
3694         LASSERT(lnet_net_unique(net->net_id, &the_lnet.ln_nets, NULL));
3695
3696         memset(&tun, 0, sizeof(tun));
3697
3698         tun.lt_cmn.lct_peer_timeout =
3699           (!conf->cfg_config_u.cfg_net.net_peer_timeout) ? DEFAULT_PEER_TIMEOUT :
3700                 conf->cfg_config_u.cfg_net.net_peer_timeout;
3701         tun.lt_cmn.lct_peer_tx_credits =
3702           (!conf->cfg_config_u.cfg_net.net_peer_tx_credits) ? DEFAULT_PEER_CREDITS :
3703                 conf->cfg_config_u.cfg_net.net_peer_tx_credits;
3704         tun.lt_cmn.lct_peer_rtr_credits =
3705           conf->cfg_config_u.cfg_net.net_peer_rtr_credits;
3706         tun.lt_cmn.lct_max_tx_credits =
3707           (!conf->cfg_config_u.cfg_net.net_max_tx_credits) ? DEFAULT_CREDITS :
3708                 conf->cfg_config_u.cfg_net.net_max_tx_credits;
3709
3710         rc = lnet_add_net_common(net, &tun);
3711
3712 out_unlock_clean:
3713         mutex_unlock(&the_lnet.ln_api_mutex);
3714         while (!list_empty(&net_head)) {
3715                 /* net_head list is empty in success case */
3716                 net = list_entry(net_head.next, struct lnet_net, net_list);
3717                 list_del_init(&net->net_list);
3718                 lnet_net_free(net);
3719         }
3720         return rc;
3721 }
3722
3723 int
3724 lnet_dyn_del_net(__u32 net_id)
3725 {
3726         struct lnet_net  *net;
3727         struct lnet_ping_buffer *pbuf;
3728         struct lnet_handle_md ping_mdh;
3729         int               rc;
3730         int               net_ni_count;
3731
3732         /* don't allow userspace to shutdown the LOLND */
3733         if (LNET_NETTYP(net_id) == LOLND)
3734                 return -EINVAL;
3735
3736         mutex_lock(&the_lnet.ln_api_mutex);
3737
3738         lnet_net_lock(0);
3739
3740         net = lnet_get_net_locked(net_id);
3741         if (net == NULL) {
3742                 lnet_net_unlock(0);
3743                 rc = -EINVAL;
3744                 goto out;
3745         }
3746
3747         net_ni_count = lnet_get_net_ni_count_locked(net);
3748
3749         lnet_net_unlock(0);
3750
3751         /* create and link a new ping info, before removing the old one */
3752         rc = lnet_ping_target_setup(&pbuf, &ping_mdh,
3753                                     lnet_get_ni_count() - net_ni_count, false);
3754         if (rc != 0)
3755                 goto out;
3756
3757         lnet_shutdown_lndnet(net);
3758
3759         lnet_acceptor_stop();
3760
3761         lnet_ping_target_update(pbuf, ping_mdh);
3762
3763 out:
3764         mutex_unlock(&the_lnet.ln_api_mutex);
3765
3766         return rc;
3767 }
3768
3769 void lnet_incr_dlc_seq(void)
3770 {
3771         atomic_inc(&lnet_dlc_seq_no);
3772 }
3773
3774 __u32 lnet_get_dlc_seq_locked(void)
3775 {
3776         return atomic_read(&lnet_dlc_seq_no);
3777 }
3778
3779 static void
3780 lnet_ni_set_healthv(lnet_nid_t nid, int value, bool all)
3781 {
3782         struct lnet_net *net;
3783         struct lnet_ni *ni;
3784
3785         lnet_net_lock(LNET_LOCK_EX);
3786         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3787                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3788                         if (all || (nid_is_nid4(&ni->ni_nid) &&
3789                                     lnet_nid_to_nid4(&ni->ni_nid) == nid)) {
3790                                 atomic_set(&ni->ni_healthv, value);
3791                                 if (list_empty(&ni->ni_recovery) &&
3792                                     value < LNET_MAX_HEALTH_VALUE) {
3793                                         CERROR("manually adding local NI %s to recovery\n",
3794                                                libcfs_nidstr(&ni->ni_nid));
3795                                         list_add_tail(&ni->ni_recovery,
3796                                                       &the_lnet.ln_mt_localNIRecovq);
3797                                         lnet_ni_addref_locked(ni, 0);
3798                                 }
3799                                 if (!all) {
3800                                         lnet_net_unlock(LNET_LOCK_EX);
3801                                         return;
3802                                 }
3803                         }
3804                 }
3805         }
3806         lnet_net_unlock(LNET_LOCK_EX);
3807 }
3808
3809 static void
3810 lnet_ni_set_conns_per_peer(lnet_nid_t nid, int value, bool all)
3811 {
3812         struct lnet_net *net;
3813         struct lnet_ni *ni;
3814
3815         lnet_net_lock(LNET_LOCK_EX);
3816         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
3817                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
3818                         if (lnet_nid_to_nid4(&ni->ni_nid) != nid && !all)
3819                                 continue;
3820                         if (LNET_NETTYP(net->net_id) == SOCKLND)
3821                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_sock.lnd_conns_per_peer = value;
3822                         else if (LNET_NETTYP(net->net_id) == O2IBLND)
3823                                 ni->ni_lnd_tunables.lnd_tun_u.lnd_o2ib.lnd_conns_per_peer = value;
3824                         if (!all) {
3825                                 lnet_net_unlock(LNET_LOCK_EX);
3826                                 return;
3827                         }
3828                 }
3829         }
3830         lnet_net_unlock(LNET_LOCK_EX);
3831 }
3832
3833 static int
3834 lnet_get_local_ni_hstats(struct lnet_ioctl_local_ni_hstats *stats)
3835 {
3836         int cpt, rc = 0;
3837         struct lnet_ni *ni;
3838         lnet_nid_t nid = stats->hlni_nid;
3839
3840         cpt = lnet_net_lock_current();
3841         ni = lnet_nid2ni_locked(nid, cpt);
3842
3843         if (!ni) {
3844                 rc = -ENOENT;
3845                 goto unlock;
3846         }
3847
3848         stats->hlni_local_interrupt = atomic_read(&ni->ni_hstats.hlt_local_interrupt);
3849         stats->hlni_local_dropped = atomic_read(&ni->ni_hstats.hlt_local_dropped);
3850         stats->hlni_local_aborted = atomic_read(&ni->ni_hstats.hlt_local_aborted);
3851         stats->hlni_local_no_route = atomic_read(&ni->ni_hstats.hlt_local_no_route);
3852         stats->hlni_local_timeout = atomic_read(&ni->ni_hstats.hlt_local_timeout);
3853         stats->hlni_local_error = atomic_read(&ni->ni_hstats.hlt_local_error);
3854         stats->hlni_fatal_error = atomic_read(&ni->ni_fatal_error_on);
3855         stats->hlni_health_value = atomic_read(&ni->ni_healthv);
3856         stats->hlni_ping_count = ni->ni_ping_count;
3857         stats->hlni_next_ping = ni->ni_next_ping;
3858
3859 unlock:
3860         lnet_net_unlock(cpt);
3861
3862         return rc;
3863 }
3864
3865 static int
3866 lnet_get_local_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3867 {
3868         struct lnet_ni *ni;
3869         int i = 0;
3870
3871         lnet_net_lock(LNET_LOCK_EX);
3872         list_for_each_entry(ni, &the_lnet.ln_mt_localNIRecovq, ni_recovery) {
3873                 if (!nid_is_nid4(&ni->ni_nid))
3874                         continue;
3875                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&ni->ni_nid);
3876                 i++;
3877                 if (i >= LNET_MAX_SHOW_NUM_NID)
3878                         break;
3879         }
3880         lnet_net_unlock(LNET_LOCK_EX);
3881         list->rlst_num_nids = i;
3882
3883         return 0;
3884 }
3885
3886 static int
3887 lnet_get_peer_ni_recovery_list(struct lnet_ioctl_recovery_list *list)
3888 {
3889         struct lnet_peer_ni *lpni;
3890         int i = 0;
3891
3892         lnet_net_lock(LNET_LOCK_EX);
3893         list_for_each_entry(lpni, &the_lnet.ln_mt_peerNIRecovq, lpni_recovery) {
3894                 list->rlst_nid_array[i] = lnet_nid_to_nid4(&lpni->lpni_nid);
3895                 i++;
3896                 if (i >= LNET_MAX_SHOW_NUM_NID)
3897                         break;
3898         }
3899         lnet_net_unlock(LNET_LOCK_EX);
3900         list->rlst_num_nids = i;
3901
3902         return 0;
3903 }
3904
3905 /**
3906  * LNet ioctl handler.
3907  *
3908  */
3909 int
3910 LNetCtl(unsigned int cmd, void *arg)
3911 {
3912         struct libcfs_ioctl_data *data = arg;
3913         struct lnet_ioctl_config_data *config;
3914         struct lnet_process_id    id = {0};
3915         struct lnet_ni           *ni;
3916         int                       rc;
3917
3918         BUILD_BUG_ON(sizeof(struct lnet_ioctl_net_config) +
3919                      sizeof(struct lnet_ioctl_config_data) > LIBCFS_IOC_DATA_MAX);
3920
3921         switch (cmd) {
3922         case IOC_LIBCFS_GET_NI:
3923                 rc = LNetGetId(data->ioc_count, &id);
3924                 data->ioc_nid = id.nid;
3925                 return rc;
3926
3927         case IOC_LIBCFS_FAIL_NID:
3928                 return lnet_fail_nid(data->ioc_nid, data->ioc_count);
3929
3930         case IOC_LIBCFS_ADD_ROUTE: {
3931                 /* default router sensitivity to 1 */
3932                 unsigned int sensitivity = 1;
3933                 config = arg;
3934
3935                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3936                         return -EINVAL;
3937
3938                 if (config->cfg_config_u.cfg_route.rtr_sensitivity) {
3939                         sensitivity =
3940                           config->cfg_config_u.cfg_route.rtr_sensitivity;
3941                 }
3942
3943                 mutex_lock(&the_lnet.ln_api_mutex);
3944                 rc = lnet_add_route(config->cfg_net,
3945                                     config->cfg_config_u.cfg_route.rtr_hop,
3946                                     config->cfg_nid,
3947                                     config->cfg_config_u.cfg_route.
3948                                         rtr_priority, sensitivity);
3949                 mutex_unlock(&the_lnet.ln_api_mutex);
3950                 return rc;
3951         }
3952
3953         case IOC_LIBCFS_DEL_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_del_route(config->cfg_net, config->cfg_nid);
3961                 mutex_unlock(&the_lnet.ln_api_mutex);
3962                 return rc;
3963
3964         case IOC_LIBCFS_GET_ROUTE:
3965                 config = arg;
3966
3967                 if (config->cfg_hdr.ioc_len < sizeof(*config))
3968                         return -EINVAL;
3969
3970                 mutex_lock(&the_lnet.ln_api_mutex);
3971                 rc = lnet_get_route(config->cfg_count,
3972                                     &config->cfg_net,
3973                                     &config->cfg_config_u.cfg_route.rtr_hop,
3974                                     &config->cfg_nid,
3975                                     &config->cfg_config_u.cfg_route.rtr_flags,
3976                                     &config->cfg_config_u.cfg_route.
3977                                         rtr_priority,
3978                                     &config->cfg_config_u.cfg_route.
3979                                         rtr_sensitivity);
3980                 mutex_unlock(&the_lnet.ln_api_mutex);
3981                 return rc;
3982
3983         case IOC_LIBCFS_GET_LOCAL_NI: {
3984                 struct lnet_ioctl_config_ni *cfg_ni;
3985                 struct lnet_ioctl_config_lnd_tunables *tun = NULL;
3986                 struct lnet_ioctl_element_stats *stats;
3987                 __u32 tun_size;
3988
3989                 cfg_ni = arg;
3990
3991                 /* get the tunables if they are available */
3992                 if (cfg_ni->lic_cfg_hdr.ioc_len <
3993                     sizeof(*cfg_ni) + sizeof(*stats) + sizeof(*tun))
3994                         return -EINVAL;
3995
3996                 stats = (struct lnet_ioctl_element_stats *)
3997                         cfg_ni->lic_bulk;
3998                 tun = (struct lnet_ioctl_config_lnd_tunables *)
3999                                 (cfg_ni->lic_bulk + sizeof(*stats));
4000
4001                 tun_size = cfg_ni->lic_cfg_hdr.ioc_len - sizeof(*cfg_ni) -
4002                         sizeof(*stats);
4003
4004                 mutex_lock(&the_lnet.ln_api_mutex);
4005                 rc = lnet_get_ni_config(cfg_ni, tun, stats, tun_size);
4006                 mutex_unlock(&the_lnet.ln_api_mutex);
4007                 return rc;
4008         }
4009
4010         case IOC_LIBCFS_GET_LOCAL_NI_MSG_STATS: {
4011                 struct lnet_ioctl_element_msg_stats *msg_stats = arg;
4012
4013                 if (msg_stats->im_hdr.ioc_len != sizeof(*msg_stats))
4014                         return -EINVAL;
4015
4016                 mutex_lock(&the_lnet.ln_api_mutex);
4017                 rc = lnet_get_ni_stats(msg_stats);
4018                 mutex_unlock(&the_lnet.ln_api_mutex);
4019
4020                 return rc;
4021         }
4022
4023         case IOC_LIBCFS_GET_NET: {
4024                 size_t total = sizeof(*config) +
4025                                sizeof(struct lnet_ioctl_net_config);
4026                 config = arg;
4027
4028                 if (config->cfg_hdr.ioc_len < total)
4029                         return -EINVAL;
4030
4031                 mutex_lock(&the_lnet.ln_api_mutex);
4032                 rc = lnet_get_net_config(config);
4033                 mutex_unlock(&the_lnet.ln_api_mutex);
4034                 return rc;
4035         }
4036
4037         case IOC_LIBCFS_GET_LNET_STATS:
4038         {
4039                 struct lnet_ioctl_lnet_stats *lnet_stats = arg;
4040
4041                 if (lnet_stats->st_hdr.ioc_len < sizeof(*lnet_stats))
4042                         return -EINVAL;
4043
4044                 mutex_lock(&the_lnet.ln_api_mutex);
4045                 rc = lnet_counters_get(&lnet_stats->st_cntrs);
4046                 mutex_unlock(&the_lnet.ln_api_mutex);
4047                 return rc;
4048         }
4049
4050         case IOC_LIBCFS_RESET_LNET_STATS:
4051         {
4052                 mutex_lock(&the_lnet.ln_api_mutex);
4053                 lnet_counters_reset();
4054                 mutex_unlock(&the_lnet.ln_api_mutex);
4055                 return 0;
4056         }
4057
4058         case IOC_LIBCFS_CONFIG_RTR:
4059                 config = arg;
4060
4061                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4062                         return -EINVAL;
4063
4064                 mutex_lock(&the_lnet.ln_api_mutex);
4065                 if (config->cfg_config_u.cfg_buffers.buf_enable) {
4066                         rc = lnet_rtrpools_enable();
4067                         mutex_unlock(&the_lnet.ln_api_mutex);
4068                         return rc;
4069                 }
4070                 lnet_rtrpools_disable();
4071                 mutex_unlock(&the_lnet.ln_api_mutex);
4072                 return 0;
4073
4074         case IOC_LIBCFS_ADD_BUF:
4075                 config = arg;
4076
4077                 if (config->cfg_hdr.ioc_len < sizeof(*config))
4078                         return -EINVAL;
4079
4080                 mutex_lock(&the_lnet.ln_api_mutex);
4081                 rc = lnet_rtrpools_adjust(config->cfg_config_u.cfg_buffers.
4082                                                 buf_tiny,
4083                                           config->cfg_config_u.cfg_buffers.
4084                                                 buf_small,
4085                                           config->cfg_config_u.cfg_buffers.
4086                                                 buf_large);
4087                 mutex_unlock(&the_lnet.ln_api_mutex);
4088                 return rc;
4089
4090         case IOC_LIBCFS_SET_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                 lnet_net_lock(LNET_LOCK_EX);
4096                 lnet_numa_range = numa->sv_value;
4097                 lnet_net_unlock(LNET_LOCK_EX);
4098                 return 0;
4099         }
4100
4101         case IOC_LIBCFS_GET_NUMA_RANGE: {
4102                 struct lnet_ioctl_set_value *numa;
4103                 numa = arg;
4104                 if (numa->sv_hdr.ioc_len != sizeof(*numa))
4105                         return -EINVAL;
4106                 numa->sv_value = lnet_numa_range;
4107                 return 0;
4108         }
4109
4110         case IOC_LIBCFS_GET_BUF: {
4111                 struct lnet_ioctl_pool_cfg *pool_cfg;
4112                 size_t total = sizeof(*config) + sizeof(*pool_cfg);
4113
4114                 config = arg;
4115
4116                 if (config->cfg_hdr.ioc_len < total)
4117                         return -EINVAL;
4118
4119                 pool_cfg = (struct lnet_ioctl_pool_cfg *)config->cfg_bulk;
4120
4121                 mutex_lock(&the_lnet.ln_api_mutex);
4122                 rc = lnet_get_rtr_pool_cfg(config->cfg_count, pool_cfg);
4123                 mutex_unlock(&the_lnet.ln_api_mutex);
4124                 return rc;
4125         }
4126
4127         case IOC_LIBCFS_GET_LOCAL_HSTATS: {
4128                 struct lnet_ioctl_local_ni_hstats *stats = arg;
4129
4130                 if (stats->hlni_hdr.ioc_len < sizeof(*stats))
4131                         return -EINVAL;
4132
4133                 mutex_lock(&the_lnet.ln_api_mutex);
4134                 rc = lnet_get_local_ni_hstats(stats);
4135                 mutex_unlock(&the_lnet.ln_api_mutex);
4136
4137                 return rc;
4138         }
4139
4140         case IOC_LIBCFS_GET_RECOVERY_QUEUE: {
4141                 struct lnet_ioctl_recovery_list *list = arg;
4142                 if (list->rlst_hdr.ioc_len < sizeof(*list))
4143                         return -EINVAL;
4144
4145                 mutex_lock(&the_lnet.ln_api_mutex);
4146                 if (list->rlst_type == LNET_HEALTH_TYPE_LOCAL_NI)
4147                         rc = lnet_get_local_ni_recovery_list(list);
4148                 else
4149                         rc = lnet_get_peer_ni_recovery_list(list);
4150                 mutex_unlock(&the_lnet.ln_api_mutex);
4151                 return rc;
4152         }
4153
4154         case IOC_LIBCFS_ADD_PEER_NI: {
4155                 struct lnet_ioctl_peer_cfg *cfg = arg;
4156
4157                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4158                         return -EINVAL;
4159
4160                 mutex_lock(&the_lnet.ln_api_mutex);
4161                 rc = lnet_add_peer_ni(cfg->prcfg_prim_nid,
4162                                       cfg->prcfg_cfg_nid,
4163                                       cfg->prcfg_mr, false);
4164                 mutex_unlock(&the_lnet.ln_api_mutex);
4165                 return rc;
4166         }
4167
4168         case IOC_LIBCFS_DEL_PEER_NI: {
4169                 struct lnet_ioctl_peer_cfg *cfg = arg;
4170
4171                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4172                         return -EINVAL;
4173
4174                 mutex_lock(&the_lnet.ln_api_mutex);
4175                 rc = lnet_del_peer_ni(cfg->prcfg_prim_nid,
4176                                       cfg->prcfg_cfg_nid);
4177                 mutex_unlock(&the_lnet.ln_api_mutex);
4178                 return rc;
4179         }
4180
4181         case IOC_LIBCFS_GET_PEER_INFO: {
4182                 struct lnet_ioctl_peer *peer_info = arg;
4183
4184                 if (peer_info->pr_hdr.ioc_len < sizeof(*peer_info))
4185                         return -EINVAL;
4186
4187                 mutex_lock(&the_lnet.ln_api_mutex);
4188                 rc = lnet_get_peer_ni_info(
4189                    peer_info->pr_count,
4190                    &peer_info->pr_nid,
4191                    peer_info->pr_lnd_u.pr_peer_credits.cr_aliveness,
4192                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ncpt,
4193                    &peer_info->pr_lnd_u.pr_peer_credits.cr_refcount,
4194                    &peer_info->pr_lnd_u.pr_peer_credits.cr_ni_peer_tx_credits,
4195                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_credits,
4196                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_rtr_credits,
4197                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_min_tx_credits,
4198                    &peer_info->pr_lnd_u.pr_peer_credits.cr_peer_tx_qnob);
4199                 mutex_unlock(&the_lnet.ln_api_mutex);
4200                 return rc;
4201         }
4202
4203         case IOC_LIBCFS_GET_PEER_NI: {
4204                 struct lnet_ioctl_peer_cfg *cfg = arg;
4205
4206                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4207                         return -EINVAL;
4208
4209                 mutex_lock(&the_lnet.ln_api_mutex);
4210                 rc = lnet_get_peer_info(cfg,
4211                                         (void __user *)cfg->prcfg_bulk);
4212                 mutex_unlock(&the_lnet.ln_api_mutex);
4213                 return rc;
4214         }
4215
4216         case IOC_LIBCFS_GET_PEER_LIST: {
4217                 struct lnet_ioctl_peer_cfg *cfg = arg;
4218
4219                 if (cfg->prcfg_hdr.ioc_len < sizeof(*cfg))
4220                         return -EINVAL;
4221
4222                 mutex_lock(&the_lnet.ln_api_mutex);
4223                 rc = lnet_get_peer_list(&cfg->prcfg_count, &cfg->prcfg_size,
4224                                 (struct lnet_process_id __user *)cfg->prcfg_bulk);
4225                 mutex_unlock(&the_lnet.ln_api_mutex);
4226                 return rc;
4227         }
4228
4229         case IOC_LIBCFS_SET_HEALHV: {
4230                 struct lnet_ioctl_reset_health_cfg *cfg = arg;
4231                 int value;
4232                 if (cfg->rh_hdr.ioc_len < sizeof(*cfg))
4233                         return -EINVAL;
4234                 if (cfg->rh_value < 0 ||
4235                     cfg->rh_value > LNET_MAX_HEALTH_VALUE)
4236                         value = LNET_MAX_HEALTH_VALUE;
4237                 else
4238                         value = cfg->rh_value;
4239                 CDEBUG(D_NET, "Manually setting healthv to %d for %s:%s. all = %d\n",
4240                        value, (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI) ?
4241                        "local" : "peer", libcfs_nid2str(cfg->rh_nid), cfg->rh_all);
4242                 mutex_lock(&the_lnet.ln_api_mutex);
4243                 if (cfg->rh_type == LNET_HEALTH_TYPE_LOCAL_NI)
4244                         lnet_ni_set_healthv(cfg->rh_nid, value,
4245                                              cfg->rh_all);
4246                 else
4247                         lnet_peer_ni_set_healthv(cfg->rh_nid, value,
4248                                                   cfg->rh_all);
4249                 mutex_unlock(&the_lnet.ln_api_mutex);
4250                 return 0;
4251         }
4252
4253         case IOC_LIBCFS_SET_CONNS_PER_PEER: {
4254                 struct lnet_ioctl_reset_conns_per_peer_cfg *cfg = arg;
4255                 int value;
4256
4257                 if (cfg->rcpp_hdr.ioc_len < sizeof(*cfg))
4258                         return -EINVAL;
4259                 if (cfg->rcpp_value < 0)
4260                         value = 1;
4261                 else
4262                         value = cfg->rcpp_value;
4263                 CDEBUG(D_NET,
4264                        "Setting conns_per_peer to %d for %s. all = %d\n",
4265                        value, libcfs_nid2str(cfg->rcpp_nid), cfg->rcpp_all);
4266                 mutex_lock(&the_lnet.ln_api_mutex);
4267                 lnet_ni_set_conns_per_peer(cfg->rcpp_nid, value, cfg->rcpp_all);
4268                 mutex_unlock(&the_lnet.ln_api_mutex);
4269                 return 0;
4270         }
4271
4272         case IOC_LIBCFS_NOTIFY_ROUTER: {
4273                 time64_t deadline = ktime_get_real_seconds() - data->ioc_u64[0];
4274
4275                 /* The deadline passed in by the user should be some time in
4276                  * seconds in the future since the UNIX epoch. We have to map
4277                  * that deadline to the wall clock.
4278                  */
4279                 deadline += ktime_get_seconds();
4280                 return lnet_notify(NULL, data->ioc_nid, data->ioc_flags, false,
4281                                    deadline);
4282         }
4283
4284         case IOC_LIBCFS_LNET_DIST:
4285                 rc = LNetDist(data->ioc_nid, &data->ioc_nid, &data->ioc_u32[1]);
4286                 if (rc < 0 && rc != -EHOSTUNREACH)
4287                         return rc;
4288
4289                 data->ioc_u32[0] = rc;
4290                 return 0;
4291
4292         case IOC_LIBCFS_TESTPROTOCOMPAT:
4293                 the_lnet.ln_testprotocompat = data->ioc_flags;
4294                 return 0;
4295
4296         case IOC_LIBCFS_LNET_FAULT:
4297                 return lnet_fault_ctl(data->ioc_flags, data);
4298
4299         case IOC_LIBCFS_PING: {
4300                 signed long timeout;
4301
4302                 id.nid = data->ioc_nid;
4303                 id.pid = data->ioc_u32[0];
4304
4305                 /* If timeout is negative then set default of 3 minutes */
4306                 if (((s32)data->ioc_u32[1] <= 0) ||
4307                     data->ioc_u32[1] > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4308                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4309                 else
4310                         timeout = nsecs_to_jiffies(data->ioc_u32[1] * NSEC_PER_MSEC);
4311
4312                 rc = lnet_ping(id, timeout, data->ioc_pbuf1,
4313                                data->ioc_plen1 / sizeof(struct lnet_process_id));
4314
4315                 if (rc < 0)
4316                         return rc;
4317
4318                 data->ioc_count = rc;
4319                 return 0;
4320         }
4321
4322         case IOC_LIBCFS_PING_PEER: {
4323                 struct lnet_ioctl_ping_data *ping = arg;
4324                 struct lnet_peer *lp;
4325                 signed long timeout;
4326
4327                 /* If timeout is negative then set default of 3 minutes */
4328                 if (((s32)ping->op_param) <= 0 ||
4329                     ping->op_param > (DEFAULT_PEER_TIMEOUT * MSEC_PER_SEC))
4330                         timeout = cfs_time_seconds(DEFAULT_PEER_TIMEOUT);
4331                 else
4332                         timeout = nsecs_to_jiffies(ping->op_param * NSEC_PER_MSEC);
4333
4334                 rc = lnet_ping(ping->ping_id, timeout,
4335                                ping->ping_buf,
4336                                ping->ping_count);
4337                 if (rc < 0)
4338                         return rc;
4339
4340                 mutex_lock(&the_lnet.ln_api_mutex);
4341                 lp = lnet_find_peer(ping->ping_id.nid);
4342                 if (lp) {
4343                         ping->ping_id.nid =
4344                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4345                         ping->mr_info = lnet_peer_is_multi_rail(lp);
4346                         lnet_peer_decref_locked(lp);
4347                 }
4348                 mutex_unlock(&the_lnet.ln_api_mutex);
4349
4350                 ping->ping_count = rc;
4351                 return 0;
4352         }
4353
4354         case IOC_LIBCFS_DISCOVER: {
4355                 struct lnet_ioctl_ping_data *discover = arg;
4356                 struct lnet_peer *lp;
4357
4358                 rc = lnet_discover(discover->ping_id, discover->op_param,
4359                                    discover->ping_buf,
4360                                    discover->ping_count);
4361                 if (rc < 0)
4362                         return rc;
4363
4364                 mutex_lock(&the_lnet.ln_api_mutex);
4365                 lp = lnet_find_peer(discover->ping_id.nid);
4366                 if (lp) {
4367                         discover->ping_id.nid =
4368                                 lnet_nid_to_nid4(&lp->lp_primary_nid);
4369                         discover->mr_info = lnet_peer_is_multi_rail(lp);
4370                         lnet_peer_decref_locked(lp);
4371                 }
4372                 mutex_unlock(&the_lnet.ln_api_mutex);
4373
4374                 discover->ping_count = rc;
4375                 return 0;
4376         }
4377
4378         case IOC_LIBCFS_ADD_UDSP: {
4379                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4380                 __u32 bulk_size = ioc_udsp->iou_hdr.ioc_len;
4381
4382                 mutex_lock(&the_lnet.ln_api_mutex);
4383                 rc = lnet_udsp_demarshal_add(arg, bulk_size);
4384                 if (!rc) {
4385                         rc = lnet_udsp_apply_policies(NULL, false);
4386                         CDEBUG(D_NET, "policy application returned %d\n", rc);
4387                         rc = 0;
4388                 }
4389                 mutex_unlock(&the_lnet.ln_api_mutex);
4390
4391                 return rc;
4392         }
4393
4394         case IOC_LIBCFS_DEL_UDSP: {
4395                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4396                 int idx = ioc_udsp->iou_idx;
4397
4398                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4399                         return -EINVAL;
4400
4401                 mutex_lock(&the_lnet.ln_api_mutex);
4402                 rc = lnet_udsp_del_policy(idx);
4403                 if (!rc) {
4404                         rc = lnet_udsp_apply_policies(NULL, false);
4405                         CDEBUG(D_NET, "policy re-application returned %d\n",
4406                                rc);
4407                         rc = 0;
4408                 }
4409                 mutex_unlock(&the_lnet.ln_api_mutex);
4410
4411                 return rc;
4412         }
4413
4414         case IOC_LIBCFS_GET_UDSP_SIZE: {
4415                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4416                 struct lnet_udsp *udsp;
4417
4418                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4419                         return -EINVAL;
4420
4421                 rc = 0;
4422
4423                 mutex_lock(&the_lnet.ln_api_mutex);
4424                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4425                 if (!udsp) {
4426                         rc = -ENOENT;
4427                 } else {
4428                         /* coming in iou_idx will hold the idx of the udsp
4429                          * to get the size of. going out the iou_idx will
4430                          * hold the size of the UDSP found at the passed
4431                          * in index.
4432                          */
4433                         ioc_udsp->iou_idx = lnet_get_udsp_size(udsp);
4434                         if (ioc_udsp->iou_idx < 0)
4435                                 rc = -EINVAL;
4436                 }
4437                 mutex_unlock(&the_lnet.ln_api_mutex);
4438
4439                 return rc;
4440         }
4441
4442         case IOC_LIBCFS_GET_UDSP: {
4443                 struct lnet_ioctl_udsp *ioc_udsp = arg;
4444                 struct lnet_udsp *udsp;
4445
4446                 if (ioc_udsp->iou_hdr.ioc_len < sizeof(*ioc_udsp))
4447                         return -EINVAL;
4448
4449                 rc = 0;
4450
4451                 mutex_lock(&the_lnet.ln_api_mutex);
4452                 udsp = lnet_udsp_get_policy(ioc_udsp->iou_idx);
4453                 if (!udsp)
4454                         rc = -ENOENT;
4455                 else
4456                         rc = lnet_udsp_marshal(udsp, ioc_udsp);
4457                 mutex_unlock(&the_lnet.ln_api_mutex);
4458
4459                 return rc;
4460         }
4461
4462         case IOC_LIBCFS_GET_CONST_UDSP_INFO: {
4463                 struct lnet_ioctl_construct_udsp_info *info = arg;
4464
4465                 if (info->cud_hdr.ioc_len < sizeof(*info))
4466                         return -EINVAL;
4467
4468                 CDEBUG(D_NET, "GET_UDSP_INFO for %s\n",
4469                        libcfs_nid2str(info->cud_nid));
4470
4471                 mutex_lock(&the_lnet.ln_api_mutex);
4472                 lnet_udsp_get_construct_info(info);
4473                 mutex_unlock(&the_lnet.ln_api_mutex);
4474
4475                 return 0;
4476         }
4477
4478         default:
4479                 ni = lnet_net2ni_addref(data->ioc_net);
4480                 if (ni == NULL)
4481                         return -EINVAL;
4482
4483                 if (ni->ni_net->net_lnd->lnd_ctl == NULL)
4484                         rc = -EINVAL;
4485                 else
4486                         rc = ni->ni_net->net_lnd->lnd_ctl(ni, cmd, arg);
4487
4488                 lnet_ni_decref(ni);
4489                 return rc;
4490         }
4491         /* not reached */
4492 }
4493 EXPORT_SYMBOL(LNetCtl);
4494
4495 void LNetDebugPeer(struct lnet_process_id id)
4496 {
4497         lnet_debug_peer(id.nid);
4498 }
4499 EXPORT_SYMBOL(LNetDebugPeer);
4500
4501 /**
4502  * Determine if the specified peer \a nid is on the local node.
4503  *
4504  * \param nid   peer nid to check
4505  *
4506  * \retval true         If peer NID is on the local node.
4507  * \retval false        If peer NID is not on the local node.
4508  */
4509 bool LNetIsPeerLocal(lnet_nid_t nid)
4510 {
4511         struct lnet_net *net;
4512         struct lnet_ni *ni;
4513         int cpt;
4514
4515         cpt = lnet_net_lock_current();
4516         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4517                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4518                         if (lnet_nid_to_nid4(&ni->ni_nid) == nid) {
4519                                 lnet_net_unlock(cpt);
4520                                 return true;
4521                         }
4522                 }
4523         }
4524         lnet_net_unlock(cpt);
4525
4526         return false;
4527 }
4528 EXPORT_SYMBOL(LNetIsPeerLocal);
4529
4530 /**
4531  * Retrieve the struct lnet_process_id ID of LNet interface at \a index.
4532  * Note that all interfaces share a same PID, as requested by LNetNIInit().
4533  *
4534  * \param index Index of the interface to look up.
4535  * \param id On successful return, this location will hold the
4536  * struct lnet_process_id ID of the interface.
4537  *
4538  * \retval 0 If an interface exists at \a index.
4539  * \retval -ENOENT If no interface has been found.
4540  */
4541 int
4542 LNetGetId(unsigned int index, struct lnet_process_id *id)
4543 {
4544         struct lnet_ni   *ni;
4545         struct lnet_net  *net;
4546         int               cpt;
4547         int               rc = -ENOENT;
4548
4549         LASSERT(the_lnet.ln_refcount > 0);
4550
4551         cpt = lnet_net_lock_current();
4552
4553         list_for_each_entry(net, &the_lnet.ln_nets, net_list) {
4554                 list_for_each_entry(ni, &net->net_ni_list, ni_netlist) {
4555                         if (!nid_is_nid4(&ni->ni_nid))
4556                                 /* FIXME this needs to be handled */
4557                                 continue;
4558                         if (index-- != 0)
4559                                 continue;
4560
4561                         id->nid = lnet_nid_to_nid4(&ni->ni_nid);
4562                         id->pid = the_lnet.ln_pid;
4563                         rc = 0;
4564                         break;
4565                 }
4566         }
4567
4568         lnet_net_unlock(cpt);
4569         return rc;
4570 }
4571 EXPORT_SYMBOL(LNetGetId);
4572
4573 struct ping_data {
4574         int rc;
4575         int replied;
4576         struct lnet_handle_md mdh;
4577         struct completion completion;
4578 };
4579
4580 static void
4581 lnet_ping_event_handler(struct lnet_event *event)
4582 {
4583         struct ping_data *pd = event->md_user_ptr;
4584
4585         CDEBUG(D_NET, "ping event (%d %d)%s\n",
4586                event->type, event->status,
4587                event->unlinked ? " unlinked" : "");
4588
4589         if (event->status) {
4590                 if (!pd->rc)
4591                         pd->rc = event->status;
4592         } else if (event->type == LNET_EVENT_REPLY) {
4593                 pd->replied = 1;
4594                 pd->rc = event->mlength;
4595         }
4596         if (event->unlinked)
4597                 complete(&pd->completion);
4598 }
4599
4600 static int lnet_ping(struct lnet_process_id id, signed long timeout,
4601                      struct lnet_process_id __user *ids, int n_ids)
4602 {
4603         struct lnet_md md = { NULL };
4604         struct ping_data pd = { 0 };
4605         struct lnet_ping_buffer *pbuf;
4606         struct lnet_process_id tmpid;
4607         int i;
4608         int nob;
4609         int rc;
4610         int rc2;
4611
4612         /* n_ids limit is arbitrary */
4613         if (n_ids <= 0 || id.nid == LNET_NID_ANY)
4614                 return -EINVAL;
4615
4616         /*
4617          * if the user buffer has more space than the lnet_interfaces_max
4618          * then only fill it up to lnet_interfaces_max
4619          */
4620         if (n_ids > lnet_interfaces_max)
4621                 n_ids = lnet_interfaces_max;
4622
4623         if (id.pid == LNET_PID_ANY)
4624                 id.pid = LNET_PID_LUSTRE;
4625
4626         pbuf = lnet_ping_buffer_alloc(n_ids, GFP_NOFS);
4627         if (!pbuf)
4628                 return -ENOMEM;
4629
4630         /* initialize md content */
4631         md.start     = &pbuf->pb_info;
4632         md.length    = LNET_PING_INFO_SIZE(n_ids);
4633         md.threshold = 2; /* GET/REPLY */
4634         md.max_size  = 0;
4635         md.options   = LNET_MD_TRUNCATE;
4636         md.user_ptr  = &pd;
4637         md.handler   = lnet_ping_event_handler;
4638
4639         init_completion(&pd.completion);
4640
4641         rc = LNetMDBind(&md, LNET_UNLINK, &pd.mdh);
4642         if (rc != 0) {
4643                 CERROR("Can't bind MD: %d\n", rc);
4644                 goto fail_ping_buffer_decref;
4645         }
4646
4647         rc = LNetGet(LNET_NID_ANY, pd.mdh, id,
4648                      LNET_RESERVED_PORTAL,
4649                      LNET_PROTO_PING_MATCHBITS, 0, false);
4650
4651         if (rc != 0) {
4652                 /* Don't CERROR; this could be deliberate! */
4653                 rc2 = LNetMDUnlink(pd.mdh);
4654                 LASSERT(rc2 == 0);
4655
4656                 /* NB must wait for the UNLINK event below... */
4657         }
4658
4659         if (wait_for_completion_timeout(&pd.completion, timeout) == 0) {
4660                 /* Ensure completion in finite time... */
4661                 LNetMDUnlink(pd.mdh);
4662                 wait_for_completion(&pd.completion);
4663         }
4664         if (!pd.replied) {
4665                 rc = -EIO;
4666                 goto fail_ping_buffer_decref;
4667         }
4668
4669         nob = pd.rc;
4670         LASSERT(nob >= 0 && nob <= LNET_PING_INFO_SIZE(n_ids));
4671
4672         rc = -EPROTO;           /* if I can't parse... */
4673
4674         if (nob < 8) {
4675                 CERROR("%s: ping info too short %d\n",
4676                        libcfs_id2str(id), nob);
4677                 goto fail_ping_buffer_decref;
4678         }
4679
4680         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC)) {
4681                 lnet_swap_pinginfo(pbuf);
4682         } else if (pbuf->pb_info.pi_magic != LNET_PROTO_PING_MAGIC) {
4683                 CERROR("%s: Unexpected magic %08x\n",
4684                        libcfs_id2str(id), pbuf->pb_info.pi_magic);
4685                 goto fail_ping_buffer_decref;
4686         }
4687
4688         if ((pbuf->pb_info.pi_features & LNET_PING_FEAT_NI_STATUS) == 0) {
4689                 CERROR("%s: ping w/o NI status: 0x%x\n",
4690                        libcfs_id2str(id), pbuf->pb_info.pi_features);
4691                 goto fail_ping_buffer_decref;
4692         }
4693
4694         if (nob < LNET_PING_INFO_SIZE(0)) {
4695                 CERROR("%s: Short reply %d(%d min)\n",
4696                        libcfs_id2str(id),
4697                        nob, (int)LNET_PING_INFO_SIZE(0));
4698                 goto fail_ping_buffer_decref;
4699         }
4700
4701         if (pbuf->pb_info.pi_nnis < n_ids)
4702                 n_ids = pbuf->pb_info.pi_nnis;
4703
4704         if (nob < LNET_PING_INFO_SIZE(n_ids)) {
4705                 CERROR("%s: Short reply %d(%d expected)\n",
4706                        libcfs_id2str(id),
4707                        nob, (int)LNET_PING_INFO_SIZE(n_ids));
4708                 goto fail_ping_buffer_decref;
4709         }
4710
4711         rc = -EFAULT;           /* if I segv in copy_to_user()... */
4712
4713         memset(&tmpid, 0, sizeof(tmpid));
4714         for (i = 0; i < n_ids; i++) {
4715                 tmpid.pid = pbuf->pb_info.pi_pid;
4716                 tmpid.nid = pbuf->pb_info.pi_ni[i].ns_nid;
4717                 if (copy_to_user(&ids[i], &tmpid, sizeof(tmpid)))
4718                         goto fail_ping_buffer_decref;
4719         }
4720         rc = pbuf->pb_info.pi_nnis;
4721
4722  fail_ping_buffer_decref:
4723         lnet_ping_buffer_decref(pbuf);
4724         return rc;
4725 }
4726
4727 static int
4728 lnet_discover(struct lnet_process_id id, __u32 force,
4729               struct lnet_process_id __user *ids, int n_ids)
4730 {
4731         struct lnet_peer_ni *lpni;
4732         struct lnet_peer_ni *p;
4733         struct lnet_peer *lp;
4734         struct lnet_process_id *buf;
4735         int cpt;
4736         int i;
4737         int rc;
4738
4739         if (n_ids <= 0 ||
4740             id.nid == LNET_NID_ANY)
4741                 return -EINVAL;
4742
4743         if (id.pid == LNET_PID_ANY)
4744                 id.pid = LNET_PID_LUSTRE;
4745
4746         /*
4747          * If the user buffer has more space than the lnet_interfaces_max,
4748          * then only fill it up to lnet_interfaces_max.
4749          */
4750         if (n_ids > lnet_interfaces_max)
4751                 n_ids = lnet_interfaces_max;
4752
4753         CFS_ALLOC_PTR_ARRAY(buf, n_ids);
4754         if (!buf)
4755                 return -ENOMEM;
4756
4757         cpt = lnet_net_lock_current();
4758         lpni = lnet_nid2peerni_locked(id.nid, LNET_NID_ANY, cpt);
4759         if (IS_ERR(lpni)) {
4760                 rc = PTR_ERR(lpni);
4761                 goto out;
4762         }
4763
4764         /*
4765          * Clearing the NIDS_UPTODATE flag ensures the peer will
4766          * be discovered, provided discovery has not been disabled.
4767          */
4768         lp = lpni->lpni_peer_net->lpn_peer;
4769         spin_lock(&lp->lp_lock);
4770         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
4771         /* If the force flag is set, force a PING and PUSH as well. */
4772         if (force)
4773                 lp->lp_state |= LNET_PEER_FORCE_PING | LNET_PEER_FORCE_PUSH;
4774         spin_unlock(&lp->lp_lock);
4775         rc = lnet_discover_peer_locked(lpni, cpt, true);
4776         if (rc)
4777                 goto out_decref;
4778
4779         /* The lpni (or lp) for this NID may have changed and our ref is
4780          * the only thing keeping the old one around. Release the ref
4781          * and lookup the lpni again
4782          */
4783         lnet_peer_ni_decref_locked(lpni);
4784         lpni = lnet_find_peer_ni_locked(id.nid);
4785         if (!lpni) {
4786                 rc = -ENOENT;
4787                 goto out;
4788         }
4789         lp = lpni->lpni_peer_net->lpn_peer;
4790
4791         i = 0;
4792         p = NULL;
4793         while ((p = lnet_get_next_peer_ni_locked(lp, NULL, p)) != NULL) {
4794                 buf[i].pid = id.pid;
4795                 buf[i].nid = lnet_nid_to_nid4(&p->lpni_nid);
4796                 if (++i >= n_ids)
4797                         break;
4798         }
4799         rc = i;
4800
4801 out_decref:
4802         lnet_peer_ni_decref_locked(lpni);
4803 out:
4804         lnet_net_unlock(cpt);
4805
4806         if (rc >= 0)
4807                 if (copy_to_user(ids, buf, rc * sizeof(*buf)))
4808                         rc = -EFAULT;
4809         CFS_FREE_PTR_ARRAY(buf, n_ids);
4810
4811         return rc;
4812 }
4813
4814 /**
4815  * Retrieve peer discovery status.
4816  *
4817  * \retval 1 if lnet_peer_discovery_disabled is 0
4818  * \retval 0 if lnet_peer_discovery_disabled is 1
4819  */
4820 int
4821 LNetGetPeerDiscoveryStatus(void)
4822 {
4823         return !lnet_peer_discovery_disabled;
4824 }
4825 EXPORT_SYMBOL(LNetGetPeerDiscoveryStatus);