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